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