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