index.php 86 KB

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