index.php 87 KB

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