]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Merge pull request #666 from ArthurHoaro/slim-api
[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 $shortUrl = $LINKSDB[$id]['shorturl'];
1249 } else {
1250 // New link
1251 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1252 $updated = null;
1253 $shortUrl = link_small_hash($created, $id);
1254 }
1255
1256 // Remove multiple spaces.
1257 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1258 // Remove first '-' char in tags.
1259 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1260 // Remove duplicates.
1261 $tags = implode(' ', array_unique(explode(' ', $tags)));
1262
1263 $url = trim($_POST['lf_url']);
1264 if (! startsWith($url, 'http:') && ! startsWith($url, 'https:')
1265 && ! startsWith($url, 'ftp:') && ! startsWith($url, 'magnet:')
1266 && ! startsWith($url, '?') && ! startsWith($url, 'javascript:')
1267 ) {
1268 $url = 'http://' . $url;
1269 }
1270
1271 $link = array(
1272 'id' => $id,
1273 'title' => trim($_POST['lf_title']),
1274 'url' => $url,
1275 'description' => $_POST['lf_description'],
1276 'private' => (isset($_POST['lf_private']) ? 1 : 0),
1277 'created' => $created,
1278 'updated' => $updated,
1279 'tags' => str_replace(',', ' ', $tags),
1280 'shorturl' => $shortUrl,
1281 );
1282
1283 // If title is empty, use the URL as title.
1284 if ($link['title'] == '') {
1285 $link['title'] = $link['url'];
1286 }
1287
1288 $pluginManager->executeHooks('save_link', $link);
1289
1290 $LINKSDB[$id] = $link;
1291 $LINKSDB->save($conf->get('resource.page_cache'));
1292 pubsubhub($conf);
1293
1294 // If we are called from the bookmarklet, we must close the popup:
1295 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1296 echo '<script>self.close();</script>';
1297 exit;
1298 }
1299
1300 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
1301 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1302 // Scroll to the link which has been edited.
1303 $location .= '#' . $link['shorturl'];
1304 // After saving the link, redirect to the page the user was on.
1305 header('Location: '. $location);
1306 exit;
1307 }
1308
1309 // -------- User clicked the "Cancel" button when editing a link.
1310 if (isset($_POST['cancel_edit']))
1311 {
1312 // If we are called from the bookmarklet, we must close the popup:
1313 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1314 $link = $LINKSDB[(int) escape($_POST['lf_id'])];
1315 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1316 // Scroll to the link which has been edited.
1317 $returnurl .= '#'. $link['shorturl'];
1318 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1319 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1320 exit;
1321 }
1322
1323 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1324 if (isset($_POST['delete_link']))
1325 {
1326 if (!tokenOk($_POST['token'])) die('Wrong token.');
1327
1328 // We do not need to ask for confirmation:
1329 // - confirmation is handled by JavaScript
1330 // - we are protected from XSRF by the token.
1331
1332 // FIXME! We keep `lf_linkdate` for consistency before a proper API. To be removed.
1333 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : intval(escape($_POST['lf_linkdate']));
1334
1335 $pluginManager->executeHooks('delete_link', $LINKSDB[$id]);
1336
1337 unset($LINKSDB[$id]);
1338 $LINKSDB->save('resource.page_cache'); // save to disk
1339
1340 // If we are called from the bookmarklet, we must close the popup:
1341 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1342 // Pick where we're going to redirect
1343 // =============================================================
1344 // Basically, we can't redirect to where we were previously if it was a permalink
1345 // or an edit_link, because it would 404.
1346 // Cases:
1347 // - / : nothing in $_GET, redirect to self
1348 // - /?page : redirect to self
1349 // - /?searchterm : redirect to self (there might be other links)
1350 // - /?searchtags : redirect to self
1351 // - /permalink : redirect to / (the link does not exist anymore)
1352 // - /?edit_link : redirect to / (the link does not exist anymore)
1353 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1354 // redirect is not satisfied, and only then redirect to /
1355 $location = "?";
1356 // Self redirection
1357 if (count($_GET) == 0
1358 || isset($_GET['page'])
1359 || isset($_GET['searchterm'])
1360 || isset($_GET['searchtags'])
1361 ) {
1362 if (isset($_POST['returnurl'])) {
1363 $location = $_POST['returnurl']; // Handle redirects given by the form
1364 } else {
1365 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('delete_link'));
1366 }
1367 }
1368
1369 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1370 exit;
1371 }
1372
1373 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1374 if (isset($_GET['edit_link']))
1375 {
1376 $id = (int) escape($_GET['edit_link']);
1377 $link = $LINKSDB[$id]; // Read database
1378 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1379 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1380 $data = array(
1381 'link' => $link,
1382 'link_is_new' => false,
1383 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1384 'tags' => $LINKSDB->allTags(),
1385 );
1386 $pluginManager->executeHooks('render_editlink', $data);
1387
1388 foreach ($data as $key => $value) {
1389 $PAGE->assign($key, $value);
1390 }
1391
1392 $PAGE->renderPage('editlink');
1393 exit;
1394 }
1395
1396 // -------- User want to post a new link: Display link edit form.
1397 if (isset($_GET['post'])) {
1398 $url = cleanup_url($_GET['post']);
1399
1400 $link_is_new = false;
1401 // Check if URL is not already in database (in this case, we will edit the existing link)
1402 $link = $LINKSDB->getLinkFromUrl($url);
1403 if (! $link)
1404 {
1405 $link_is_new = true;
1406 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
1407 // Get title if it was provided in URL (by the bookmarklet).
1408 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1409 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1410 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1411 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1412 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1413 // 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.)
1414 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1415 // Short timeout to keep the application responsive
1416 list($headers, $content) = get_http_response($url, 4);
1417 if (strpos($headers[0], '200 OK') !== false) {
1418 // Retrieve charset.
1419 $charset = get_charset($headers, $content);
1420 // Extract title.
1421 $title = html_extract_title($content);
1422 // Re-encode title in utf-8 if necessary.
1423 if (! empty($title) && strtolower($charset) != 'utf-8') {
1424 $title = mb_convert_encoding($title, 'utf-8', $charset);
1425 }
1426 }
1427 }
1428
1429 if ($url == '') {
1430 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1431 $title = 'Note: ';
1432 }
1433 $url = escape($url);
1434 $title = escape($title);
1435
1436 $link = array(
1437 'linkdate' => $linkdate,
1438 'title' => $title,
1439 'url' => $url,
1440 'description' => $description,
1441 'tags' => $tags,
1442 'private' => $private
1443 );
1444 } else {
1445 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1446 }
1447
1448 $data = array(
1449 'link' => $link,
1450 'link_is_new' => $link_is_new,
1451 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1452 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1453 'tags' => $LINKSDB->allTags(),
1454 'default_private_links' => $conf->get('privacy.default_private_links', false),
1455 );
1456 $pluginManager->executeHooks('render_editlink', $data);
1457
1458 foreach ($data as $key => $value) {
1459 $PAGE->assign($key, $value);
1460 }
1461
1462 $PAGE->renderPage('editlink');
1463 exit;
1464 }
1465
1466 if ($targetPage == Router::$PAGE_EXPORT) {
1467 // Export links as a Netscape Bookmarks file
1468
1469 if (empty($_GET['selection'])) {
1470 $PAGE->renderPage('export');
1471 exit;
1472 }
1473
1474 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1475 $selection = $_GET['selection'];
1476 if (isset($_GET['prepend_note_url'])) {
1477 $prependNoteUrl = $_GET['prepend_note_url'];
1478 } else {
1479 $prependNoteUrl = false;
1480 }
1481
1482 try {
1483 $PAGE->assign(
1484 'links',
1485 NetscapeBookmarkUtils::filterAndFormat(
1486 $LINKSDB,
1487 $selection,
1488 $prependNoteUrl,
1489 index_url($_SERVER)
1490 )
1491 );
1492 } catch (Exception $exc) {
1493 header('Content-Type: text/plain; charset=utf-8');
1494 echo $exc->getMessage();
1495 exit;
1496 }
1497 $now = new DateTime();
1498 header('Content-Type: text/html; charset=utf-8');
1499 header(
1500 'Content-disposition: attachment; filename=bookmarks_'
1501 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1502 );
1503 $PAGE->assign('date', $now->format(DateTime::RFC822));
1504 $PAGE->assign('eol', PHP_EOL);
1505 $PAGE->assign('selection', $selection);
1506 $PAGE->renderPage('export.bookmarks');
1507 exit;
1508 }
1509
1510 if ($targetPage == Router::$PAGE_IMPORT) {
1511 // Upload a Netscape bookmark dump to import its contents
1512
1513 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1514 // Show import dialog
1515 $PAGE->assign('maxfilesize', getMaxFileSize());
1516 $PAGE->renderPage('import');
1517 exit;
1518 }
1519
1520 // Import bookmarks from an uploaded file
1521 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1522 // The file is too big or some form field may be missing.
1523 echo '<script>alert("The file you are trying to upload is probably'
1524 .' bigger than what this webserver can accept ('
1525 .getMaxFileSize().' bytes).'
1526 .' Please upload in smaller chunks.");document.location=\'?do='
1527 .Router::$PAGE_IMPORT .'\';</script>';
1528 exit;
1529 }
1530 if (! tokenOk($_POST['token'])) {
1531 die('Wrong token.');
1532 }
1533 $status = NetscapeBookmarkUtils::import(
1534 $_POST,
1535 $_FILES,
1536 $LINKSDB,
1537 $conf->get('resource.page_cache')
1538 );
1539 echo '<script>alert("'.$status.'");document.location=\'?do='
1540 .Router::$PAGE_IMPORT .'\';</script>';
1541 exit;
1542 }
1543
1544 // Plugin administration page
1545 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1546 $pluginMeta = $pluginManager->getPluginsMeta();
1547
1548 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1549 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
1550 // Load parameters.
1551 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1552 uasort(
1553 $enabledPlugins,
1554 function($a, $b) { return $a['order'] - $b['order']; }
1555 );
1556 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
1557
1558 $PAGE->assign('enabledPlugins', $enabledPlugins);
1559 $PAGE->assign('disabledPlugins', $disabledPlugins);
1560 $PAGE->renderPage('pluginsadmin');
1561 exit;
1562 }
1563
1564 // Plugin administration form action
1565 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1566 try {
1567 if (isset($_POST['parameters_form'])) {
1568 unset($_POST['parameters_form']);
1569 foreach ($_POST as $param => $value) {
1570 $conf->set('plugins.'. $param, escape($value));
1571 }
1572 }
1573 else {
1574 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1575 }
1576 $conf->write(isLoggedIn());
1577 }
1578 catch (Exception $e) {
1579 error_log(
1580 'ERROR while saving plugin configuration:.' . PHP_EOL .
1581 $e->getMessage()
1582 );
1583
1584 // TODO: do not handle exceptions/errors in JS.
1585 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
1586 exit;
1587 }
1588 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1589 exit;
1590 }
1591
1592 // -------- Otherwise, simply display search form and links:
1593 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1594 exit;
1595 }
1596
1597 /**
1598 * Template for the list of links (<div id="linklist">)
1599 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1600 *
1601 * @param pageBuilder $PAGE pageBuilder instance.
1602 * @param LinkDB $LINKSDB LinkDB instance.
1603 * @param ConfigManager $conf Configuration Manager instance.
1604 * @param PluginManager $pluginManager Plugin Manager instance.
1605 */
1606 function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
1607 {
1608 // Used in templates
1609 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
1610 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
1611
1612 // Smallhash filter
1613 if (! empty($_SERVER['QUERY_STRING'])
1614 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1615 try {
1616 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1617 } catch (LinkNotFoundException $e) {
1618 $PAGE->render404($e->getMessage());
1619 exit;
1620 }
1621 } else {
1622 // Filter links according search parameters.
1623 $privateonly = !empty($_SESSION['privateonly']);
1624 $linksToDisplay = $LINKSDB->filterSearch($_GET, false, $privateonly);
1625 }
1626
1627 // ---- Handle paging.
1628 $keys = array();
1629 foreach ($linksToDisplay as $key => $value) {
1630 $keys[] = $key;
1631 }
1632
1633
1634
1635 // Select articles according to paging.
1636 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1637 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1638 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1639 $page = $page < 1 ? 1 : $page;
1640 $page = $page > $pagecount ? $pagecount : $page;
1641 // Start index.
1642 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1643 $end = $i + $_SESSION['LINKS_PER_PAGE'];
1644 $linkDisp = array();
1645 while ($i<$end && $i<count($keys))
1646 {
1647 $link = $linksToDisplay[$keys[$i]];
1648 $link['description'] = format_description($link['description'], $conf->get('redirector.url'));
1649 $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
1650 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1651 $link['timestamp'] = $link['created']->getTimestamp();
1652 if (! empty($link['updated'])) {
1653 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1654 } else {
1655 $link['updated_timestamp'] = '';
1656 }
1657 $taglist = explode(' ', $link['tags']);
1658 uasort($taglist, 'strcasecmp');
1659 $link['taglist'] = $taglist;
1660 // Check for both signs of a note: starting with ? and 7 chars long.
1661 if ($link['url'][0] === '?' &&
1662 strlen($link['url']) === 7) {
1663 $link['url'] = index_url($_SERVER) . $link['url'];
1664 }
1665
1666 $linkDisp[$keys[$i]] = $link;
1667 $i++;
1668 }
1669
1670 // Compute paging navigation
1671 $searchtagsUrl = empty($searchtags) ? '' : '&searchtags=' . urlencode($searchtags);
1672 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1673 $previous_page_url = '';
1674 if ($i != count($keys)) {
1675 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
1676 }
1677 $next_page_url='';
1678 if ($page>1) {
1679 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1680 }
1681
1682 // Fill all template fields.
1683 $data = array(
1684 'previous_page_url' => $previous_page_url,
1685 'next_page_url' => $next_page_url,
1686 'page_current' => $page,
1687 'page_max' => $pagecount,
1688 'result_count' => count($linksToDisplay),
1689 'search_term' => $searchterm,
1690 'search_tags' => $searchtags,
1691 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1692 'links' => $linkDisp,
1693 'tags' => $LINKSDB->allTags(),
1694 );
1695
1696 // If there is only a single link, we change on-the-fly the title of the page.
1697 if (count($linksToDisplay) == 1) {
1698 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1699 }
1700
1701 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
1702
1703 foreach ($data as $key => $value) {
1704 $PAGE->assign($key, $value);
1705 }
1706
1707 return;
1708 }
1709
1710 /**
1711 * Compute the thumbnail for a link.
1712 *
1713 * With a link to the original URL.
1714 * Understands various services (youtube.com...)
1715 * Input: $url = URL for which the thumbnail must be found.
1716 * $href = if provided, this URL will be followed instead of $url
1717 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1718 * Some of them may be missing.
1719 * Return an empty array if no thumbnail available.
1720 *
1721 * @param ConfigManager $conf Configuration Manager instance.
1722 * @param string $url
1723 * @param string|bool $href
1724 *
1725 * @return array
1726 */
1727 function computeThumbnail($conf, $url, $href = false)
1728 {
1729 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1730 if ($href==false) $href=$url;
1731
1732 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1733 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1734 // ^^^^^^^^^^^ ^^^^^^^^^^^
1735 $domain = parse_url($url,PHP_URL_HOST);
1736 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1737 {
1738 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
1739 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
1740 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1741 }
1742 if ($domain=='youtu.be') // Youtube short links
1743 {
1744 $path = parse_url($url,PHP_URL_PATH);
1745 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
1746 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1747 }
1748 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1749 {
1750 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract image filename.
1751 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
1752 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1753 }
1754
1755 if ($domain=='imgur.com')
1756 {
1757 $path = parse_url($url,PHP_URL_PATH);
1758 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1759 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
1760 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1761 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
1762 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1763
1764 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
1765 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1766 }
1767 if ($domain=='i.imgur.com')
1768 {
1769 $pi = pathinfo(parse_url($url,PHP_URL_PATH));
1770 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
1771 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1772 }
1773 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1774 {
1775 if (strpos($url,'dailymotion.com/video/')!==false)
1776 {
1777 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1778 return array('src'=>$thumburl,
1779 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1780 }
1781 }
1782 if (endsWith($domain,'.imageshack.us'))
1783 {
1784 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1785 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1786 {
1787 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1788 return array('src'=>$thumburl,
1789 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1790 }
1791 }
1792
1793 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1794 // So we deport the thumbnail generation in order not to slow down page generation
1795 // (and we also cache the thumbnail)
1796
1797 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1798
1799 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1800 || $domain=='vimeo.com'
1801 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1802 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1803 )
1804 {
1805 if ($domain=='vimeo.com')
1806 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1807 $path = parse_url($url,PHP_URL_PATH);
1808 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1809 }
1810 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
1811 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1812 $path = parse_url($url,PHP_URL_PATH);
1813 if (!preg_match('!/\d+.+?!',$path)) return array();
1814 }
1815 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1816 { // Make sure this TED URL points to a video (/talks/...)
1817 $path = parse_url($url,PHP_URL_PATH);
1818 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1819 }
1820 $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)
1821 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1822 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1823 }
1824
1825 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1826 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1827 // But using the extension will do.
1828 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1829 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1830 {
1831 $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)
1832 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1833 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1834 }
1835 return array(); // No thumbnail.
1836
1837 }
1838
1839
1840 // Returns the HTML code to display a thumbnail for a link
1841 // with a link to the original URL.
1842 // Understands various services (youtube.com...)
1843 // Input: $url = URL for which the thumbnail must be found.
1844 // $href = if provided, this URL will be followed instead of $url
1845 // Returns '' if no thumbnail available.
1846 function thumbnail($url,$href=false)
1847 {
1848 // FIXME!
1849 global $conf;
1850 $t = computeThumbnail($conf, $url,$href);
1851 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1852
1853 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1854 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1855 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1856 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1857 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1858 $html.='></a>';
1859 return $html;
1860 }
1861
1862 // Returns the HTML code to display a thumbnail for a link
1863 // for the picture wall (using lazy image loading)
1864 // Understands various services (youtube.com...)
1865 // Input: $url = URL for which the thumbnail must be found.
1866 // $href = if provided, this URL will be followed instead of $url
1867 // Returns '' if no thumbnail available.
1868 function lazyThumbnail($conf, $url,$href=false)
1869 {
1870 // FIXME!
1871 global $conf;
1872 $t = computeThumbnail($conf, $url,$href);
1873 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1874
1875 $html='<a href="'.escape($t['href']).'">';
1876
1877 // Lazy image
1878 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1879
1880 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1881 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1882 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1883 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1884 $html.='>';
1885
1886 // No-JavaScript fallback.
1887 $html.='<noscript><img src="'.escape($t['src']).'"';
1888 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1889 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1890 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1891 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1892 $html.='></noscript></a>';
1893
1894 return $html;
1895 }
1896
1897
1898 /**
1899 * Installation
1900 * This function should NEVER be called if the file data/config.php exists.
1901 *
1902 * @param ConfigManager $conf Configuration Manager instance.
1903 */
1904 function install($conf)
1905 {
1906 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1907 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1908
1909
1910 // This part makes sure sessions works correctly.
1911 // (Because on some hosts, session.save_path may not be set correctly,
1912 // or we may not have write access to it.)
1913 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1914 { // Step 2: Check if data in session is correct.
1915 echo '<pre>Sessions do not seem to work correctly on your server.<br>';
1916 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>';
1917 echo 'It currently points to '.session_save_path().'<br>';
1918 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>';
1919 echo '<br><a href="?">Click to try again.</a></pre>';
1920 die;
1921 }
1922 if (!isset($_SESSION['session_tested']))
1923 { // Step 1 : Try to store data in session and reload page.
1924 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1925 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1926 }
1927 if (isset($_GET['test_session']))
1928 { // Step 3: Sessions are OK. Remove test parameter from URL.
1929 header('Location: '.index_url($_SERVER));
1930 }
1931
1932
1933 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1934 {
1935 $tz = 'UTC';
1936 if (!empty($_POST['continent']) && !empty($_POST['city'])
1937 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1938 ) {
1939 $tz = $_POST['continent'].'/'.$_POST['city'];
1940 }
1941 $conf->set('general.timezone', $tz);
1942 $login = $_POST['setlogin'];
1943 $conf->set('credentials.login', $login);
1944 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1945 $conf->set('credentials.salt', $salt);
1946 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1947 if (!empty($_POST['title'])) {
1948 $conf->set('general.title', escape($_POST['title']));
1949 } else {
1950 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1951 }
1952 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1953 $conf->set('api.enabled', !empty($_POST['enableApi']));
1954 $conf->set(
1955 'api.secret',
1956 generate_api_secret(
1957 $this->conf->get('credentials.login'),
1958 $this->conf->get('credentials.salt')
1959 )
1960 );
1961 try {
1962 // Everything is ok, let's create config file.
1963 $conf->write(isLoggedIn());
1964 }
1965 catch(Exception $e) {
1966 error_log(
1967 'ERROR while writing config file after installation.' . PHP_EOL .
1968 $e->getMessage()
1969 );
1970
1971 // TODO: do not handle exceptions/errors in JS.
1972 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1973 exit;
1974 }
1975 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1976 exit;
1977 }
1978
1979 // Display config form:
1980 list($timezone_form, $timezone_js) = generateTimeZoneForm();
1981 $timezone_html = '';
1982 if ($timezone_form != '') {
1983 $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
1984 }
1985
1986 $PAGE = new PageBuilder($conf);
1987 $PAGE->assign('timezone_html',$timezone_html);
1988 $PAGE->assign('timezone_js',$timezone_js);
1989 $PAGE->renderPage('install');
1990 exit;
1991 }
1992
1993 /**
1994 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1995 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1996 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1997 * This function is called by passing the URL:
1998 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1999 * [URL] is the URL of the link (e.g. a flickr page)
2000 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2001 * The function below will fetch the image from the webservice and store it in the cache.
2002 *
2003 * @param ConfigManager $conf Configuration Manager instance,
2004 */
2005 function genThumbnail($conf)
2006 {
2007 // Make sure the parameters in the URL were generated by us.
2008 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
2009 if ($sign!=$_GET['hmac']) die('Naughty boy!');
2010
2011 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
2012 // Let's see if we don't already have the image for this URL in the cache.
2013 $thumbname=hash('sha1',$_GET['url']).'.jpg';
2014 if (is_file($cacheDir .'/'. $thumbname))
2015 { // We have the thumbnail, just serve it:
2016 header('Content-Type: image/jpeg');
2017 echo file_get_contents($cacheDir .'/'. $thumbname);
2018 return;
2019 }
2020 // We may also serve a blank image (if service did not respond)
2021 $blankname=hash('sha1',$_GET['url']).'.gif';
2022 if (is_file($cacheDir .'/'. $blankname))
2023 {
2024 header('Content-Type: image/gif');
2025 echo file_get_contents($cacheDir .'/'. $blankname);
2026 return;
2027 }
2028
2029 // Otherwise, generate the thumbnail.
2030 $url = $_GET['url'];
2031 $domain = parse_url($url,PHP_URL_HOST);
2032
2033 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
2034 {
2035 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2036 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
2037
2038 // Is this a link to an image, or to a flickr page ?
2039 $imageurl='';
2040 if (endsWith(parse_url($url, PHP_URL_PATH), '.jpg'))
2041 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2042 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
2043 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
2044 }
2045 else // This is a flickr page (html)
2046 {
2047 // Get the flickr html page.
2048 list($headers, $content) = get_http_response($url, 20);
2049 if (strpos($headers[0], '200 OK') !== false)
2050 {
2051 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2052 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
2053 if (!empty($matches[1])) $imageurl=$matches[1];
2054
2055 // In albums (and some other pages), the link rel="image_src" is not provided,
2056 // but flickr provides:
2057 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2058 if ($imageurl=='')
2059 {
2060 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
2061 if (!empty($matches[1])) $imageurl=$matches[1];
2062 }
2063 }
2064 }
2065
2066 if ($imageurl!='')
2067 { // Let's download the image.
2068 // Image is 240x120, so 10 seconds to download should be enough.
2069 list($headers, $content) = get_http_response($imageurl, 10);
2070 if (strpos($headers[0], '200 OK') !== false) {
2071 // Save image to cache.
2072 file_put_contents($cacheDir .'/'. $thumbname, $content);
2073 header('Content-Type: image/jpeg');
2074 echo $content;
2075 return;
2076 }
2077 }
2078 }
2079
2080 elseif ($domain=='vimeo.com' )
2081 {
2082 // This is more complex: we have to perform a HTTP request, then parse the result.
2083 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2084 $vid = substr(parse_url($url,PHP_URL_PATH),1);
2085 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2086 if (strpos($headers[0], '200 OK') !== false) {
2087 $t = unserialize($content);
2088 $imageurl = $t[0]['thumbnail_medium'];
2089 // Then we download the image and serve it to our client.
2090 list($headers, $content) = get_http_response($imageurl, 10);
2091 if (strpos($headers[0], '200 OK') !== false) {
2092 // Save image to cache.
2093 file_put_contents($cacheDir .'/'. $thumbname, $content);
2094 header('Content-Type: image/jpeg');
2095 echo $content;
2096 return;
2097 }
2098 }
2099 }
2100
2101 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2102 {
2103 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2104 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2105 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2106 list($headers, $content) = get_http_response($url, 5);
2107 if (strpos($headers[0], '200 OK') !== false) {
2108 // Extract the link to the thumbnail
2109 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2110 if (!empty($matches[1]))
2111 { // Let's download the image.
2112 $imageurl=$matches[1];
2113 // No control on image size, so wait long enough
2114 list($headers, $content) = get_http_response($imageurl, 20);
2115 if (strpos($headers[0], '200 OK') !== false) {
2116 $filepath = $cacheDir .'/'. $thumbname;
2117 file_put_contents($filepath, $content); // Save image to cache.
2118 if (resizeImage($filepath))
2119 {
2120 header('Content-Type: image/jpeg');
2121 echo file_get_contents($filepath);
2122 return;
2123 }
2124 }
2125 }
2126 }
2127 }
2128
2129 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2130 {
2131 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2132 // http://xkcd.com/327/
2133 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2134 list($headers, $content) = get_http_response($url, 5);
2135 if (strpos($headers[0], '200 OK') !== false) {
2136 // Extract the link to the thumbnail
2137 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2138 if (!empty($matches[1]))
2139 { // Let's download the image.
2140 $imageurl=$matches[1];
2141 // No control on image size, so wait long enough
2142 list($headers, $content) = get_http_response($imageurl, 20);
2143 if (strpos($headers[0], '200 OK') !== false) {
2144 $filepath = $cacheDir.'/'.$thumbname;
2145 // Save image to cache.
2146 file_put_contents($filepath, $content);
2147 if (resizeImage($filepath))
2148 {
2149 header('Content-Type: image/jpeg');
2150 echo file_get_contents($filepath);
2151 return;
2152 }
2153 }
2154 }
2155 }
2156 }
2157
2158 else
2159 {
2160 // For all other domains, we try to download the image and make a thumbnail.
2161 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2162 list($headers, $content) = get_http_response($url, 30);
2163 if (strpos($headers[0], '200 OK') !== false) {
2164 $filepath = $cacheDir .'/'.$thumbname;
2165 // Save image to cache.
2166 file_put_contents($filepath, $content);
2167 if (resizeImage($filepath))
2168 {
2169 header('Content-Type: image/jpeg');
2170 echo file_get_contents($filepath);
2171 return;
2172 }
2173 }
2174 }
2175
2176
2177 // Otherwise, return an empty image (8x8 transparent gif)
2178 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2179 // Also put something in cache so that this URL is not requested twice.
2180 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2181 header('Content-Type: image/gif');
2182 echo $blankgif;
2183 }
2184
2185 // Make a thumbnail of the image (to width: 120 pixels)
2186 // Returns true if success, false otherwise.
2187 function resizeImage($filepath)
2188 {
2189 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2190
2191 // Trick: some stupid people rename GIF as JPEG... or else.
2192 // So we really try to open each image type whatever the extension is.
2193 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2194 $im=false;
2195 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2196 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2197 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2198 if (!$im) return false; // Unable to open image (corrupted or not an image)
2199 $w = imagesx($im);
2200 $h = imagesy($im);
2201 $ystart = 0; $yheight=$h;
2202 if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
2203 $nw = 120; // Desired width
2204 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2205 // Resize image:
2206 $im2 = imagecreatetruecolor($nw,$nh);
2207 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2208 imageinterlace($im2,true); // For progressive JPEG.
2209 $tempname=$filepath.'_TEMP.jpg';
2210 imagejpeg($im2, $tempname, 90);
2211 imagedestroy($im);
2212 imagedestroy($im2);
2213 unlink($filepath);
2214 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2215 return true;
2216 }
2217
2218 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
2219 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
2220 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2221 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2222 }
2223
2224 $linkDb = new LinkDB(
2225 $conf->get('resource.datastore'),
2226 isLoggedIn(),
2227 $conf->get('privacy.hide_public_links'),
2228 $conf->get('redirector.url'),
2229 $conf->get('redirector.encode_url')
2230 );
2231
2232 $container = new \Slim\Container();
2233 $container['conf'] = $conf;
2234 $container['plugins'] = $pluginManager;
2235 $app = new \Slim\App($container);
2236
2237 // REST API routes
2238 $app->group('/api/v1', function() {
2239 $this->get('/info', '\Api\Controllers\Info:getInfo');
2240 })->add('\Api\ApiMiddleware');
2241
2242 $response = $app->run(true);
2243 // Hack to make Slim and Shaarli router work together:
2244 // If a Slim route isn't found, we call renderPage().
2245 if ($response->getStatusCode() == 404) {
2246 // We use UTF-8 for proper international characters handling.
2247 header('Content-Type: text/html; charset=utf-8');
2248 renderPage($conf, $pluginManager, $linkDb);
2249 } else {
2250 $app->respond($response);
2251 }