index.php 88 KB

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