PageRenderTime 60ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/index.php

https://github.com/jcsaaddupuy/Shaarli
PHP | 2423 lines | 1783 code | 221 blank | 419 comment | 428 complexity | c2b639aa2b3dc7db5a9c7f92d3a9ed63 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // Shaarli 0.0.41 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 webspace 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']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt'; // For updates check of Shaarli.
  29. $GLOBALS['config']['UPDATECHECK_INTERVAL'] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
  30. // Note: You must have publisher.php in the same directory as Shaarli index.php
  31. $GLOBALS['config']['ACTUAL_SERVER_PORT'] = $_SERVER["SERVER_PORT"] ; //Override port used in generated URLs.
  32. // -----------------------------------------------------------------------------------------------
  33. // You should not touch below (or at your own risks !)
  34. // Optionnal config file.
  35. if (is_file($GLOBALS['config']['DATADIR'].'/options.php')) require($GLOBALS['config']['DATADIR'].'/options.php');
  36. define('shaarli_version','0.0.41 beta');
  37. define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
  38. define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
  39. // Force cookie path (but do not change lifetime)
  40. $cookie=session_get_cookie_params();
  41. $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
  42. session_set_cookie_params($cookie['lifetime'],$cookiedir,$_SERVER['SERVER_NAME']); // Set default cookie expiration and path.
  43. // Set session parameters on server side.
  44. define('INACTIVITY_TIMEOUT',3600); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
  45. ini_set('session.use_cookies', 1); // Use cookies to store session.
  46. ini_set('session.use_only_cookies', 1); // Force cookies for session (phpsessionID forbidden in URL)
  47. ini_set('session.use_trans_sid', false); // Prevent php to use sessionID in URL if cookies are disabled.
  48. session_name('shaarli');
  49. if (session_id() == '') session_start(); // Start session if needed (Some server auto-start sessions).
  50. // PHP Settings
  51. ini_set('max_input_time','60'); // High execution time in case of problematic imports/exports.
  52. ini_set('memory_limit', '128M'); // Try to set max upload file size and read (May not work on some hosts).
  53. ini_set('post_max_size', '16M');
  54. ini_set('upload_max_filesize', '16M');
  55. checkphpversion();
  56. error_reporting(E_ALL^E_WARNING); // See all error except warnings.
  57. //error_reporting(-1); // See all errors (for debugging only)
  58. include "inc/rain.tpl.class.php"; //include Rain TPL
  59. raintpl::$tpl_dir = "tpl/"; // template directory
  60. if (!is_dir('tmp')) { mkdir('tmp',0705); chmod('tmp',0705); }
  61. raintpl::$cache_dir = "tmp/"; // cache directory
  62. ob_start(); // Output buffering for the page cache.
  63. // In case stupid admin has left magic_quotes enabled in php.ini:
  64. if (get_magic_quotes_gpc())
  65. {
  66. function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
  67. $_POST = array_map('stripslashes_deep', $_POST);
  68. $_GET = array_map('stripslashes_deep', $_GET);
  69. $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
  70. }
  71. // Prevent caching on client side or proxy: (yes, it's ugly)
  72. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  73. header("Cache-Control: no-store, no-cache, must-revalidate");
  74. header("Cache-Control: post-check=0, pre-check=0", false);
  75. header("Pragma: no-cache");
  76. // Directories creations (Note that your web host may require differents rights than 705.)
  77. 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>');
  78. if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); }
  79. if (!is_dir('tmp')) { mkdir('tmp',0705); chmod('tmp',0705); } // For RainTPL temporary files.
  80. if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
  81. // Second check to see if Shaarli can write in its directory, because on some hosts is_writable() is not reliable.
  82. if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) die('<pre>ERROR: Shaarli does not have the right to write in its own directory ('.realpath(dirname(__FILE__)).').</pre>');
  83. if ($GLOBALS['config']['ENABLE_LOCALCACHE'])
  84. {
  85. if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); }
  86. if (!is_file($GLOBALS['config']['CACHEDIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['CACHEDIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
  87. }
  88. // Handling of old config file which do not have the new parameters.
  89. if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.htmlspecialchars(indexUrl());
  90. if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
  91. if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
  92. if (empty($GLOBALS['disablesessionprotection'])) $GLOBALS['disablesessionprotection']=false;
  93. if (empty($GLOBALS['disablejquery'])) $GLOBALS['disablejquery']=false;
  94. if (empty($GLOBALS['privateLinkByDefault'])) $GLOBALS['privateLinkByDefault']=false;
  95. // I really need to rewrite Shaarli with a proper configuation manager.
  96. // Run config screen if first run:
  97. if (!is_file($GLOBALS['config']['CONFIG_FILE'])) install();
  98. require $GLOBALS['config']['CONFIG_FILE']; // Read login/password hash into $GLOBALS.
  99. autoLocale(); // Sniff browser language and set date format accordingly.
  100. header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
  101. // Check php version
  102. function checkphpversion()
  103. {
  104. if (version_compare(PHP_VERSION, '5.1.0') < 0)
  105. {
  106. header('Content-Type: text/plain; charset=utf-8');
  107. echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at least php 5.1.0, and thus cannot run. Sorry.';
  108. exit;
  109. }
  110. }
  111. // Checks if an update is available for Shaarli.
  112. // (at most once a day, and only for registered user.)
  113. // Output: '' = no new version.
  114. // other= the available version.
  115. function checkUpdate()
  116. {
  117. if (!isLoggedIn()) return ''; // Do not check versions for visitors.
  118. // Get latest version number at most once a day.
  119. if (!is_file($GLOBALS['config']['UPDATECHECK_FILENAME']) || (filemtime($GLOBALS['config']['UPDATECHECK_FILENAME'])<time()-($GLOBALS['config']['UPDATECHECK_INTERVAL'])))
  120. {
  121. $version=shaarli_version;
  122. list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2);
  123. if (strpos($httpstatus,'200 OK')!==false) $version=$data;
  124. // If failed, nevermind. We don't want to bother the user with that.
  125. file_put_contents($GLOBALS['config']['UPDATECHECK_FILENAME'],$version); // touch file date
  126. }
  127. // Compare versions:
  128. $newestversion=file_get_contents($GLOBALS['config']['UPDATECHECK_FILENAME']);
  129. if (version_compare($newestversion,shaarli_version)==1) return $newestversion;
  130. return '';
  131. }
  132. // -----------------------------------------------------------------------------------------------
  133. // Simple cache system (mainly for the RSS/ATOM feeds).
  134. class pageCache
  135. {
  136. private $url; // Full URL of the page to cache (typically the value returned by pageUrl())
  137. private $shouldBeCached; // boolean: Should this url be cached ?
  138. private $filename; // Name of the cache file for this url
  139. /*
  140. $url = url (typically the value returned by pageUrl())
  141. $shouldBeCached = boolean. If false, the cache will be disabled.
  142. */
  143. public function __construct($url,$shouldBeCached)
  144. {
  145. $this->url = $url;
  146. $this->filename = $GLOBALS['config']['PAGECACHE'].'/'.sha1($url).'.cache';
  147. $this->shouldBeCached = $shouldBeCached;
  148. }
  149. // If the page should be cached and a cached version exists,
  150. // returns the cached version (otherwise, return null).
  151. public function cachedVersion()
  152. {
  153. if (!$this->shouldBeCached) return null;
  154. if (is_file($this->filename)) { return file_get_contents($this->filename); exit; }
  155. return null;
  156. }
  157. // Put a page in the cache.
  158. public function cache($page)
  159. {
  160. if (!$this->shouldBeCached) return;
  161. if (!is_dir($GLOBALS['config']['PAGECACHE'])) { mkdir($GLOBALS['config']['PAGECACHE'],0705); chmod($GLOBALS['config']['PAGECACHE'],0705); }
  162. file_put_contents($this->filename,$page);
  163. }
  164. // Purge the whole cache.
  165. // (call with pageCache::purgeCache())
  166. public static function purgeCache()
  167. {
  168. if (is_dir($GLOBALS['config']['PAGECACHE']))
  169. {
  170. $handler = opendir($GLOBALS['config']['PAGECACHE']);
  171. if ($handler!==false)
  172. {
  173. while (($filename = readdir($handler))!==false)
  174. {
  175. if (endsWith($filename,'.cache')) { unlink($GLOBALS['config']['PAGECACHE'].'/'.$filename); }
  176. }
  177. closedir($handler);
  178. }
  179. }
  180. }
  181. }
  182. // -----------------------------------------------------------------------------------------------
  183. // Log to text file
  184. function logm($message)
  185. {
  186. $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
  187. file_put_contents($GLOBALS['config']['DATADIR'].'/log.txt',$t,FILE_APPEND);
  188. }
  189. // Same as nl2br(), but escapes < and >
  190. function nl2br_escaped($html)
  191. {
  192. return str_replace('>','&gt;',str_replace('<','&lt;',nl2br($html)));
  193. }
  194. /* Returns the small hash of a string
  195. eg. smallHash('20111006_131924') --> yZH23w
  196. Small hashes:
  197. - are unique (well, as unique as crc32, at last)
  198. - are always 6 characters long.
  199. - only use the following characters: a-z A-Z 0-9 - _ @
  200. - are NOT cryptographically secure (they CAN be forged)
  201. In Shaarli, they are used as a tinyurl-like link to individual entries.
  202. */
  203. function smallHash($text)
  204. {
  205. $t = rtrim(base64_encode(hash('crc32',$text,true)),'=');
  206. $t = str_replace('+','-',$t); // Get rid of characters which need encoding in URLs.
  207. $t = str_replace('/','_',$t);
  208. $t = str_replace('=','@',$t);
  209. return $t;
  210. }
  211. // In a string, converts urls to clickable links.
  212. // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
  213. function text2clickable($url)
  214. {
  215. $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'];
  216. return preg_replace('!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si','<a href="'.$redir.'$1" rel="nofollow">$1</a>',$url);
  217. }
  218. // This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
  219. // even in the absence of <pre> (This is used in description to keep text formatting)
  220. function keepMultipleSpaces($text)
  221. {
  222. return str_replace(' ',' &nbsp;',$text);
  223. }
  224. // ------------------------------------------------------------------------------------------
  225. // Sniff browser language to display dates in the right format automatically.
  226. // (Note that is may not work on your server if the corresponding local is not installed.)
  227. function autoLocale()
  228. {
  229. $loc='en_US'; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
  230. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
  231. { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
  232. if (preg_match('/([a-z]{2}(-[a-z]{2})?)/i',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches)) $loc=$matches[1];
  233. }
  234. setlocale(LC_TIME,$loc); // LC_TIME = Set local for date/time format only.
  235. }
  236. // ------------------------------------------------------------------------------------------
  237. // PubSubHubbub protocol support (if enabled) [UNTESTED]
  238. // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
  239. if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) include './publisher.php';
  240. function pubsubhub()
  241. {
  242. if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
  243. {
  244. $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
  245. $topic_url = array (
  246. indexUrl().'?do=atom',
  247. indexUrl().'?do=rss'
  248. );
  249. $p->publish_update($topic_url);
  250. }
  251. }
  252. // ------------------------------------------------------------------------------------------
  253. // Session management
  254. // Returns the IP address of the client (Used to prevent session cookie hijacking.)
  255. function allIPs()
  256. {
  257. $ip = $_SERVER["REMOTE_ADDR"];
  258. // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
  259. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
  260. if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
  261. return $ip;
  262. }
  263. // Check that user/password is correct.
  264. function check_auth($login,$password)
  265. {
  266. $hash = sha1($password.$login.$GLOBALS['salt']);
  267. if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash'])
  268. { // Login/password is correct.
  269. $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // generate unique random number (different than phpsessionid)
  270. $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
  271. $_SESSION['username']=$login;
  272. $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
  273. logm('Login successful');
  274. return True;
  275. }
  276. logm('Login failed for user '.$login);
  277. return False;
  278. }
  279. // Returns true if the user is logged in.
  280. function isLoggedIn()
  281. {
  282. if ($GLOBALS['config']['OPEN_SHAARLI']) return true;
  283. if (!isset($GLOBALS['login'])) return false; // Shaarli is not configured yet.
  284. // If session does not exist on server side, or IP address has changed, or session has expired, logout.
  285. if (empty($_SESSION['uid']) || ($GLOBALS['disablesessionprotection']==false && $_SESSION['ip']!=allIPs()) || time()>=$_SESSION['expires_on'])
  286. {
  287. logout();
  288. return false;
  289. }
  290. if (!empty($_SESSION['longlastingsession'])) $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
  291. else $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
  292. return true;
  293. }
  294. // Force logout.
  295. function logout() { if (isset($_SESSION)) { unset($_SESSION['uid']); unset($_SESSION['ip']); unset($_SESSION['username']); unset($_SESSION['privateonly']); } }
  296. // ------------------------------------------------------------------------------------------
  297. // Brute force protection system
  298. // Several consecutive failed logins will ban the IP address for 30 minutes.
  299. 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?>");
  300. include $GLOBALS['config']['IPBANS_FILENAME'];
  301. // Signal a failed login. Will ban the IP if too many failures:
  302. function ban_loginFailed()
  303. {
  304. $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
  305. if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
  306. $gb['FAILURES'][$ip]++;
  307. if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1))
  308. {
  309. $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION'];
  310. logm('IP address banned from login');
  311. }
  312. $GLOBALS['IPBANS'] = $gb;
  313. file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
  314. }
  315. // Signals a successful login. Resets failed login counter.
  316. function ban_loginOk()
  317. {
  318. $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
  319. unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
  320. $GLOBALS['IPBANS'] = $gb;
  321. file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
  322. }
  323. // Checks if the user CAN login. If 'true', the user can try to login.
  324. function ban_canLogin()
  325. {
  326. $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
  327. if (isset($gb['BANS'][$ip]))
  328. {
  329. // User is banned. Check if the ban has expired:
  330. if ($gb['BANS'][$ip]<=time())
  331. { // Ban expired, user can try to login again.
  332. logm('Ban lifted.');
  333. unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
  334. file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
  335. return true; // Ban has expired, user can login.
  336. }
  337. return false; // User is banned.
  338. }
  339. return true; // User is not banned.
  340. }
  341. // ------------------------------------------------------------------------------------------
  342. // Process login form: Check if login/password is correct.
  343. if (isset($_POST['login']))
  344. {
  345. if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
  346. if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
  347. { // Login/password is ok.
  348. ban_loginOk();
  349. // If user wants to keep the session cookie even after the browser closes:
  350. if (!empty($_POST['longlastingsession']))
  351. {
  352. $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year)
  353. $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side.
  354. $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
  355. session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
  356. // Note: Never forget the trailing slash on the cookie path !
  357. session_regenerate_id(true); // Send cookie with new expiration date to browser.
  358. }
  359. else // Standard session expiration (=when browser closes)
  360. {
  361. $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
  362. session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
  363. session_regenerate_id(true);
  364. }
  365. // Optional redirect after login:
  366. if (isset($_GET['post'])) { header('Location: ?post='.urlencode($_GET['post']).(!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); exit; }
  367. if (isset($_POST['returnurl']))
  368. {
  369. if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
  370. header('Location: '.$_POST['returnurl']); exit;
  371. }
  372. header('Location: ?'); exit;
  373. }
  374. else
  375. {
  376. ban_loginFailed();
  377. $redir = '';
  378. if (isset($_GET['post'])) { $redir = '&post='.urlencode($_GET['post']).(!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):''); }
  379. echo '<script language="JavaScript">alert("Wrong login/password.");document.location=\'?do=login'.$redir.'\';</script>'; // Redirect to login screen.
  380. exit;
  381. }
  382. }
  383. // ------------------------------------------------------------------------------------------
  384. // Misc utility functions:
  385. // Returns the server URL (including port and http/https), without path.
  386. // eg. "http://myserver.com:8080"
  387. // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
  388. function serverUrl()
  389. {
  390. $https = (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS'])=='on')) || $GLOBALS['config']['ACTUAL_SERVER_PORT'] =='443'; // HTTPS detection.
  391. $serverport = ($GLOBALS['config']['ACTUAL_SERVER_PORT'] =='80' || ($https && $GLOBALS['config']['ACTUAL_SERVER_PORT'] =='443') ? '' : ':'.$GLOBALS['config']['ACTUAL_SERVER_PORT'] );
  392. return 'http'.($https?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport;
  393. }
  394. // Returns the absolute URL of current script, without the query.
  395. // (eg. http://sebsauvage.net/links/)
  396. function indexUrl()
  397. {
  398. $scriptname = $_SERVER["SCRIPT_NAME"];
  399. // If the script is named 'index.php', we remove it (for better looking URLs,
  400. // eg. http://mysite.com/shaarli/?abcde instead of http://mysite.com/shaarli/index.php?abcde)
  401. if (endswith($scriptname,'index.php')) $scriptname = substr($scriptname,0,strlen($scriptname)-9);
  402. return serverUrl() . $scriptname;
  403. }
  404. // Returns the absolute URL of current script, WITH the query.
  405. // (eg. http://sebsauvage.net/links/?toto=titi&spamspamspam=humbug)
  406. function pageUrl()
  407. {
  408. return indexUrl().(!empty($_SERVER["QUERY_STRING"]) ? '?'.$_SERVER["QUERY_STRING"] : '');
  409. }
  410. // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
  411. function return_bytes($val)
  412. {
  413. $val = trim($val); $last=strtolower($val[strlen($val)-1]);
  414. switch($last)
  415. {
  416. case 'g': $val *= 1024;
  417. case 'm': $val *= 1024;
  418. case 'k': $val *= 1024;
  419. }
  420. return $val;
  421. }
  422. // Try to determine max file size for uploads (POST).
  423. // Returns an integer (in bytes)
  424. function getMaxFileSize()
  425. {
  426. $size1 = return_bytes(ini_get('post_max_size'));
  427. $size2 = return_bytes(ini_get('upload_max_filesize'));
  428. // Return the smaller of two:
  429. $maxsize = min($size1,$size2);
  430. // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
  431. return $maxsize;
  432. }
  433. // Tells if a string start with a substring or not.
  434. function startsWith($haystack,$needle,$case=true)
  435. {
  436. if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
  437. return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
  438. }
  439. // Tells if a string ends with a substring or not.
  440. function endsWith($haystack,$needle,$case=true)
  441. {
  442. if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
  443. return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
  444. }
  445. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
  446. (used to build the ADD_DATE attribute in Netscape-bookmarks file)
  447. PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
  448. function linkdate2timestamp($linkdate)
  449. {
  450. $Y=$M=$D=$h=$m=$s=0;
  451. $r = sscanf($linkdate,'%4d%2d%2d_%2d%2d%2d',$Y,$M,$D,$h,$m,$s);
  452. return mktime($h,$m,$s,$M,$D,$Y);
  453. }
  454. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
  455. (used to build the pubDate attribute in RSS feed.) */
  456. function linkdate2rfc822($linkdate)
  457. {
  458. return date('r',linkdate2timestamp($linkdate)); // 'r' is for RFC822 date format.
  459. }
  460. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
  461. (used to build the updated tags in ATOM feed.) */
  462. function linkdate2iso8601($linkdate)
  463. {
  464. return date('c',linkdate2timestamp($linkdate)); // 'c' is for ISO 8601 date format.
  465. }
  466. /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
  467. (used to display link date on screen)
  468. The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
  469. function linkdate2locale($linkdate)
  470. {
  471. return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale.
  472. // Note that if you use a local which is not installed on your webserver,
  473. // the date will not be displayed in the chosen locale, but probably in US notation.
  474. }
  475. // Parse HTTP response headers and return an associative array.
  476. function http_parse_headers_shaarli( $headers )
  477. {
  478. $res=array();
  479. foreach($headers as $header)
  480. {
  481. $i = strpos($header,': ');
  482. if ($i!==false)
  483. {
  484. $key=substr($header,0,$i);
  485. $value=substr($header,$i+2,strlen($header)-$i-2);
  486. $res[$key]=$value;
  487. }
  488. }
  489. return $res;
  490. }
  491. /* GET an URL.
  492. Input: $url : url to get (http://...)
  493. $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
  494. Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
  495. [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
  496. [2] = data
  497. Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
  498. if (strpos($httpstatus,'200 OK')!==false)
  499. echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
  500. else
  501. echo 'There was an error: '.htmlspecialchars($httpstatus)
  502. */
  503. function getHTTP($url,$timeout=30)
  504. {
  505. try
  506. {
  507. $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
  508. $context = stream_context_create($options);
  509. $data=file_get_contents($url,false,$context,-1, 4000000); // We download at most 4 Mb from source.
  510. if (!$data) { return array('HTTP Error',array(),''); }
  511. $httpStatus=$http_response_header[0]; // eg. "HTTP/1.1 200 OK"
  512. $responseHeaders=http_parse_headers_shaarli($http_response_header);
  513. return array($httpStatus,$responseHeaders,$data);
  514. }
  515. catch (Exception $e) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
  516. {
  517. return array($e->getMessage(),'','');
  518. }
  519. }
  520. // Extract title from an HTML document.
  521. // (Returns an empty string if not found.)
  522. function html_extract_title($html)
  523. {
  524. return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ;
  525. }
  526. // ------------------------------------------------------------------------------------------
  527. // Token management for XSRF protection
  528. // Token should be used in any form which acts on data (create,update,delete,import...).
  529. if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
  530. // Returns a token.
  531. function getToken()
  532. {
  533. $rnd = sha1(uniqid('',true).'_'.mt_rand().$GLOBALS['salt']); // We generate a random string.
  534. $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
  535. return $rnd;
  536. }
  537. // Tells if a token is ok. Using this function will destroy the token.
  538. // true=token is ok.
  539. function tokenOk($token)
  540. {
  541. if (isset($_SESSION['tokens'][$token]))
  542. {
  543. unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
  544. return true; // Token is ok.
  545. }
  546. return false; // Wrong token, or already used.
  547. }
  548. // ------------------------------------------------------------------------------------------
  549. /* This class is in charge of building the final page.
  550. (This is basically a wrapper around RainTPL which pre-fills some fields.)
  551. p = new pageBuilder;
  552. p.assign('myfield','myvalue');
  553. p.renderPage('mytemplate');
  554. */
  555. class pageBuilder
  556. {
  557. private $tpl; // RainTPL template
  558. function __construct()
  559. {
  560. $this->tpl=false;
  561. }
  562. private function initialize()
  563. {
  564. $this->tpl = new RainTPL;
  565. $this->tpl->assign('newversion',checkUpdate());
  566. $this->tpl->assign('feedurl',htmlspecialchars(indexUrl()));
  567. $searchcrits=''; // Search criteria
  568. if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.urlencode($_GET['searchtags']);
  569. elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.urlencode($_GET['searchterm']);
  570. $this->tpl->assign('searchcrits',$searchcrits);
  571. $this->tpl->assign('source',indexUrl());
  572. $this->tpl->assign('version',shaarli_version);
  573. $this->tpl->assign('scripturl',indexUrl());
  574. $this->tpl->assign('pagetitle','Shaarli');
  575. $this->tpl->assign('privateonly',!empty($_SESSION['privateonly'])); // Show only private links ?
  576. if (!empty($GLOBALS['title'])) $this->tpl->assign('pagetitle',$GLOBALS['title']);
  577. if (!empty($GLOBALS['pagetitle'])) $this->tpl->assign('pagetitle',$GLOBALS['pagetitle']);
  578. $this->tpl->assign('shaarlititle',empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title'] );
  579. return;
  580. }
  581. // The following assign() method is basically the same as RainTPL (except that it's lazy)
  582. public function assign($what,$where)
  583. {
  584. if ($this->tpl===false) $this->initialize(); // Lazy initialization
  585. $this->tpl->assign($what,$where);
  586. }
  587. // Render a specific page (using a template).
  588. // eg. pb.renderPage('picwall')
  589. public function renderPage($page)
  590. {
  591. if ($this->tpl===false) $this->initialize(); // Lazy initialization
  592. $this->tpl->draw($page);
  593. }
  594. }
  595. // ------------------------------------------------------------------------------------------
  596. /* Data storage for links.
  597. This object behaves like an associative array.
  598. Example:
  599. $mylinks = new linkdb();
  600. echo $mylinks['20110826_161819']['title'];
  601. foreach($mylinks as $link)
  602. echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
  603. Available keys:
  604. title : Title of the link
  605. url : URL of the link. Can be absolute or relative. Relative URLs are permalinks (eg.'?m-ukcw')
  606. description : description of the entry
  607. private : Is this link private ? 0=no, other value=yes
  608. linkdate : date of the creation of this entry, in the form YYYYMMDD_HHMMSS (eg.'20110914_192317')
  609. tags : tags attached to this entry (separated by spaces)
  610. We implement 3 interfaces:
  611. - ArrayAccess so that this object behaves like an associative array.
  612. - Iterator so that this object can be used in foreach() loops.
  613. - Countable interface so that we can do a count() on this object.
  614. */
  615. class linkdb implements Iterator, Countable, ArrayAccess
  616. {
  617. private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
  618. private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
  619. private $keys; // List of linkdate keys (for the Iterator interface implementation)
  620. private $position; // Position in the $this->keys array. (for the Iterator interface implementation.)
  621. private $loggedin; // Is the used logged in ? (used to filter private links)
  622. // Constructor:
  623. function __construct($isLoggedIn)
  624. // Input : $isLoggedIn : is the used logged in ?
  625. {
  626. $this->loggedin = $isLoggedIn;
  627. $this->checkdb(); // Make sure data file exists.
  628. $this->readdb(); // Then read it.
  629. }
  630. // ---- Countable interface implementation
  631. public function count() { return count($this->links); }
  632. // ---- ArrayAccess interface implementation
  633. public function offsetSet($offset, $value)
  634. {
  635. if (!$this->loggedin) die('You are not authorized to add a link.');
  636. if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.');
  637. if (empty($offset)) die('You must specify a key.');
  638. $this->links[$offset] = $value;
  639. $this->urls[$value['url']]=$offset;
  640. }
  641. public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
  642. public function offsetUnset($offset)
  643. {
  644. if (!$this->loggedin) die('You are not authorized to delete a link.');
  645. $url = $this->links[$offset]['url']; unset($this->urls[$url]);
  646. unset($this->links[$offset]);
  647. }
  648. public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
  649. // ---- Iterator interface implementation
  650. function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
  651. function key() { return $this->keys[$this->position]; } // current key
  652. function current() { return $this->links[$this->keys[$this->position]]; } // current value
  653. function next() { ++$this->position; } // go to next item
  654. function valid() { return isset($this->keys[$this->position]); } // Check if current position is valid.
  655. // ---- Misc methods
  656. private function checkdb() // Check if db directory and file exists.
  657. {
  658. if (!file_exists($GLOBALS['config']['DATASTORE'])) // Create a dummy database for example.
  659. {
  660. $this->links = array();
  661. $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');
  662. $this->links[$link['linkdate']] = $link;
  663. $link = array('title'=>'My secret stuff... - Pastebin.com','url'=>'http://pastebin.com/smCEEeSn','description'=>'SShhhh!! I\'m a private link only YOU can see. You can delete me too.','private'=>1,'linkdate'=>'20110914_074522','tags'=>'secretstuff');
  664. $this->links[$link['linkdate']] = $link;
  665. file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
  666. }
  667. }
  668. // Read database from disk to memory
  669. private function readdb()
  670. {
  671. // Read data
  672. $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
  673. // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
  674. // If user is not logged in, filter private links.
  675. if (!$this->loggedin)
  676. {
  677. $toremove=array();
  678. foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
  679. foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
  680. }
  681. // Keep the list of the mapping URLs-->linkdate up-to-date.
  682. $this->urls=array();
  683. foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
  684. }
  685. // Save database from memory to disk.
  686. public function savedb()
  687. {
  688. if (!$this->loggedin) die('You are not authorized to change the database.');
  689. file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
  690. invalidateCaches();
  691. }
  692. // Returns the link for a given URL (if it exists). false it does not exist.
  693. public function getLinkFromUrl($url)
  694. {
  695. if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
  696. return false;
  697. }
  698. // Case insentitive search among links (in url, title and description). Returns filtered list of links.
  699. // eg. print_r($mydb->filterFulltext('hollandais'));
  700. public function filterFulltext($searchterms)
  701. {
  702. // FIXME: explode(' ',$searchterms) and perform a AND search.
  703. // FIXME: accept double-quotes to search for a string "as is" ?
  704. $filtered=array();
  705. $s = strtolower($searchterms);
  706. foreach($this->links as $l)
  707. {
  708. $found= (strpos(strtolower($l['title']),$s)!==false)
  709. || (strpos(strtolower($l['description']),$s)!==false)
  710. || (strpos(strtolower($l['url']),$s)!==false)
  711. || (strpos(strtolower($l['tags']),$s)!==false);
  712. if ($found) $filtered[$l['linkdate']] = $l;
  713. }
  714. krsort($filtered);
  715. return $filtered;
  716. }
  717. // Filter by tag.
  718. // You can specify one or more tags (tags can be separated by space or comma).
  719. // eg. print_r($mydb->filterTags('linux programming'));
  720. public function filterTags($tags,$casesensitive=false)
  721. {
  722. $t = str_replace(',',' ',($casesensitive?$tags:strtolower($tags)));
  723. $searchtags=explode(' ',$t);
  724. $filtered=array();
  725. foreach($this->links as $l)
  726. {
  727. $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags'])));
  728. if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
  729. $filtered[$l['linkdate']] = $l;
  730. }
  731. krsort($filtered);
  732. return $filtered;
  733. }
  734. // Filter by day. Day must be in the form 'YYYYMMDD' (eg. '20120125')
  735. // Sort order is: older articles first.
  736. // eg. print_r($mydb->filterDay('20120125'));
  737. public function filterDay($day)
  738. {
  739. $filtered=array();
  740. foreach($this->links as $l)
  741. {
  742. if (startsWith($l['linkdate'],$day)) $filtered[$l['linkdate']] = $l;
  743. }
  744. ksort($filtered);
  745. return $filtered;
  746. }
  747. // Filter by smallHash.
  748. // Only 1 article is returned.
  749. public function filterSmallHash($smallHash)
  750. {
  751. $filtered=array();
  752. foreach($this->links as $l)
  753. {
  754. if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
  755. {
  756. $filtered[$l['linkdate']] = $l;
  757. return $filtered;
  758. }
  759. }
  760. return $filtered;
  761. }
  762. // Returns the list of all tags
  763. // Output: associative array key=tags, value=0
  764. public function allTags()
  765. {
  766. $tags=array();
  767. foreach($this->links as $link)
  768. foreach(explode(' ',$link['tags']) as $tag)
  769. if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
  770. arsort($tags); // Sort tags by usage (most used tag first)
  771. return $tags;
  772. }
  773. // Returns the list of days containing articles (oldest first)
  774. // Output: An array containing days (in format YYYYMMDD).
  775. public function days()
  776. {
  777. $linkdays=array();
  778. foreach(array_keys($this->links) as $day)
  779. {
  780. $linkdays[substr($day,0,8)]=0;
  781. }
  782. $linkdays=array_keys($linkdays);
  783. sort($linkdays);
  784. return $linkdays;
  785. }
  786. }
  787. // ------------------------------------------------------------------------------------------
  788. // Ouput the last 50 links in RSS 2.0 format.
  789. function showRSS()
  790. {
  791. header('Content-Type: application/rss+xml; charset=utf-8');
  792. // $usepermalink : If true, use permalink instead of final link.
  793. // User just has to add 'permalink' in URL parameters. eg. http://mysite.com/shaarli/?do=rss&permalinks
  794. $usepermalinks = isset($_GET['permalinks']);
  795. // Cache system
  796. $query = $_SERVER["QUERY_STRING"];
  797. $cache = new pageCache(pageUrl(),startsWith($query,'do=rss') && !isLoggedIn());
  798. $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
  799. // If cached was not found (or not usable), then read the database and build the response:
  800. $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
  801. // Optionnaly filter the results:
  802. $linksToDisplay=array();
  803. if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
  804. elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
  805. else $linksToDisplay = $LINKSDB;
  806. $pageaddr=htmlspecialchars(indexUrl());
  807. echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
  808. echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>';
  809. echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
  810. if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
  811. {
  812. echo '<!-- PubSubHubbub Discovery -->';
  813. echo '<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" xmlns="http://www.w3.org/2005/Atom" />';
  814. echo '<link rel="self" href="'.htmlspecialchars($pageaddr).'?do=rss" xmlns="http://www.w3.org/2005/Atom" />';
  815. echo '<!-- End Of PubSubHubbub Discovery -->';
  816. }
  817. $i=0;
  818. $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
  819. while ($i<50 && $i<count($keys))
  820. {
  821. $link = $linksToDisplay[$keys[$i]];
  822. $guid = $pageaddr.'?'.smallHash($link['linkdate']);
  823. $rfc822date = linkdate2rfc822($link['linkdate']);
  824. $absurl = htmlspecialchars($link['url']);
  825. if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
  826. if ($usepermalinks===true)
  827. echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid isPermaLink="false">'.$guid.'</guid><link>'.$guid.'</link>';
  828. else
  829. echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid isPermaLink="false">'.$guid.'</guid><link>'.$absurl.'</link>';
  830. if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date)."</pubDate>\n";
  831. if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
  832. {
  833. foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.htmlspecialchars($pageaddr).'">'.htmlspecialchars($tag).'</category>'."\n"; }
  834. }
  835. // Add permalink in description
  836. $descriptionlink = '(<a href="'.$guid.'">Permalink</a>)';
  837. // If user wants permalinks first, put the final link in description
  838. if ($usepermalinks===true) $descriptionlink = '(<a href="'.$absurl.'">Link</a>)';
  839. if (strlen($link['description'])>0) $descriptionlink = '<br>'.$descriptionlink;
  840. echo '<description><![CDATA['.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description'])))).$descriptionlink.']]></description>'."\n</item>\n";
  841. $i++;
  842. }
  843. echo '</channel></rss><!-- Cached version of '.pageUrl().' -->';
  844. $cache->cache(ob_get_contents());
  845. ob_end_flush();
  846. exit;
  847. }
  848. // ------------------------------------------------------------------------------------------
  849. // Ouput the last 50 links in ATOM format.
  850. function showATOM()
  851. {
  852. header('Content-Type: application/atom+xml; charset=utf-8');
  853. // $usepermalink : If true, use permalink instead of final link.
  854. // User just has to add 'permalink' in URL parameters. eg. http://mysite.com/shaarli/?do=atom&permalinks
  855. $usepermalinks = isset($_GET['permalinks']);
  856. // Cache system
  857. $query = $_SERVER["QUERY_STRING"];
  858. $cache = new pageCache(pageUrl(),startsWith($query,'do=atom') && !isLoggedIn());
  859. $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
  860. // If cached was not found (or not usable), then read the database and build the response:
  861. $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
  862. // Optionnaly filter the results:
  863. $linksToDisplay=array();
  864. if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
  865. elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
  866. else $linksToDisplay = $LINKSDB;
  867. $pageaddr=htmlspecialchars(indexUrl());
  868. $latestDate = '';
  869. $entries='';
  870. $i=0;
  871. $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
  872. while ($i<50 && $i<count($keys))
  873. {
  874. $link = $linksToDisplay[$keys[$i]];
  875. $guid = $pageaddr.'?'.smallHash($link['linkdate']);
  876. $iso8601date = linkdate2iso8601($link['linkdate']);
  877. $latestDate = max($latestDate,$iso8601date);
  878. $absurl = htmlspecialchars($link['url']);
  879. if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
  880. $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title>';
  881. if ($usepermalinks===true)
  882. $entries.='<link href="'.$guid.'" /><id>'.$guid.'</id>';
  883. else
  884. $entries.='<link href="'.$absurl.'" /><id>'.$guid.'</id>';
  885. if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>';
  886. // Add permalink in description
  887. $descriptionlink = htmlspecialchars('(<a href="'.$guid.'">Permalink</a>)');
  888. // If user wants permalinks first, put the final link in description
  889. if ($usepermalinks===true) $descriptionlink = htmlspecialchars('(<a href="'.$absurl.'">Link</a>)');
  890. if (strlen($link['description'])>0) $descriptionlink = '&lt;br&gt;'.$descriptionlink;
  891. $entries.='<content type="html">'.htmlspecialchars(nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))))).$descriptionlink."</content>\n";
  892. if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification)
  893. {
  894. foreach(explode(' ',$link['tags']) as $tag)
  895. { $entries.='<category scheme="'.htmlspecialchars($pageaddr,ENT_QUOTES).'" term="'.htmlspecialchars($tag,ENT_QUOTES).'" />'."\n"; }
  896. }
  897. $entries.="</entry>\n";
  898. $i++;
  899. }
  900. $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
  901. $feed.='<title>'.htmlspecialchars($GLOBALS['title']).'</title>';
  902. if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.htmlspecialchars($latestDate).'</updated>';
  903. $feed.='<link rel="self" href="'.htmlspecialchars(serverUrl().$_SERVER["REQUEST_URI"]).'" />';
  904. if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
  905. {
  906. $feed.='<!-- PubSubHubbub Discovery -->';
  907. $feed.='<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" />';
  908. $feed.='<!-- End Of PubSubHubbub Discovery -->';
  909. }
  910. $feed.='<author><name>'.htmlspecialchars($pageaddr).'</name><uri>'.htmlspecialchars($pageaddr).'</uri></author>';
  911. $feed.='<id>'.htmlspecialchars($pageaddr).'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
  912. $feed.=$entries;
  913. $feed.='</feed><!-- Cached version of '.pageUrl().' -->';
  914. echo $feed;
  915. $cache->cache(ob_get_contents());
  916. ob_end_flush();
  917. exit;
  918. }
  919. // ------------------------------------------------------------------------------------------
  920. // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
  921. // Gives the last 7 days (which have links).
  922. // This RSS feed cannot be filtered.
  923. function showDailyRSS()
  924. {
  925. // Cache system
  926. $query = $_SERVER["QUERY_STRING"];
  927. $cache = new pageCache(pageUrl(),startsWith($query,'do=dailyrss') && !isLoggedIn());
  928. $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
  929. // If cached was not found (or not usable), then read the database and build the response:
  930. $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
  931. /* Some Shaarlies may have very few links, so we need to look
  932. back in time (rsort()) until we have enough days ($nb_of_days).
  933. */
  934. $linkdates=array(); foreach($LINKSDB as $linkdate=>$value) { $linkdates[]=$linkdate; }
  935. rsort($linkdates);
  936. $nb_of_days=7; // We take 7 days.
  937. $today=Date('Ymd');
  938. $days=array();
  939. foreach($linkdates as $linkdate)
  940. {
  941. $day=substr($linkdate,0,8); // Extract day (without time)
  942. if (strcmp($day,$today)<0)
  943. {
  944. if (empty($days[$day])) $days[$day]=array();
  945. $day

Large files files are truncated, but you can click here to view the full file