index.php 108 KB

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