index.php 118 KB

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