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