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