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