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