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