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