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