]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Version 0.0.32 beta:
[github/shaarli/Shaarli.git] / index.php
1 <?php
2 // Shaarli 0.0.32 beta - Shaare your links...
3 // The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net
4 // http://sebsauvage.net/wiki/doku.php?id=php:shaarli
5 // Licence: http://www.opensource.org/licenses/zlib-license.php
6
7 // Requires: php 5.1.x
8 // (but autocomplete fields will only work if you have php 5.2.x)
9 // -----------------------------------------------------------------------------------------------
10 // User config:
11 $GLOBALS['config']['DATADIR'] = 'data'; // Data subdirectory
12 $GLOBALS['config']['CONFIG_FILE'] = $GLOBALS['config']['DATADIR'].'/config.php'; // Configuration file (user login/password)
13 $GLOBALS['config']['DATASTORE'] = $GLOBALS['config']['DATADIR'].'/datastore.php'; // Data storage file.
14 $GLOBALS['config']['LINKS_PER_PAGE'] = 20; // Default links per page.
15 $GLOBALS['config']['IPBANS_FILENAME'] = $GLOBALS['config']['DATADIR'].'/ipbans.php'; // File storage for failures and bans.
16 $GLOBALS['config']['BAN_AFTER'] = 4; // Ban IP after this many failures.
17 $GLOBALS['config']['BAN_DURATION'] = 1800; // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
18 $GLOBALS['config']['OPEN_SHAARLI'] = false; // If true, anyone can add/edit/delete links without having to login
19 $GLOBALS['config']['HIDE_TIMESTAMPS'] = false; // If true, the moment when links were saved are not shown to users that are not logged in.
20 $GLOBALS['config']['ENABLE_THUMBNAILS'] = true; // Enable thumbnails in links.
21 $GLOBALS['config']['CACHEDIR'] = 'cache'; // Cache directory for thumbnails for SLOW services (like flickr)
22 $GLOBALS['config']['ENABLE_LOCALCACHE'] = true; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce webspace usage.
23 $GLOBALS['config']['PUBSUBHUB_URL'] = ''; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
24 // Note: You must have publisher.php in the same directory as Shaarli index.php
25 // -----------------------------------------------------------------------------------------------
26 // Program config (touch at your own risks !)
27 $GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt'; // For updates check of Shaarli.
28 $GLOBALS['config']['UPDATECHECK_INTERVAL'] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
29 ini_set('max_input_time','60'); // High execution time in case of problematic imports/exports.
30 ini_set('memory_limit', '128M'); // Try to set max upload file size and read (May not work on some hosts).
31 ini_set('post_max_size', '16M');
32 ini_set('upload_max_filesize', '16M');
33 define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
34 define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
35 checkphpversion();
36 error_reporting(E_ALL^E_WARNING); // See all error except warnings.
37 //error_reporting(-1); // See all errors (for debugging only)
38
39 include "inc/rain.tpl.class.php"; //include Rain TPL
40 raintpl::$tpl_dir = "tpl/"; // template directory
41 raintpl::$cache_dir = "tmp/"; // cache directory
42
43 ob_start();
44
45 // Optionnal config file.
46 if (is_file($GLOBALS['config']['DATADIR'].'/options.php')) require($GLOBALS['config']['DATADIR'].'/options.php');
47
48 // In case stupid admin has left magic_quotes enabled in php.ini:
49 if (get_magic_quotes_gpc())
50 {
51 function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
52 $_POST = array_map('stripslashes_deep', $_POST);
53 $_GET = array_map('stripslashes_deep', $_GET);
54 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
55 }
56 // Prevent caching: (yes, it's ugly)
57 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
58 header("Cache-Control: no-store, no-cache, must-revalidate");
59 header("Cache-Control: post-check=0, pre-check=0", false);
60 header("Pragma: no-cache");
61 define('shaarli_version','0.0.32 beta');
62 if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); }
63 if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
64 if ($GLOBALS['config']['ENABLE_LOCALCACHE'])
65 {
66 if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); }
67 if (!is_file($GLOBALS['config']['CACHEDIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['CACHEDIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
68 }
69 if (!is_file($GLOBALS['config']['CONFIG_FILE'])) install();
70 require $GLOBALS['config']['CONFIG_FILE']; // Read login/password hash into $GLOBALS.
71 // Small protection against dodgy config files:
72 if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.htmlspecialchars(indexUrl());
73 if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
74 autoLocale(); // Sniff browser language and set date format accordingly.
75 header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
76 $LINKSDB=false;
77
78 // Check php version
79 function checkphpversion()
80 {
81 if (version_compare(PHP_VERSION, '5.1.0') < 0)
82 {
83 header('Content-Type: text/plain; charset=utf-8');
84 echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.';
85 exit;
86 }
87 }
88
89 // Checks if an update is available for Shaarli.
90 // (at most once a day, and only for registered user.)
91 // Output: '' = no new version.
92 // other= the available version.
93 function checkUpdate()
94 {
95 if (!isLoggedIn()) return ''; // Do not check versions for visitors.
96
97 // Get latest version number at most once a day.
98 if (!is_file($GLOBALS['config']['UPDATECHECK_FILENAME']) || (filemtime($GLOBALS['config']['UPDATECHECK_FILENAME'])<time()-($GLOBALS['config']['UPDATECHECK_INTERVAL'])))
99 {
100 $version=shaarli_version;
101 list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2);
102 if (strpos($httpstatus,'200 OK')!==false) $version=$data;
103 // If failed, nevermind. We don't want to bother the user with that.
104 file_put_contents($GLOBALS['config']['UPDATECHECK_FILENAME'],$version); // touch file date
105 }
106 // Compare versions:
107 $newestversion=file_get_contents($GLOBALS['config']['UPDATECHECK_FILENAME']);
108 if (version_compare($newestversion,shaarli_version)==1) return $newestversion;
109 return '';
110 }
111
112 // -----------------------------------------------------------------------------------------------
113 // Log to text file
114 function logm($message)
115 {
116 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
117 file_put_contents($GLOBALS['config']['DATADIR'].'/log.txt',$t,FILE_APPEND);
118 }
119
120 /* Returns the small hash of a string
121 eg. smallHash('20111006_131924') --> yZH23w
122 Small hashes:
123 - are unique (well, as unique as crc32, at last)
124 - are always 6 characters long.
125 - only use the following characters: a-z A-Z 0-9 - _ @
126 - are NOT cryptographically secure (they CAN be forged)
127 In Shaarli, they are used as a tinyurl-like link to individual entries.
128 */
129 function smallHash($text)
130 {
131 $t = rtrim(base64_encode(hash('crc32',$text,true)),'=');
132 $t = str_replace('+','-',$t); // Get rid of characters which need encoding in URLs.
133 $t = str_replace('/','_',$t);
134 $t = str_replace('=','@',$t);
135 return $t;
136 }
137
138 // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
139 function text2clickable($url)
140 {
141 $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'];
142 return preg_replace('!((?:https?|ftp)://\S+[[:alnum:]]/?)!si','<a href="'.$redir.'$1" rel="nofollow">$1</a>',$url);
143 }
144
145 // This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
146 // even in the absence of <pre> (This is used in description to keep text formatting)
147 function keepMultipleSpaces($text)
148 {
149 return str_replace(' ',' &nbsp;',$text);
150
151 }
152 // ------------------------------------------------------------------------------------------
153 // Sniff browser language to display dates in the right format automatically.
154 // (Note that is may not work on your server if the corresponding local is not installed.)
155 function autoLocale()
156 {
157 $loc='en_US'; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
158 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
159 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
160 if (preg_match('/([a-z]{2}(-[a-z]{2})?)/i',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches)) $loc=$matches[1];
161 }
162 setlocale(LC_TIME,$loc); // LC_TIME = Set local for date/time format only.
163 }
164
165 // ------------------------------------------------------------------------------------------
166 // PubSubHubbub protocol support (if enabled) [UNTESTED]
167 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
168 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) include './publisher.php';
169 function pubsubhub()
170 {
171 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
172 {
173 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
174 $topic_url = array (
175 indexUrl().'?do=atom',
176 indexUrl().'?do=rss'
177 );
178 $p->publish_update($topic_url);
179 }
180 }
181
182 // ------------------------------------------------------------------------------------------
183 // Session management
184 define('INACTIVITY_TIMEOUT',3600); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
185 ini_set('session.use_cookies', 1); // Use cookies to store session.
186 ini_set('session.use_only_cookies', 1); // Force cookies for session (phpsessionID forbidden in URL)
187 ini_set('session.use_trans_sid', false); // Prevent php to use sessionID in URL if cookies are disabled.
188 session_name('shaarli');
189 session_start();
190
191 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
192 function allIPs()
193 {
194 $ip = $_SERVER["REMOTE_ADDR"];
195 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
196 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
197 if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
198 return $ip;
199 }
200
201 // Check that user/password is correct.
202 function check_auth($login,$password)
203 {
204 $hash = sha1($password.$login.$GLOBALS['salt']);
205 if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash'])
206 { // Login/password is correct.
207 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // generate unique random number (different than phpsessionid)
208 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
209 $_SESSION['username']=$login;
210 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
211 logm('Login successful');
212 return True;
213 }
214 logm('Login failed for user '.$login);
215 return False;
216 }
217
218 // Returns true if the user is logged in.
219 function isLoggedIn()
220 {
221 if ($GLOBALS['config']['OPEN_SHAARLI']) return true;
222
223 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
224 if (empty($_SESSION['uid']) || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on'])
225 {
226 logout();
227 return false;
228 }
229 if (!empty($_SESSION['longlastingsession'])) $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
230 else $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
231
232 return true;
233 }
234
235 // Force logout.
236 function logout() { if (isset($_SESSION)) { unset($_SESSION['uid']); unset($_SESSION['ip']); unset($_SESSION['username']);} }
237
238
239 // ------------------------------------------------------------------------------------------
240 // Brute force protection system
241 // Several consecutive failed logins will ban the IP address for 30 minutes.
242 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?>");
243 include $GLOBALS['config']['IPBANS_FILENAME'];
244 // Signal a failed login. Will ban the IP if too many failures:
245 function ban_loginFailed()
246 {
247 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
248 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
249 $gb['FAILURES'][$ip]++;
250 if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1))
251 {
252 $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION'];
253 logm('IP address banned from login');
254 }
255 $GLOBALS['IPBANS'] = $gb;
256 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
257 }
258
259 // Signals a successful login. Resets failed login counter.
260 function ban_loginOk()
261 {
262 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
263 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
264 $GLOBALS['IPBANS'] = $gb;
265 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
266 }
267
268 // Checks if the user CAN login. If 'true', the user can try to login.
269 function ban_canLogin()
270 {
271 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
272 if (isset($gb['BANS'][$ip]))
273 {
274 // User is banned. Check if the ban has expired:
275 if ($gb['BANS'][$ip]<=time())
276 { // Ban expired, user can try to login again.
277 logm('Ban lifted.');
278 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
279 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
280 return true; // Ban has expired, user can login.
281 }
282 return false; // User is banned.
283 }
284 return true; // User is not banned.
285 }
286
287 // ------------------------------------------------------------------------------------------
288 // Process login form: Check if login/password is correct.
289 if (isset($_POST['login']))
290 {
291 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
292 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
293 { // Login/password is ok.
294 ban_loginOk();
295 // If user wants to keep the session cookie even after the browser closes:
296 if (!empty($_POST['longlastingsession']))
297 {
298 $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year)
299 $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side.
300 session_set_cookie_params($_SESSION['longlastingsession']); // Set session cookie expiration on client side
301 session_regenerate_id(true); // Send cookie with new expiration date to browser.
302 }
303 else // Standard session expiration (=when browser closes)
304 {
305 session_set_cookie_params(0); // 0 means "When browser closes"
306 session_regenerate_id(true);
307 }
308 // Optional redirect after login:
309 if (isset($_GET['post'])) { header('Location: ?post='.urlencode($_GET['post']).(!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); exit; }
310 if (isset($_POST['returnurl']))
311 {
312 if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
313 header('Location: '.$_POST['returnurl']); exit;
314 }
315 header('Location: ?'); exit;
316 }
317 else
318 {
319 ban_loginFailed();
320 echo '<script language="JavaScript">alert("Wrong login/password.");document.location=\'?do=login\';</script>'; // Redirect to login screen.
321 exit;
322 }
323 }
324
325 // ------------------------------------------------------------------------------------------
326 // Misc utility functions:
327
328 // Returns the server URL (including port and http/https), without path.
329 // eg. "http://myserver.com:8080"
330 // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
331 function serverUrl()
332 {
333 $serverport = ($_SERVER["SERVER_PORT"]=='80' || (!empty($_SERVER['HTTPS']) && $_SERVER["SERVER_PORT"]=='443') ? '' : ':'.$_SERVER["SERVER_PORT"]);
334 return 'http'.(!empty($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport;
335 }
336
337 function indexUrl()
338 {
339 return serverUrl() . ($_SERVER["SCRIPT_NAME"] == '/index.php' ? '' : $_SERVER["SCRIPT_NAME"]);
340 }
341
342 // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
343 function return_bytes($val)
344 {
345 $val = trim($val); $last=strtolower($val[strlen($val)-1]);
346 switch($last)
347 {
348 case 'g': $val *= 1024;
349 case 'm': $val *= 1024;
350 case 'k': $val *= 1024;
351 }
352 return $val;
353 }
354
355 // Try to determine max file size for uploads (POST).
356 // Returns an integer (in bytes)
357 function getMaxFileSize()
358 {
359 $size1 = return_bytes(ini_get('post_max_size'));
360 $size2 = return_bytes(ini_get('upload_max_filesize'));
361 // Return the smaller of two:
362 $maxsize = min($size1,$size2);
363 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
364 return $maxsize;
365 }
366
367 // Tells if a string start with a substring or not.
368 function startsWith($haystack,$needle,$case=true)
369 {
370 if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
371 return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
372 }
373
374 // Tells if a string ends with a substring or not.
375 function endsWith($haystack,$needle,$case=true)
376 {
377 if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
378 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
379 }
380
381 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
382 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
383 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
384 function linkdate2timestamp($linkdate)
385 {
386 $Y=$M=$D=$h=$m=$s=0;
387 $r = sscanf($linkdate,'%4d%2d%2d_%2d%2d%2d',$Y,$M,$D,$h,$m,$s);
388 return mktime($h,$m,$s,$M,$D,$Y);
389 }
390
391 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
392 (used to build the pubDate attribute in RSS feed.) */
393 function linkdate2rfc822($linkdate)
394 {
395 return date('r',linkdate2timestamp($linkdate)); // 'r' is for RFC822 date format.
396 }
397
398 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
399 (used to build the updated tags in ATOM feed.) */
400 function linkdate2iso8601($linkdate)
401 {
402 return date('c',linkdate2timestamp($linkdate)); // 'c' is for ISO 8601 date format.
403 }
404
405 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
406 (used to display link date on screen)
407 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
408 function linkdate2locale($linkdate)
409 {
410 return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale.
411 // Note that if you use a local which is not installed on your webserver,
412 // the date will not be displayed in the chosen locale, but probably in US notation.
413 }
414
415 // Parse HTTP response headers and return an associative array.
416 function http_parse_headers_shaarli( $headers )
417 {
418 $res=array();
419 foreach($headers as $header)
420 {
421 $i = strpos($header,': ');
422 if ($i!==false)
423 {
424 $key=substr($header,0,$i);
425 $value=substr($header,$i+2,strlen($header)-$i-2);
426 $res[$key]=$value;
427 }
428 }
429 return $res;
430 }
431
432 /* GET an URL.
433 Input: $url : url to get (http://...)
434 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
435 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
436 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
437 [2] = data
438 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
439 if (strpos($httpstatus,'200 OK')!==false)
440 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
441 else
442 echo 'There was an error: '.htmlspecialchars($httpstatus)
443 */
444 function getHTTP($url,$timeout=30)
445 {
446 try
447 {
448 $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
449 $context = stream_context_create($options);
450 $data=file_get_contents($url,false,$context,-1, 4000000); // We download at most 4 Mb from source.
451 if (!$data) { $lasterror=error_get_last(); return array($lasterror['message'],array(),''); }
452 $httpStatus=$http_response_header[0]; // eg. "HTTP/1.1 200 OK"
453 $responseHeaders=http_parse_headers_shaarli($http_response_header);
454 return array($httpStatus,$responseHeaders,$data);
455 }
456 catch (Exception $e) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
457 {
458 return array($e->getMessage(),'','');
459 }
460 }
461
462 // Extract title from an HTML document.
463 // (Returns an empty string if not found.)
464 function html_extract_title($html)
465 {
466 return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ;
467 }
468
469 // ------------------------------------------------------------------------------------------
470 // Token management for XSRF protection
471 // Token should be used in any form which acts on data (create,update,delete,import...).
472 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
473
474 // Returns a token.
475 function getToken()
476 {
477 $rnd = sha1(uniqid('',true).'_'.mt_rand()); // We generate a random string.
478 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
479 return $rnd;
480 }
481
482 // Tells if a token is ok. Using this function will destroy the token.
483 // true=token is ok.
484 function tokenOk($token)
485 {
486 if (isset($_SESSION['tokens'][$token]))
487 {
488 unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
489 return true; // Token is ok.
490 }
491 return false; // Wrong token, or already used.
492 }
493
494 // ------------------------------------------------------------------------------------------
495 /* This class is in charge of building the final page.
496 (This is basically a wrapper around RainTPL which pre-fills some fields.)
497 p = new pageBuilder;
498 p.assign('myfield','myvalue');
499 p.renderPage('mytemplate');
500
501 */
502 class pageBuilder
503 {
504 private $tpl; // RainTPL template
505 function __construct()
506 {
507 $this->tpl=false;
508 }
509
510 private function initialize()
511 {
512 global $LINKSDB;
513 $this->tpl = new RainTPL;
514 $this->tpl->assign('newversion',checkUpdate());
515 $this->tpl->assign('linkcount',count($LINKSDB));
516 $this->tpl->assign('feedurl',htmlspecialchars(indexUrl()));
517 $searchcrits=''; // Search criteria
518 if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.$_GET['searchtags'];
519 elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.$_GET['searchterm'];
520 $this->tpl->assign('searchcrits',$searchcrits);
521 $this->tpl->assign('source',indexUrl());
522 $this->tpl->assign('version',shaarli_version);
523 $this->tpl->assign('pagetitle','Shaarli');
524 if (!empty($GLOBALS['title'])) $this->tpl->assign('pagetitle',$GLOBALS['title']);
525 if (!empty($GLOBALS['pagetitle'])) $this->tpl->assign('pagetitle',$GLOBALS['pagetitle']);
526 $this->tpl->assign('shaarlititle',empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title'] );
527 return;
528 }
529
530 // The following assign() method is basically the same as RainTPL (except that it's lazy)
531 public function assign($what,$where)
532 {
533 if ($this->tpl===false) $this->initialize(); // Lazy initialization
534 $this->tpl->assign($what,$where);
535 }
536
537 // Render a specific page (using a template).
538 // eg. pb.renderPage('picwall')
539 public function renderPage($page)
540 {
541 if ($this->tpl===false) $this->initialize(); // Lazy initialization
542 $this->tpl->draw($page);
543 }
544 }
545
546 // ------------------------------------------------------------------------------------------
547 /* Data storage for links.
548 This object behaves like an associative array.
549 Example:
550 $mylinks = new linkdb();
551 echo $mylinks['20110826_161819']['title'];
552 foreach($mylinks as $link)
553 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
554
555 We implement 3 interfaces:
556 - ArrayAccess so that this object behaves like an associative array.
557 - Iterator so that this object can be used in foreach() loops.
558 - Countable interface so that we can do a count() on this object.
559 */
560 class linkdb implements Iterator, Countable, ArrayAccess
561 {
562 private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
563 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
564 private $keys; // List of linkdate keys (for the Iterator interface implementation)
565 private $position; // Position in the $this->keys array. (for the Iterator interface implementation.)
566 private $loggedin; // Is the used logged in ? (used to filter private links)
567
568 // Constructor:
569 function __construct($isLoggedIn)
570 // Input : $isLoggedIn : is the used logged in ?
571 {
572 $this->loggedin = $isLoggedIn;
573 $this->checkdb(); // Make sure data file exists.
574 $this->readdb(); // Then read it.
575 }
576
577 // ---- Countable interface implementation
578 public function count() { return count($this->links); }
579
580 // ---- ArrayAccess interface implementation
581 public function offsetSet($offset, $value)
582 {
583 if (!$this->loggedin) die('You are not authorized to add a link.');
584 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.');
585 if (empty($offset)) die('You must specify a key.');
586 $this->links[$offset] = $value;
587 $this->urls[$value['url']]=$offset;
588 }
589 public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
590 public function offsetUnset($offset)
591 {
592 if (!$this->loggedin) die('You are not authorized to delete a link.');
593 $url = $this->links[$offset]['url']; unset($this->urls[$url]);
594 unset($this->links[$offset]);
595 }
596 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
597
598 // ---- Iterator interface implementation
599 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
600 function key() { return $this->keys[$this->position]; } // current key
601 function current() { return $this->links[$this->keys[$this->position]]; } // current value
602 function next() { ++$this->position; } // go to next item
603 function valid() { return isset($this->keys[$this->position]); } // Check if current position is valid.
604
605 // ---- Misc methods
606 private function checkdb() // Check if db directory and file exists.
607 {
608 if (!file_exists($GLOBALS['config']['DATASTORE'])) // Create a dummy database for example.
609 {
610 $this->links = array();
611 $link = array('title'=>'Shaarli - sebsauvage.net','url'=>'http://sebsauvage.net/wiki/doku.php?id=php:shaarli','description'=>'Welcome to Shaarli ! This is a bookmark. To edit or delete me, you must first login.','private'=>0,'linkdate'=>'20110914_190000','tags'=>'opensource software');
612 $this->links[$link['linkdate']] = $link;
613 $link = array('title'=>'My secret stuff... - Pastebin.com','url'=>'http://pastebin.com/smCEEeSn','description'=>'SShhhh!! I\'m a private link only YOU can see. You can delete me too.','private'=>1,'linkdate'=>'20110914_074522','tags'=>'secretstuff');
614 $this->links[$link['linkdate']] = $link;
615 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
616 }
617 }
618
619 // Read database from disk to memory
620 private function readdb()
621 {
622 // Read data
623 $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
624 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
625
626 // If user is not logged in, filter private links.
627 if (!$this->loggedin)
628 {
629 $toremove=array();
630 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
631 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
632 }
633
634 // Keep the list of the mapping URLs-->linkdate up-to-date.
635 $this->urls=array();
636 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
637 }
638
639 // Save database from memory to disk.
640 public function savedb()
641 {
642 if (!$this->loggedin) die('You are not authorized to change the database.');
643 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
644 }
645
646 // Returns the link for a given URL (if it exists). false it does not exist.
647 public function getLinkFromUrl($url)
648 {
649 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
650 return false;
651 }
652
653 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
654 // eg. print_r($mydb->filterFulltext('hollandais'));
655 public function filterFulltext($searchterms)
656 {
657 // FIXME: explode(' ',$searchterms) and perform a AND search.
658 // FIXME: accept double-quotes to search for a string "as is" ?
659 $filtered=array();
660 $s = strtolower($searchterms);
661 foreach($this->links as $l)
662 {
663 $found= (strpos(strtolower($l['title']),$s)!==false)
664 || (strpos(strtolower($l['description']),$s)!==false)
665 || (strpos(strtolower($l['url']),$s)!==false)
666 || (strpos(strtolower($l['tags']),$s)!==false);
667 if ($found) $filtered[$l['linkdate']] = $l;
668 }
669 krsort($filtered);
670 return $filtered;
671 }
672
673 // Filter by tag.
674 // You can specify one or more tags (tags can be separated by space or comma).
675 // eg. print_r($mydb->filterTags('linux programming'));
676 public function filterTags($tags,$casesensitive=false)
677 {
678 $t = str_replace(',',' ',($casesensitive?$tags:strtolower($tags)));
679 $searchtags=explode(' ',$t);
680 $filtered=array();
681 foreach($this->links as $l)
682 {
683 $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags'])));
684 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
685 $filtered[$l['linkdate']] = $l;
686 }
687 krsort($filtered);
688 return $filtered;
689 }
690
691 // Filter by smallHash.
692 // Only 1 article is returned.
693 public function filterSmallHash($smallHash)
694 {
695 $filtered=array();
696 foreach($this->links as $l)
697 {
698 if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
699 {
700 $filtered[$l['linkdate']] = $l;
701 return $filtered;
702 }
703 }
704 return $filtered;
705 }
706
707 // Returns the list of all tags
708 // Output: associative array key=tags, value=0
709 public function allTags()
710 {
711 $tags=array();
712 foreach($this->links as $link)
713 foreach(explode(' ',$link['tags']) as $tag)
714 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
715 arsort($tags); // Sort tags by usage (most used tag first)
716 return $tags;
717 }
718 }
719
720 // ------------------------------------------------------------------------------------------
721 // Ouput the last 50 links in RSS 2.0 format.
722 function showRSS()
723 {
724 global $LINKSDB;
725
726 // Optionnaly filter the results:
727 $linksToDisplay=array();
728 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
729 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
730 else $linksToDisplay = $LINKSDB;
731
732 header('Content-Type: application/rss+xml; charset=utf-8');
733 $pageaddr=htmlspecialchars(indexUrl());
734 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
735 echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>';
736 echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
737 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
738 {
739 echo '<!-- PubSubHubbub Discovery -->';
740 echo '<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" xmlns="http://www.w3.org/2005/Atom" />';
741 echo '<link rel="self" href="'.htmlspecialchars($pageaddr).'?do=rss" xmlns="http://www.w3.org/2005/Atom" />';
742 echo '<!-- End Of PubSubHubbub Discovery -->';
743 }
744 $i=0;
745 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
746 while ($i<50 && $i<count($keys))
747 {
748 $link = $linksToDisplay[$keys[$i]];
749 $guid = $pageaddr.'?'.smallHash($link['linkdate']);
750 $rfc822date = linkdate2rfc822($link['linkdate']);
751 $absurl = htmlspecialchars($link['url']);
752 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
753 echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.$guid.'</guid><link>'.$absurl.'</link>';
754 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date)."</pubDate>\n";
755 if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
756 {
757 foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.htmlspecialchars($pageaddr).'">'.htmlspecialchars($tag).'</category>'."\n"; }
758 }
759 echo '<description><![CDATA['.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description'])))).']]></description>'."\n</item>\n";
760 $i++;
761 }
762 echo '</channel></rss>';
763 exit;
764 }
765
766 // ------------------------------------------------------------------------------------------
767 // Ouput the last 50 links in ATOM format.
768 function showATOM()
769 {
770 global $LINKSDB;
771
772 // Optionnaly filter the results:
773 $linksToDisplay=array();
774 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
775 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
776 else $linksToDisplay = $LINKSDB;
777
778 header('Content-Type: application/atom+xml; charset=utf-8');
779 $pageaddr=htmlspecialchars(indexUrl());
780 $latestDate = '';
781 $entries='';
782 $i=0;
783 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
784 while ($i<50 && $i<count($keys))
785 {
786 $link = $linksToDisplay[$keys[$i]];
787 $guid = $pageaddr.'?'.smallHash($link['linkdate']);
788 $iso8601date = linkdate2iso8601($link['linkdate']);
789 $latestDate = max($latestDate,$iso8601date);
790 $absurl = htmlspecialchars($link['url']);
791 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
792 $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title><link href="'.$absurl.'" /><id>'.$guid.'</id>';
793 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>';
794 $entries.='<summary>'.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))))."</summary>\n";
795 if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification)
796 {
797 foreach(explode(' ',$link['tags']) as $tag)
798 { $entries.='<category scheme="'.htmlspecialchars($pageaddr,ENT_QUOTES).'" term="'.htmlspecialchars($tag,ENT_QUOTES).'" />'."\n"; }
799 }
800 $entries.="</entry>\n";
801 $i++;
802 }
803 $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
804 $feed.='<title>'.htmlspecialchars($GLOBALS['title']).'</title>';
805 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.htmlspecialchars($latestDate).'</updated>';
806 $feed.='<link rel="self" href="'.htmlspecialchars($pageaddr).'" />';
807 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
808 {
809 $feed.='<!-- PubSubHubbub Discovery -->';
810 $feed.='<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" />';
811 $feed.='<!-- End Of PubSubHubbub Discovery -->';
812 }
813 $feed.='<author><uri>'.htmlspecialchars($pageaddr).'</uri></author>';
814 $feed.='<id>'.htmlspecialchars($pageaddr).'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
815 $feed.=$entries;
816 $feed.='</feed>';
817 echo $feed;
818 exit;
819 }
820
821 // ------------------------------------------------------------------------------------------
822 // Render HTML page (according to URL parameters and user rights)
823 function renderPage()
824 {
825 global $LINKSDB;
826
827 // -------- Display login form.
828 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login'))
829 {
830 if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; } // No need to login for open Shaarli
831 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful.
832 $PAGE = new pageBuilder;
833 $PAGE->assign('token',$token);
834 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER']:''));
835 $PAGE->renderPage('loginform');
836 exit;
837 }
838 // -------- User wants to logout.
839 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=logout'))
840 {
841 invalidateCaches();
842 logout();
843 header('Location: ?');
844 exit;
845 }
846
847 // -------- Picture wall
848 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=picwall'))
849 {
850 // Optionnaly filter the results:
851 $links=array();
852 if (!empty($_GET['searchterm'])) $links = $LINKSDB->filterFulltext($_GET['searchterm']);
853 elseif (!empty($_GET['searchtags'])) $links = $LINKSDB->filterTags(trim($_GET['searchtags']));
854 else $links = $LINKSDB;
855 $body='';
856 $linksToDisplay=array();
857
858 // Get only links which have a thumbnail.
859 foreach($links as $link)
860 {
861 $permalink='?'.htmlspecialchars(smallhash($link['linkdate']),ENT_QUOTES);
862 $thumb=thumbnail($link['url'],$permalink);
863 if ($thumb!='') // Only output links which have a thumbnail.
864 {
865 $link['thumbnail']=$thumb; // Thumbnail HTML code.
866 $link['permalink']=$permalink;
867 $linksToDisplay[]=$link; // Add to array.
868 }
869 }
870 $PAGE = new pageBuilder;
871 $PAGE->assign('linksToDisplay',$linksToDisplay);
872 $PAGE->renderPage('picwall');
873 exit;
874 }
875
876 // -------- Tag cloud
877 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
878 {
879 $tags= $LINKSDB->allTags();
880 // We sort tags alphabetically, then choose a font size according to count.
881 // First, find max value.
882 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
883 ksort($tags);
884 $tagList=array();
885 foreach($tags as $key=>$value)
886 {
887 $tagList[$key] = array('count'=>$value,'size'=>max(40*$value/$maxcount,8));
888 }
889 $PAGE = new pageBuilder;
890 $PAGE->assign('tags',$tagList);
891 $PAGE->renderPage('tagcloud');
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 $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags']).' '.urlencode(trim($_GET['addtag'])));
902 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
903 header('Location: ?'.http_build_query($params));
904 exit;
905 }
906
907 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
908 if (isset($_GET['removetag']))
909 {
910 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
911 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?'); exit; } // In case browser does not send HTTP_REFERER
912 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
913 if (isset($params['searchtags']))
914 {
915 $tags = explode(' ',$params['searchtags']);
916 $tags=array_diff($tags, array($_GET['removetag'])); // Remove value from array $tags.
917 if (count($tags)==0) unset($params['searchtags']); else $params['searchtags'] = implode(' ',$tags);
918 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
919 }
920 header('Location: ?'.http_build_query($params));
921 exit;
922 }
923
924 // -------- User wants to change the number of links per page (linksperpage=...)
925 if (isset($_GET['linksperpage']))
926 {
927 if (is_numeric($_GET['linksperpage'])) { $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); }
928 header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']));
929 exit;
930 }
931
932
933 // -------- Handle other actions allowed for non-logged in users:
934 if (!isLoggedIn())
935 {
936 // User tries to post new link but is not loggedin:
937 // Show login screen, then redirect to ?post=...
938 if (isset($_GET['post']))
939 {
940 header('Location: ?do=login&post='.urlencode($_GET['post']).(!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link.
941 exit;
942 }
943 $PAGE = new pageBuilder;
944 buildLinkList($PAGE); // Compute list of links to display
945 $PAGE->renderPage('linklist');
946 exit; // Never remove this one ! All operations below are reserved for logged in user.
947 }
948
949 // -------- All other functions are reserved for the registered user:
950
951 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
952 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=tools'))
953 {
954 $PAGE = new pageBuilder;
955 $PAGE->assign('pageabsaddr',indexUrl());
956 $PAGE->renderPage('tools');
957 exit;
958 }
959
960 // -------- User wants to change his/her password.
961 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=changepasswd'))
962 {
963 if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.');
964 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
965 {
966 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
967
968 // Make sure old password is correct.
969 $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']);
970 if ($oldhash!=$GLOBALS['hash']) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
971 // Save new password
972 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
973 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
974 writeConfig();
975 echo '<script language="JavaScript">alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
976 exit;
977 }
978 else // show the change password form.
979 {
980 $PAGE = new pageBuilder;
981 $PAGE->assign('token',getToken());
982 $PAGE->renderPage('changepassword');
983 exit;
984 }
985 }
986
987 // -------- User wants to change configuration
988 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=configure'))
989 {
990 if (!empty($_POST['title']) )
991 {
992 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
993 $tz = 'UTC';
994 if (!empty($_POST['continent']) && !empty($_POST['city']))
995 if (isTZvalid($_POST['continent'],$_POST['city']))
996 $tz = $_POST['continent'].'/'.$_POST['city'];
997 $GLOBALS['timezone'] = $tz;
998 $GLOBALS['title']=$_POST['title'];
999 $GLOBALS['redirector']=$_POST['redirector'];
1000 writeConfig();
1001 echo '<script language="JavaScript">alert("Configuration was saved.");document.location=\'?do=tools\';</script>';
1002 exit;
1003 }
1004 else // Show the configuration form.
1005 {
1006 $PAGE = new pageBuilder;
1007 $PAGE->assign('token',getToken());
1008 $PAGE->assign('title',htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES));
1009 $PAGE->assign('redirector',htmlspecialchars( empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] , ENT_QUOTES));
1010 list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']);
1011 $PAGE->assign('timezone_form',$timezone_form); // FIXME: put entire tz form generation in template ?
1012 $PAGE->assign('timezone_js',$timezone_js);
1013 $PAGE->renderPage('configure');
1014 exit;
1015 }
1016 }
1017
1018 // -------- User wants to rename a tag or delete it
1019 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=changetag'))
1020 {
1021 if (empty($_POST['fromtag']))
1022 {
1023 $PAGE = new pageBuilder;
1024 $PAGE->assign('token',getToken());
1025 $PAGE->renderPage('changetag');
1026 exit;
1027 }
1028 if (!tokenOk($_POST['token'])) die('Wrong token.');
1029
1030 // Delete a tag:
1031 if (!empty($_POST['deletetag']) && !empty($_POST['fromtag']))
1032 {
1033 $needle=trim($_POST['fromtag']);
1034 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
1035 foreach($linksToAlter as $key=>$value)
1036 {
1037 $tags = explode(' ',trim($value['tags']));
1038 unset($tags[array_search($needle,$tags)]); // Remove tag.
1039 $value['tags']=trim(implode(' ',$tags));
1040 $LINKSDB[$key]=$value;
1041 }
1042 $LINKSDB->savedb(); // save to disk
1043 invalidateCaches();
1044 echo '<script language="JavaScript">alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
1045 exit;
1046 }
1047
1048 // Rename a tag:
1049 if (!empty($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag']))
1050 {
1051 $needle=trim($_POST['fromtag']);
1052 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
1053 foreach($linksToAlter as $key=>$value)
1054 {
1055 $tags = explode(' ',trim($value['tags']));
1056 $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Remplace tags value.
1057 $value['tags']=trim(implode(' ',$tags));
1058 $LINKSDB[$key]=$value;
1059 }
1060 $LINKSDB->savedb(); // save to disk
1061 invalidateCaches();
1062 echo '<script language="JavaScript">alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
1063 exit;
1064 }
1065 }
1066
1067 // -------- User wants to add a link without using the bookmarklet: show form.
1068 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=addlink'))
1069 {
1070 $PAGE = new pageBuilder;
1071 $PAGE->renderPage('addlink');
1072 exit;
1073 }
1074
1075 // -------- User clicked the "Save" button when editing a link: Save link to database.
1076 if (isset($_POST['save_edit']))
1077 {
1078 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
1079 $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces.
1080 $linkdate=$_POST['lf_linkdate'];
1081 $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
1082 'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags));
1083 if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
1084 $LINKSDB[$linkdate] = $link;
1085 $LINKSDB->savedb(); // save to disk
1086 pubsubhub();
1087 invalidateCaches();
1088
1089 // If we are called from the bookmarklet, we must close the popup:
1090 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1091 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1092 header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on.
1093 exit;
1094 }
1095
1096 // -------- User clicked the "Cancel" button when editing a link.
1097 if (isset($_POST['cancel_edit']))
1098 {
1099 // If we are called from the bookmarklet, we must close the popup;
1100 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1101 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1102 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1103 exit;
1104 }
1105
1106 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
1107 if (isset($_POST['delete_link']))
1108 {
1109 if (!tokenOk($_POST['token'])) die('Wrong token.');
1110 // We do not need to ask for confirmation:
1111 // - confirmation is handled by javascript
1112 // - we are protected from XSRF by the token.
1113 $linkdate=$_POST['lf_linkdate'];
1114 unset($LINKSDB[$linkdate]);
1115 $LINKSDB->savedb(); // save to disk
1116 invalidateCaches();
1117 // If we are called from the bookmarklet, we must close the popup:
1118 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1119 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1120 header('Location: '.$returnurl); // After deleting the link, redirect to the page the user was on.
1121 exit;
1122 }
1123
1124 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1125 if (isset($_GET['edit_link']))
1126 {
1127 $link = $LINKSDB[$_GET['edit_link']]; // Read database
1128 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1129 $PAGE = new pageBuilder;
1130 $PAGE->assign('link',$link);
1131 $PAGE->assign('link_is_new',false);
1132 $PAGE->assign('token',getToken()); // XSRF protection.
1133 $PAGE->assign('http_referer',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''));
1134 $PAGE->renderPage('editlink');
1135 exit;
1136 }
1137
1138 // -------- User want to post a new link: Display link edit form.
1139 if (isset($_GET['post']))
1140 {
1141 $url=$_GET['post'];
1142
1143 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
1144 $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i);
1145 $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
1146 $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
1147
1148 $link_is_new = false;
1149 $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link)
1150 if (!$link)
1151 {
1152 $link_is_new = true; // This is a new link
1153 $linkdate = strval(date('Ymd_His'));
1154 $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
1155 $description=''; $tags=''; $private=0;
1156 if (($url!='') && parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;
1157 // If this is an HTTP link, we try go get the page to extact the title (otherwise we will to straight to the edit form.)
1158 if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
1159 {
1160 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
1161 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1162 if (strpos($status,'200 OK')!==false) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
1163 }
1164 if ($url=='') $url='?'.smallHash($linkdate); // In case of empty URL, this is just a text (with a link that point to itself)
1165 $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
1166 }
1167
1168 $PAGE = new pageBuilder;
1169 $PAGE->assign('link',$link);
1170 $PAGE->assign('link_is_new',$link_is_new);
1171 $PAGE->assign('token',getToken()); // XSRF protection.
1172 $PAGE->assign('http_referer',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''));
1173 $PAGE->renderPage('editlink');
1174 exit;
1175 }
1176
1177 // -------- Export as Netscape Bookmarks HTML file.
1178 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=export'))
1179 {
1180 if (empty($_GET['what']))
1181 {
1182 $PAGE = new pageBuilder;
1183 $PAGE->renderPage('export');
1184 exit;
1185 }
1186 $exportWhat=$_GET['what'];
1187 if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???');
1188
1189 header('Content-Type: text/html; charset=utf-8');
1190 header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
1191 $currentdate=date('Y/m/d H:i:s');
1192 echo <<<HTML
1193 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1194 <!-- This is an automatically generated file.
1195 It will be read and overwritten.
1196 DO NOT EDIT! -->
1197 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1198 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1199 <TITLE>Bookmarks</TITLE>
1200 <H1>Bookmarks</H1>
1201 HTML;
1202 foreach($LINKSDB as $link)
1203 {
1204 if ($exportWhat=='all' ||
1205 ($exportWhat=='private' && $link['private']!=0) ||
1206 ($exportWhat=='public' && $link['private']==0))
1207 {
1208 echo '<DT><A HREF="'.htmlspecialchars($link['url']).'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
1209 if ($link['tags']!='') echo ' TAGS="'.htmlspecialchars(str_replace(' ',',',$link['tags'])).'"';
1210 echo '>'.htmlspecialchars($link['title'])."</A>\n";
1211 if ($link['description']!='') echo '<DD>'.htmlspecialchars($link['description'])."\n";
1212 }
1213 }
1214 exit;
1215 }
1216
1217 // -------- User is uploading a file for import
1218 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=upload'))
1219 {
1220 // If file is too big, some form field may be missing.
1221 if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0))
1222 {
1223 $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] );
1224 echo '<script language="JavaScript">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=\''.htmlspecialchars($returnurl).'\';</script>';
1225 exit;
1226 }
1227 if (!tokenOk($_POST['token'])) die('Wrong token.');
1228 importFile();
1229 exit;
1230 }
1231
1232 // -------- Show upload/import dialog:
1233 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=import'))
1234 {
1235 $PAGE = new pageBuilder;
1236 $PAGE->assign('token',getToken());
1237 $PAGE->assign('maxfilesize',getMaxFileSize());
1238 $PAGE->renderPage('import');
1239 exit;
1240 }
1241
1242 // -------- Otherwise, simply display search form and links:
1243 $PAGE = new pageBuilder;
1244 buildLinkList($PAGE); // Compute list of links to display
1245 $PAGE->renderPage('linklist');
1246 exit;
1247 }
1248
1249 // -----------------------------------------------------------------------------------------------
1250 // Process the import file form.
1251 function importFile()
1252 {
1253 global $LINKSDB;
1254 $filename=$_FILES['filetoupload']['name'];
1255 $filesize=$_FILES['filetoupload']['size'];
1256 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
1257 $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ?
1258 $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ?
1259 $import_count=0;
1260
1261 // Sniff file type:
1262 $type='unknown';
1263 if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox).
1264
1265 // Then import the bookmarks.
1266 if ($type=='netscape')
1267 {
1268 // This is a standard Netscape-style bookmark file.
1269 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1270 foreach(explode('<DT>',$data) as $html) // explode is very fast
1271 {
1272 $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
1273 $d = explode('<DD>',$html);
1274 if (startswith($d[0],'<A '))
1275 {
1276 $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : ''); // Get description (optional)
1277 preg_match('!<A .*?>(.*?)</A>!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : ''); // Get title
1278 $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8');
1279 preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER); // Get all other attributes
1280 $raw_add_date=0;
1281 foreach($matches as $m)
1282 {
1283 $attr=$m[1]; $value=$m[2];
1284 if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
1285 elseif ($attr=='ADD_DATE') $raw_add_date=intval($value);
1286 elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
1287 elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
1288 }
1289 if ($link['url']!='')
1290 {
1291 if ($private==1) $link['private']=1;
1292 $dblink = $LINKSDB->getLinkFromUrl($link['url']); // See if the link is already in database.
1293 if ($dblink==false)
1294 { // Link not in database, let's import it...
1295 if (empty($raw_add_date)) $raw_add_date=time(); // In case of shitty bookmark file with no ADD_DATE
1296
1297 // Make sure date/time is not already used by another link.
1298 // (Some bookmark files have several different links with the same ADD_DATE)
1299 // We increment date by 1 second until we find a date which is not used in db.
1300 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1301 while (!empty($LINKSDB[date('Ymd_His',$raw_add_date)])) { $raw_add_date++; }// Yes, I know it's ugly.
1302 $link['linkdate']=date('Ymd_His',$raw_add_date);
1303 $LINKSDB[$link['linkdate']] = $link;
1304 $import_count++;
1305 }
1306 else // link already present in database.
1307 {
1308 if ($overwrite)
1309 { // If overwrite is required, we import link data, except date/time.
1310 $link['linkdate']=$dblink['linkdate'];
1311 $LINKSDB[$link['linkdate']] = $link;
1312 $import_count++;
1313 }
1314 }
1315
1316 }
1317 }
1318 }
1319 $LINKSDB->savedb();
1320 invalidateCaches();
1321 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
1322 }
1323 else
1324 {
1325 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
1326 }
1327 }
1328
1329 // -----------------------------------------------------------------------------------------------
1330 // Template for the list of links (<div id="linklist">)
1331 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1332 function buildLinkList($PAGE)
1333 {
1334 global $LINKSDB; // Get the links database.
1335
1336 // ---- Filter link database according to parameters
1337 $linksToDisplay=array();
1338 $search_type='';
1339 $search_crits='';
1340 if (!empty($_GET['searchterm'])) // Fulltext search
1341 {
1342 $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
1343 $search_crits=htmlspecialchars(trim($_GET['searchterm']));
1344 $search_type='fulltext';
1345 }
1346 elseif (!empty($_GET['searchtags'])) // Search by tag
1347 {
1348 $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
1349 $search_crits=explode(' ',trim($_GET['searchtags']));
1350 $search_type='tags';
1351 }
1352 elseif (isset($_SERVER["QUERY_STRING"]) && preg_match('/[a-zA-Z0-9-_@]{6}(&.+?)?/',$_SERVER["QUERY_STRING"])) // Detect smallHashes in URL
1353 {
1354 $linksToDisplay = $LINKSDB->filterSmallHash(substr(trim($_SERVER["QUERY_STRING"], '/'),0,6));
1355 $search_type='permalink';
1356 }
1357 else
1358 $linksToDisplay = $LINKSDB; // otherwise, display without filtering.
1359
1360
1361 // ---- Handle paging.
1362 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1363 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1364 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1365 */
1366 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // Stupid and ugly. Thanks php.
1367
1368 // If there is only a single link, we change on-the-fly the title of the page.
1369 if (count($linksToDisplay)==1) $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title'];
1370
1371 // Select articles according to paging.
1372 $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
1373 $pagecount = ($pagecount==0 ? 1 : $pagecount);
1374 $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
1375 $page = ( $page<1 ? 1 : $page );
1376 $page = ( $page>$pagecount ? $pagecount : $page );
1377 $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
1378 $end = $i+$_SESSION['LINKS_PER_PAGE'];
1379 $linkDisp=array(); // Links to display
1380 while ($i<$end && $i<count($keys))
1381 {
1382 $link = $linksToDisplay[$keys[$i]];
1383 $link['description']=nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))));
1384 $title=$link['title'];
1385 $classLi = $i%2!=0 ? '' : 'publicLinkHightLight';
1386 $link['class'] = ($link['private']==0 ? $classLi : 'private');
1387 $link['localdate']=linkdate2locale($link['linkdate']);
1388 $link['taglist']=explode(' ',$link['tags']);
1389 $linkDisp[$keys[$i]] = $link;
1390 $i++;
1391 }
1392
1393 // Compute paging navigation
1394 $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] );
1395 $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] );
1396 $paging='';
1397 $previous_page_url=''; if ($i!=count($keys)) $previous_page_url='?page='.($page+1).$searchterm.$searchtags;
1398 $next_page_url='';if ($page>1) $next_page_url='?page='.($page-1).$searchterm.$searchtags;
1399
1400 $token = ''; if (isLoggedIn()) $token=getToken();
1401
1402 // Fill all template fields.
1403 $PAGE->assign('previous_page_url',$previous_page_url);
1404 $PAGE->assign('next_page_url',$next_page_url);
1405 $PAGE->assign('page_current',$page);
1406 $PAGE->assign('page_max',$pagecount);
1407 $PAGE->assign('result_count',count($linksToDisplay));
1408 $PAGE->assign('search_type',$search_type);
1409 $PAGE->assign('search_crits',$search_crits);
1410 $PAGE->assign('redirector',empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector']); // optional redirector URL
1411 $PAGE->assign('token',$token);
1412 $PAGE->assign('links',$linkDisp);
1413 return;
1414 }
1415
1416 // Returns the HTML code to display a thumbnail for a link
1417 // with a link to the original URL.
1418 // Understands various services (youtube.com...)
1419 // Input: $url = url for which the thumbnail must be found.
1420 // $href = if provided, this URL will be followed instead of $url
1421 function thumbnail($url,$href=false)
1422 {
1423 if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return '';
1424
1425 if ($href==false) $href=$url;
1426
1427 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1428 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1429 // ^^^^^^^^^^^ ^^^^^^^^^^^
1430 $domain = parse_url($url,PHP_URL_HOST);
1431 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1432 {
1433 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
1434 if (!empty($params['v'])) return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi/'.htmlspecialchars($params['v']).'/default.jpg" width="120" height="90"></a>';
1435 }
1436 if ($domain=='youtu.be') // Youtube short links
1437 {
1438 $path = parse_url($url,PHP_URL_PATH);
1439 return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi'.htmlspecialchars($path).'/default.jpg" width="120" height="90"></a>';
1440 }
1441 if ($domain=='imgur.com')
1442 {
1443 $path = parse_url($url,PHP_URL_PATH);
1444 if (startsWith($path,'/a/')) return ''; // Thumbnails for albums are not available.
1445 if (startsWith($path,'/r/')) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars(basename($path)).'s.jpg" width="90" height="90"></a>';
1446 if (startsWith($path,'/gallery/')) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com'.htmlspecialchars(substr($path,8)).'s.jpg" width="90" height="90"></a>';
1447 if (substr_count($path,'/')==1) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars(substr($path,1)).'s.jpg" width="90" height="90"></a>';
1448 }
1449 if ($domain=='i.imgur.com')
1450 {
1451 $pi = pathinfo(parse_url($url,PHP_URL_PATH));
1452 if (!empty($pi['filename'])) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars($pi['filename']).'s.jpg" width="90" height="90"></a>';
1453 }
1454 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1455 {
1456 if (strpos($url,'dailymotion.com/video/')!==false)
1457 {
1458 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1459 return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
1460 }
1461 }
1462 if (endsWith($domain,'.imageshack.us'))
1463 {
1464 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1465 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1466 {
1467 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1468 return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
1469 }
1470 }
1471
1472 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1473 // So we deport the thumbnail generation in order not to slow down page generation
1474 // (and we also cache the thumbnail)
1475
1476 if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return ''; // If local cache is disabled, no thumbnails for services which require the use a local cache.
1477
1478 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1479 || $domain=='vimeo.com'
1480 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1481 )
1482 {
1483 if ($domain=='vimeo.com')
1484 { // Make sure this vimeo url points to a video (/xxx... where xxx is numeric)
1485 $path = parse_url($url,PHP_URL_PATH);
1486 if (!preg_match('!/\d+.+?!',$path)) return ''; // This is not a single video URL.
1487 }
1488 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1489 { // Make sure this TED url points to a video (/talks/...)
1490 $path = parse_url($url,PHP_URL_PATH);
1491 if ("/talks/" !== substr($path,0,7)) return ''; // This is not a single video URL.
1492 }
1493 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
1494 return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';
1495 }
1496
1497 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1498 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1499 // But using the extension will do.
1500 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1501 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1502 {
1503 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
1504 return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';
1505 }
1506 return ''; // No thumbnail.
1507
1508 }
1509
1510 // -----------------------------------------------------------------------------------------------
1511 // Installation
1512 // This function should NEVER be called if the file data/config.php exists.
1513 function install()
1514 {
1515 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1516 if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1517
1518 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1519 {
1520 $tz = 'UTC';
1521 if (!empty($_POST['continent']) && !empty($_POST['city']))
1522 if (isTZvalid($_POST['continent'],$_POST['city']))
1523 $tz = $_POST['continent'].'/'.$_POST['city'];
1524 $GLOBALS['timezone'] = $tz;
1525 // Everything is ok, let's create config file.
1526 $GLOBALS['login'] = $_POST['setlogin'];
1527 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
1528 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
1529 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.htmlspecialchars(indexUrl()) : $_POST['title'] );
1530 writeConfig();
1531 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>';
1532 exit;
1533 }
1534
1535 // Display config form:
1536 list($timezone_form,$timezone_js) = templateTZform();
1537 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
1538
1539 $PAGE = new pageBuilder;
1540 $PAGE->assign('timezone_html',$timezone_html);
1541 $PAGE->assign('timezone_js',$timezone_js);
1542 $PAGE->renderPage('install');
1543 exit;
1544 }
1545
1546 // Generates the timezone selection form and javascript.
1547 // Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1548 // Output: array(html,js)
1549 // Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1550 // Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1551 function templateTZform($ptz=false)
1552 {
1553 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1554 {
1555 // Try to split the provided timezone.
1556 if ($ptz==false) { $l=timezone_identifiers_list(); $ptz=$l[0]; }
1557 $spos=strpos($ptz,'/'); $pcontinent=substr($ptz,0,$spos); $pcity=substr($ptz,$spos+1);
1558
1559 // Display config form:
1560 $timezone_form = '';
1561 $timezone_js = '';
1562 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1563 // We split the list in continents/cities.
1564 $continents = array();
1565 $cities = array();
1566 foreach(timezone_identifiers_list() as $tz)
1567 {
1568 if ($tz=='UTC') $tz='UTC/UTC';
1569 $spos = strpos($tz,'/');
1570 if ($spos!==false)
1571 {
1572 $continent=substr($tz,0,$spos); $city=substr($tz,$spos+1);
1573 $continents[$continent]=1;
1574 if (!isset($cities[$continent])) $cities[$continent]=array();
1575 $cities[$continent].='<option value="'.$city.'"'.($pcity==$city?'selected':'').'>'.$city.'</option>';
1576 }
1577 }
1578 $continents_html = '';
1579 $continents = array_keys($continents);
1580 foreach($continents as $continent)
1581 $continents_html.='<option value="'.$continent.'"'.($pcontinent==$continent?'selected':'').'>'.$continent.'</option>';
1582 $cities_html = $cities[$pcontinent];
1583 $timezone_form = "Continent: <select name=\"continent\" id=\"continent\" onChange=\"onChangecontinent();\">${continents_html}</select><br /><br />";
1584 $timezone_form .= "City: <select name=\"city\" id=\"city\">${cities[$pcontinent]}</select><br /><br />";
1585 $timezone_js = "<script language=\"JavaScript\">";
1586 $timezone_js .= "function onChangecontinent(){document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];}";
1587 $timezone_js .= "var citiescontinent = ".json_encode($cities).";" ;
1588 $timezone_js .= "</script>" ;
1589 return array($timezone_form,$timezone_js);
1590 }
1591 return array('','');
1592 }
1593
1594 // Tells if a timezone is valid or not.
1595 // If not valid, returns false.
1596 // If system does not support timezone list, returns false.
1597 function isTZvalid($continent,$city)
1598 {
1599 $tz = $continent.'/'.$city;
1600 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1601 {
1602 if (in_array($tz, timezone_identifiers_list())) // it's a valid timezone ?
1603 return true;
1604 }
1605 return false;
1606 }
1607
1608
1609 // Webservices (for use with jQuery/jQueryUI)
1610 // eg. index.php?ws=tags&term=minecr
1611 function processWS()
1612 {
1613 if (empty($_GET['ws']) || empty($_GET['term'])) return;
1614 $term = $_GET['term'];
1615 global $LINKSDB;
1616 header('Content-Type: application/json; charset=utf-8');
1617
1618 // Search in tags (case insentitive, cumulative search)
1619 if ($_GET['ws']=='tags')
1620 {
1621 $tags=explode(' ',str_replace(',',' ',$term)); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
1622 $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags
1623 $suggested=array();
1624 /* To speed up things, we store list of tags in session */
1625 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1626 foreach($_SESSION['tags'] as $key=>$value)
1627 {
1628 if (startsWith($key,$last,$case=false) && !in_array($key,$tags)) $suggested[$addtags.$key.' ']=0;
1629 }
1630 echo json_encode(array_keys($suggested));
1631 exit;
1632 }
1633
1634 // Search a single tag (case sentitive, single tag search)
1635 if ($_GET['ws']=='singletag')
1636 {
1637 /* To speed up things, we store list of tags in session */
1638 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1639 foreach($_SESSION['tags'] as $key=>$value)
1640 {
1641 if (startsWith($key,$term,$case=true)) $suggested[$key]=0;
1642 }
1643 echo json_encode(array_keys($suggested));
1644 exit;
1645 }
1646 }
1647
1648 // Re-write configuration file according to globals.
1649 // Requires some $GLOBALS to be set (login,hash,salt,title).
1650 // If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1651 // (otherwise, the function simply returns.)
1652 function writeConfig()
1653 {
1654 if (is_file($GLOBALS['config']['CONFIG_FILE']) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config.
1655 if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
1656 $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; ';
1657 $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).';';
1658 $config .= '$GLOBALS[\'redirector\']='.var_export($GLOBALS['redirector'],true).'; ';
1659 $config .= ' ?>';
1660 if (!file_put_contents($GLOBALS['config']['CONFIG_FILE'],$config) || strcmp(file_get_contents($GLOBALS['config']['CONFIG_FILE']),$config)!=0)
1661 {
1662 echo '<script language="JavaScript">alert("Shaarli could not create the config file. Please make sure Shaarli has the right to write in the folder is it installed in.");document.location=\'?\';</script>';
1663 exit;
1664 }
1665 }
1666
1667 /* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
1668 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1669 The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
1670 This function is called by passing the url:
1671 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1672 [URL] is the URL of the link (eg. a flickr page)
1673 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1674 The function below will fetch the image from the webservice and store it in the cache.
1675 */
1676 function genThumbnail()
1677 {
1678 // Make sure the parameters in the URL were generated by us.
1679 $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']);
1680 if ($sign!=$_GET['hmac']) die('Naughty boy !');
1681
1682 // Let's see if we don't already have the image for this URL in the cache.
1683 $thumbname=hash('sha1',$_GET['url']).'.jpg';
1684 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname))
1685 { // We have the thumbnail, just serve it:
1686 header('Content-Type: image/jpeg');
1687 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname);
1688 return;
1689 }
1690 // We may also serve a blank image (if service did not respond)
1691 $blankname=hash('sha1',$_GET['url']).'.gif';
1692 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname))
1693 {
1694 header('Content-Type: image/gif');
1695 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname);
1696 return;
1697 }
1698
1699 // Otherwise, generate the thumbnail.
1700 $url = $_GET['url'];
1701 $domain = parse_url($url,PHP_URL_HOST);
1702
1703 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
1704 {
1705 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1706 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1707 // All images in Flickr are in the form:
1708 // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
1709 // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
1710 // We want the 240x120 format, which is _m.jpg.
1711 // We search for the first image in the page which does not have the _s size,
1712 // when use the _m to get the thumbnail.
1713
1714 // Is this a link to an image, or to a flickr page ?
1715 $imageurl='';
1716 if (endswith(parse_url($url,PHP_URL_PATH),'.jpg'))
1717 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1718 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
1719 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1720 }
1721 else // this is a flickr page (html)
1722 {
1723 list($httpstatus,$headers,$data) = getHTTP($url,20); // Get the flickr html page.
1724 if (strpos($httpstatus,'200 OK')!==false)
1725 {
1726 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!',$data,$matches);
1727 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1728 }
1729 }
1730 if ($imageurl!='')
1731 { // Let's download the image.
1732 list($httpstatus,$headers,$data) = getHTTP($imageurl,10); // Image is 240x120, so 10 seconds to download should be enough.
1733 if (strpos($httpstatus,'200 OK')!==false)
1734 {
1735 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
1736 header('Content-Type: image/jpeg');
1737 echo $data;
1738 return;
1739 }
1740 }
1741 }
1742
1743 elseif ($domain=='vimeo.com' )
1744 {
1745 // This is more complex: we have to perform a HTTP request, then parse the result.
1746 // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
1747 $vid = substr(parse_url($url,PHP_URL_PATH),1);
1748 list($httpstatus,$headers,$data) = getHTTP('http://vimeo.com/api/v2/video/'.htmlspecialchars($vid).'.php',5);
1749 if (strpos($httpstatus,'200 OK')!==false)
1750 {
1751 $t = unserialize($data);
1752 $imageurl = $t[0]['thumbnail_medium'];
1753 // Then we download the image and serve it to our client.
1754 list($httpstatus,$headers,$data) = getHTTP($imageurl,10);
1755 if (strpos($httpstatus,'200 OK')!==false)
1756 {
1757 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
1758 header('Content-Type: image/jpeg');
1759 echo $data;
1760 return;
1761 }
1762 }
1763 }
1764
1765 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1766 {
1767 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
1768 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
1769 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
1770 list($httpstatus,$headers,$data) = getHTTP($url,5);
1771 if (strpos($httpstatus,'200 OK')!==false)
1772 {
1773 // Extract the link to the thumbnail
1774 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)[^s]!',$data,$matches);
1775 if (!empty($matches[1]))
1776 { // Let's download the image.
1777 $imageurl=$matches[1];
1778 list($httpstatus,$headers,$data) = getHTTP($imageurl,20); // No control on image size, so wait long enough.
1779 if (strpos($httpstatus,'200 OK')!==false)
1780 {
1781 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
1782 file_put_contents($filepath,$data); // Save image to cache.
1783 if (resizeImage($filepath))
1784 {
1785 header('Content-Type: image/jpeg');
1786 echo file_get_contents($filepath);
1787 return;
1788 }
1789 }
1790 }
1791 }
1792 }
1793
1794 else
1795 {
1796 // For all other domains, we try to download the image and make a thumbnail.
1797 list($httpstatus,$headers,$data) = getHTTP($url,30); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1798 if (strpos($httpstatus,'200 OK')!==false)
1799 {
1800 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
1801 file_put_contents($filepath,$data); // Save image to cache.
1802 if (resizeImage($filepath))
1803 {
1804 header('Content-Type: image/jpeg');
1805 echo file_get_contents($filepath);
1806 return;
1807 }
1808 }
1809 }
1810
1811
1812 // Otherwise, return an empty image (8x8 transparent gif)
1813 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
1814 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice.
1815 header('Content-Type: image/gif');
1816 echo $blankgif;
1817 }
1818
1819 // Make a thumbnail of the image (to width: 120 pixels)
1820 // Returns true if success, false otherwise.
1821 function resizeImage($filepath)
1822 {
1823 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
1824
1825 // Trick: some stupid people rename GIF as JPEG... or else.
1826 // So we really try to open each image type whatever the extension is.
1827 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
1828 $im=false;
1829 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
1830 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
1831 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
1832 if (!$im) return false; // Unable to open image (corrupted or not an image)
1833 $w = imagesx($im);
1834 $h = imagesy($im);
1835 $ystart = 0; $yheight=$h;
1836 if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
1837 $nw = 120; // Desired width
1838 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
1839 // Resize image:
1840 $im2 = imagecreatetruecolor($nw,$nh);
1841 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
1842 imageinterlace($im2,true); // For progressive JPEG.
1843 $tempname=$filepath.'_TEMP.jpg';
1844 imagejpeg($im2, $tempname, 90);
1845 imagedestroy($im);
1846 imagedestroy($im2);
1847 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
1848 return true;
1849 }
1850
1851 // Invalidate caches when the database is changed or the user logs out.
1852 // (eg. tags cache).
1853 function invalidateCaches()
1854 {
1855 unset($_SESSION['tags']);
1856 }
1857
1858 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database.
1859 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
1860 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
1861 if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE'];
1862 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
1863 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; }
1864 renderPage();
1865 ?>