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