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