index.php 103 KB

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