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