]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Move tag renaming code to LinkDB and unit test it
[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 * @param History $history instance
689 */
690 function renderPage($conf, $pluginManager, $LINKSDB, $history)
691 {
692 $updater = new Updater(
693 read_updates_file($conf->get('resource.updates')),
694 $LINKSDB,
695 $conf,
696 isLoggedIn()
697 );
698 try {
699 $newUpdates = $updater->update();
700 if (! empty($newUpdates)) {
701 write_updates_file(
702 $conf->get('resource.updates'),
703 $updater->getDoneUpdates()
704 );
705 }
706 }
707 catch(Exception $e) {
708 die($e->getMessage());
709 }
710
711 $PAGE = new PageBuilder($conf, $LINKSDB);
712 $PAGE->assign('linkcount', count($LINKSDB));
713 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
714 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
715
716 // Determine which page will be rendered.
717 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
718 $targetPage = Router::findPage($query, $_GET, isLoggedIn());
719
720 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
721 // Then assign generated data to RainTPL.
722 $common_hooks = array(
723 'includes',
724 'header',
725 'footer',
726 );
727
728 foreach($common_hooks as $name) {
729 $plugin_data = array();
730 $pluginManager->executeHooks('render_' . $name, $plugin_data,
731 array(
732 'target' => $targetPage,
733 'loggedin' => isLoggedIn()
734 )
735 );
736 $PAGE->assign('plugins_' . $name, $plugin_data);
737 }
738
739 // -------- Display login form.
740 if ($targetPage == Router::$PAGE_LOGIN)
741 {
742 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
743 if (isset($_GET['username'])) {
744 $PAGE->assign('username', escape($_GET['username']));
745 }
746 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
747 $PAGE->renderPage('loginform');
748 exit;
749 }
750 // -------- User wants to logout.
751 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
752 {
753 invalidateCaches($conf->get('resource.page_cache'));
754 logout();
755 header('Location: ?');
756 exit;
757 }
758
759 // -------- Picture wall
760 if ($targetPage == Router::$PAGE_PICWALL)
761 {
762 // Optionally filter the results:
763 $links = $LINKSDB->filterSearch($_GET);
764 $linksToDisplay = array();
765
766 // Get only links which have a thumbnail.
767 foreach($links as $link)
768 {
769 $permalink='?'.$link['shorturl'];
770 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
771 if ($thumb!='') // Only output links which have a thumbnail.
772 {
773 $link['thumbnail']=$thumb; // Thumbnail HTML code.
774 $linksToDisplay[]=$link; // Add to array.
775 }
776 }
777
778 $data = array(
779 'linksToDisplay' => $linksToDisplay,
780 );
781 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
782
783 foreach ($data as $key => $value) {
784 $PAGE->assign($key, $value);
785 }
786
787 $PAGE->renderPage('picwall');
788 exit;
789 }
790
791 // -------- Tag cloud
792 if ($targetPage == Router::$PAGE_TAGCLOUD)
793 {
794 $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
795 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
796 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
797
798 // We sort tags alphabetically, then choose a font size according to count.
799 // First, find max value.
800 $maxcount = 0;
801 foreach ($tags as $value) {
802 $maxcount = max($maxcount, $value);
803 }
804
805 alphabetical_sort($tags, true, true);
806
807 $tagList = array();
808 foreach($tags as $key => $value) {
809 // Tag font size scaling:
810 // default 15 and 30 logarithm bases affect scaling,
811 // 22 and 6 are arbitrary font sizes for max and min sizes.
812 $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
813 $tagList[$key] = array(
814 'count' => $value,
815 'size' => number_format($size, 2, '.', ''),
816 );
817 }
818
819 $data = array(
820 'search_tags' => implode(' ', $filteringTags),
821 'tags' => $tagList,
822 );
823 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
824
825 foreach ($data as $key => $value) {
826 $PAGE->assign($key, $value);
827 }
828
829 $PAGE->renderPage('tag.cloud');
830 exit;
831 }
832
833 // -------- Tag cloud
834 if ($targetPage == Router::$PAGE_TAGLIST)
835 {
836 $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
837 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
838 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
839
840 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
841 alphabetical_sort($tags, false, true);
842 }
843
844 $data = [
845 'search_tags' => implode(' ', $filteringTags),
846 'tags' => $tags,
847 ];
848 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => isLoggedIn()]);
849
850 foreach ($data as $key => $value) {
851 $PAGE->assign($key, $value);
852 }
853
854 $PAGE->renderPage('tag.list');
855 exit;
856 }
857
858 // Daily page.
859 if ($targetPage == Router::$PAGE_DAILY) {
860 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
861 }
862
863 // ATOM and RSS feed.
864 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
865 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
866 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
867
868 // Cache system
869 $query = $_SERVER['QUERY_STRING'];
870 $cache = new CachedPage(
871 $conf->get('resource.page_cache'),
872 page_url($_SERVER),
873 startsWith($query,'do='. $targetPage) && !isLoggedIn()
874 );
875 $cached = $cache->cachedVersion();
876 if (!empty($cached)) {
877 echo $cached;
878 exit;
879 }
880
881 // Generate data.
882 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn());
883 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
884 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !isLoggedIn());
885 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
886 $data = $feedGenerator->buildData();
887
888 // Process plugin hook.
889 $pluginManager->executeHooks('render_feed', $data, array(
890 'loggedin' => isLoggedIn(),
891 'target' => $targetPage,
892 ));
893
894 // Render the template.
895 $PAGE->assignAll($data);
896 $PAGE->renderPage('feed.'. $feedType);
897 $cache->cache(ob_get_contents());
898 ob_end_flush();
899 exit;
900 }
901
902 // Display opensearch plugin (XML)
903 if ($targetPage == Router::$PAGE_OPENSEARCH) {
904 header('Content-Type: application/xml; charset=utf-8');
905 $PAGE->assign('serverurl', index_url($_SERVER));
906 $PAGE->renderPage('opensearch');
907 exit;
908 }
909
910 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
911 if (isset($_GET['addtag']))
912 {
913 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
914 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
915 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
916
917 // Prevent redirection loop
918 if (isset($params['addtag'])) {
919 unset($params['addtag']);
920 }
921
922 // Check if this tag is already in the search query and ignore it if it is.
923 // Each tag is always separated by a space
924 if (isset($params['searchtags'])) {
925 $current_tags = explode(' ', $params['searchtags']);
926 } else {
927 $current_tags = array();
928 }
929 $addtag = true;
930 foreach ($current_tags as $value) {
931 if ($value === $_GET['addtag']) {
932 $addtag = false;
933 break;
934 }
935 }
936 // Append the tag if necessary
937 if (empty($params['searchtags'])) {
938 $params['searchtags'] = trim($_GET['addtag']);
939 }
940 else if ($addtag) {
941 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
942 }
943
944 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
945 header('Location: ?'.http_build_query($params));
946 exit;
947 }
948
949 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
950 if (isset($_GET['removetag'])) {
951 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
952 if (empty($_SERVER['HTTP_REFERER'])) {
953 header('Location: ?');
954 exit;
955 }
956
957 // In case browser does not send HTTP_REFERER
958 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
959
960 // Prevent redirection loop
961 if (isset($params['removetag'])) {
962 unset($params['removetag']);
963 }
964
965 if (isset($params['searchtags'])) {
966 $tags = explode(' ', $params['searchtags']);
967 // Remove value from array $tags.
968 $tags = array_diff($tags, array($_GET['removetag']));
969 $params['searchtags'] = implode(' ',$tags);
970
971 if (empty($params['searchtags'])) {
972 unset($params['searchtags']);
973 }
974
975 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
976 }
977 header('Location: ?'.http_build_query($params));
978 exit;
979 }
980
981 // -------- User wants to change the number of links per page (linksperpage=...)
982 if (isset($_GET['linksperpage'])) {
983 if (is_numeric($_GET['linksperpage'])) {
984 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
985 }
986
987 if (! empty($_SERVER['HTTP_REFERER'])) {
988 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
989 } else {
990 $location = '?';
991 }
992 header('Location: '. $location);
993 exit;
994 }
995
996 // -------- User wants to see only private links (toggle)
997 if (isset($_GET['privateonly'])) {
998 if (empty($_SESSION['privateonly'])) {
999 $_SESSION['privateonly'] = 1; // See only private links
1000 } else {
1001 unset($_SESSION['privateonly']); // See all links
1002 }
1003
1004 if (! empty($_SERVER['HTTP_REFERER'])) {
1005 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('privateonly'));
1006 } else {
1007 $location = '?';
1008 }
1009 header('Location: '. $location);
1010 exit;
1011 }
1012
1013 // -------- Handle other actions allowed for non-logged in users:
1014 if (!isLoggedIn())
1015 {
1016 // User tries to post new link but is not logged in:
1017 // Show login screen, then redirect to ?post=...
1018 if (isset($_GET['post']))
1019 {
1020 header( // Redirect to login page, then back to post link.
1021 'Location: ?do=login&post='.urlencode($_GET['post']).
1022 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
1023 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
1024 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
1025 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
1026 );
1027 exit;
1028 }
1029
1030 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1031 if (isset($_GET['edit_link'])) {
1032 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
1033 exit;
1034 }
1035
1036 exit; // Never remove this one! All operations below are reserved for logged in user.
1037 }
1038
1039 // -------- All other functions are reserved for the registered user:
1040
1041 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1042 if ($targetPage == Router::$PAGE_TOOLS)
1043 {
1044 $data = array(
1045 'pageabsaddr' => index_url($_SERVER),
1046 'sslenabled' => !empty($_SERVER['HTTPS'])
1047 );
1048 $pluginManager->executeHooks('render_tools', $data);
1049
1050 foreach ($data as $key => $value) {
1051 $PAGE->assign($key, $value);
1052 }
1053
1054 $PAGE->renderPage('tools');
1055 exit;
1056 }
1057
1058 // -------- User wants to change his/her password.
1059 if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
1060 {
1061 if ($conf->get('security.open_shaarli')) {
1062 die('You are not supposed to change a password on an Open Shaarli.');
1063 }
1064
1065 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
1066 {
1067 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away!
1068
1069 // Make sure old password is correct.
1070 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
1071 if ($oldhash!= $conf->get('credentials.hash')) { echo '<script>alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
1072 // Save new password
1073 // Salt renders rainbow-tables attacks useless.
1074 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
1075 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
1076 try {
1077 $conf->write(isLoggedIn());
1078 }
1079 catch(Exception $e) {
1080 error_log(
1081 'ERROR while writing config file after changing password.' . PHP_EOL .
1082 $e->getMessage()
1083 );
1084
1085 // TODO: do not handle exceptions/errors in JS.
1086 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1087 exit;
1088 }
1089 echo '<script>alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
1090 exit;
1091 }
1092 else // show the change password form.
1093 {
1094 $PAGE->renderPage('changepassword');
1095 exit;
1096 }
1097 }
1098
1099 // -------- User wants to change configuration
1100 if ($targetPage == Router::$PAGE_CONFIGURE)
1101 {
1102 if (!empty($_POST['title']) )
1103 {
1104 if (!tokenOk($_POST['token'])) {
1105 die('Wrong token.'); // Go away!
1106 }
1107 $tz = 'UTC';
1108 if (!empty($_POST['continent']) && !empty($_POST['city'])
1109 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1110 ) {
1111 $tz = $_POST['continent'] . '/' . $_POST['city'];
1112 }
1113 $conf->set('general.timezone', $tz);
1114 $conf->set('general.title', escape($_POST['title']));
1115 $conf->set('general.header_link', escape($_POST['titleLink']));
1116 $conf->set('resource.theme', escape($_POST['theme']));
1117 $conf->set('redirector.url', escape($_POST['redirector']));
1118 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1119 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1120 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1121 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1122 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1123 $conf->set('api.enabled', !empty($_POST['enableApi']));
1124 $conf->set('api.secret', escape($_POST['apiSecret']));
1125 try {
1126 $conf->write(isLoggedIn());
1127 $history->updateSettings();
1128 invalidateCaches($conf->get('resource.page_cache'));
1129 }
1130 catch(Exception $e) {
1131 error_log(
1132 'ERROR while writing config file after configuration update.' . PHP_EOL .
1133 $e->getMessage()
1134 );
1135
1136 // TODO: do not handle exceptions/errors in JS.
1137 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1138 exit;
1139 }
1140 echo '<script>alert("Configuration was saved.");document.location=\'?do=configure\';</script>';
1141 exit;
1142 }
1143 else // Show the configuration form.
1144 {
1145 $PAGE->assign('title', $conf->get('general.title'));
1146 $PAGE->assign('theme', $conf->get('resource.theme'));
1147 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
1148 $PAGE->assign('redirector', $conf->get('redirector.url'));
1149 list($continents, $cities) = generateTimeZoneData(
1150 timezone_identifiers_list(),
1151 $conf->get('general.timezone')
1152 );
1153 $PAGE->assign('continents', $continents);
1154 $PAGE->assign('cities', $cities);
1155 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1156 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1157 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1158 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1159 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1160 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1161 $PAGE->assign('api_secret', $conf->get('api.secret'));
1162 $PAGE->renderPage('configure');
1163 exit;
1164 }
1165 }
1166
1167 // -------- User wants to rename a tag or delete it
1168 if ($targetPage == Router::$PAGE_CHANGETAG)
1169 {
1170 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1171 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1172 $PAGE->renderPage('changetag');
1173 exit;
1174 }
1175
1176 if (!tokenOk($_POST['token'])) {
1177 die('Wrong token.');
1178 }
1179
1180 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1181 $LINKSDB->save($conf->get('resource.page_cache'));
1182 foreach ($alteredLinks as $link) {
1183 $history->updateLink($link);
1184 }
1185 $delete = empty($_POST['totag']);
1186 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1187 $alert = $delete
1188 ? sprintf(t('The tag was removed from %d links.'), count($alteredLinks))
1189 : sprintf(t('The tag was renamed in %d links.'), count($alteredLinks));
1190 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1191 exit;
1192 }
1193
1194 // -------- User wants to add a link without using the bookmarklet: Show form.
1195 if ($targetPage == Router::$PAGE_ADDLINK)
1196 {
1197 $PAGE->renderPage('addlink');
1198 exit;
1199 }
1200
1201 // -------- User clicked the "Save" button when editing a link: Save link to database.
1202 if (isset($_POST['save_edit']))
1203 {
1204 // Go away!
1205 if (! tokenOk($_POST['token'])) {
1206 die('Wrong token.');
1207 }
1208
1209 // lf_id should only be present if the link exists.
1210 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1211 // Linkdate is kept here to:
1212 // - use the same permalink for notes as they're displayed when creating them
1213 // - let users hack creation date of their posts
1214 // See: https://github.com/shaarli/Shaarli/wiki/Datastore-hacks#changing-the-timestamp-for-a-link
1215 $linkdate = escape($_POST['lf_linkdate']);
1216 if (isset($LINKSDB[$id])) {
1217 // Edit
1218 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1219 $updated = new DateTime();
1220 $shortUrl = $LINKSDB[$id]['shorturl'];
1221 $new = false;
1222 } else {
1223 // New link
1224 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1225 $updated = null;
1226 $shortUrl = link_small_hash($created, $id);
1227 $new = true;
1228 }
1229
1230 // Remove multiple spaces.
1231 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1232 // Remove first '-' char in tags.
1233 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1234 // Remove duplicates.
1235 $tags = implode(' ', array_unique(explode(' ', $tags)));
1236
1237 $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
1238
1239 $link = array(
1240 'id' => $id,
1241 'title' => trim($_POST['lf_title']),
1242 'url' => $url,
1243 'description' => $_POST['lf_description'],
1244 'private' => (isset($_POST['lf_private']) ? 1 : 0),
1245 'created' => $created,
1246 'updated' => $updated,
1247 'tags' => str_replace(',', ' ', $tags),
1248 'shorturl' => $shortUrl,
1249 );
1250
1251 // If title is empty, use the URL as title.
1252 if ($link['title'] == '') {
1253 $link['title'] = $link['url'];
1254 }
1255
1256 $pluginManager->executeHooks('save_link', $link);
1257
1258 $LINKSDB[$id] = $link;
1259 $LINKSDB->save($conf->get('resource.page_cache'));
1260 if ($new) {
1261 $history->addLink($link);
1262 } else {
1263 $history->updateLink($link);
1264 }
1265
1266 // If we are called from the bookmarklet, we must close the popup:
1267 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1268 echo '<script>self.close();</script>';
1269 exit;
1270 }
1271
1272 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
1273 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1274 // Scroll to the link which has been edited.
1275 $location .= '#' . $link['shorturl'];
1276 // After saving the link, redirect to the page the user was on.
1277 header('Location: '. $location);
1278 exit;
1279 }
1280
1281 // -------- User clicked the "Cancel" button when editing a link.
1282 if (isset($_POST['cancel_edit']))
1283 {
1284 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1285 if (! isset($LINKSDB[$id])) {
1286 header('Location: ?');
1287 }
1288 // If we are called from the bookmarklet, we must close the popup:
1289 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1290 $link = $LINKSDB[$id];
1291 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1292 // Scroll to the link which has been edited.
1293 $returnurl .= '#'. $link['shorturl'];
1294 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1295 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1296 exit;
1297 }
1298
1299 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1300 if ($targetPage == Router::$PAGE_DELETELINK)
1301 {
1302 if (! tokenOk($_GET['token'])) {
1303 die('Wrong token.');
1304 }
1305
1306 if (strpos($_GET['lf_linkdate'], ' ') !== false) {
1307 $ids = array_values(array_filter(preg_split('/\s+/', escape($_GET['lf_linkdate']))));
1308 } else {
1309 $ids = [$_GET['lf_linkdate']];
1310 }
1311 foreach ($ids as $id) {
1312 $id = (int) escape($id);
1313 $link = $LINKSDB[$id];
1314 $pluginManager->executeHooks('delete_link', $link);
1315 unset($LINKSDB[$id]);
1316 }
1317 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1318 $history->deleteLink($link);
1319
1320 // If we are called from the bookmarklet, we must close the popup:
1321 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1322
1323 $location = '?';
1324 if (isset($_SERVER['HTTP_REFERER'])) {
1325 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1326 $location = generateLocation(
1327 $_SERVER['HTTP_REFERER'],
1328 $_SERVER['HTTP_HOST'],
1329 ['delete_link', 'edit_link', $link['shorturl']]
1330 );
1331 }
1332
1333 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1334 exit;
1335 }
1336
1337 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1338 if (isset($_GET['edit_link']))
1339 {
1340 $id = (int) escape($_GET['edit_link']);
1341 $link = $LINKSDB[$id]; // Read database
1342 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1343 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1344 $data = array(
1345 'link' => $link,
1346 'link_is_new' => false,
1347 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1348 'tags' => $LINKSDB->linksCountPerTag(),
1349 );
1350 $pluginManager->executeHooks('render_editlink', $data);
1351
1352 foreach ($data as $key => $value) {
1353 $PAGE->assign($key, $value);
1354 }
1355
1356 $PAGE->renderPage('editlink');
1357 exit;
1358 }
1359
1360 // -------- User want to post a new link: Display link edit form.
1361 if (isset($_GET['post'])) {
1362 $url = cleanup_url($_GET['post']);
1363
1364 $link_is_new = false;
1365 // Check if URL is not already in database (in this case, we will edit the existing link)
1366 $link = $LINKSDB->getLinkFromUrl($url);
1367 if (! $link)
1368 {
1369 $link_is_new = true;
1370 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
1371 // Get title if it was provided in URL (by the bookmarklet).
1372 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1373 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1374 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1375 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1376 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1377 // 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.)
1378 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1379 // Short timeout to keep the application responsive
1380 list($headers, $content) = get_http_response($url, 4);
1381 if (strpos($headers[0], '200 OK') !== false) {
1382 // Retrieve charset.
1383 $charset = get_charset($headers, $content);
1384 // Extract title.
1385 $title = html_extract_title($content);
1386 // Re-encode title in utf-8 if necessary.
1387 if (! empty($title) && strtolower($charset) != 'utf-8') {
1388 $title = mb_convert_encoding($title, 'utf-8', $charset);
1389 }
1390 }
1391 }
1392
1393 if ($url == '') {
1394 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1395 $title = 'Note: ';
1396 }
1397 $url = escape($url);
1398 $title = escape($title);
1399
1400 $link = array(
1401 'linkdate' => $linkdate,
1402 'title' => $title,
1403 'url' => $url,
1404 'description' => $description,
1405 'tags' => $tags,
1406 'private' => $private,
1407 );
1408 } else {
1409 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1410 }
1411
1412 $data = array(
1413 'link' => $link,
1414 'link_is_new' => $link_is_new,
1415 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1416 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1417 'tags' => $LINKSDB->linksCountPerTag(),
1418 'default_private_links' => $conf->get('privacy.default_private_links', false),
1419 );
1420 $pluginManager->executeHooks('render_editlink', $data);
1421
1422 foreach ($data as $key => $value) {
1423 $PAGE->assign($key, $value);
1424 }
1425
1426 $PAGE->renderPage('editlink');
1427 exit;
1428 }
1429
1430 if ($targetPage == Router::$PAGE_EXPORT) {
1431 // Export links as a Netscape Bookmarks file
1432
1433 if (empty($_GET['selection'])) {
1434 $PAGE->renderPage('export');
1435 exit;
1436 }
1437
1438 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1439 $selection = $_GET['selection'];
1440 if (isset($_GET['prepend_note_url'])) {
1441 $prependNoteUrl = $_GET['prepend_note_url'];
1442 } else {
1443 $prependNoteUrl = false;
1444 }
1445
1446 try {
1447 $PAGE->assign(
1448 'links',
1449 NetscapeBookmarkUtils::filterAndFormat(
1450 $LINKSDB,
1451 $selection,
1452 $prependNoteUrl,
1453 index_url($_SERVER)
1454 )
1455 );
1456 } catch (Exception $exc) {
1457 header('Content-Type: text/plain; charset=utf-8');
1458 echo $exc->getMessage();
1459 exit;
1460 }
1461 $now = new DateTime();
1462 header('Content-Type: text/html; charset=utf-8');
1463 header(
1464 'Content-disposition: attachment; filename=bookmarks_'
1465 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1466 );
1467 $PAGE->assign('date', $now->format(DateTime::RFC822));
1468 $PAGE->assign('eol', PHP_EOL);
1469 $PAGE->assign('selection', $selection);
1470 $PAGE->renderPage('export.bookmarks');
1471 exit;
1472 }
1473
1474 if ($targetPage == Router::$PAGE_IMPORT) {
1475 // Upload a Netscape bookmark dump to import its contents
1476
1477 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1478 // Show import dialog
1479 $PAGE->assign(
1480 'maxfilesize',
1481 get_max_upload_size(
1482 ini_get('post_max_size'),
1483 ini_get('upload_max_filesize'),
1484 false
1485 )
1486 );
1487 $PAGE->assign(
1488 'maxfilesizeHuman',
1489 get_max_upload_size(
1490 ini_get('post_max_size'),
1491 ini_get('upload_max_filesize'),
1492 true
1493 )
1494 );
1495 $PAGE->renderPage('import');
1496 exit;
1497 }
1498
1499 // Import bookmarks from an uploaded file
1500 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1501 // The file is too big or some form field may be missing.
1502 echo '<script>alert("The file you are trying to upload is probably'
1503 .' bigger than what this webserver can accept ('
1504 .get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize')).').'
1505 .' Please upload in smaller chunks.");document.location=\'?do='
1506 .Router::$PAGE_IMPORT .'\';</script>';
1507 exit;
1508 }
1509 if (! tokenOk($_POST['token'])) {
1510 die('Wrong token.');
1511 }
1512 $status = NetscapeBookmarkUtils::import(
1513 $_POST,
1514 $_FILES,
1515 $LINKSDB,
1516 $conf,
1517 $history
1518 );
1519 echo '<script>alert("'.$status.'");document.location=\'?do='
1520 .Router::$PAGE_IMPORT .'\';</script>';
1521 exit;
1522 }
1523
1524 // Plugin administration page
1525 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1526 $pluginMeta = $pluginManager->getPluginsMeta();
1527
1528 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1529 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
1530 // Load parameters.
1531 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1532 uasort(
1533 $enabledPlugins,
1534 function($a, $b) { return $a['order'] - $b['order']; }
1535 );
1536 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
1537
1538 $PAGE->assign('enabledPlugins', $enabledPlugins);
1539 $PAGE->assign('disabledPlugins', $disabledPlugins);
1540 $PAGE->renderPage('pluginsadmin');
1541 exit;
1542 }
1543
1544 // Plugin administration form action
1545 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1546 try {
1547 if (isset($_POST['parameters_form'])) {
1548 unset($_POST['parameters_form']);
1549 foreach ($_POST as $param => $value) {
1550 $conf->set('plugins.'. $param, escape($value));
1551 }
1552 }
1553 else {
1554 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1555 }
1556 $conf->write(isLoggedIn());
1557 $history->updateSettings();
1558 }
1559 catch (Exception $e) {
1560 error_log(
1561 'ERROR while saving plugin configuration:.' . PHP_EOL .
1562 $e->getMessage()
1563 );
1564
1565 // TODO: do not handle exceptions/errors in JS.
1566 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
1567 exit;
1568 }
1569 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1570 exit;
1571 }
1572
1573 // Get a fresh token
1574 if ($targetPage == Router::$GET_TOKEN) {
1575 header('Content-Type:text/plain');
1576 echo getToken($conf);
1577 exit;
1578 }
1579
1580 // -------- Otherwise, simply display search form and links:
1581 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1582 exit;
1583 }
1584
1585 /**
1586 * Template for the list of links (<div id="linklist">)
1587 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1588 *
1589 * @param pageBuilder $PAGE pageBuilder instance.
1590 * @param LinkDB $LINKSDB LinkDB instance.
1591 * @param ConfigManager $conf Configuration Manager instance.
1592 * @param PluginManager $pluginManager Plugin Manager instance.
1593 */
1594 function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
1595 {
1596 // Used in templates
1597 if (isset($_GET['searchtags'])) {
1598 if (! empty($_GET['searchtags'])) {
1599 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1600 } else {
1601 $searchtags = false;
1602 }
1603 } else {
1604 $searchtags = '';
1605 }
1606 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1607
1608 // Smallhash filter
1609 if (! empty($_SERVER['QUERY_STRING'])
1610 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1611 try {
1612 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1613 } catch (LinkNotFoundException $e) {
1614 $PAGE->render404($e->getMessage());
1615 exit;
1616 }
1617 } else {
1618 // Filter links according search parameters.
1619 $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
1620 $request = [
1621 'searchtags' => $searchtags,
1622 'searchterm' => $searchterm,
1623 ];
1624 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility);
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 = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY);
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 = $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 'visibility' => ! empty($_SESSION['privateonly']) ? 'private' : '',
1692 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1693 'links' => $linkDisp,
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 $conf->get('credentials.login'),
1958 $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 $PAGE = new PageBuilder($conf);
1980 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1981 $PAGE->assign('continents', $continents);
1982 $PAGE->assign('cities', $cities);
1983 $PAGE->renderPage('install');
1984 exit;
1985 }
1986
1987 /**
1988 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1989 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1990 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1991 * This function is called by passing the URL:
1992 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1993 * [URL] is the URL of the link (e.g. a flickr page)
1994 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1995 * The function below will fetch the image from the webservice and store it in the cache.
1996 *
1997 * @param ConfigManager $conf Configuration Manager instance,
1998 */
1999 function genThumbnail($conf)
2000 {
2001 // Make sure the parameters in the URL were generated by us.
2002 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
2003 if ($sign!=$_GET['hmac']) die('Naughty boy!');
2004
2005 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
2006 // Let's see if we don't already have the image for this URL in the cache.
2007 $thumbname=hash('sha1',$_GET['url']).'.jpg';
2008 if (is_file($cacheDir .'/'. $thumbname))
2009 { // We have the thumbnail, just serve it:
2010 header('Content-Type: image/jpeg');
2011 echo file_get_contents($cacheDir .'/'. $thumbname);
2012 return;
2013 }
2014 // We may also serve a blank image (if service did not respond)
2015 $blankname=hash('sha1',$_GET['url']).'.gif';
2016 if (is_file($cacheDir .'/'. $blankname))
2017 {
2018 header('Content-Type: image/gif');
2019 echo file_get_contents($cacheDir .'/'. $blankname);
2020 return;
2021 }
2022
2023 // Otherwise, generate the thumbnail.
2024 $url = $_GET['url'];
2025 $domain = parse_url($url,PHP_URL_HOST);
2026
2027 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
2028 {
2029 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2030 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
2031
2032 // Is this a link to an image, or to a flickr page ?
2033 $imageurl='';
2034 if (endsWith(parse_url($url, PHP_URL_PATH), '.jpg'))
2035 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2036 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
2037 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
2038 }
2039 else // This is a flickr page (html)
2040 {
2041 // Get the flickr html page.
2042 list($headers, $content) = get_http_response($url, 20);
2043 if (strpos($headers[0], '200 OK') !== false)
2044 {
2045 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2046 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
2047 if (!empty($matches[1])) $imageurl=$matches[1];
2048
2049 // In albums (and some other pages), the link rel="image_src" is not provided,
2050 // but flickr provides:
2051 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2052 if ($imageurl=='')
2053 {
2054 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
2055 if (!empty($matches[1])) $imageurl=$matches[1];
2056 }
2057 }
2058 }
2059
2060 if ($imageurl!='')
2061 { // Let's download the image.
2062 // Image is 240x120, so 10 seconds to download should be enough.
2063 list($headers, $content) = get_http_response($imageurl, 10);
2064 if (strpos($headers[0], '200 OK') !== false) {
2065 // Save image to cache.
2066 file_put_contents($cacheDir .'/'. $thumbname, $content);
2067 header('Content-Type: image/jpeg');
2068 echo $content;
2069 return;
2070 }
2071 }
2072 }
2073
2074 elseif ($domain=='vimeo.com' )
2075 {
2076 // This is more complex: we have to perform a HTTP request, then parse the result.
2077 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2078 $vid = substr(parse_url($url,PHP_URL_PATH),1);
2079 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2080 if (strpos($headers[0], '200 OK') !== false) {
2081 $t = unserialize($content);
2082 $imageurl = $t[0]['thumbnail_medium'];
2083 // Then we download the image and serve it to our client.
2084 list($headers, $content) = get_http_response($imageurl, 10);
2085 if (strpos($headers[0], '200 OK') !== false) {
2086 // Save image to cache.
2087 file_put_contents($cacheDir .'/'. $thumbname, $content);
2088 header('Content-Type: image/jpeg');
2089 echo $content;
2090 return;
2091 }
2092 }
2093 }
2094
2095 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2096 {
2097 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2098 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2099 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2100 list($headers, $content) = get_http_response($url, 5);
2101 if (strpos($headers[0], '200 OK') !== false) {
2102 // Extract the link to the thumbnail
2103 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2104 if (!empty($matches[1]))
2105 { // Let's download the image.
2106 $imageurl=$matches[1];
2107 // No control on image size, so wait long enough
2108 list($headers, $content) = get_http_response($imageurl, 20);
2109 if (strpos($headers[0], '200 OK') !== false) {
2110 $filepath = $cacheDir .'/'. $thumbname;
2111 file_put_contents($filepath, $content); // Save image to cache.
2112 if (resizeImage($filepath))
2113 {
2114 header('Content-Type: image/jpeg');
2115 echo file_get_contents($filepath);
2116 return;
2117 }
2118 }
2119 }
2120 }
2121 }
2122
2123 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2124 {
2125 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2126 // http://xkcd.com/327/
2127 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2128 list($headers, $content) = get_http_response($url, 5);
2129 if (strpos($headers[0], '200 OK') !== false) {
2130 // Extract the link to the thumbnail
2131 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2132 if (!empty($matches[1]))
2133 { // Let's download the image.
2134 $imageurl=$matches[1];
2135 // No control on image size, so wait long enough
2136 list($headers, $content) = get_http_response($imageurl, 20);
2137 if (strpos($headers[0], '200 OK') !== false) {
2138 $filepath = $cacheDir.'/'.$thumbname;
2139 // Save image to cache.
2140 file_put_contents($filepath, $content);
2141 if (resizeImage($filepath))
2142 {
2143 header('Content-Type: image/jpeg');
2144 echo file_get_contents($filepath);
2145 return;
2146 }
2147 }
2148 }
2149 }
2150 }
2151
2152 else
2153 {
2154 // For all other domains, we try to download the image and make a thumbnail.
2155 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2156 list($headers, $content) = get_http_response($url, 30);
2157 if (strpos($headers[0], '200 OK') !== false) {
2158 $filepath = $cacheDir .'/'.$thumbname;
2159 // Save image to cache.
2160 file_put_contents($filepath, $content);
2161 if (resizeImage($filepath))
2162 {
2163 header('Content-Type: image/jpeg');
2164 echo file_get_contents($filepath);
2165 return;
2166 }
2167 }
2168 }
2169
2170
2171 // Otherwise, return an empty image (8x8 transparent gif)
2172 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2173 // Also put something in cache so that this URL is not requested twice.
2174 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2175 header('Content-Type: image/gif');
2176 echo $blankgif;
2177 }
2178
2179 // Make a thumbnail of the image (to width: 120 pixels)
2180 // Returns true if success, false otherwise.
2181 function resizeImage($filepath)
2182 {
2183 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2184
2185 // Trick: some stupid people rename GIF as JPEG... or else.
2186 // So we really try to open each image type whatever the extension is.
2187 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2188 $im=false;
2189 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2190 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2191 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2192 if (!$im) return false; // Unable to open image (corrupted or not an image)
2193 $w = imagesx($im);
2194 $h = imagesy($im);
2195 $ystart = 0; $yheight=$h;
2196 if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
2197 $nw = 120; // Desired width
2198 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2199 // Resize image:
2200 $im2 = imagecreatetruecolor($nw,$nh);
2201 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2202 imageinterlace($im2,true); // For progressive JPEG.
2203 $tempname=$filepath.'_TEMP.jpg';
2204 imagejpeg($im2, $tempname, 90);
2205 imagedestroy($im);
2206 imagedestroy($im2);
2207 unlink($filepath);
2208 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2209 return true;
2210 }
2211
2212 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
2213 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
2214 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2215 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2216 }
2217
2218 try {
2219 $history = new History($conf->get('resource.history'));
2220 } catch(Exception $e) {
2221 die($e->getMessage());
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 $container['history'] = $history;
2236 $app = new \Slim\App($container);
2237
2238 // REST API routes
2239 $app->group('/api/v1', function() {
2240 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2241 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2242 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2243 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
2244 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
2245 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
2246 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
2247 })->add('\Shaarli\Api\ApiMiddleware');
2248
2249 $response = $app->run(true);
2250 // Hack to make Slim and Shaarli router work together:
2251 // If a Slim route isn't found and NOT API call, we call renderPage().
2252 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2253 // We use UTF-8 for proper international characters handling.
2254 header('Content-Type: text/html; charset=utf-8');
2255 renderPage($conf, $pluginManager, $linkDb, $history);
2256 } else {
2257 $app->respond($response);
2258 }