]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - index.php
Version 0.0.30 beta:
[github/shaarli/Shaarli.git] / index.php
index 276deb847ee4ba3ffbc80927318922a3d01c4491..88be084bd1e8c9cb90969a3b732ec73ce94437af 100644 (file)
--- a/index.php
+++ b/index.php
@@ -1,27 +1,31 @@
 <?php
-// Shaarli 0.0.19 beta - Shaare your links...
+// Shaarli 0.0.30 beta - Shaare your links...
 // The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net
 // http://sebsauvage.net/wiki/doku.php?id=php:shaarli
 // Licence: http://www.opensource.org/licenses/zlib-license.php
 
 // Requires: php 5.1.x
-
+// (but autocomplete fields will only work if you have php 5.2.x)
 // -----------------------------------------------------------------------------------------------
 // User config:
-define('DATADIR','data'); // Data subdirectory
-define('CONFIG_FILE',DATADIR.'/config.php'); // Configuration file (user login/password)
-define('DATASTORE',DATADIR.'/datastore.php'); // Data storage file.
-define('LINKS_PER_PAGE',20); // Default links per page.
-define('IPBANS_FILENAME',DATADIR.'/ipbans.php'); // File storage for failures and bans.
-define('BAN_AFTER',4);       // Ban IP after this many failures.
-define('BAN_DURATION',1800); // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
-define('OPEN_SHAARLI',false); // If true, anyone can add/edit/delete links without having to login
-define('HIDE_TIMESTAMPS',false); // If true, the moment when links were saved are not shown to users that are not logged in.
-
+$GLOBALS['config']['DATADIR'] = 'data'; // Data subdirectory
+$GLOBALS['config']['CONFIG_FILE'] = $GLOBALS['config']['DATADIR'].'/config.php'; // Configuration file (user login/password)
+$GLOBALS['config']['DATASTORE'] = $GLOBALS['config']['DATADIR'].'/datastore.php'; // Data storage file.
+$GLOBALS['config']['LINKS_PER_PAGE'] = 20; // Default links per page.
+$GLOBALS['config']['IPBANS_FILENAME'] = $GLOBALS['config']['DATADIR'].'/ipbans.php'; // File storage for failures and bans.
+$GLOBALS['config']['BAN_AFTER'] = 4;        // Ban IP after this many failures.
+$GLOBALS['config']['BAN_DURATION'] = 1800;  // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
+$GLOBALS['config']['OPEN_SHAARLI'] = false; // If true, anyone can add/edit/delete links without having to login
+$GLOBALS['config']['HIDE_TIMESTAMPS'] = false; // If true, the moment when links were saved are not shown to users that are not logged in.
+$GLOBALS['config']['ENABLE_THUMBNAILS'] = true; // Enable thumbnails in links.
+$GLOBALS['config']['CACHEDIR'] = 'cache'; // Cache directory for thumbnails for SLOW services (like flickr)
+$GLOBALS['config']['ENABLE_LOCALCACHE'] = true; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce webspace usage.
+$GLOBALS['config']['PUBSUBHUB_URL'] = ''; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
+                                          // Note: You must have publisher.php in the same directory as Shaarli index.php   
 // -----------------------------------------------------------------------------------------------
 // Program config (touch at your own risks !)
-define('UPDATECHECK_FILENAME',DATADIR.'/lastupdatecheck.txt'); // For updates check of Shaarli.
-define('UPDATECHECK_INTERVAL',86400); // Updates check frequency for Shaarli. 86400 seconds=24 hours
+$GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt'; // For updates check of Shaarli.
+$GLOBALS['config']['UPDATECHECK_INTERVAL'] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
 ini_set('max_input_time','60');  // High execution time in case of problematic imports/exports.
 ini_set('memory_limit', '128M');  // Try to set max upload file size and read (May not work on some hosts).
 ini_set('post_max_size', '16M');
@@ -34,6 +38,9 @@ error_reporting(E_ALL^E_WARNING);  // See all error except warnings.
 //error_reporting(-1); // See all errors (for debugging only)
 ob_start();
 
+// Optionnal config file.
+if (is_file($GLOBALS['config']['DATADIR'].'/options.php')) require($GLOBALS['config']['DATADIR'].'/options.php');
+
 // In case stupid admin has left magic_quotes enabled in php.ini:
 if (get_magic_quotes_gpc()) 
 {
@@ -47,11 +54,16 @@ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 header("Cache-Control: no-store, no-cache, must-revalidate");
 header("Cache-Control: post-check=0, pre-check=0", false);
 header("Pragma: no-cache");
-define('shaarli_version','0.0.19 beta');
-if (!is_dir(DATADIR)) { mkdir(DATADIR,0705); chmod(DATADIR,0705); }
-if (!is_file(DATADIR.'/.htaccess')) { file_put_contents(DATADIR.'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.    
-if (!is_file(CONFIG_FILE)) install();
-require CONFIG_FILE;  // Read login/password hash into $GLOBALS.
+define('shaarli_version','0.0.30 beta');
+if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); }
+if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.    
+if ($GLOBALS['config']['ENABLE_LOCALCACHE'])
+{
+    if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); }
+    if (!is_file($GLOBALS['config']['CACHEDIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['CACHEDIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.    
+}
+if (!is_file($GLOBALS['config']['CONFIG_FILE'])) install();
+require $GLOBALS['config']['CONFIG_FILE'];  // Read login/password hash into $GLOBALS.
 // Small protection against dodgy config files:
 if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']);
 if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
@@ -79,16 +91,16 @@ function checkUpdate()
     if (!isLoggedIn()) return ''; // Do not check versions for visitors.
     
     // Get latest version number at most once a day.
-    if (!is_file(UPDATECHECK_FILENAME) || (filemtime(UPDATECHECK_FILENAME)<time()-(UPDATECHECK_INTERVAL)))
+    if (!is_file($GLOBALS['config']['UPDATECHECK_FILENAME']) || (filemtime($GLOBALS['config']['UPDATECHECK_FILENAME'])<time()-($GLOBALS['config']['UPDATECHECK_INTERVAL'])))
     {
         $version=shaarli_version;
         list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2);
-        if (strpos($httpstatus,'200 OK')) $version=$data;
+        if (strpos($httpstatus,'200 OK')!==false) $version=$data;
         // If failed, nevermind. We don't want to bother the user with that.  
-        file_put_contents(UPDATECHECK_FILENAME,$version); // touch file date
+        file_put_contents($GLOBALS['config']['UPDATECHECK_FILENAME'],$version); // touch file date
     }
     // Compare versions:
-    $newestversion=file_get_contents(UPDATECHECK_FILENAME);
+    $newestversion=file_get_contents($GLOBALS['config']['UPDATECHECK_FILENAME']);
     if (version_compare($newestversion,shaarli_version)==1) return $newestversion;
     return '';
 }
@@ -98,9 +110,33 @@ function checkUpdate()
 function logm($message)
 {
     $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
-    file_put_contents(DATADIR.'/log.txt',$t,FILE_APPEND);
+    file_put_contents($GLOBALS['config']['DATADIR'].'/log.txt',$t,FILE_APPEND);
+}
+
+/* Returns the small hash of a string
+   eg. smallHash('20111006_131924') --> yZH23w
+   Small hashes:
+     - are unique (well, as unique as crc32, at last)
+     - are always 6 characters long.
+     - only use the following characters: a-z A-Z 0-9 - _ @
+     - are NOT cryptographically secure (they CAN be forged)
+   In Shaarli, they are used as a tinyurl-like link to individual entries.
+*/  
+function smallHash($text)
+{
+    $t = rtrim(base64_encode(hash('crc32',$text,true)),'=');
+    $t = str_replace('+','-',$t); // Get rid of characters which need encoding in URLs.
+    $t = str_replace('/','_',$t);
+    $t = str_replace('=','@',$t);
+    return $t;
 }
 
+// Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
+function text2clickable($url)
+{
+    $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'];
+    return preg_replace('!((?:https?|ftp)://\S+[[:alnum:]]/?)!si','<a href="'.$redir.'$1" rel="nofollow">$1</a>',$url);
+}
 // ------------------------------------------------------------------------------------------
 // Sniff browser language to display dates in the right format automatically.
 // (Note that is may not work on your server if the corresponding local is not installed.)
@@ -114,6 +150,23 @@ function autoLocale()
     setlocale(LC_TIME,$loc);  // LC_TIME = Set local for date/time format only.
 }
 
+// ------------------------------------------------------------------------------------------
+// PubSubHubbub protocol support (if enabled)  [UNTESTED]
+// (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
+if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) include './publisher.php';
+function pubsubhub()
+{
+    if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
+    {
+       $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
+       $topic_url = array (
+                       serverUrl().$_SERVER['SCRIPT_NAME'].'?do=atom',
+                       serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss'
+                    );
+       $p->publish_update($topic_url);
+    }
+}
+
 // ------------------------------------------------------------------------------------------
 // Session management
 define('INACTIVITY_TIMEOUT',3600); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
@@ -153,7 +206,7 @@ function check_auth($login,$password)
 // Returns true if the user is logged in.
 function isLoggedIn()
 { 
-    if (OPEN_SHAARLI) return true; 
+    if ($GLOBALS['config']['OPEN_SHAARLI']) return true; 
     
     // If session does not exist on server side, or IP address has changed, or session has expired, logout.
     if (empty($_SESSION['uid']) || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on'])
@@ -161,7 +214,9 @@ function isLoggedIn()
         logout();
         return false;
     }
-    $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT;  // User accessed a page : Update his/her session expiration date.
+    if (!empty($_SESSION['longlastingsession']))  $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
+    else $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
+    
     return true;
 }
 
@@ -172,21 +227,21 @@ function logout() { if (isset($_SESSION)) { unset($_SESSION['uid']); unset($_SES
 // ------------------------------------------------------------------------------------------
 // Brute force protection system
 // Several consecutive failed logins will ban the IP address for 30 minutes.
-if (!is_file(IPBANS_FILENAME)) file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>");
-include IPBANS_FILENAME;
+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?>");
+include $GLOBALS['config']['IPBANS_FILENAME'];
 // Signal a failed login. Will ban the IP if too many failures:
 function ban_loginFailed()
 {
     $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
     if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
     $gb['FAILURES'][$ip]++;
-    if ($gb['FAILURES'][$ip]>(BAN_AFTER-1))
+    if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1))
     {
-        $gb['BANS'][$ip]=time()+BAN_DURATION;
+        $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION'];
         logm('IP address banned from login');
     }
     $GLOBALS['IPBANS'] = $gb;
-    file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
+    file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
 }
 
 // Signals a successful login. Resets failed login counter.
@@ -195,7 +250,7 @@ function ban_loginOk()
     $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
     unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
     $GLOBALS['IPBANS'] = $gb;
-    file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
+    file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
 }
 
 // Checks if the user CAN login. If 'true', the user can try to login.
@@ -209,7 +264,7 @@ function ban_canLogin()
         {   // Ban expired, user can try to login again.
             logm('Ban lifted.');
             unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
-            file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
+            file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
             return true; // Ban has expired, user can login.
         }
         return false; // User is banned.
@@ -224,9 +279,22 @@ if (isset($_POST['login']))
     if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
     if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
     {   // Login/password is ok.
-        ban_loginOk();
+        ban_loginOk();  
+        // If user wants to keep the session cookie even after the browser closes:
+        if (!empty($_POST['longlastingsession']))
+        {
+            $_SESSION['longlastingsession']=31536000;  // (31536000 seconds = 1 year)
+            $_SESSION['expires_on']=time()+$_SESSION['longlastingsession'];  // Set session expiration on server-side.
+            session_set_cookie_params($_SESSION['longlastingsession']); // Set session cookie expiration on client side 
+            session_regenerate_id(true);  // Send cookie with new expiration date to browser.
+        }
+        else // Standard session expiration (=when browser closes)
+        {
+            session_set_cookie_params(0); // 0 means "When browser closes"
+            session_regenerate_id(true); 
+        }
         // Optional redirect after login:
-        if (isset($_GET['post'])) { header('Location: ?post='.urlencode($_GET['post']).(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); exit; }
+        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; }
         if (isset($_POST['returnurl']))
         { 
             if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
@@ -328,13 +396,13 @@ function linkdate2locale($linkdate)
 }
 
 // Parse HTTP response headers and return an associative array.
-function http_parse_headers( $headers ) 
+function http_parse_headers_shaarli( $headers ) 
 {
     $res=array();
     foreach($headers as $header)
     {
         $i = strpos($header,': ');
-        if ($i)
+        if ($i!==false)
         {
             $key=substr($header,0,$i);
             $value=substr($header,$i+2,strlen($header)-$i-2);
@@ -351,7 +419,7 @@ function http_parse_headers( $headers )
                       [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
                       [2] = data
     Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
-             if (strpos($httpstatus,'200 OK'))
+             if (strpos($httpstatus,'200 OK')!==false)
                  echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
              else
                  echo 'There was an error: '.htmlspecialchars($httpstatus)
@@ -362,10 +430,10 @@ function getHTTP($url,$timeout=30)
     {
         $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
         $context = stream_context_create($options);
-        $data=file_get_contents($url,false,$context,-1, 2000000); // We download at most 2 Mb from source.
+        $data=file_get_contents($url,false,$context,-1, 4000000); // We download at most 4 Mb from source.
         if (!$data) { $lasterror=error_get_last();  return array($lasterror['message'],array(),''); }
         $httpStatus=$http_response_header[0]; // eg. "HTTP/1.1 200 OK"
-        $responseHeaders=http_parse_headers($http_response_header);
+        $responseHeaders=http_parse_headers_shaarli($http_response_header);
         return array($httpStatus,$responseHeaders,$data);
     }
     catch (Exception $e)  // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
@@ -378,7 +446,7 @@ function getHTTP($url,$timeout=30)
 // (Returns an empty string if not found.)
 function html_extract_title($html) 
 {
-  return preg_match('!<title>(.*?)</title>!i', $html, $matches) ? $matches[1] : '';
+  return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ;   
 }
 
 // ------------------------------------------------------------------------------------------
@@ -469,14 +537,14 @@ class linkdb implements Iterator, Countable, ArrayAccess
     // ---- Misc methods
     private function checkdb() // Check if db directory and file exists.
     {
-        if (!file_exists(DATASTORE)) // Create a dummy database for example.
+        if (!file_exists($GLOBALS['config']['DATASTORE'])) // Create a dummy database for example.
         {
              $this->links = array();
              $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');
              $this->links[$link['linkdate']] = $link;
              $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');
              $this->links[$link['linkdate']] = $link;             
-             file_put_contents(DATASTORE, PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
+             file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
         }    
     }
     
@@ -484,7 +552,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
     private function readdb() 
     {
         // Read data
-        $this->links=(file_exists(DATASTORE) ? unserialize(gzinflate(base64_decode(substr(file_get_contents(DATASTORE),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
+        $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
         // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
         
         // If user is not logged in, filter private links.
@@ -504,7 +572,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
     public function savedb() 
     {
         if (!$this->loggedin) die('You are not authorized to change the database.');
-        file_put_contents(DATASTORE, PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
+        file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
     }
     
     // Returns the link for a given URL (if it exists). false it does not exist.
@@ -524,7 +592,10 @@ class linkdb implements Iterator, Countable, ArrayAccess
         $s = strtolower($searchterms);
         foreach($this->links as $l)
         { 
-            $found=strpos(strtolower($l['title']),$s) || strpos(strtolower($l['description']),$s) || strpos(strtolower($l['url']),$s) || strpos(strtolower($l['tags']),$s);
+            $found=   (strpos(strtolower($l['title']),$s)!==false)
+                   || (strpos(strtolower($l['description']),$s)!==false)
+                   || (strpos(strtolower($l['url']),$s)!==false)
+                   || (strpos(strtolower($l['tags']),$s)!==false);
             if ($found) $filtered[$l['linkdate']] = $l;
         }
         krsort($filtered);
@@ -548,6 +619,22 @@ class linkdb implements Iterator, Countable, ArrayAccess
         krsort($filtered);
         return $filtered;
     }   
+    
+    // Filter by smallHash.
+    // Only 1 article is returned.
+    public function filterSmallHash($smallHash)
+    {
+        $filtered=array();
+        foreach($this->links as $l)
+        { 
+            if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
+            {
+                $filtered[$l['linkdate']] = $l;
+                return $filtered;
+            }
+        }
+        return $filtered;
+    }     
 
     // Returns the list of all tags
     // Output: associative array key=tags, value=0
@@ -574,20 +661,33 @@ function showRSS()
     elseif (!empty($_GET['searchtags']))   $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
     else $linksToDisplay = $LINKSDB;
         
-    header('Content-Type: application/xhtml+xml; charset=utf-8');
+    header('Content-Type: application/rss+xml; charset=utf-8');
     $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]);
     echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
     echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>';
-    echo '<description>Shared links</description><language></language><copyright>'.$pageaddr.'</copyright>'."\n\n";
+    echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
+    if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
+    {
+        echo '<!-- PubSubHubbub Discovery -->';
+        echo '<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" xmlns="http://www.w3.org/2005/Atom" />';
+        echo '<link rel="self" href="'.htmlspecialchars($pageaddr).'?do=rss" xmlns="http://www.w3.org/2005/Atom" />';
+        echo '<!-- End Of PubSubHubbub Discovery -->';
+    }
     $i=0;
     $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; }  // No, I can't use array_keys().
     while ($i<50 && $i<count($keys))
     {
         $link = $linksToDisplay[$keys[$i]];
         $rfc822date = linkdate2rfc822($link['linkdate']);
-        echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.htmlspecialchars($link['url']).'</guid><link>'.htmlspecialchars($link['url']).'</link>';
-        if (!HIDE_TIMESTAMPS || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date).'</pubDate>';
-        echo '<description><![CDATA['.nl2br(htmlspecialchars($link['description'])).']]></description></item>'."\n";      
+        $absurl = htmlspecialchars($link['url']);
+        if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl;  // make permalink URL absolute
+        echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.$absurl.'</guid><link>'.$absurl.'</link>';
+        if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date)."</pubDate>\n";
+        if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
+        {     
+            foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.htmlspecialchars($pageaddr).'">'.htmlspecialchars($tag).'</category>'."\n"; }
+        }          
+        echo '<description><![CDATA['.nl2br(text2clickable(htmlspecialchars($link['description']))).']]></description>'."\n</item>\n";      
         $i++;
     }
     echo '</channel></rss>';
@@ -606,7 +706,7 @@ function showATOM()
     elseif (!empty($_GET['searchtags']))   $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
     else $linksToDisplay = $LINKSDB;
     
-    header('Content-Type: application/xhtml+xml; charset=utf-8');
+    header('Content-Type: application/atom+xml; charset=utf-8');
     $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]);
     $latestDate = '';
     $entries='';
@@ -617,15 +717,29 @@ function showATOM()
         $link = $linksToDisplay[$keys[$i]];
         $iso8601date = linkdate2iso8601($link['linkdate']);
         $latestDate = max($latestDate,$iso8601date);
-        $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title><link href="'.htmlspecialchars($link['url']).'"/><id>'.htmlspecialchars($link['url']).'</id>';
-        if (!HIDE_TIMESTAMPS || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>';
-        $entries.='<summary>'.nl2br(htmlspecialchars($link['description'])).'</summary></entry>'."\n";      
+        $absurl = htmlspecialchars($link['url']);
+        if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl;  // make permalink URL absolute        
+        $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title><link href="'.$absurl.'" /><id>'.$absurl.'</id>';
+        if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>';
+        $entries.='<summary>'.nl2br(text2clickable(htmlspecialchars($link['description'])))."</summary>\n";
+        if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification)
+        {     
+            foreach(explode(' ',$link['tags']) as $tag)
+                { $entries.='<category scheme="'.htmlspecialchars($pageaddr,ENT_QUOTES).'" term="'.htmlspecialchars($tag,ENT_QUOTES).'" />'."\n"; }
+        }  
+        $entries.="</entry>\n";      
         $i++;
     }
     $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
     $feed.='<title>'.htmlspecialchars($GLOBALS['title']).'</title>';
-    if (!HIDE_TIMESTAMPS || isLoggedIn()) $feed.='<updated>'.htmlspecialchars($latestDate).'</updated>';
-    $feed.='<link href="'.htmlspecialchars($pageaddr).'" />';
+    if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.htmlspecialchars($latestDate).'</updated>';
+    $feed.='<link rel="self" href="'.htmlspecialchars($pageaddr).'" />';
+    if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
+    {
+        $feed.='<!-- PubSubHubbub Discovery -->';
+        $feed.='<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" />';
+        $feed.='<!-- End Of PubSubHubbub Discovery -->';
+    }
     $feed.='<author><uri>'.htmlspecialchars($pageaddr).'</uri></author>';
     $feed.='<id>'.htmlspecialchars($pageaddr).'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
     $feed.=$entries;
@@ -647,7 +761,7 @@ function renderPage()
     // -------- Display login form.
     if (startswith($_SERVER["QUERY_STRING"],'do=login'))
     {
-        if (OPEN_SHAARLI) { header('Location: ?'); exit; }  // No need to login for open Shaarli
+        if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; }  // No need to login for open Shaarli
         if (!ban_canLogin())
         { 
             $loginform='<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>';
@@ -656,13 +770,13 @@ function renderPage()
             exit;
         }
         $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');        
-        $loginform='<div id="headerform"><form method="post" name="loginform">Login: <input type="text" name="login">&nbsp;&nbsp;&nbsp;Password : <input type="password" name="password"> <input type="submit" value="Login" class="bigbutton"><input type="hidden" name="token" value="'.getToken().'">'.$returnurl_html.'</form></div>';
+        $loginform='<div id="headerform"><form method="post" name="loginform">Login: <input type="text" name="login">&nbsp;&nbsp;&nbsp;Password : <input type="password" name="password"> <input type="submit" value="Login" class="bigbutton"><br>';
+        $loginform.='<input style="margin:10 0 0 40;" type="checkbox" name="longlastingsession" id="longlastingsession"><label for="longlastingsession">&nbsp;Stay signed in (Do not check on public computers)</label><input type="hidden" name="token" value="'.getToken().'">'.$returnurl_html.'</form></div>';
         $onload = 'onload="document.loginform.login.focus();"';
         $data = array('pageheader'=>$loginform,'body'=>'','onload'=>$onload); 
         templatePage($data);
         exit;
     }
-    
     // -------- User wants to logout.
     if (startswith($_SERVER["QUERY_STRING"],'do=logout'))
     { 
@@ -672,6 +786,33 @@ function renderPage()
         exit; 
     }  
 
+    // -------- Picture wall
+    if (startswith($_SERVER["QUERY_STRING"],'do=picwall'))
+    { 
+        // Optionnaly filter the results:
+        $linksToDisplay=array();
+        if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
+        elseif (!empty($_GET['searchtags']))   $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
+        else $linksToDisplay = $LINKSDB;
+        $body='';
+        
+        foreach($linksToDisplay as $link)
+        {
+               $href='?'.htmlspecialchars(smallhash($link['linkdate']),ENT_QUOTES);
+            $thumb=thumbnail($link['url'],$href);
+            if ($thumb!='')
+            {
+                $body.='<div class="picwall_pictureframe">'.$thumb.'<a href="'.$href.'"><span class="info">'.htmlspecialchars($link['title']).'</span></a></div>';
+                
+            }
+        }
+        $body = '<center><div id="picwall_container">'.$body.'<hr style="width:0;height:0;clear:both;"></div></center>';
+        $data = array('pageheader'=>'<br>&nbsp;','body'=>$body,'onload'=>''); 
+        templatePage($data);
+        exit;        
+        
+    }      
+
     // -------- Tag cloud
     if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
     { 
@@ -739,19 +880,18 @@ function renderPage()
         // Show login screen, then redirect to ?post=...
         if (isset($_GET['post'])) 
         {
-            header('Location: ?do=login&post='.urlencode($_GET['post']).(isset($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link.
+            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.
             exit;
         }
         
         // Show search form and display list of links.
         $searchform=<<<HTML
 <div id="headerform" style="width:100%; white-space:nowrap;";>
-    <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
-    <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
+    <form method="GET" class="searchform" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:30%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
+    <form method="GET" class="tagfilter" name="tagfilter" style="display:inline;margin-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:10%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
 </div>
 HTML;
-        $onload = 'onload="document.searchform.searchterm.focus();"';
-        $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload); 
+        $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>''); 
         templatePage($data);
         exit; // Never remove this one ! All operations below are reserved for logged in user.
     }
@@ -763,15 +903,15 @@ HTML;
     {
         $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ?
         // The javascript code for the bookmarklet:
-        $changepwd = (OPEN_SHAARLI ? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
+        $changepwd = ($GLOBALS['config']['OPEN_SHAARLI'] ? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
         $toolbar= <<<HTML
-<div id="headerform"><br>
+<div id="toolsdiv"><br>
     {$changepwd}        
     <a href="?do=configure"><b>Configure your Shaarli</b></a> - Change Title, timezone...<br><br>
     <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
     <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
     <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
-    <a class="smallbutton" style="color:black;" onclick="alert('Drag this link to your bookmarks toolbar, or right-click it and choose Bookmark This Link...');return false;" href="javascript:javascript:(function(){var%20url%20=%20location.href;var%20title%20=%20document.title%20||%20url;window.open('{$pageabsaddr}?post='%20+%20encodeURIComponent(url)+'&amp;title='%20+%20encodeURIComponent(title)+'&amp;source=bookmarklet','_blank','menubar=no,height=400,width=608,toolbar=no,scrollbars=no,status=no');})();">Shaare link</a> - Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....). Then click "Shaare link" button in any page you want to share.<br><br>
+    <a class="smallbutton"  onclick="alert('Drag this link to your bookmarks toolbar, or right-click it and choose Bookmark This Link...');return false;" href="javascript:javascript:(function(){var%20url%20=%20location.href;var%20title%20=%20document.title%20||%20url;window.open('{$pageabsaddr}?post='%20+%20encodeURIComponent(url)+'&amp;title='%20+%20encodeURIComponent(title)+'&amp;source=bookmarklet','_blank','menubar=no,height=400,width=608,toolbar=no,scrollbars=no,status=no');})();">Shaare link</a> - Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....). Then click "Shaare link" button in any page you want to share.<br><br>
 </div>
 HTML;
         $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>''); 
@@ -782,7 +922,7 @@ HTML;
     // -------- User wants to change his/her password.
     if (startswith($_SERVER["QUERY_STRING"],'do=changepasswd'))
     {
-        if (OPEN_SHAARLI) die('You are not supposed to change a password on an Open Shaarli.');
+        if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.');
         if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
         {
             if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
@@ -801,7 +941,7 @@ HTML;
         {
             $token = getToken();
             $changepwdform= <<<HTML
-<form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
+<form method="POST" action="" name="changepasswordform" id="changepasswordform">
 Old password: <input type="password" name="oldpassword">&nbsp; &nbsp;
 New password: <input type="password" name="setpassword">
 <input type="hidden" name="token" value="{$token}">
@@ -825,6 +965,7 @@ HTML;
                     $tz = $_POST['continent'].'/'.$_POST['city'];            
             $GLOBALS['timezone'] = $tz;
             $GLOBALS['title']=$_POST['title'];
+            $GLOBALS['redirector']=$_POST['redirector'];
             writeConfig();
             echo '<script language="JavaScript">alert("Configuration was saved.");document.location=\'?do=tools\';</script>';
             exit;
@@ -833,6 +974,7 @@ HTML;
         {
             $token = getToken();
             $title = htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES);
+            $redirector = htmlspecialchars( empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] , ENT_QUOTES);
             list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']);
             $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
             $changepwdform= <<<HTML
@@ -840,6 +982,7 @@ ${timezone_js}<form method="POST" action="" name="configform" id="configform"><i
 <table border="0" cellpadding="20">
 <tr><td><b>Page title:</b></td><td><input type="text" name="title" id="title" size="50" value="{$title}"></td></tr>
 {$timezone_html}
+<tr><td valign="top"><b>Redirector</b></td><td><input type="text" name="redirector" id="redirector" size="50" value="{$redirector}"><br>(e.g. <i>http://anonym.to/?</i> will mask the HTTP_REFERER)</td></tr>
 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
 </table>
 </form>
@@ -857,7 +1000,7 @@ HTML;
         {
             $token = getToken();
             $changetagform = <<<HTML
-<form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
+<form method="POST" action="" name="changetag" id="changetag">
 <input type="hidden" name="token" value="{$token}">
 Tag: <input type="text" name="fromtag" id="fromtag">
 <input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">      
@@ -910,7 +1053,7 @@ HTML;
     if (startswith($_SERVER["QUERY_STRING"],'do=addlink'))
     {
         $onload = 'onload="document.addform.post.focus();"';
-        $addform= '<div id="headerform"><form method="GET" action="" name="addform"><input type="text" name="post" style="width:70%;"> <input type="submit" value="Add link" class="bigbutton"></div>';
+        $addform= '<div id="headerform"><form method="GET" action="" name="addform" class="addform"><input type="text" name="post" style="width:50%;"> <input type="submit" value="Add link" class="bigbutton"></div>';
         $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload); 
         templatePage($data);
         exit;
@@ -923,10 +1066,11 @@ HTML;
         $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces.
         $linkdate=$_POST['lf_linkdate'];
         $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
-                      'linkdate'=>$linkdate,'tags'=>$tags);        
+                      'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags));        
         if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
         $LINKSDB[$linkdate] = $link;
         $LINKSDB->savedb(); // save to disk
+        pubsubhub();
         invalidateCaches();
         
         // If we are called from the bookmarklet, we must close the popup:
@@ -981,9 +1125,9 @@ HTML;
         $url=$_GET['post'];
 
         // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
-        $i=strpos($url,'&utm_source='); if ($i) $url=substr($url,0,$i);
-        $i=strpos($url,'?utm_source='); if ($i) $url=substr($url,0,$i);
-        $i=strpos($url,'#xtor=RSS-'); if ($i) $url=substr($url,0,$i);
+        $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i);
+        $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
+        $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
         
         $link_is_new = false;
         $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link)
@@ -993,14 +1137,15 @@ HTML;
             $linkdate = strval(date('Ymd_His'));
             $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
             $description=''; $tags=''; $private=0;
-            if (parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;                
+            if (($url!='') && parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;                
             // 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.)
             if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
             {
                 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
                 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html 
-                if (strpos($status,'200 OK')) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
+                if (strpos($status,'200 OK')!==false) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
             }
+            if ($url=='') $url='?'.smallHash($linkdate); // In case of empty URL, this is just a text (with a link that point to itself)
             $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0); 
         }
         list($editform,$onload)=templateEditForm($link,$link_is_new); 
@@ -1015,7 +1160,7 @@ HTML;
         if (empty($_GET['what']))
         {
             $toolbar= <<<HTML
-<div id="headerform"><br>
+<div id="toolsdiv">
     <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
     <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
     <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
@@ -1077,9 +1222,9 @@ HTML;
         $maxfilesize=getMaxFileSize();
         $onload = 'onload="document.uploadform.filetoupload.focus();"';
         $uploadform=<<<HTML
-<div id="headerform">
+<div id="uploaddiv">
 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
-<form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
+<form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform" id="uploadform">
     <input type="hidden" name="token" value="{$token}">
     <input type="file" name="filetoupload" size="80">
     <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
@@ -1097,12 +1242,11 @@ HTML;
     // -------- Otherwise, simply display search form and links:
     $searchform=<<<HTML
 <div id="headerform" style="width:100%; white-space:nowrap;";>
-    <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
-    <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
+    <form method="GET" class="searchform" name="searchform"><input type="text" name="searchterm" style="width:30%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
+    <form method="GET" class="tagfilter" name="tagfilter" style="margin-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:10%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
 </div>
 HTML;
-    $onload = 'onload="document.searchform.searchterm.focus();"';
-    $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload); 
+    $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>''); 
     templatePage($data);
     exit;
 }    
@@ -1219,24 +1363,28 @@ HTML;
 function templateLinkList()
 {     
     global $LINKSDB;
-    
+
     // Search according to entered search terms:
     $linksToDisplay=array();
     $searched='';
     if (!empty($_GET['searchterm'])) // Fulltext search
     {
         $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
-        $searched='&nbsp;<b>'.count($linksToDisplay).' results for <i>'.htmlspecialchars(trim($_GET['searchterm'])).'</i></b>:';
+        $searched=count($linksToDisplay).' results for <i>'.htmlspecialchars(trim($_GET['searchterm'])).'</i>:';
     }
     elseif (!empty($_GET['searchtags'])) // Search by tag
     {
         $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
         $tagshtml=''; foreach(explode(' ',trim($_GET['searchtags'])) as $tag) $tagshtml.='<span class="linktag" title="Remove tag"><a href="?removetag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).' <span style="border-left:1px solid #aaa; padding-left:5px; color:#6767A7;">x</span></a></span> ';
-        $searched='&nbsp;<b>'.count($linksToDisplay).' results for tags '.$tagshtml.':</b>';    
+        $searched=''.count($linksToDisplay).' results for tags '.$tagshtml.':';    
+    }
+    elseif (preg_match('/[a-zA-Z0-9-_@]{6}/',$_SERVER["QUERY_STRING"])) // Detect smallHashes in URL
+    {
+        $linksToDisplay = $LINKSDB->filterSmallHash($_SERVER["QUERY_STRING"]);
     }
     else
         $linksToDisplay = $LINKSDB;  // otherwise, display without filtering.
-   
+    if ($searched!='') $searched='<div id="searchcriteria">'.$searched.'</div>';
     $linklist='';
     $actions='';
     
@@ -1246,26 +1394,45 @@ function templateLinkList()
        If my class implements ArrayAccess, why won't array_keys() accept it ?  ( $keys=array_keys($linksToDisplay); )
     */
     $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // Stupid and ugly. Thanks php.
+
+    // If there is only a single link, we change on-the-fly the title of the page.
+    if (count($linksToDisplay)==1) $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title'];
+
     $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
     $pagecount = ($pagecount==0 ? 1 : $pagecount);
     $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
     $page = ( $page<1 ? 1 : $page );
     $page = ( $page>$pagecount ? $pagecount : $page );
     $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
-    $end = $i+$_SESSION['LINKS_PER_PAGE'];    
+    $end = $i+$_SESSION['LINKS_PER_PAGE'];  
+    $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector']; // optional redirector URL
+    $token = ''; if (isLoggedIn()) $token=getToken();
+    
     while ($i<$end && $i<count($keys))
     {  
         $link = $linksToDisplay[$keys[$i]];
-        $description=$link['description'];
+        $description=text2clickable(htmlspecialchars($link['description']));
         $title=$link['title'];
-        $classprivate = ($link['private']==0 ? '' : 'class="private"');
-        if (isLoggedIn()) $actions=' <form method="GET" class="buttoneditform"><input type="hidden" name="edit_link" value="'.$link['linkdate'].'"><input type="submit" value="Edit" class="smallbutton"></form>';
+        $classLi =  $i%2!=0 ? '' : 'class="publicLinkHightLight"';
+        $classprivate = ($link['private']==0 ? $classLi : 'class="private"');
+        if (isLoggedIn())
+        {
+            $actions=' <form method="GET" class="buttoneditform"><input type="hidden" name="edit_link" value="'.$link['linkdate'].'"><input type="submit" value="Edit" class="smallbutton"></form>';
+            $actions.=' <form method="POST" class="buttoneditform"><input type="hidden" name="lf_linkdate" value="'.$link['linkdate'].'">';
+            $actions.='<input type="hidden" name="token" value="'.$token.'"><input type="submit" value="Delete" name="delete_link" class="smallbutton" onClick="return confirmDeleteLink();"></form>';
+        }
         $tags='';
-        if ($link['tags']!='') foreach(explode(' ',$link['tags']) as $tag) { $tags.='<span class="linktag" title="Add tag"><a href="?addtag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).'</a></span> '; }
-        $linklist.='<li '.$classprivate.'><span class="linktitle"><a href="'.htmlspecialchars($link['url']).'">'.htmlspecialchars($title).'</a></span>'.$actions.'<br>';
-        if ($description!='') $linklist.='<div class="linkdescription">'.nl2br(htmlspecialchars($description)).'</div><br>';
-        if (!HIDE_TIMESTAMPS || isLoggedIn()) $linklist.='<span class="linkdate">'.htmlspecialchars(linkdate2locale($link['linkdate'])).' - </span>';
-        $linklist.='<span class="linkurl">'.htmlspecialchars($link['url']).'</span><br>'.$tags."</li>\n";  
+        if ($link['tags']!='')
+        {
+            foreach(explode(' ',$link['tags']) as $tag) { $tags.='<span class="linktag" title="Add tag"><a href="?addtag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).'</a></span> '; }
+            $tags='<div class="linktaglist">'.$tags.'</div>';
+        }
+        $linklist.='<li '.$classprivate.'><div class="thumbnail">'.thumbnail($link['url']).'</div>';
+        $linklist.='<div class="linkcontainer"><span class="linktitle"><a href="'.$redir.htmlspecialchars($link['url']).'">'.htmlspecialchars($title).'</a></span>'.$actions.'<br>';
+        if ($description!='') $linklist.='<div class="linkdescription">'.nl2br($description).'</div><br>';
+        if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $linklist.='<span class="linkdate" title="Permalink"><a href="?'.smallHash($link['linkdate']).'">'.htmlspecialchars(linkdate2locale($link['linkdate'])).' - permalink</a> - </span>';
+        else $linklist.='<span class="linkdate" title="Short link here"><a href="?'.smallHash($link['linkdate']).'">permalink</a> - </span>';
+        $linklist.='<span class="linkurl" title="Short link">'.htmlspecialchars($link['url']).'</span><br>'.$tags."</div></li>\n";  
         $i++;
     } 
     
@@ -1279,13 +1446,99 @@ function templateLinkList()
     $linksperpage = <<<HTML
 <div style="float:right; padding-right:5px;">
 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
- <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
+ <form method="GET" style="display:inline;" class="linksperpage"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
 HTML;
     $paging = '<div class="paging">'.$linksperpage.$paging.'</div>';
     $linklist='<div id="linklist">'.$paging.$searched.'<ul>'.$linklist.'</ul>'.$paging.'</div>';
     return $linklist;
 }
 
+// Returns the HTML code to display a thumbnail for a link
+// with a link to the original URL.
+// Understands various services (youtube.com...)
+// Input: $url = url for which the thumbnail must be found.
+//        $href = if provided, this URL will be followed instead of $url 
+function thumbnail($url,$href=false)
+{
+    if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return '';
+    
+    if ($href==false) $href=$url;
+    
+    // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
+    // (eg. http://www.youtube.com/watch?v=spVypYk4kto --->  http://img.youtube.com/vi/spVypYk4kto/default.jpg )
+    //                                     ^^^^^^^^^^^                                 ^^^^^^^^^^^
+    $domain = parse_url($url,PHP_URL_HOST);
+    if ($domain=='youtube.com' || $domain=='www.youtube.com')
+    {
+        parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
+        if (!empty($params['v'])) return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi/'.htmlspecialchars($params['v']).'/default.jpg" width="120" height="90"></a>';
+    }
+    if ($domain=='youtu.be') // Youtube short links
+    {
+        $path = parse_url($url,PHP_URL_PATH);
+        return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi'.htmlspecialchars($path).'/default.jpg" width="120" height="90"></a>';
+    } 
+    if ($domain=='imgur.com')
+    {
+        $path = parse_url($url,PHP_URL_PATH);
+        if (startsWith($path,'/a/')) return ''; // Thumbnails for albums are not available.
+        if (startsWith($path,'/r/')) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars(basename($path)).'s.jpg" width="90" height="90"></a>';
+        if (startsWith($path,'/gallery/')) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com'.htmlspecialchars(substr($path,8)).'s.jpg" width="90" height="90"></a>';
+        if (substr_count($path,'/')==1) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars(substr($path,1)).'s.jpg" width="90" height="90"></a>';
+    }
+    if ($domain=='i.imgur.com')
+    {
+        $pi = pathinfo(parse_url($url,PHP_URL_PATH));
+        if (!empty($pi['filename'])) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars($pi['filename']).'s.jpg" width="90" height="90"></a>';
+    } 
+    if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
+    {
+        if (strpos($url,'dailymotion.com/video/')!==false)
+        {
+            $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
+            return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
+        }
+    } 
+    if (endsWith($domain,'.imageshack.us'))
+    {
+        $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
+        if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
+        {
+            $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
+            return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
+        }
+    }
+
+    // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
+    // So we deport the thumbnail generation in order not to slow down page generation
+    // (and we also cache the thumbnail)
+    
+    if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return ''; // If local cache is disabled, no thumbnails for services which require the use a local cache.
+    
+    if ($domain=='flickr.com' || endsWith($domain,'.flickr.com') || $domain=='vimeo.com')
+    {
+       if ($domain=='vimeo.com')
+       {   // Make sure this vimeo url points to a video (/xxx... where xxx is numeric)
+               $path = parse_url($url,PHP_URL_PATH); 
+               if (!preg_match('!/\d+.+?!',$path)) return ''; // This is not a single video URL.
+       }
+        $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
+        return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';
+    }
+
+    // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
+    // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
+    // But using the extension will do.
+    $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
+    if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
+    {
+        $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
+        return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';        
+    }
+    return ''; // No thumbnail.
+
+}
+
 // -----------------------------------------------------------------------------------------------
 // Template for the whole page.
 /* Input: $data (associative array).
@@ -1303,7 +1556,7 @@ function templatePage($data)
     if ($newversion!='') $newversion='<div id="newversion"><span style="text-decoration:blink;">&#x25CF;</span> Shaarli '.htmlspecialchars($newversion).' is <a href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli#download">available</a>.</div>';
     $linkcount = count($LINKSDB);
     $open='';
-    if (OPEN_SHAARLI)
+    if ($GLOBALS['config']['OPEN_SHAARLI'])
     {
         $menu=' <a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>';
         $open='Open ';
@@ -1316,10 +1569,10 @@ function templatePage($data)
         if (!array_key_exists($k,$data)) $data[$k]='';
     }
     $jsincludes=''; $jsincludes_bottom = '';
-    if (OPEN_SHAARLI || isLoggedIn())
+    if ($GLOBALS['config']['OPEN_SHAARLI'] || isLoggedIn())
     { 
-        $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>'; 
         $source = serverUrl().$_SERVER['SCRIPT_NAME'];  
+        $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>'; 
         $jsincludes_bottom = <<<JS
 <script language="JavaScript">
 $(document).ready(function() 
@@ -1332,29 +1585,35 @@ $(document).ready(function()
 JS;
     }
     $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']); 
-    if (!empty($_GET['searchtags'])) $feedurl.='&searchtags='.$_GET['searchtags'];
-    elseif (!empty($_GET['searchterm'])) $feedurl.='&searchterm='.$_GET['searchterm'];
+    $searchcrits=''; // Search criteria
+    if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.$_GET['searchtags'];
+    elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.$_GET['searchterm'];
+    $filtered_feed= ($searchcrits=='' ? '' : 'Filtered ');
+    $version=shaarli_version;
 
     $title = htmlspecialchars( $GLOBALS['title'] );
+    $pagetitle = htmlspecialchars( empty($GLOBALS['pagetitle']) ? $title : $GLOBALS['pagetitle'] );
     echo <<<HTML
 <html>
 <head>
-<title>{$title}</title>
-<link rel="alternate" type="application/rss+xml" href="{$feedurl}" />
-<link type="text/css" rel="stylesheet" href="shaarli.css" />
+<title>{$pagetitle}</title>
+<link rel="alternate" type="application/rss+xml" href="{$feedurl}?do=rss{$searchcrits}" title="{$filtered_feed}RSS Feed" />
+<link rel="alternate" type="application/atom+xml" href="{$feedurl}?do=atom{$searchcrits}" title="{$filtered_feed}ATOM Feed" />
+<link href="./images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
+<link type="text/css" rel="stylesheet" href="shaarli.css?version={$version}" />
 {$jsincludes}
 </head>
 <body {$data['onload']}>{$newversion}
-<div id="pageheader"><div style="float:right; font-style:italic; color:#bbb; text-align:right; padding:0 5 0 0;">Shaare your links...<br>{$linkcount} links</div>
-    <b><i>{$title}</i></b> - <a href="?">Home</a>&nbsp;{$menu}&nbsp;<a href="{$feedurl}?do=rss" style="padding-left:30px;">RSS Feed</a> <a href="{$feedurl}?do=atom" style="padding-left:10px;">ATOM Feed</a>
-&nbsp;&nbsp; <a href="?do=tagcloud">Tag cloud</a>
+<div id="pageheader"><div id="logo" title="Share your links !"></div><div style="float:right; font-style:italic; color:#bbb; text-align:right; padding:0 5 0 0;">Shaare your links...<br>{$linkcount} links</div>
+    <span id="shaarli_title"><a href="?">{$title}</a></span> - <a href="?">Home</a>&nbsp;{$menu}&nbsp;<a href="{$feedurl}?do=rss{$searchcrits}">RSS Feed</a> <a href="{$feedurl}?do=atom{$searchcrits}" style="padding-left:10px;">ATOM Feed</a>
+&nbsp;&nbsp; <a href="?do=tagcloud">Tag cloud</a>&nbsp;&nbsp; <a href="?do=picwall{$searchcrits}">Picture wall</a>
 {$data['pageheader']}
 </div>
 {$data['body']}
 
 HTML;
     $exectime = round(microtime(true)-$STARTTIME,4);
-    echo '<div id="footer"><b><a href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli">Shaarli '.shaarli_version.'</a></b> - The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net<br>Who gives a shit that this page was generated in '.$exectime.' seconds&nbsp;?</div>';
+    echo '<div id="footer"><b><a href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli">Shaarli '.shaarli_version.'</a></b> - The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net. Theme by idleman.fr.<br>Who gives a shit that this page was generated in '.$exectime.' seconds&nbsp;?</div>';
     if (isLoggedIn()) echo '<script language="JavaScript">function confirmDeleteLink() { var agree=confirm("Are you sure you want to delete this link ?"); if (agree) return true ; else return false ; }</script>';
     echo $jsincludes_bottom.'</body></html>';
 }
@@ -1428,7 +1687,7 @@ function templateTZform($ptz=false)
         {
             if ($tz=='UTC') $tz='UTC/UTC';
             $spos = strpos($tz,'/');
-            if ($spos)
+            if ($spos!==false)
             {
                 $continent=substr($tz,0,$spos); $city=substr($tz,$spos+1);
                 $continents[$continent]=1;
@@ -1479,14 +1738,14 @@ function processWS()
     // Search in tags (case insentitive, cumulative search)
     if ($_GET['ws']=='tags')
     { 
-        $tags=explode(' ',$term); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
+        $tags=explode(' ',str_replace(',',' ',$term)); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
         $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags
         $suggested=array();
         /* To speed up things, we store list of tags in session */
         if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags(); 
         foreach($_SESSION['tags'] as $key=>$value)
         {
-            if (startsWith($key,$last,$case=false)) $suggested[$addtags.$key.' ']=0;
+            if (startsWith($key,$last,$case=false) && !in_array($key,$tags)) $suggested[$addtags.$key.' ']=0;
         }      
         echo json_encode(array_keys($suggested));
         exit;
@@ -1512,16 +1771,171 @@ function processWS()
 // (otherwise, the function simply returns.)
 function writeConfig()
 {
-    if (is_file(CONFIG_FILE) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config.
+    if (is_file($GLOBALS['config']['CONFIG_FILE']) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config.
+    if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
     $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; ';
-    $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).'; ?>';    
-    if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(CONFIG_FILE),$config)!=0)
+    $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).';';
+    $config .= '$GLOBALS[\'redirector\']='.var_export($GLOBALS['redirector'],true).'; ';
+    $config .= ' ?>';    
+    if (!file_put_contents($GLOBALS['config']['CONFIG_FILE'],$config) || strcmp(file_get_contents($GLOBALS['config']['CONFIG_FILE']),$config)!=0)
     {
         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>';
         exit;
     }
 }
 
+/* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
+   I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
+   The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
+   This function is called by passing the url:
+   http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
+   [URL] is the URL of the link (eg. a flickr page)
+   [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
+   The function below will fetch the image from the webservice and store it in the cache.
+*/
+function genThumbnail()
+{
+    // Make sure the parameters in the URL were generated by us.
+    $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']);
+    if ($sign!=$_GET['hmac']) die('Naughty boy !'); 
+    
+    // Let's see if we don't already have the image for this URL in the cache.
+    $thumbname=hash('sha1',$_GET['url']).'.jpg';
+    if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname))
+    {   // We have the thumbnail, just serve it:
+        header('Content-Type: image/jpeg');
+        echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname);  
+        return;
+    }
+    // We may also serve a blank image (if service did not respond)
+    $blankname=hash('sha1',$_GET['url']).'.gif';
+    if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname))
+    {
+        header('Content-Type: image/gif');
+        echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname);  
+        return;
+    }    
+    
+    // Otherwise, generate the thumbnail.
+    $url = $_GET['url'];
+    $domain = parse_url($url,PHP_URL_HOST);
+
+    if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
+    {    
+        // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
+        // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
+        // All images in Flickr are in the form:
+        // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
+        // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
+        // We want the 240x120 format, which is _m.jpg.
+        // We search for the first image in the page which does not have the _s size,
+        // when use the _m to get the thumbnail.
+
+        // Is this a link to an image, or to a flickr page ?
+        $imageurl='';
+        if (endswith(parse_url($url,PHP_URL_PATH),'.jpg'))
+        {  // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
+            preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
+            if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';  
+        }
+        else // this is a flickr page (html)
+        {
+            list($httpstatus,$headers,$data) = getHTTP($url,20); // Get the flickr html page.
+            if (strpos($httpstatus,'200 OK')!==false)
+            {
+                preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!',$data,$matches);
+                if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';  
+            }
+        }
+        if ($imageurl!='')
+        {   // Let's download the image.
+            list($httpstatus,$headers,$data) = getHTTP($imageurl,10); // Image is 240x120, so 10 seconds to download should be enough.
+            if (strpos($httpstatus,'200 OK')!==false)
+            {
+                file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
+                header('Content-Type: image/jpeg');
+                echo $data;
+                return;
+            }
+        } 
+    }
+
+    if ($domain=='vimeo.com' )
+    {
+        // This is more complex: we have to perform a HTTP request, then parse the result.
+        // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
+        $vid = substr(parse_url($url,PHP_URL_PATH),1);
+        list($httpstatus,$headers,$data) = getHTTP('http://vimeo.com/api/v2/video/'.htmlspecialchars($vid).'.php',5);
+        if (strpos($httpstatus,'200 OK')!==false)
+        {
+            $t = unserialize($data);
+            $imageurl = $t[0]['thumbnail_medium'];
+            // Then we download the image and serve it to our client.
+            list($httpstatus,$headers,$data) = getHTTP($imageurl,10);
+            if (strpos($httpstatus,'200 OK')!==false)
+            {
+                file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
+                header('Content-Type: image/jpeg');
+                echo $data;
+                return;
+            }           
+        }  
+    }
+    
+    // For all other domains, we try to download the image and make a thumbnail.
+    list($httpstatus,$headers,$data) = getHTTP($url,30);  // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
+    if (strpos($httpstatus,'200 OK')!==false)
+    {
+        $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
+        file_put_contents($filepath,$data); // Save image to cache.
+        if (resizeImage($filepath))
+        {
+            header('Content-Type: image/jpeg');
+            echo file_get_contents($filepath);  
+            return;
+        }
+    }  
+
+
+    // Otherwise, return an empty image (8x8 transparent gif)
+    $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
+    file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice.
+    header('Content-Type: image/gif');
+    echo $blankgif;
+}
+
+// Make a thumbnail of the image (to width: 120 pixels)
+// Returns true if success, false otherwise.
+function resizeImage($filepath)
+{
+    if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
+
+    // Trick: some stupid people rename GIF as JPEG... or else.
+    // So we really try to open each image type whatever the extension is.
+    $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
+    $im=false;
+    $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
+    $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
+    $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
+    if (!$im) return false;  // Unable to open image (corrupted or not an image)
+    $w = imagesx($im);
+    $h = imagesy($im);
+    $ystart = 0; $yheight=$h;
+    if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
+    $nw = 120;   // Desired width
+    $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
+    // Resize image:
+    $im2 = imagecreatetruecolor($nw,$nh);
+    imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
+    imageinterlace($im2,true); // For progressive JPEG.
+    $tempname=$filepath.'_TEMP.jpg';
+    imagejpeg($im2, $tempname, 90);
+    imagedestroy($im);
+    imagedestroy($im2);
+    rename($tempname,$filepath);  // Overwrite original picture with thumbnail.
+    return true;
+}
+
 // Invalidate caches when the database is changed or the user logs out.
 // (eg. tags cache).
 function invalidateCaches()
@@ -1529,9 +1943,10 @@ function invalidateCaches()
     unset($_SESSION['tags']);
 }
 
-$LINKSDB=new linkdb(isLoggedIn() || OPEN_SHAARLI);  // Read links from database (and filter private links if used it not logged in).
+if (startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; }  // Thumbnail generation/cache does not need the link database.
+$LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);  // Read links from database (and filter private links if used it not logged in).
 if (startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
-if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=LINKS_PER_PAGE;
+if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE'];
 if (startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
 if (startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; }
 renderPage();