index.php 119 KB

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