index.php 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462
  1. <?php
  2. /**
  3. * Shaarli v0.6.1 - Shaare your links...
  4. *
  5. * The personal, minimalist, super-fast, no-database Delicious clone.
  6. *
  7. * Friendly fork by the Shaarli community:
  8. * - https://github.com/shaarli/Shaarli
  9. *
  10. * Original project by sebsauvage.net:
  11. * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
  12. * - https://github.com/sebsauvage/Shaarli
  13. *
  14. * Licence: http://www.opensource.org/licenses/zlib-license.php
  15. *
  16. * Requires: PHP 5.3.x
  17. */
  18. // Set 'UTC' as the default timezone if it is not defined in php.ini
  19. // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
  20. if (date_default_timezone_get() == '') {
  21. date_default_timezone_set('UTC');
  22. }
  23. /* -----------------------------------------------------------------------------
  24. * Hardcoded parameters
  25. * You should not touch any code below (or at your own risks!)
  26. * (These parameters can be overwritten by editing the file /data/config.php)
  27. * -----------------------------------------------------------------------------
  28. */
  29. /*
  30. * Shaarli directories & configuration files
  31. */
  32. // Data subdirectory
  33. $GLOBALS['config']['DATADIR'] = 'data';
  34. // Main configuration file
  35. $GLOBALS['config']['CONFIG_FILE'] = $GLOBALS['config']['DATADIR'].'/config.php';
  36. // Link datastore
  37. $GLOBALS['config']['DATASTORE'] = $GLOBALS['config']['DATADIR'].'/datastore.php';
  38. // Banned IPs
  39. $GLOBALS['config']['IPBANS_FILENAME'] = $GLOBALS['config']['DATADIR'].'/ipbans.php';
  40. // Access log
  41. $GLOBALS['config']['LOG_FILE'] = $GLOBALS['config']['DATADIR'].'/log.txt';
  42. // For updates check of Shaarli
  43. $GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt';
  44. // RainTPL cache directory (keep the trailing slash!)
  45. $GLOBALS['config']['RAINTPL_TMP'] = 'tmp/';
  46. // Raintpl template directory (keep the trailing slash!)
  47. $GLOBALS['config']['RAINTPL_TPL'] = 'tpl/';
  48. // Thumbnail cache directory
  49. $GLOBALS['config']['CACHEDIR'] = 'cache';
  50. // Atom & RSS feed cache directory
  51. $GLOBALS['config']['PAGECACHE'] = 'pagecache';
  52. /*
  53. * Global configuration
  54. */
  55. // Ban IP after this many failures
  56. $GLOBALS['config']['BAN_AFTER'] = 4;
  57. // Ban duration for IP address after login failures (in seconds)
  58. $GLOBALS['config']['BAN_DURATION'] = 1800;
  59. // Feed options
  60. // Enable RSS permalinks by default.
  61. // This corresponds to the default behavior of shaarli before this was added as an option.
  62. $GLOBALS['config']['ENABLE_RSS_PERMALINKS'] = true;
  63. // If true, an extra "ATOM feed" button will be displayed in the toolbar
  64. $GLOBALS['config']['SHOW_ATOM'] = false;
  65. // Link display options
  66. $GLOBALS['config']['HIDE_PUBLIC_LINKS'] = false;
  67. $GLOBALS['config']['HIDE_TIMESTAMPS'] = false;
  68. $GLOBALS['config']['LINKS_PER_PAGE'] = 20;
  69. // Open Shaarli (true): anyone can add/edit/delete links without having to login
  70. $GLOBALS['config']['OPEN_SHAARLI'] = false;
  71. // Thumbnails
  72. // Display thumbnails in links
  73. $GLOBALS['config']['ENABLE_THUMBNAILS'] = true;
  74. // Store thumbnails in a local cache
  75. $GLOBALS['config']['ENABLE_LOCALCACHE'] = true;
  76. // Update check frequency for Shaarli. 86400 seconds=24 hours
  77. $GLOBALS['config']['UPDATECHECK_BRANCH'] = 'stable';
  78. $GLOBALS['config']['UPDATECHECK_INTERVAL'] = 86400;
  79. /*
  80. * Plugin configuration
  81. *
  82. * Warning: order matters!
  83. *
  84. * These settings may be be overriden in:
  85. * - data/config.php
  86. * - each plugin's configuration file
  87. */
  88. //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
  89. // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
  90. // 'wallabag', 'markdown', 'addlink_toolbar',
  91. //);
  92. $GLOBALS['config']['ENABLED_PLUGINS'] = array('qrcode');
  93. //$GLOBALS['plugins']['WALLABAG_URL'] = 'https://demo.wallabag.org/';
  94. // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
  95. $GLOBALS['config']['PUBSUBHUB_URL'] = '';
  96. /*
  97. * PHP configuration
  98. */
  99. define('shaarli_version', '0.6.1');
  100. // http://server.com/x/shaarli --> /shaarli/
  101. define('WEB_PATH', substr($_SERVER["REQUEST_URI"], 0, 1+strrpos($_SERVER["REQUEST_URI"], '/', 0)));
  102. // High execution time in case of problematic imports/exports.
  103. ini_set('max_input_time','60');
  104. // Try to set max upload file size and read
  105. ini_set('memory_limit', '128M');
  106. ini_set('post_max_size', '16M');
  107. ini_set('upload_max_filesize', '16M');
  108. // See all error except warnings
  109. error_reporting(E_ALL^E_WARNING);
  110. // See all errors (for debugging only)
  111. //error_reporting(-1);
  112. /*
  113. * User configuration
  114. */
  115. if (is_file($GLOBALS['config']['CONFIG_FILE'])) {
  116. require_once $GLOBALS['config']['CONFIG_FILE'];
  117. }
  118. // Shaarli library
  119. require_once 'application/ApplicationUtils.php';
  120. require_once 'application/Cache.php';
  121. require_once 'application/CachedPage.php';
  122. require_once 'application/FileUtils.php';
  123. require_once 'application/HttpUtils.php';
  124. require_once 'application/LinkDB.php';
  125. require_once 'application/TimeZone.php';
  126. require_once 'application/Url.php';
  127. require_once 'application/Utils.php';
  128. require_once 'application/Config.php';
  129. require_once 'application/PluginManager.php';
  130. require_once 'application/Router.php';
  131. // Ensure the PHP version is supported
  132. try {
  133. ApplicationUtils::checkPHPVersion('5.3', PHP_VERSION);
  134. } catch(Exception $exc) {
  135. header('Content-Type: text/plain; charset=utf-8');
  136. echo $exc->getMessage();
  137. exit;
  138. }
  139. // Force cookie path (but do not change lifetime)
  140. $cookie = session_get_cookie_params();
  141. $cookiedir = '';
  142. if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
  143. $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
  144. }
  145. // Set default cookie expiration and path.
  146. session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
  147. // Set session parameters on server side.
  148. // If the user does not access any page within this time, his/her session is considered expired.
  149. define('INACTIVITY_TIMEOUT', 3600); // in seconds.
  150. // Use cookies to store session.
  151. ini_set('session.use_cookies', 1);
  152. // Force cookies for session (phpsessionID forbidden in URL).
  153. ini_set('session.use_only_cookies', 1);
  154. // Prevent PHP form using sessionID in URL if cookies are disabled.
  155. ini_set('session.use_trans_sid', false);
  156. session_name('shaarli');
  157. // Start session if needed (Some server auto-start sessions).
  158. if (session_id() == '') {
  159. session_start();
  160. }
  161. // Regenerate session ID if invalid or not defined in cookie.
  162. if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) {
  163. session_regenerate_id(true);
  164. $_COOKIE['shaarli'] = session_id();
  165. }
  166. include "inc/rain.tpl.class.php"; //include Rain TPL
  167. raintpl::$tpl_dir = $GLOBALS['config']['RAINTPL_TPL']; // template directory
  168. raintpl::$cache_dir = $GLOBALS['config']['RAINTPL_TMP']; // cache directory
  169. $pluginManager = PluginManager::getInstance();
  170. $pluginManager->load($GLOBALS['config']['ENABLED_PLUGINS']);
  171. ob_start(); // Output buffering for the page cache.
  172. // In case stupid admin has left magic_quotes enabled in php.ini:
  173. if (get_magic_quotes_gpc())
  174. {
  175. function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
  176. $_POST = array_map('stripslashes_deep', $_POST);
  177. $_GET = array_map('stripslashes_deep', $_GET);
  178. $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
  179. }
  180. // Prevent caching on client side or proxy: (yes, it's ugly)
  181. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  182. header("Cache-Control: no-store, no-cache, must-revalidate");
  183. header("Cache-Control: post-check=0, pre-check=0", false);
  184. header("Pragma: no-cache");
  185. // Handling of old config file which do not have the new parameters.
  186. if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.escape(index_url($_SERVER));
  187. if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
  188. if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
  189. if (empty($GLOBALS['disablesessionprotection'])) $GLOBALS['disablesessionprotection']=false;
  190. if (empty($GLOBALS['privateLinkByDefault'])) $GLOBALS['privateLinkByDefault']=false;
  191. if (empty($GLOBALS['titleLink'])) $GLOBALS['titleLink']='?';
  192. // I really need to rewrite Shaarli with a proper configuation manager.
  193. if (! is_file($GLOBALS['config']['CONFIG_FILE'])) {
  194. // Ensure Shaarli has proper access to its resources
  195. $errors = ApplicationUtils::checkResourcePermissions($GLOBALS['config']);
  196. if ($errors != array()) {
  197. $message = '<p>Insufficient permissions:</p><ul>';
  198. foreach ($errors as $error) {
  199. $message .= '<li>'.$error.'</li>';
  200. }
  201. $message .= '</ul>';
  202. header('Content-Type: text/html; charset=utf-8');
  203. echo $message;
  204. exit;
  205. }
  206. // Display the installation form if no existing config is found
  207. install();
  208. }
  209. $GLOBALS['title'] = !empty($GLOBALS['title']) ? escape($GLOBALS['title']) : '';
  210. $GLOBALS['titleLink'] = !empty($GLOBALS['titleLink']) ? escape($GLOBALS['titleLink']) : '';
  211. $GLOBALS['redirector'] = !empty($GLOBALS['redirector']) ? escape($GLOBALS['redirector']) : '';
  212. // a token depending of deployment salt, user password, and the current ip
  213. define('STAY_SIGNED_IN_TOKEN', sha1($GLOBALS['hash'].$_SERVER["REMOTE_ADDR"].$GLOBALS['salt']));
  214. autoLocale(); // Sniff browser language and set date format accordingly.
  215. header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
  216. //==================================================================================================
  217. // Checking session state (i.e. is the user still logged in)
  218. //==================================================================================================
  219. function setup_login_state() {
  220. if ($GLOBALS['config']['OPEN_SHAARLI']) {
  221. return true;
  222. }
  223. $userIsLoggedIn = false; // By default, we do not consider the user as logged in;
  224. $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
  225. if (!isset($GLOBALS['login'])) {
  226. $userIsLoggedIn = false; // Shaarli is not configured yet.
  227. $loginFailure = true;
  228. }
  229. if (isset($_COOKIE['shaarli_staySignedIn']) &&
  230. $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN &&
  231. !$loginFailure)
  232. {
  233. fillSessionInfo();
  234. $userIsLoggedIn = true;
  235. }
  236. // If session does not exist on server side, or IP address has changed, or session has expired, logout.
  237. if (empty($_SESSION['uid']) ||
  238. ($GLOBALS['disablesessionprotection']==false && $_SESSION['ip']!=allIPs()) ||
  239. time() >= $_SESSION['expires_on'])
  240. {
  241. logout();
  242. $userIsLoggedIn = false;
  243. $loginFailure = true;
  244. }
  245. if (!empty($_SESSION['longlastingsession'])) {
  246. $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
  247. }
  248. else {
  249. $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
  250. }
  251. if (!$loginFailure) {
  252. $userIsLoggedIn = true;
  253. }
  254. return $userIsLoggedIn;
  255. }
  256. $userIsLoggedIn = setup_login_state();
  257. // -----------------------------------------------------------------------------------------------
  258. // Log to text file
  259. function logm($message)
  260. {
  261. $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
  262. file_put_contents($GLOBALS['config']['LOG_FILE'], $t, FILE_APPEND);
  263. }
  264. // ------------------------------------------------------------------------------------------
  265. // Sniff browser language to display dates in the right format automatically.
  266. // (Note that is may not work on your server if the corresponding local is not installed.)
  267. function autoLocale()
  268. {
  269. $attempts = array('en_US'); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
  270. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
  271. { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
  272. if (preg_match('/([a-z]{2})-?([a-z]{2})?/i',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches)) {
  273. $loc = $matches[1] . (!empty($matches[2]) ? '_' . strtoupper($matches[2]) : '');
  274. $attempts = array($loc.'.UTF-8', $loc, str_replace('_', '-', $loc).'.UTF-8', str_replace('_', '-', $loc),
  275. $loc . '_' . strtoupper($loc).'.UTF-8', $loc . '_' . strtoupper($loc),
  276. $loc . '_' . $loc.'.UTF-8', $loc . '_' . $loc, $loc . '-' . strtoupper($loc).'.UTF-8',
  277. $loc . '-' . strtoupper($loc), $loc . '-' . $loc.'.UTF-8', $loc . '-' . $loc);
  278. }
  279. }
  280. setlocale(LC_TIME, $attempts); // LC_TIME = Set local for date/time format only.
  281. }
  282. // ------------------------------------------------------------------------------------------
  283. // PubSubHubbub protocol support (if enabled) [UNTESTED]
  284. // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
  285. if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) include './publisher.php';
  286. function pubsubhub()
  287. {
  288. if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
  289. {
  290. $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
  291. $topic_url = array (
  292. index_url($_SERVER).'?do=atom',
  293. index_url($_SERVER).'?do=rss'
  294. );
  295. $p->publish_update($topic_url);
  296. }
  297. }
  298. // ------------------------------------------------------------------------------------------
  299. // Session management
  300. // Returns the IP address of the client (Used to prevent session cookie hijacking.)
  301. function allIPs()
  302. {
  303. $ip = $_SERVER["REMOTE_ADDR"];
  304. // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
  305. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
  306. if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
  307. return $ip;
  308. }
  309. function fillSessionInfo() {
  310. $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
  311. $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
  312. $_SESSION['username']=$GLOBALS['login'];
  313. $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
  314. }
  315. // Check that user/password is correct.
  316. function check_auth($login,$password)
  317. {
  318. $hash = sha1($password.$login.$GLOBALS['salt']);
  319. if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash'])
  320. { // Login/password is correct.
  321. fillSessionInfo();
  322. logm('Login successful');
  323. return True;
  324. }
  325. logm('Login failed for user '.$login);
  326. return False;
  327. }
  328. // Returns true if the user is logged in.
  329. function isLoggedIn()
  330. {
  331. global $userIsLoggedIn;
  332. return $userIsLoggedIn;
  333. }
  334. // Force logout.
  335. function logout() {
  336. if (isset($_SESSION)) {
  337. unset($_SESSION['uid']);
  338. unset($_SESSION['ip']);
  339. unset($_SESSION['username']);
  340. unset($_SESSION['privateonly']);
  341. }
  342. setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH);
  343. }
  344. // ------------------------------------------------------------------------------------------
  345. // Brute force protection system
  346. // Several consecutive failed logins will ban the IP address for 30 minutes.
  347. if (!is_file($GLOBALS['config']['IPBANS_FILENAME'])) file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>");
  348. include $GLOBALS['config']['IPBANS_FILENAME'];
  349. // Signal a failed login. Will ban the IP if too many failures:
  350. function ban_loginFailed()
  351. {
  352. $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
  353. if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
  354. $gb['FAILURES'][$ip]++;
  355. if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1))
  356. {
  357. $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION'];
  358. logm('IP address banned from login');
  359. }
  360. $GLOBALS['IPBANS'] = $gb;
  361. file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
  362. }
  363. // Signals a successful login. Resets failed login counter.
  364. function ban_loginOk()
  365. {
  366. $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
  367. unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
  368. $GLOBALS['IPBANS'] = $gb;
  369. file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
  370. }
  371. // Checks if the user CAN login. If 'true', the user can try to login.
  372. function ban_canLogin()
  373. {
  374. $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
  375. if (isset($gb['BANS'][$ip]))
  376. {
  377. // User is banned. Check if the ban has expired:
  378. if ($gb['BANS'][$ip]<=time())
  379. { // Ban expired, user can try to login again.
  380. logm('Ban lifted.');
  381. unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
  382. file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
  383. return true; // Ban has expired, user can login.
  384. }
  385. return false; // User is banned.
  386. }
  387. return true; // User is not banned.
  388. }
  389. // ------------------------------------------------------------------------------------------
  390. // Process login form: Check if login/password is correct.
  391. if (isset($_POST['login']))
  392. {
  393. if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
  394. if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
  395. { // Login/password is OK.
  396. ban_loginOk();
  397. // If user wants to keep the session cookie even after the browser closes:
  398. if (!empty($_POST['longlastingsession']))
  399. {
  400. setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN, time()+31536000, WEB_PATH);
  401. $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year)
  402. $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side.
  403. $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
  404. session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
  405. // Note: Never forget the trailing slash on the cookie path!
  406. session_regenerate_id(true); // Send cookie with new expiration date to browser.
  407. }
  408. else // Standard session expiration (=when browser closes)
  409. {
  410. $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
  411. session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
  412. session_regenerate_id(true);
  413. }
  414. // Optional redirect after login:
  415. if (isset($_GET['post'])) {
  416. $uri = '?post='. urlencode($_GET['post']);
  417. foreach (array('description', 'source', 'title') as $param) {
  418. if (!empty($_GET[$param])) {
  419. $uri .= '&'.$param.'='.urlencode($_GET[$param]);
  420. }
  421. }
  422. header('Location: '. $uri);
  423. exit;
  424. }
  425. if (isset($_GET['edit_link'])) {
  426. header('Location: ?edit_link='. escape($_GET['edit_link']));
  427. exit;
  428. }
  429. if (isset($_POST['returnurl'])) {
  430. // Prevent loops over login screen.
  431. if (strpos($_POST['returnurl'], 'do=login') === false) {
  432. header('Location: '. escape($_POST['returnurl']));
  433. exit;
  434. }
  435. }
  436. header('Location: ?'); exit;
  437. }
  438. else
  439. {
  440. ban_loginFailed();
  441. $redir = '';
  442. if (isset($_GET['post'])) {
  443. $redir = '?post=' . urlencode($_GET['post']);
  444. foreach (array('description', 'source', 'title') as $param) {
  445. if (!empty($_GET[$param])) {
  446. $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
  447. }
  448. }
  449. }
  450. echo '<script>alert("Wrong login/password.");document.location=\'?do=login'.$redir.'\';</script>'; // Redirect to login screen.
  451. exit;
  452. }
  453. }
  454. // ------------------------------------------------------------------------------------------
  455. // Misc utility functions:
  456. // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
  457. function return_bytes($val)
  458. {
  459. $val = trim($val); $last=strtolower($val[strlen($val)-1]);
  460. switch($last)
  461. {
  462. case 'g': $val *= 1024;
  463. case 'm': $val *= 1024;
  464. case 'k': $val *= 1024;
  465. }
  466. return $val;
  467. }
  468. // Try to determine max file size for uploads (POST).
  469. // Returns an integer (in bytes)
  470. function getMaxFileSize()
  471. {
  472. $size1 = return_bytes(ini_get('post_max_size'));
  473. $size2 = return_bytes(ini_get('upload_max_filesize'));
  474. // Return the smaller of two:
  475. $maxsize = min($size1,$size2);
  476. // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
  477. return $maxsize;
  478. }
  479. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
  480. (used to build the ADD_DATE attribute in Netscape-bookmarks file)
  481. PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
  482. function linkdate2timestamp($linkdate)
  483. {
  484. if(strcmp($linkdate, '_000000') !== 0 || !$linkdate){
  485. $Y=$M=$D=$h=$m=$s=0;
  486. $r = sscanf($linkdate,'%4d%2d%2d_%2d%2d%2d',$Y,$M,$D,$h,$m,$s);
  487. return mktime($h,$m,$s,$M,$D,$Y);
  488. }
  489. return time();
  490. }
  491. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
  492. (used to build the pubDate attribute in RSS feed.) */
  493. function linkdate2rfc822($linkdate)
  494. {
  495. return date('r',linkdate2timestamp($linkdate)); // 'r' is for RFC822 date format.
  496. }
  497. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
  498. (used to build the updated tags in ATOM feed.) */
  499. function linkdate2iso8601($linkdate)
  500. {
  501. return date('c',linkdate2timestamp($linkdate)); // 'c' is for ISO 8601 date format.
  502. }
  503. // Extract title from an HTML document.
  504. // (Returns an empty string if not found.)
  505. function html_extract_title($html)
  506. {
  507. return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ;
  508. }
  509. // ------------------------------------------------------------------------------------------
  510. // Token management for XSRF protection
  511. // Token should be used in any form which acts on data (create,update,delete,import...).
  512. if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
  513. // Returns a token.
  514. function getToken()
  515. {
  516. $rnd = sha1(uniqid('',true).'_'.mt_rand().$GLOBALS['salt']); // We generate a random string.
  517. $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
  518. return $rnd;
  519. }
  520. // Tells if a token is OK. Using this function will destroy the token.
  521. // true=token is OK.
  522. function tokenOk($token)
  523. {
  524. if (isset($_SESSION['tokens'][$token]))
  525. {
  526. unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
  527. return true; // Token is OK.
  528. }
  529. return false; // Wrong token, or already used.
  530. }
  531. // ------------------------------------------------------------------------------------------
  532. /* This class is in charge of building the final page.
  533. (This is basically a wrapper around RainTPL which pre-fills some fields.)
  534. p = new pageBuilder;
  535. p.assign('myfield','myvalue');
  536. p.renderPage('mytemplate');
  537. */
  538. class pageBuilder
  539. {
  540. private $tpl; // RainTPL template
  541. function __construct()
  542. {
  543. $this->tpl = false;
  544. }
  545. /**
  546. * Initialize all default tpl tags.
  547. */
  548. private function initialize()
  549. {
  550. $this->tpl = new RainTPL;
  551. try {
  552. $version = ApplicationUtils::checkUpdate(
  553. shaarli_version,
  554. $GLOBALS['config']['UPDATECHECK_FILENAME'],
  555. $GLOBALS['config']['UPDATECHECK_INTERVAL'],
  556. $GLOBALS['config']['ENABLE_UPDATECHECK'],
  557. isLoggedIn(),
  558. $GLOBALS['config']['UPDATECHECK_BRANCH']
  559. );
  560. $this->tpl->assign('newVersion', escape($version));
  561. $this->tpl->assign('versionError', '');
  562. } catch (Exception $exc) {
  563. logm($exc->getMessage());
  564. $this->tpl->assign('newVersion', '');
  565. $this->tpl->assign('versionError', escape($exc->getMessage()));
  566. }
  567. $this->tpl->assign('feedurl', escape(index_url($_SERVER)));
  568. $searchcrits = ''; // Search criteria
  569. if (!empty($_GET['searchtags'])) {
  570. $searchcrits .= '&searchtags=' . urlencode($_GET['searchtags']);
  571. }
  572. elseif (!empty($_GET['searchterm'])) {
  573. $searchcrits .= '&searchterm=' . urlencode($_GET['searchterm']);
  574. }
  575. $this->tpl->assign('searchcrits', $searchcrits);
  576. $this->tpl->assign('source', index_url($_SERVER));
  577. $this->tpl->assign('version', shaarli_version);
  578. $this->tpl->assign('scripturl', index_url($_SERVER));
  579. $this->tpl->assign('pagetitle', 'Shaarli');
  580. $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links?
  581. if (!empty($GLOBALS['title'])) {
  582. $this->tpl->assign('pagetitle', $GLOBALS['title']);
  583. }
  584. if (!empty($GLOBALS['titleLink'])) {
  585. $this->tpl->assign('titleLink', $GLOBALS['titleLink']);
  586. }
  587. if (!empty($GLOBALS['pagetitle'])) {
  588. $this->tpl->assign('pagetitle', $GLOBALS['pagetitle']);
  589. }
  590. $this->tpl->assign('shaarlititle', empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title']);
  591. if (!empty($GLOBALS['plugin_errors'])) {
  592. $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']);
  593. }
  594. }
  595. // The following assign() method is basically the same as RainTPL (except that it's lazy)
  596. public function assign($what,$where)
  597. {
  598. if ($this->tpl===false) $this->initialize(); // Lazy initialization
  599. $this->tpl->assign($what,$where);
  600. }
  601. // Render a specific page (using a template).
  602. // e.g. pb.renderPage('picwall')
  603. public function renderPage($page)
  604. {
  605. if ($this->tpl===false) $this->initialize(); // Lazy initialization
  606. $this->tpl->draw($page);
  607. }
  608. }
  609. // ------------------------------------------------------------------------------------------
  610. // Output the last N links in RSS 2.0 format.
  611. function showRSS()
  612. {
  613. header('Content-Type: application/rss+xml; charset=utf-8');
  614. // $usepermalink : If true, use permalink instead of final link.
  615. // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
  616. // Also enabled through a config option
  617. $usepermalinks = isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS'];
  618. // Cache system
  619. $query = $_SERVER["QUERY_STRING"];
  620. $cache = new CachedPage(
  621. $GLOBALS['config']['PAGECACHE'],
  622. page_url($_SERVER),
  623. startsWith($query,'do=rss') && !isLoggedIn()
  624. );
  625. $cached = $cache->cachedVersion();
  626. if (! empty($cached)) {
  627. echo $cached;
  628. exit;
  629. }
  630. // If cached was not found (or not usable), then read the database and build the response:
  631. $LINKSDB = new LinkDB(
  632. $GLOBALS['config']['DATASTORE'],
  633. isLoggedIn(),
  634. $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
  635. $GLOBALS['redirector']
  636. );
  637. // Read links from database (and filter private links if user it not logged in).
  638. // Optionally filter the results:
  639. $linksToDisplay=array();
  640. if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
  641. else if (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
  642. else $linksToDisplay = $LINKSDB;
  643. $nblinksToDisplay = 50; // Number of links to display.
  644. if (!empty($_GET['nb'])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
  645. {
  646. $nblinksToDisplay = $_GET['nb']=='all' ? count($linksToDisplay) : max($_GET['nb']+0,1) ;
  647. }
  648. $pageaddr=escape(index_url($_SERVER));
  649. echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
  650. echo '<channel><title>'.$GLOBALS['title'].'</title><link>'.$pageaddr.'</link>';
  651. echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
  652. if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
  653. {
  654. echo '<!-- PubSubHubbub Discovery -->';
  655. echo '<link rel="hub" href="'.escape($GLOBALS['config']['PUBSUBHUB_URL']).'" xmlns="http://www.w3.org/2005/Atom" />';
  656. echo '<link rel="self" href="'.$pageaddr.'?do=rss" xmlns="http://www.w3.org/2005/Atom" />';
  657. echo '<!-- End Of PubSubHubbub Discovery -->';
  658. }
  659. $i=0;
  660. $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
  661. while ($i<$nblinksToDisplay && $i<count($keys))
  662. {
  663. $link = $linksToDisplay[$keys[$i]];
  664. $guid = $pageaddr.'?'.smallHash($link['linkdate']);
  665. $rfc822date = linkdate2rfc822($link['linkdate']);
  666. $absurl = $link['url'];
  667. if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
  668. if ($usepermalinks===true)
  669. echo '<item><title>'.$link['title'].'</title><guid isPermaLink="true">'.$guid.'</guid><link>'.$guid.'</link>';
  670. else
  671. echo '<item><title>'.$link['title'].'</title><guid isPermaLink="false">'.$guid.'</guid><link>'.$absurl.'</link>';
  672. if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.escape($rfc822date)."</pubDate>\n";
  673. if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
  674. {
  675. foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.$pageaddr.'">'.$tag.'</category>'."\n"; }
  676. }
  677. // Add permalink in description
  678. $descriptionlink = '(<a href="'.$guid.'">Permalink</a>)';
  679. // If user wants permalinks first, put the final link in description
  680. if ($usepermalinks===true) $descriptionlink = '(<a href="'.$absurl.'">Link</a>)';
  681. if (strlen($link['description'])>0) $descriptionlink = '<br>'.$descriptionlink;
  682. echo '<description><![CDATA['.
  683. format_description($link['description'], $GLOBALS['redirector']) .
  684. $descriptionlink . ']]></description>' . "\n</item>\n";
  685. $i++;
  686. }
  687. echo '</channel></rss><!-- Cached version of '.escape(page_url($_SERVER)).' -->';
  688. $cache->cache(ob_get_contents());
  689. ob_end_flush();
  690. exit;
  691. }
  692. // ------------------------------------------------------------------------------------------
  693. // Output the last N links in ATOM format.
  694. function showATOM()
  695. {
  696. header('Content-Type: application/atom+xml; charset=utf-8');
  697. // $usepermalink : If true, use permalink instead of final link.
  698. // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
  699. $usepermalinks = isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS'];
  700. // Cache system
  701. $query = $_SERVER["QUERY_STRING"];
  702. $cache = new CachedPage(
  703. $GLOBALS['config']['PAGECACHE'],
  704. page_url($_SERVER),
  705. startsWith($query,'do=atom') && !isLoggedIn()
  706. );
  707. $cached = $cache->cachedVersion();
  708. if (!empty($cached)) {
  709. echo $cached;
  710. exit;
  711. }
  712. // If cached was not found (or not usable), then read the database and build the response:
  713. // Read links from database (and filter private links if used it not logged in).
  714. $LINKSDB = new LinkDB(
  715. $GLOBALS['config']['DATASTORE'],
  716. isLoggedIn(),
  717. $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
  718. $GLOBALS['redirector']
  719. );
  720. // Optionally filter the results:
  721. $linksToDisplay=array();
  722. if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
  723. else if (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
  724. else $linksToDisplay = $LINKSDB;
  725. $nblinksToDisplay = 50; // Number of links to display.
  726. if (!empty($_GET['nb'])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
  727. {
  728. $nblinksToDisplay = $_GET['nb']=='all' ? count($linksToDisplay) : max($_GET['nb']+0,1) ;
  729. }
  730. $pageaddr=escape(index_url($_SERVER));
  731. $latestDate = '';
  732. $entries='';
  733. $i=0;
  734. $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
  735. while ($i<$nblinksToDisplay && $i<count($keys))
  736. {
  737. $link = $linksToDisplay[$keys[$i]];
  738. $guid = $pageaddr.'?'.smallHash($link['linkdate']);
  739. $iso8601date = linkdate2iso8601($link['linkdate']);
  740. $latestDate = max($latestDate,$iso8601date);
  741. $absurl = $link['url'];
  742. if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
  743. $entries.='<entry><title>'.$link['title'].'</title>';
  744. if ($usepermalinks===true)
  745. $entries.='<link href="'.$guid.'" /><id>'.$guid.'</id>';
  746. else
  747. $entries.='<link href="'.$absurl.'" /><id>'.$guid.'</id>';
  748. if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.escape($iso8601date).'</updated>';
  749. // Add permalink in description
  750. $descriptionlink = '(<a href="'.$guid.'">Permalink</a>)';
  751. // If user wants permalinks first, put the final link in description
  752. if ($usepermalinks===true) $descriptionlink = '(<a href="'.$absurl.'">Link</a>)';
  753. if (strlen($link['description'])>0) $descriptionlink = '<br>'.$descriptionlink;
  754. $entries .= '<content type="html"><![CDATA['.
  755. format_description($link['description'], $GLOBALS['redirector']) .
  756. $descriptionlink . "]]></content>\n";
  757. if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification)
  758. {
  759. foreach(explode(' ',$link['tags']) as $tag)
  760. { $entries.='<category scheme="'.$pageaddr.'" term="'.$tag.'" />'."\n"; }
  761. }
  762. $entries.="</entry>\n";
  763. $i++;
  764. }
  765. $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
  766. $feed.='<title>'.$GLOBALS['title'].'</title>';
  767. if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.escape($latestDate).'</updated>';
  768. $feed.='<link rel="self" href="'.escape(server_url($_SERVER).$_SERVER["REQUEST_URI"]).'" />';
  769. if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
  770. {
  771. $feed.='<!-- PubSubHubbub Discovery -->';
  772. $feed.='<link rel="hub" href="'.escape($GLOBALS['config']['PUBSUBHUB_URL']).'" />';
  773. $feed.='<!-- End Of PubSubHubbub Discovery -->';
  774. }
  775. $feed.='<author><name>'.$pageaddr.'</name><uri>'.$pageaddr.'</uri></author>';
  776. $feed.='<id>'.$pageaddr.'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
  777. $feed.=$entries;
  778. $feed.='</feed><!-- Cached version of '.escape(page_url($_SERVER)).' -->';
  779. echo $feed;
  780. $cache->cache(ob_get_contents());
  781. ob_end_flush();
  782. exit;
  783. }
  784. // ------------------------------------------------------------------------------------------
  785. // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
  786. // Gives the last 7 days (which have links).
  787. // This RSS feed cannot be filtered.
  788. function showDailyRSS() {
  789. // Cache system
  790. $query = $_SERVER["QUERY_STRING"];
  791. $cache = new CachedPage(
  792. $GLOBALS['config']['PAGECACHE'],
  793. page_url($_SERVER),
  794. startsWith($query,'do=dailyrss') && !isLoggedIn()
  795. );
  796. $cached = $cache->cachedVersion();
  797. if (!empty($cached)) {
  798. echo $cached;
  799. exit;
  800. }
  801. // If cached was not found (or not usable), then read the database and build the response:
  802. // Read links from database (and filter private links if used it not logged in).
  803. $LINKSDB = new LinkDB(
  804. $GLOBALS['config']['DATASTORE'],
  805. isLoggedIn(),
  806. $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
  807. $GLOBALS['redirector']
  808. );
  809. /* Some Shaarlies may have very few links, so we need to look
  810. back in time (rsort()) until we have enough days ($nb_of_days).
  811. */
  812. $linkdates = array();
  813. foreach ($LINKSDB as $linkdate => $value) {
  814. $linkdates[] = $linkdate;
  815. }
  816. rsort($linkdates);
  817. $nb_of_days = 7; // We take 7 days.
  818. $today = Date('Ymd');
  819. $days = array();
  820. foreach ($linkdates as $linkdate) {
  821. $day = substr($linkdate, 0, 8); // Extract day (without time)
  822. if (strcmp($day,$today) < 0) {
  823. if (empty($days[$day])) {
  824. $days[$day] = array();
  825. }
  826. $days[$day][] = $linkdate;
  827. }
  828. if (count($days) > $nb_of_days) {
  829. break; // Have we collected enough days?
  830. }
  831. }
  832. // Build the RSS feed.
  833. header('Content-Type: application/rss+xml; charset=utf-8');
  834. $pageaddr = escape(index_url($_SERVER));
  835. echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
  836. echo '<channel>';
  837. echo '<title>Daily - '. $GLOBALS['title'] . '</title>';
  838. echo '<link>'. $pageaddr .'</link>';
  839. echo '<description>Daily shared links</description>';
  840. echo '<language>en-en</language>';
  841. echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
  842. // For each day.
  843. foreach ($days as $day => $linkdates) {
  844. $daydate = linkdate2timestamp($day.'_000000'); // Full text date
  845. $rfc822date = linkdate2rfc822($day.'_000000');
  846. $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
  847. // Build the HTML body of this RSS entry.
  848. $html = '';
  849. $href = '';
  850. $links = array();
  851. // We pre-format some fields for proper output.
  852. foreach ($linkdates as $linkdate) {
  853. $l = $LINKSDB[$linkdate];
  854. $l['formatedDescription'] = format_description($l['description'], $GLOBALS['redirector']);
  855. $l['thumbnail'] = thumbnail($l['url']);
  856. $l['timestamp'] = linkdate2timestamp($l['linkdate']);
  857. if (startsWith($l['url'], '?')) {
  858. $l['url'] = index_url($_SERVER) . $l['url']; // make permalink URL absolute
  859. }
  860. $links[$linkdate] = $l;
  861. }
  862. // Then build the HTML for this day:
  863. $tpl = new RainTPL;
  864. $tpl->assign('title', $GLOBALS['title']);
  865. $tpl->assign('daydate', $daydate);
  866. $tpl->assign('absurl', $absurl);
  867. $tpl->assign('links', $links);
  868. $tpl->assign('rfc822date', escape($rfc822date));
  869. $html = $tpl->draw('dailyrss', $return_string=true);
  870. echo $html . PHP_EOL;
  871. }
  872. echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
  873. $cache->cache(ob_get_contents());
  874. ob_end_flush();
  875. exit;
  876. }
  877. // "Daily" page.
  878. function showDaily()
  879. {
  880. $LINKSDB = new LinkDB(
  881. $GLOBALS['config']['DATASTORE'],
  882. isLoggedIn(),
  883. $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
  884. $GLOBALS['redirector']
  885. );
  886. $day=Date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
  887. if (isset($_GET['day'])) $day=$_GET['day'];
  888. $days = $LINKSDB->days();
  889. $i = array_search($day,$days);
  890. if ($i===false) { $i=count($days)-1; $day=$days[$i]; }
  891. $previousday='';
  892. $nextday='';
  893. if ($i!==false)
  894. {
  895. if ($i>=1) $previousday=$days[$i-1];
  896. if ($i<count($days)-1) $nextday=$days[$i+1];
  897. }
  898. try {
  899. $linksToDisplay = $LINKSDB->filterDay($day);
  900. } catch (Exception $exc) {
  901. error_log($exc);
  902. $linksToDisplay = array();
  903. }
  904. // We pre-format some fields for proper output.
  905. foreach($linksToDisplay as $key=>$link)
  906. {
  907. $taglist = explode(' ',$link['tags']);
  908. uasort($taglist, 'strcasecmp');
  909. $linksToDisplay[$key]['taglist']=$taglist;
  910. $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $GLOBALS['redirector']);
  911. $linksToDisplay[$key]['thumbnail'] = thumbnail($link['url']);
  912. $linksToDisplay[$key]['timestamp'] = linkdate2timestamp($link['linkdate']);
  913. }
  914. /* We need to spread the articles on 3 columns.
  915. I did not want to use a JavaScript lib like http://masonry.desandro.com/
  916. so I manually spread entries with a simple method: I roughly evaluate the
  917. height of a div according to title and description length.
  918. */
  919. $columns=array(array(),array(),array()); // Entries to display, for each column.
  920. $fill=array(0,0,0); // Rough estimate of columns fill.
  921. foreach($linksToDisplay as $key=>$link)
  922. {
  923. // Roughly estimate length of entry (by counting characters)
  924. // Title: 30 chars = 1 line. 1 line is 30 pixels height.
  925. // Description: 836 characters gives roughly 342 pixel height.
  926. // This is not perfect, but it's usually OK.
  927. $length=strlen($link['title'])+(342*strlen($link['description']))/836;
  928. if ($link['thumbnail']) $length +=100; // 1 thumbnails roughly takes 100 pixels height.
  929. // Then put in column which is the less filled:
  930. $smallest=min($fill); // find smallest value in array.
  931. $index=array_search($smallest,$fill); // find index of this smallest value.
  932. array_push($columns[$index],$link); // Put entry in this column.
  933. $fill[$index]+=$length;
  934. }
  935. $PAGE = new pageBuilder;
  936. $data = array(
  937. 'linksToDisplay' => $linksToDisplay,
  938. 'linkcount' => count($LINKSDB),
  939. 'cols' => $columns,
  940. 'day' => linkdate2timestamp($day.'_000000'),
  941. 'previousday' => $previousday,
  942. 'nextday' => $nextday,
  943. );
  944. $pluginManager = PluginManager::getInstance();
  945. $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn()));
  946. foreach ($data as $key => $value) {
  947. $PAGE->assign($key, $value);
  948. }
  949. $PAGE->renderPage('daily');
  950. exit;
  951. }
  952. // Renders the linklist
  953. function showLinkList($PAGE, $LINKSDB) {
  954. buildLinkList($PAGE,$LINKSDB); // Compute list of links to display
  955. $PAGE->renderPage('linklist');
  956. }
  957. // ------------------------------------------------------------------------------------------
  958. // Render HTML page (according to URL parameters and user rights)
  959. function renderPage()
  960. {
  961. $LINKSDB = new LinkDB(
  962. $GLOBALS['config']['DATASTORE'],
  963. isLoggedIn(),
  964. $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
  965. $GLOBALS['redirector']
  966. );
  967. $PAGE = new pageBuilder;
  968. // Determine which page will be rendered.
  969. $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
  970. $targetPage = Router::findPage($query, $_GET, isLoggedIn());
  971. // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
  972. // Then assign generated data to RainTPL.
  973. $common_hooks = array(
  974. 'header',
  975. 'footer',
  976. 'includes',
  977. );
  978. $pluginManager = PluginManager::getInstance();
  979. foreach($common_hooks as $name) {
  980. $plugin_data = array();
  981. $pluginManager->executeHooks('render_' . $name, $plugin_data,
  982. array(
  983. 'target' => $targetPage,
  984. 'loggedin' => isLoggedIn()
  985. )
  986. );
  987. $PAGE->assign('plugins_' . $name, $plugin_data);
  988. }
  989. // -------- Display login form.
  990. if ($targetPage == Router::$PAGE_LOGIN)
  991. {
  992. if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; } // No need to login for open Shaarli
  993. $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful.
  994. $PAGE->assign('token',$token);
  995. $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
  996. $PAGE->renderPage('loginform');
  997. exit;
  998. }
  999. // -------- User wants to logout.
  1000. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=logout'))
  1001. {
  1002. invalidateCaches($GLOBALS['config']['PAGECACHE']);
  1003. logout();
  1004. header('Location: ?');
  1005. exit;
  1006. }
  1007. // -------- Picture wall
  1008. if ($targetPage == Router::$PAGE_PICWALL)
  1009. {
  1010. // Optionally filter the results:
  1011. $links=array();
  1012. if (!empty($_GET['searchterm'])) $links = $LINKSDB->filterFulltext($_GET['searchterm']);
  1013. elseif (!empty($_GET['searchtags'])) $links = $LINKSDB->filterTags(trim($_GET['searchtags']));
  1014. else $links = $LINKSDB;
  1015. $body='';
  1016. $linksToDisplay=array();
  1017. // Get only links which have a thumbnail.
  1018. foreach($links as $link)
  1019. {
  1020. $permalink='?'.escape(smallhash($link['linkdate']));
  1021. $thumb=lazyThumbnail($link['url'],$permalink);
  1022. if ($thumb!='') // Only output links which have a thumbnail.
  1023. {
  1024. $link['thumbnail']=$thumb; // Thumbnail HTML code.
  1025. $linksToDisplay[]=$link; // Add to array.
  1026. }
  1027. }
  1028. $data = array(
  1029. 'linkcount' => count($LINKSDB),
  1030. 'linksToDisplay' => $linksToDisplay,
  1031. );
  1032. $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
  1033. foreach ($data as $key => $value) {
  1034. $PAGE->assign($key, $value);
  1035. }
  1036. $PAGE->renderPage('picwall');
  1037. exit;
  1038. }
  1039. // -------- Tag cloud
  1040. if ($targetPage == Router::$PAGE_TAGCLOUD)
  1041. {
  1042. $tags= $LINKSDB->allTags();
  1043. // We sort tags alphabetically, then choose a font size according to count.
  1044. // First, find max value.
  1045. $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
  1046. ksort($tags);
  1047. $tagList=array();
  1048. foreach($tags as $key=>$value)
  1049. // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
  1050. {
  1051. $tagList[$key] = array('count'=>$value,'size'=>log($value, 15) / log($maxcount, 30) * (22-6) + 6);
  1052. }
  1053. $data = array(
  1054. 'linkcount' => count($LINKSDB),
  1055. 'tags' => $tagList,
  1056. );
  1057. $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
  1058. foreach ($data as $key => $value) {
  1059. $PAGE->assign($key, $value);
  1060. }
  1061. $PAGE->renderPage('tagcloud');
  1062. exit;
  1063. }
  1064. // Display openseach plugin (XML)
  1065. if ($targetPage == Router::$PAGE_OPENSEARCH) {
  1066. header('Content-Type: application/xml; charset=utf-8');
  1067. $PAGE->assign('serverurl', index_url($_SERVER));
  1068. $PAGE->renderPage('opensearch');
  1069. exit;
  1070. }
  1071. // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
  1072. if (isset($_GET['addtag']))
  1073. {
  1074. // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
  1075. if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
  1076. parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
  1077. // Prevent redirection loop
  1078. if (isset($params['addtag'])) {
  1079. unset($params['addtag']);
  1080. }
  1081. // Check if this tag is already in the search query and ignore it if it is.
  1082. // Each tag is always separated by a space
  1083. if (isset($params['searchtags'])) {
  1084. $current_tags = explode(' ', $params['searchtags']);
  1085. } else {
  1086. $current_tags = array();
  1087. }
  1088. $addtag = true;
  1089. foreach ($current_tags as $value) {
  1090. if ($value === $_GET['addtag']) {
  1091. $addtag = false;
  1092. break;
  1093. }
  1094. }
  1095. // Append the tag if necessary
  1096. if (empty($params['searchtags'])) {
  1097. $params['searchtags'] = trim($_GET['addtag']);
  1098. }
  1099. else if ($addtag) {
  1100. $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
  1101. }
  1102. unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
  1103. header('Location: ?'.http_build_query($params));
  1104. exit;
  1105. }
  1106. // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
  1107. if (isset($_GET['removetag'])) {
  1108. // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
  1109. if (empty($_SERVER['HTTP_REFERER'])) {
  1110. header('Location: ?');
  1111. exit;
  1112. }
  1113. // In case browser does not send HTTP_REFERER
  1114. parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
  1115. // Prevent redirection loop
  1116. if (isset($params['removetag'])) {
  1117. unset($params['removetag']);
  1118. }
  1119. if (isset($params['searchtags'])) {
  1120. $tags = explode(' ',$params['searchtags']);
  1121. $tags=array_diff($tags, array($_GET['removetag'])); // Remove value from array $tags.
  1122. if (count($tags)==0) {
  1123. unset($params['searchtags']);
  1124. } else {
  1125. $params['searchtags'] = implode(' ',$tags);
  1126. }
  1127. unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
  1128. }
  1129. header('Location: ?'.http_build_query($params));
  1130. exit;
  1131. }
  1132. // -------- User wants to change the number of links per page (linksperpage=...)
  1133. if (isset($_GET['linksperpage'])) {
  1134. if (is_numeric($_GET['linksperpage'])) {
  1135. $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
  1136. }
  1137. header('Location: '. generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage')));
  1138. exit;
  1139. }
  1140. // -------- User wants to see only private links (toggle)
  1141. if (isset($_GET['privateonly'])) {
  1142. if (empty($_SESSION['privateonly'])) {
  1143. $_SESSION['privateonly'] = 1; // See only private links
  1144. } else {
  1145. unset($_SESSION['privateonly']); // See all links
  1146. }
  1147. header('Location: '. generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('privateonly')));
  1148. exit;
  1149. }
  1150. // -------- Handle other actions allowed for non-logged in users:
  1151. if (!isLoggedIn())
  1152. {
  1153. // User tries to post new link but is not logged in:
  1154. // Show login screen, then redirect to ?post=...
  1155. if (isset($_GET['post']))
  1156. {
  1157. header('Location: ?do=login&post='.urlencode($_GET['post']).(!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').(!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link.
  1158. exit;
  1159. }
  1160. // Same case as above except that user tried to access ?do=addlink without being logged in
  1161. // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
  1162. if (isset($_GET['do']) && $_GET['do'] === 'addlink') {
  1163. header('Location: ?do=login&post=');
  1164. exit;
  1165. }
  1166. showLinkList($PAGE, $LINKSDB);
  1167. if (isset($_GET['edit_link'])) {
  1168. header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
  1169. exit;
  1170. }
  1171. exit; // Never remove this one! All operations below are reserved for logged in user.
  1172. }
  1173. // -------- All other functions are reserved for the registered user:
  1174. // -------- Display the Tools menu if requested (import/export/bookmarklet...)
  1175. if ($targetPage == Router::$PAGE_TOOLS)
  1176. {
  1177. $data = array(
  1178. 'linkcount' => count($LINKSDB),
  1179. 'pageabsaddr' => index_url($_SERVER),
  1180. );
  1181. $pluginManager->executeHooks('render_tools', $data);
  1182. foreach ($data as $key => $value) {
  1183. $PAGE->assign($key, $value);
  1184. }
  1185. $PAGE->renderPage('tools');
  1186. exit;
  1187. }
  1188. // -------- User wants to change his/her password.
  1189. if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
  1190. {
  1191. if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.');
  1192. if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
  1193. {
  1194. if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away!
  1195. // Make sure old password is correct.
  1196. $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']);
  1197. if ($oldhash!=$GLOBALS['hash']) { echo '<script>alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
  1198. // Save new password
  1199. $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
  1200. $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
  1201. try {
  1202. writeConfig($GLOBALS, isLoggedIn());
  1203. }
  1204. catch(Exception $e) {
  1205. error_log(
  1206. 'ERROR while writing config file after changing password.' . PHP_EOL .
  1207. $e->getMessage()
  1208. );
  1209. // TODO: do not handle exceptions/errors in JS.
  1210. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
  1211. exit;
  1212. }
  1213. echo '<script>alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
  1214. exit;
  1215. }
  1216. else // show the change password form.
  1217. {
  1218. $PAGE->assign('linkcount',count($LINKSDB));
  1219. $PAGE->assign('token',getToken());
  1220. $PAGE->renderPage('changepassword');
  1221. exit;
  1222. }
  1223. }
  1224. // -------- User wants to change configuration
  1225. if ($targetPage == Router::$PAGE_CONFIGURE)
  1226. {
  1227. if (!empty($_POST['title']) )
  1228. {
  1229. if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away!
  1230. $tz = 'UTC';
  1231. if (!empty($_POST['continent']) && !empty($_POST['city']))
  1232. if (isTimeZoneValid($_POST['continent'],$_POST['city']))
  1233. $tz = $_POST['continent'].'/'.$_POST['city'];
  1234. $GLOBALS['timezone'] = $tz;
  1235. $GLOBALS['title']=$_POST['title'];
  1236. $GLOBALS['titleLink']=$_POST['titleLink'];
  1237. $GLOBALS['redirector']=$_POST['redirector'];
  1238. $GLOBALS['disablesessionprotection']=!empty($_POST['disablesessionprotection']);
  1239. $GLOBALS['privateLinkByDefault']=!empty($_POST['privateLinkByDefault']);
  1240. $GLOBALS['config']['ENABLE_RSS_PERMALINKS']= !empty($_POST['enableRssPermalinks']);
  1241. $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']);
  1242. $GLOBALS['config']['HIDE_PUBLIC_LINKS'] = !empty($_POST['hidePublicLinks']);
  1243. try {
  1244. writeConfig($GLOBALS, isLoggedIn());
  1245. }
  1246. catch(Exception $e) {
  1247. error_log(
  1248. 'ERROR while writing config file after configuration update.' . PHP_EOL .
  1249. $e->getMessage()
  1250. );
  1251. // TODO: do not handle exceptions/errors in JS.
  1252. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
  1253. exit;
  1254. }
  1255. echo '<script>alert("Configuration was saved.");document.location=\'?do=tools\';</script>';
  1256. exit;
  1257. }
  1258. else // Show the configuration form.
  1259. {
  1260. $PAGE->assign('linkcount',count($LINKSDB));
  1261. $PAGE->assign('token',getToken());
  1262. $PAGE->assign('title', empty($GLOBALS['title']) ? '' : $GLOBALS['title'] );
  1263. $PAGE->assign('redirector', empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] );
  1264. list($timezone_form, $timezone_js) = generateTimeZoneForm($GLOBALS['timezone']);
  1265. $PAGE->assign('timezone_form', $timezone_form);
  1266. $PAGE->assign('timezone_js',$timezone_js);
  1267. $PAGE->renderPage('configure');
  1268. exit;
  1269. }
  1270. }
  1271. // -------- User wants to rename a tag or delete it
  1272. if ($targetPage == Router::$PAGE_CHANGETAG)
  1273. {
  1274. if (empty($_POST['fromtag']))
  1275. {
  1276. $PAGE->assign('linkcount',count($LINKSDB));
  1277. $PAGE->assign('token',getToken());
  1278. $PAGE->assign('tags', $LINKSDB->allTags());
  1279. $PAGE->renderPage('changetag');
  1280. exit;
  1281. }
  1282. if (!tokenOk($_POST['token'])) die('Wrong token.');
  1283. // Delete a tag:
  1284. if (!empty($_POST['deletetag']) && !empty($_POST['fromtag']))
  1285. {
  1286. $needle=trim($_POST['fromtag']);
  1287. $linksToAlter = $LINKSDB->filterTags($needle,true); // True for case-sensitive tag search.
  1288. foreach($linksToAlter as $key=>$value)
  1289. {
  1290. $tags = explode(' ',trim($value['tags']));
  1291. unset($tags[array_search($needle,$tags)]); // Remove tag.
  1292. $value['tags']=trim(implode(' ',$tags));
  1293. $LINKSDB[$key]=$value;
  1294. }
  1295. $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']);
  1296. echo '<script>alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
  1297. exit;
  1298. }
  1299. // Rename a tag:
  1300. if (!empty($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag']))
  1301. {
  1302. $needle=trim($_POST['fromtag']);
  1303. $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
  1304. foreach($linksToAlter as $key=>$value)
  1305. {
  1306. $tags = explode(' ',trim($value['tags']));
  1307. $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Replace tags value.
  1308. $value['tags']=trim(implode(' ',$tags));
  1309. $LINKSDB[$key]=$value;
  1310. }
  1311. $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); // Save to disk.
  1312. echo '<script>alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
  1313. exit;
  1314. }
  1315. }
  1316. // -------- User wants to add a link without using the bookmarklet: Show form.
  1317. if ($targetPage == Router::$PAGE_ADDLINK)
  1318. {
  1319. $PAGE->assign('linkcount',count($LINKSDB));
  1320. $PAGE->renderPage('addlink');
  1321. exit;
  1322. }
  1323. // -------- User clicked the "Save" button when editing a link: Save link to database.
  1324. if (isset($_POST['save_edit']))
  1325. {
  1326. if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away!
  1327. $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces.
  1328. $tags = implode(' ', array_unique(explode(' ', $tags))); // Remove duplicates.
  1329. $linkdate=$_POST['lf_linkdate'];
  1330. $url = trim($_POST['lf_url']);
  1331. if (!startsWith($url,'http:') && !startsWith($url,'https:') && !startsWith($url,'ftp:') && !startsWith($url,'magnet:') && !startsWith($url,'?') && !startsWith($url,'javascript:'))
  1332. $url = 'http://'.$url;
  1333. $link = array('title'=>trim($_POST['lf_title']),'url'=>$url,'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
  1334. 'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags));
  1335. if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
  1336. $pluginManager->executeHooks('save_link', $link);
  1337. $LINKSDB[$linkdate] = $link;
  1338. $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); // Save to disk.
  1339. pubsubhub();
  1340. // If we are called from the bookmarklet, we must close the popup:
  1341. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
  1342. echo '<script>self.close();</script>';
  1343. exit;
  1344. }
  1345. $returnurl = !empty($_POST['returnurl']) ? escape($_POST['returnurl']): '?';
  1346. $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
  1347. $location .= '#'.smallHash($_POST['lf_linkdate']); // Scroll to the link which has been edited.
  1348. header('Location: '. $location); // After saving the link, redirect to the page the user was on.
  1349. exit;
  1350. }
  1351. // -------- User clicked the "Cancel" button when editing a link.
  1352. if (isset($_POST['cancel_edit']))
  1353. {
  1354. // If we are called from the bookmarklet, we must close the popup:
  1355. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
  1356. $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
  1357. $returnurl .= '#'.smallHash($_POST['lf_linkdate']); // Scroll to the link which has been edited.
  1358. $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
  1359. header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
  1360. exit;
  1361. }
  1362. // -------- User clicked the "Delete" button when editing a link: Delete link from database.
  1363. if (isset($_POST['delete_link']))
  1364. {
  1365. if (!tokenOk($_POST['token'])) die('Wrong token.');
  1366. // We do not need to ask for confirmation:
  1367. // - confirmation is handled by JavaScript
  1368. // - we are protected from XSRF by the token.
  1369. $linkdate=$_POST['lf_linkdate'];
  1370. $pluginManager->executeHooks('delete_link', $LINKSDB[$linkdate]);
  1371. unset($LINKSDB[$linkdate]);
  1372. $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']); // save to disk
  1373. // If we are called from the bookmarklet, we must close the popup:
  1374. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
  1375. // Pick where we're going to redirect
  1376. // =============================================================
  1377. // Basically, we can't redirect to where we were previously if it was a permalink
  1378. // or an edit_link, because it would 404.
  1379. // Cases:
  1380. // - / : nothing in $_GET, redirect to self
  1381. // - /?page : redirect to self
  1382. // - /?searchterm : redirect to self (there might be other links)
  1383. // - /?searchtags : redirect to self
  1384. // - /permalink : redirect to / (the link does not exist anymore)
  1385. // - /?edit_link : redirect to / (the link does not exist anymore)
  1386. // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
  1387. // redirect is not satisfied, and only then redirect to /
  1388. $location = "?";
  1389. // Self redirection
  1390. if (count($_GET) == 0
  1391. || isset($_GET['page'])
  1392. || isset($_GET['searchterm'])
  1393. || isset($_GET['searchtags'])
  1394. ) {
  1395. if (isset($_POST['returnurl'])) {
  1396. $location = $_POST['returnurl']; // Handle redirects given by the form
  1397. } else {
  1398. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('delete_link'));
  1399. }
  1400. }
  1401. header('Location: ' . $location); // After deleting the link, redirect to appropriate location
  1402. exit;
  1403. }
  1404. // -------- User clicked the "EDIT" button on a link: Display link edit form.
  1405. if (isset($_GET['edit_link']))
  1406. {
  1407. $link = $LINKSDB[$_GET['edit_link']]; // Read database
  1408. if (!$link) { header('Location: ?'); exit; } // Link not found in database.
  1409. $data = array(
  1410. 'linkcount' => count($LINKSDB),
  1411. 'link' => $link,
  1412. 'link_is_new' => false,
  1413. 'token' => getToken(),
  1414. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
  1415. 'tags' => $LINKSDB->allTags(),
  1416. );
  1417. $pluginManager->executeHooks('render_editlink', $data);
  1418. foreach ($data as $key => $value) {
  1419. $PAGE->assign($key, $value);
  1420. }
  1421. $PAGE->renderPage('editlink');
  1422. exit;
  1423. }
  1424. // -------- User want to post a new link: Display link edit form.
  1425. if (isset($_GET['post'])) {
  1426. $url = cleanup_url($_GET['post']);
  1427. $link_is_new = false;
  1428. // Check if URL is not already in database (in this case, we will edit the existing link)
  1429. $link = $LINKSDB->getLinkFromUrl($url);
  1430. if (!$link)
  1431. {
  1432. $link_is_new = true;
  1433. $linkdate = strval(date('Ymd_His'));
  1434. // Get title if it was provided in URL (by the bookmarklet).
  1435. $title = empty($_GET['title']) ? '' : escape($_GET['title']);
  1436. // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
  1437. $description = empty($_GET['description']) ? '' : escape($_GET['description']);
  1438. $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
  1439. $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
  1440. // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
  1441. if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
  1442. // Short timeout to keep the application responsive
  1443. list($headers, $data) = get_http_url($url, 4);
  1444. // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
  1445. if (strpos($headers[0], '200 OK') !== false) {
  1446. // Look for charset in html header.
  1447. preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
  1448. // If found, extract encoding.
  1449. if (!empty($meta[0])) {
  1450. // Get encoding specified in header.
  1451. preg_match('#charset="?(.*)"#si', $meta[0], $enc);
  1452. // If charset not found, use utf-8.
  1453. $html_charset = (!empty($enc[1])) ? strtolower($enc[1]) : 'utf-8';
  1454. }
  1455. else {
  1456. $html_charset = 'utf-8';
  1457. }
  1458. // Extract title
  1459. $title = html_extract_title($data);
  1460. if (!empty($title)) {
  1461. // Re-encode title in utf-8 if necessary.
  1462. $title = ($html_charset == 'iso-8859-1') ? utf8_encode($title) : $title;
  1463. }
  1464. }
  1465. }
  1466. if ($url == '') {
  1467. $url = '?' . smallHash($linkdate);
  1468. $title = 'Note: ';
  1469. }
  1470. $link = array(
  1471. 'linkdate' => $linkdate,
  1472. 'title' => $title,
  1473. 'url' => $url,
  1474. 'description' => $description,
  1475. 'tags' => $tags,
  1476. 'private' => $private
  1477. );
  1478. }
  1479. $data = array(
  1480. 'linkcount' => count($LINKSDB),
  1481. 'link' => $link,
  1482. 'link_is_new' => $link_is_new,
  1483. 'token' => getToken(), // XSRF protection.
  1484. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
  1485. 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
  1486. 'tags' => $LINKSDB->allTags(),
  1487. );
  1488. $pluginManager->executeHooks('render_editlink', $data);
  1489. foreach ($data as $key => $value) {
  1490. $PAGE->assign($key, $value);
  1491. }
  1492. $PAGE->renderPage('editlink');
  1493. exit;
  1494. }
  1495. // -------- Export as Netscape Bookmarks HTML file.
  1496. if ($targetPage == Router::$PAGE_EXPORT)
  1497. {
  1498. if (empty($_GET['what']))
  1499. {
  1500. $PAGE->assign('linkcount',count($LINKSDB));
  1501. $PAGE->renderPage('export');
  1502. exit;
  1503. }
  1504. $exportWhat=$_GET['what'];
  1505. if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export???');
  1506. header('Content-Type: text/html; charset=utf-8');
  1507. header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
  1508. $currentdate=date('Y/m/d H:i:s');
  1509. echo <<<HTML
  1510. <!DOCTYPE NETSCAPE-Bookmark-file-1>
  1511. <!-- This is an automatically generated file.
  1512. It will be read and overwritten.
  1513. DO NOT EDIT! -->
  1514. <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
  1515. <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
  1516. <TITLE>Bookmarks</TITLE>
  1517. <H1>Bookmarks</H1>
  1518. HTML;
  1519. foreach($LINKSDB as $link)
  1520. {
  1521. if ($exportWhat=='all' ||
  1522. ($exportWhat=='private' && $link['private']!=0) ||
  1523. ($exportWhat=='public' && $link['private']==0))
  1524. {
  1525. echo '<DT><A HREF="'.$link['url'].'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
  1526. if ($link['tags']!='') echo ' TAGS="'.str_replace(' ',',',$link['tags']).'"';
  1527. echo '>'.$link['title']."</A>\n";
  1528. if ($link['description']!='') echo '<DD>'.$link['description']."\n";
  1529. }
  1530. }
  1531. exit;
  1532. }
  1533. // -------- User is uploading a file for import
  1534. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=upload'))
  1535. {
  1536. // If file is too big, some form field may be missing.
  1537. if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0))
  1538. {
  1539. $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] );
  1540. echo '<script>alert("The file you are trying to upload is probably bigger than what this webserver can accept ('.getMaxFileSize().' bytes). Please upload in smaller chunks.");document.location=\''.escape($returnurl).'\';</script>';
  1541. exit;
  1542. }
  1543. if (!tokenOk($_POST['token'])) die('Wrong token.');
  1544. importFile();
  1545. exit;
  1546. }
  1547. // -------- Show upload/import dialog:
  1548. if ($targetPage == Router::$PAGE_IMPORT)
  1549. {
  1550. $PAGE->assign('linkcount',count($LINKSDB));
  1551. $PAGE->assign('token',getToken());
  1552. $PAGE->assign('maxfilesize',getMaxFileSize());
  1553. $PAGE->renderPage('import');
  1554. exit;
  1555. }
  1556. // -------- Otherwise, simply display search form and links:
  1557. showLinkList($PAGE, $LINKSDB);
  1558. exit;
  1559. }
  1560. // -----------------------------------------------------------------------------------------------
  1561. // Process the import file form.
  1562. function importFile()
  1563. {
  1564. if (!isLoggedIn()) { die('Not allowed.'); }
  1565. $LINKSDB = new LinkDB(
  1566. $GLOBALS['config']['DATASTORE'],
  1567. isLoggedIn(),
  1568. $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
  1569. $GLOBALS['redirector']
  1570. );
  1571. $filename=$_FILES['filetoupload']['name'];
  1572. $filesize=$_FILES['filetoupload']['size'];
  1573. $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
  1574. $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private?
  1575. $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones?
  1576. $import_count=0;
  1577. // Sniff file type:
  1578. $type='unknown';
  1579. if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox).
  1580. // Then import the bookmarks.
  1581. if ($type=='netscape')
  1582. {
  1583. // This is a standard Netscape-style bookmark file.
  1584. // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
  1585. foreach(explode('<DT>',$data) as $html) // explode is very fast
  1586. {
  1587. $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
  1588. $d = explode('<DD>',$html);
  1589. if (startswith($d[0],'<A '))
  1590. {
  1591. $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : ''); // Get description (optional)
  1592. preg_match('!<A .*?>(.*?)</A>!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : ''); // Get title
  1593. $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8');
  1594. preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER); // Get all other attributes
  1595. $raw_add_date=0;
  1596. foreach($matches as $m)
  1597. {
  1598. $attr=$m[1]; $value=$m[2];
  1599. if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
  1600. elseif ($attr=='ADD_DATE')
  1601. {
  1602. $raw_add_date=intval($value);
  1603. if ($raw_add_date>30000000000) $raw_add_date/=1000; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
  1604. }
  1605. elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
  1606. elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
  1607. }
  1608. if ($link['url']!='')
  1609. {
  1610. if ($private==1) $link['private']=1;
  1611. $dblink = $LINKSDB->getLinkFromUrl($link['url']); // See if the link is already in database.
  1612. if ($dblink==false)
  1613. { // Link not in database, let's import it...
  1614. if (empty($raw_add_date)) $raw_add_date=time(); // In case of shitty bookmark file with no ADD_DATE
  1615. // Make sure date/time is not already used by another link.
  1616. // (Some bookmark files have several different links with the same ADD_DATE)
  1617. // We increment date by 1 second until we find a date which is not used in DB.
  1618. // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
  1619. while (!empty($LINKSDB[date('Ymd_His',$raw_add_date)])) { $raw_add_date++; }// Yes, I know it's ugly.
  1620. $link['linkdate']=date('Ymd_His',$raw_add_date);
  1621. $LINKSDB[$link['linkdate']] = $link;
  1622. $import_count++;
  1623. }
  1624. else // Link already present in database.
  1625. {
  1626. if ($overwrite)
  1627. { // If overwrite is required, we import link data, except date/time.
  1628. $link['linkdate']=$dblink['linkdate'];
  1629. $LINKSDB[$link['linkdate']] = $link;
  1630. $import_count++;
  1631. }
  1632. }
  1633. }
  1634. }
  1635. }
  1636. $LINKSDB->savedb($GLOBALS['config']['PAGECACHE']);
  1637. echo '<script>alert("File '.json_encode($filename).' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
  1638. }
  1639. else
  1640. {
  1641. echo '<script>alert("File '.json_encode($filename).' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
  1642. }
  1643. }
  1644. // -----------------------------------------------------------------------------------------------
  1645. // Template for the list of links (<div id="linklist">)
  1646. // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
  1647. function buildLinkList($PAGE,$LINKSDB)
  1648. {
  1649. // ---- Filter link database according to parameters
  1650. $linksToDisplay=array();
  1651. $search_type='';
  1652. $search_crits='';
  1653. if (isset($_GET['searchterm'])) // Fulltext search
  1654. {
  1655. $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
  1656. $search_crits=escape(trim($_GET['searchterm']));
  1657. $search_type='fulltext';
  1658. }
  1659. elseif (isset($_GET['searchtags'])) // Search by tag
  1660. {
  1661. $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
  1662. $search_crits=explode(' ',escape(trim($_GET['searchtags'])));
  1663. $search_type='tags';
  1664. }
  1665. elseif (isset($_SERVER['QUERY_STRING']) && preg_match('/[a-zA-Z0-9-_@]{6}(&.+?)?/',$_SERVER['QUERY_STRING'])) // Detect smallHashes in URL
  1666. {
  1667. $linksToDisplay = $LINKSDB->filterSmallHash(substr(trim($_SERVER["QUERY_STRING"], '/'),0,6));
  1668. if (count($linksToDisplay)==0)
  1669. {
  1670. header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
  1671. echo '<h1>404 Not found.</h1>Oh crap. The link you are trying to reach does not exist or has been deleted.';
  1672. echo '<br>Would you mind <a href="?">clicking here</a>?';
  1673. exit;
  1674. }
  1675. $search_type='permalink';
  1676. }
  1677. else
  1678. $linksToDisplay = $LINKSDB; // Otherwise, display without filtering.
  1679. // Option: Show only private links
  1680. if (!empty($_SESSION['privateonly']))
  1681. {
  1682. $tmp = array();
  1683. foreach($linksToDisplay as $linkdate=>$link)
  1684. {
  1685. if ($link['private']!=0) $tmp[$linkdate]=$link;
  1686. }
  1687. $linksToDisplay=$tmp;
  1688. }
  1689. // ---- Handle paging.
  1690. /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess???
  1691. "Warning: array_keys() expects parameter 1 to be array, object given in ... "
  1692. If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
  1693. */
  1694. $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // Stupid and ugly. Thanks PHP.
  1695. // If there is only a single link, we change on-the-fly the title of the page.
  1696. if (count($linksToDisplay)==1) $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title'];
  1697. // Select articles according to paging.
  1698. $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
  1699. $pagecount = ($pagecount==0 ? 1 : $pagecount);
  1700. $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
  1701. $page = ( $page<1 ? 1 : $page );
  1702. $page = ( $page>$pagecount ? $pagecount : $page );
  1703. $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
  1704. $end = $i+$_SESSION['LINKS_PER_PAGE'];
  1705. $linkDisp=array(); // Links to display
  1706. while ($i<$end && $i<count($keys))
  1707. {
  1708. $link = $linksToDisplay[$keys[$i]];
  1709. $link['description'] = format_description($link['description'], $GLOBALS['redirector']);
  1710. $classLi = $i%2!=0 ? '' : 'publicLinkHightLight';
  1711. $link['class'] = ($link['private']==0 ? $classLi : 'private');
  1712. $link['timestamp']=linkdate2timestamp($link['linkdate']);
  1713. $taglist = explode(' ',$link['tags']);
  1714. uasort($taglist, 'strcasecmp');
  1715. $link['taglist']=$taglist;
  1716. $link['shorturl'] = smallHash($link['linkdate']);
  1717. if ($link["url"][0] === '?' && // Check for both signs of a note: starting with ? and 7 chars long. I doubt that you'll post any links that look like this.
  1718. strlen($link["url"]) === 7) {
  1719. $link["url"] = index_url($_SERVER) . $link["url"];
  1720. }
  1721. $linkDisp[$keys[$i]] = $link;
  1722. $i++;
  1723. }
  1724. // Compute paging navigation
  1725. $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] );
  1726. $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] );
  1727. $paging='';
  1728. $previous_page_url=''; if ($i!=count($keys)) $previous_page_url='?page='.($page+1).$searchterm.$searchtags;
  1729. $next_page_url='';if ($page>1) $next_page_url='?page='.($page-1).$searchterm.$searchtags;
  1730. $token = ''; if (isLoggedIn()) $token=getToken();
  1731. // Fill all template fields.
  1732. $data = array(
  1733. 'pagetitle' => $GLOBALS['pagetitle'],
  1734. 'linkcount' => count($LINKSDB),
  1735. 'previous_page_url' => $previous_page_url,
  1736. 'next_page_url' => $next_page_url,
  1737. 'page_current' => $page,
  1738. 'page_max' => $pagecount,
  1739. 'result_count' => count($linksToDisplay),
  1740. 'search_type' => $search_type,
  1741. 'search_crits' => $search_crits,
  1742. 'redirector' => empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'], // Optional redirector URL.
  1743. 'token' => $token,
  1744. 'links' => $linkDisp,
  1745. 'tags' => $LINKSDB->allTags(),
  1746. );
  1747. $pluginManager = PluginManager::getInstance();
  1748. $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
  1749. foreach ($data as $key => $value) {
  1750. $PAGE->assign($key, $value);
  1751. }
  1752. return;
  1753. }
  1754. // Compute the thumbnail for a link.
  1755. //
  1756. // With a link to the original URL.
  1757. // Understands various services (youtube.com...)
  1758. // Input: $url = URL for which the thumbnail must be found.
  1759. // $href = if provided, this URL will be followed instead of $url
  1760. // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
  1761. // Some of them may be missing.
  1762. // Return an empty array if no thumbnail available.
  1763. function computeThumbnail($url,$href=false)
  1764. {
  1765. if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return array();
  1766. if ($href==false) $href=$url;
  1767. // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
  1768. // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
  1769. // ^^^^^^^^^^^ ^^^^^^^^^^^
  1770. $domain = parse_url($url,PHP_URL_HOST);
  1771. if ($domain=='youtube.com' || $domain=='www.youtube.com')
  1772. {
  1773. parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
  1774. if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
  1775. 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
  1776. }
  1777. if ($domain=='youtu.be') // Youtube short links
  1778. {
  1779. $path = parse_url($url,PHP_URL_PATH);
  1780. return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
  1781. 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
  1782. }
  1783. if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
  1784. {
  1785. parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract image filename.
  1786. if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
  1787. 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
  1788. }
  1789. if ($domain=='imgur.com')
  1790. {
  1791. $path = parse_url($url,PHP_URL_PATH);
  1792. if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
  1793. if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
  1794. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1795. if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
  1796. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1797. if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
  1798. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1799. }
  1800. if ($domain=='i.imgur.com')
  1801. {
  1802. $pi = pathinfo(parse_url($url,PHP_URL_PATH));
  1803. if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
  1804. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1805. }
  1806. if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
  1807. {
  1808. if (strpos($url,'dailymotion.com/video/')!==false)
  1809. {
  1810. $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
  1811. return array('src'=>$thumburl,
  1812. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
  1813. }
  1814. }
  1815. if (endsWith($domain,'.imageshack.us'))
  1816. {
  1817. $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
  1818. if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
  1819. {
  1820. $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
  1821. return array('src'=>$thumburl,
  1822. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
  1823. }
  1824. }
  1825. // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
  1826. // So we deport the thumbnail generation in order not to slow down page generation
  1827. // (and we also cache the thumbnail)
  1828. if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
  1829. if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
  1830. || $domain=='vimeo.com'
  1831. || $domain=='ted.com' || endsWith($domain,'.ted.com')
  1832. || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
  1833. )
  1834. {
  1835. if ($domain=='vimeo.com')
  1836. { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
  1837. $path = parse_url($url,PHP_URL_PATH);
  1838. if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
  1839. }
  1840. if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
  1841. { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
  1842. $path = parse_url($url,PHP_URL_PATH);
  1843. if (!preg_match('!/\d+.+?!',$path)) return array();
  1844. }
  1845. if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
  1846. { // Make sure this TED URL points to a video (/talks/...)
  1847. $path = parse_url($url,PHP_URL_PATH);
  1848. if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
  1849. }
  1850. $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
  1851. return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
  1852. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
  1853. }
  1854. // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
  1855. // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
  1856. // But using the extension will do.
  1857. $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
  1858. if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
  1859. {
  1860. $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
  1861. return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
  1862. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
  1863. }
  1864. return array(); // No thumbnail.
  1865. }
  1866. // Returns the HTML code to display a thumbnail for a link
  1867. // with a link to the original URL.
  1868. // Understands various services (youtube.com...)
  1869. // Input: $url = URL for which the thumbnail must be found.
  1870. // $href = if provided, this URL will be followed instead of $url
  1871. // Returns '' if no thumbnail available.
  1872. function thumbnail($url,$href=false)
  1873. {
  1874. $t = computeThumbnail($url,$href);
  1875. if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
  1876. $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
  1877. if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
  1878. if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
  1879. if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
  1880. if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
  1881. $html.='></a>';
  1882. return $html;
  1883. }
  1884. // Returns the HTML code to display a thumbnail for a link
  1885. // for the picture wall (using lazy image loading)
  1886. // Understands various services (youtube.com...)
  1887. // Input: $url = URL for which the thumbnail must be found.
  1888. // $href = if provided, this URL will be followed instead of $url
  1889. // Returns '' if no thumbnail available.
  1890. function lazyThumbnail($url,$href=false)
  1891. {
  1892. $t = computeThumbnail($url,$href);
  1893. if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
  1894. $html='<a href="'.escape($t['href']).'">';
  1895. // Lazy image
  1896. $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
  1897. if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
  1898. if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
  1899. if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
  1900. if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
  1901. $html.='>';
  1902. // No-JavaScript fallback.
  1903. $html.='<noscript><img src="'.escape($t['src']).'"';
  1904. if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
  1905. if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
  1906. if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
  1907. if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
  1908. $html.='></noscript></a>';
  1909. return $html;
  1910. }
  1911. // -----------------------------------------------------------------------------------------------
  1912. // Installation
  1913. // This function should NEVER be called if the file data/config.php exists.
  1914. function install()
  1915. {
  1916. // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
  1917. if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
  1918. // This part makes sure sessions works correctly.
  1919. // (Because on some hosts, session.save_path may not be set correctly,
  1920. // or we may not have write access to it.)
  1921. if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
  1922. { // Step 2: Check if data in session is correct.
  1923. echo '<pre>Sessions do not seem to work correctly on your server.<br>';
  1924. echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>';
  1925. echo 'It currently points to '.session_save_path().'<br>';
  1926. echo 'Check that the hostname used to access Shaarli contains a dot. On some browsers, accessing your server via a hostname like \'localhost\' or any custom hostname without a dot causes cookie storage to fail. We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>';
  1927. echo '<br><a href="?">Click to try again.</a></pre>';
  1928. die;
  1929. }
  1930. if (!isset($_SESSION['session_tested']))
  1931. { // Step 1 : Try to store data in session and reload page.
  1932. $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
  1933. header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
  1934. }
  1935. if (isset($_GET['test_session']))
  1936. { // Step 3: Sessions are OK. Remove test parameter from URL.
  1937. header('Location: '.index_url($_SERVER));
  1938. }
  1939. if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
  1940. {
  1941. $tz = 'UTC';
  1942. if (!empty($_POST['continent']) && !empty($_POST['city'])) {
  1943. if (isTimeZoneValid($_POST['continent'], $_POST['city'])) {
  1944. $tz = $_POST['continent'].'/'.$_POST['city'];
  1945. }
  1946. }
  1947. $GLOBALS['timezone'] = $tz;
  1948. // Everything is ok, let's create config file.
  1949. $GLOBALS['login'] = $_POST['setlogin'];
  1950. $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
  1951. $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
  1952. $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.escape(index_url($_SERVER)) : $_POST['title'] );
  1953. $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']);
  1954. try {
  1955. writeConfig($GLOBALS, isLoggedIn());
  1956. }
  1957. catch(Exception $e) {
  1958. error_log(
  1959. 'ERROR while writing config file after installation.' . PHP_EOL .
  1960. $e->getMessage()
  1961. );
  1962. // TODO: do not handle exceptions/errors in JS.
  1963. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
  1964. exit;
  1965. }
  1966. echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
  1967. exit;
  1968. }
  1969. // Display config form:
  1970. list($timezone_form, $timezone_js) = generateTimeZoneForm();
  1971. $timezone_html = '';
  1972. if ($timezone_form != '') {
  1973. $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
  1974. }
  1975. $PAGE = new pageBuilder;
  1976. $PAGE->assign('timezone_html',$timezone_html);
  1977. $PAGE->assign('timezone_js',$timezone_js);
  1978. $PAGE->renderPage('install');
  1979. exit;
  1980. }
  1981. /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
  1982. I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
  1983. The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
  1984. This function is called by passing the URL:
  1985. http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
  1986. [URL] is the URL of the link (e.g. a flickr page)
  1987. [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
  1988. The function below will fetch the image from the webservice and store it in the cache.
  1989. */
  1990. function genThumbnail()
  1991. {
  1992. // Make sure the parameters in the URL were generated by us.
  1993. $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']);
  1994. if ($sign!=$_GET['hmac']) die('Naughty boy!');
  1995. // Let's see if we don't already have the image for this URL in the cache.
  1996. $thumbname=hash('sha1',$_GET['url']).'.jpg';
  1997. if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname))
  1998. { // We have the thumbnail, just serve it:
  1999. header('Content-Type: image/jpeg');
  2000. echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname);
  2001. return;
  2002. }
  2003. // We may also serve a blank image (if service did not respond)
  2004. $blankname=hash('sha1',$_GET['url']).'.gif';
  2005. if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname))
  2006. {
  2007. header('Content-Type: image/gif');
  2008. echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname);
  2009. return;
  2010. }
  2011. // Otherwise, generate the thumbnail.
  2012. $url = $_GET['url'];
  2013. $domain = parse_url($url,PHP_URL_HOST);
  2014. if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
  2015. {
  2016. // Crude replacement to handle new flickr domain policy (They prefer www. now)
  2017. $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
  2018. // Is this a link to an image, or to a flickr page ?
  2019. $imageurl='';
  2020. if (endswith(parse_url($url,PHP_URL_PATH),'.jpg'))
  2021. { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
  2022. preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
  2023. if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
  2024. }
  2025. else // This is a flickr page (html)
  2026. {
  2027. // Get the flickr html page.
  2028. list($headers, $data) = get_http_url($url, 20);
  2029. if (strpos($headers[0], '200 OK') !== false)
  2030. {
  2031. // flickr now nicely provides the URL of the thumbnail in each flickr page.
  2032. preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!',$data,$matches);
  2033. if (!empty($matches[1])) $imageurl=$matches[1];
  2034. // In albums (and some other pages), the link rel="image_src" is not provided,
  2035. // but flickr provides:
  2036. // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
  2037. if ($imageurl=='')
  2038. {
  2039. preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!',$data,$matches);
  2040. if (!empty($matches[1])) $imageurl=$matches[1];
  2041. }
  2042. }
  2043. }
  2044. if ($imageurl!='')
  2045. { // Let's download the image.
  2046. // Image is 240x120, so 10 seconds to download should be enough.
  2047. list($headers, $data) = get_http_url($imageurl, 10);
  2048. if (strpos($headers[0], '200 OK') !== false) {
  2049. file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
  2050. header('Content-Type: image/jpeg');
  2051. echo $data;
  2052. return;
  2053. }
  2054. }
  2055. }
  2056. elseif ($domain=='vimeo.com' )
  2057. {
  2058. // This is more complex: we have to perform a HTTP request, then parse the result.
  2059. // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
  2060. $vid = substr(parse_url($url,PHP_URL_PATH),1);
  2061. list($headers, $data) = get_http_url('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
  2062. if (strpos($headers[0], '200 OK') !== false) {
  2063. $t = unserialize($data);
  2064. $imageurl = $t[0]['thumbnail_medium'];
  2065. // Then we download the image and serve it to our client.
  2066. list($headers, $data) = get_http_url($imageurl, 10);
  2067. if (strpos($headers[0], '200 OK') !== false) {
  2068. file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
  2069. header('Content-Type: image/jpeg');
  2070. echo $data;
  2071. return;
  2072. }
  2073. }
  2074. }
  2075. elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
  2076. {
  2077. // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
  2078. // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
  2079. // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
  2080. list($headers, $data) = get_http_url($url, 5);
  2081. if (strpos($headers[0], '200 OK') !== false) {
  2082. // Extract the link to the thumbnail
  2083. preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!',$data,$matches);
  2084. if (!empty($matches[1]))
  2085. { // Let's download the image.
  2086. $imageurl=$matches[1];
  2087. // No control on image size, so wait long enough
  2088. list($headers, $data) = get_http_url($imageurl, 20);
  2089. if (strpos($headers[0], '200 OK') !== false) {
  2090. $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
  2091. file_put_contents($filepath,$data); // Save image to cache.
  2092. if (resizeImage($filepath))
  2093. {
  2094. header('Content-Type: image/jpeg');
  2095. echo file_get_contents($filepath);
  2096. return;
  2097. }
  2098. }
  2099. }
  2100. }
  2101. }
  2102. elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
  2103. {
  2104. // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
  2105. // http://xkcd.com/327/
  2106. // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
  2107. list($headers, $data) = get_http_url($url, 5);
  2108. if (strpos($headers[0], '200 OK') !== false) {
  2109. // Extract the link to the thumbnail
  2110. preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!',$data,$matches);
  2111. if (!empty($matches[1]))
  2112. { // Let's download the image.
  2113. $imageurl=$matches[1];
  2114. // No control on image size, so wait long enough
  2115. list($headers, $data) = get_http_url($imageurl, 20);
  2116. if (strpos($headers[0], '200 OK') !== false) {
  2117. $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
  2118. file_put_contents($filepath,$data); // Save image to cache.
  2119. if (resizeImage($filepath))
  2120. {
  2121. header('Content-Type: image/jpeg');
  2122. echo file_get_contents($filepath);
  2123. return;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. }
  2129. else
  2130. {
  2131. // For all other domains, we try to download the image and make a thumbnail.
  2132. // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
  2133. list($headers, $data) = get_http_url($url, 30);
  2134. if (strpos($headers[0], '200 OK') !== false) {
  2135. $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
  2136. file_put_contents($filepath,$data); // Save image to cache.
  2137. if (resizeImage($filepath))
  2138. {
  2139. header('Content-Type: image/jpeg');
  2140. echo file_get_contents($filepath);
  2141. return;
  2142. }
  2143. }
  2144. }
  2145. // Otherwise, return an empty image (8x8 transparent gif)
  2146. $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
  2147. file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice.
  2148. header('Content-Type: image/gif');
  2149. echo $blankgif;
  2150. }
  2151. // Make a thumbnail of the image (to width: 120 pixels)
  2152. // Returns true if success, false otherwise.
  2153. function resizeImage($filepath)
  2154. {
  2155. if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
  2156. // Trick: some stupid people rename GIF as JPEG... or else.
  2157. // So we really try to open each image type whatever the extension is.
  2158. $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
  2159. $im=false;
  2160. $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
  2161. $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
  2162. $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
  2163. if (!$im) return false; // Unable to open image (corrupted or not an image)
  2164. $w = imagesx($im);
  2165. $h = imagesy($im);
  2166. $ystart = 0; $yheight=$h;
  2167. if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
  2168. $nw = 120; // Desired width
  2169. $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
  2170. // Resize image:
  2171. $im2 = imagecreatetruecolor($nw,$nh);
  2172. imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
  2173. imageinterlace($im2,true); // For progressive JPEG.
  2174. $tempname=$filepath.'_TEMP.jpg';
  2175. imagejpeg($im2, $tempname, 90);
  2176. imagedestroy($im);
  2177. imagedestroy($im2);
  2178. unlink($filepath);
  2179. rename($tempname,$filepath); // Overwrite original picture with thumbnail.
  2180. return true;
  2181. }
  2182. try {
  2183. mergeDeprecatedConfig($GLOBALS, isLoggedIn());
  2184. } catch(Exception $e) {
  2185. error_log(
  2186. 'ERROR while merging deprecated options.php file.' . PHP_EOL .
  2187. $e->getMessage()
  2188. );
  2189. }
  2190. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database.
  2191. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
  2192. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; }
  2193. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=dailyrss')) { showDailyRSS(); exit; }
  2194. if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=daily')) { showDaily(); exit; }
  2195. if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE'];
  2196. renderPage();
  2197. ?>