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