index.php 112 KB

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