]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - index.php
Version 0.0.15 beta:
[github/shaarli/Shaarli.git] / index.php
index d1f31609bcd43907962ad9de1e7c387f77b984ed..babce3dca8f6aa5b380b1c11775cec37883af557 100644 (file)
--- a/index.php
+++ b/index.php
@@ -1,5 +1,5 @@
 <?php
-// Shaarli 0.0.11 beta - Shaare your links...
+// Shaarli 0.0.15 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
@@ -15,36 +15,39 @@ 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)
-if (get_magic_quotes_gpc())
-{
-    header('Content-Type: text/plain; charset=utf-8');
-    echo "ERROR: magic_quotes_gpc is ON in your php config. This is *BAD*. You *MUST* disable it, either by changing the value in php.ini,\n";
-    echo "or by adding the following line in .htaccess: php_flag magic_quotes_gpc Off"; exit;
-}
-checkphpversion();
+define('OPEN_SHAARLI',false); // If true, anyone can add/edit/delete links without having to login
 
 // -----------------------------------------------------------------------------------------------
 // Program config (touch at your own risks !)
+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');
+ini_set('upload_max_filesize', '16M');
+define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
+define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
+$STARTTIME = microtime(true);  // Measure page execution time.
+checkphpversion();
 error_reporting(E_ALL^E_WARNING);  // See all error except warnings.
 //error_reporting(-1); // See all errors (for debugging only)
-$STARTTIME = microtime(true);  // Measure page execution time.
 ob_start();
+// In case stupid admin has left magic_quotes enabled in php.ini:
+if (get_magic_quotes_gpc()) 
+{
+    function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
+    $_POST = array_map('stripslashes_deep', $_POST);
+    $_GET = array_map('stripslashes_deep', $_GET);
+    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
+}
 // Prevent caching: (yes, it's ugly)
 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.11 beta');
+define('shaarli_version','0.0.15 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.
-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');
-ini_set('upload_max_filesize', '16M');
-define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
-define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
 autoLocale(); // Sniff browser language and set date format accordingly.
 header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
 $LINKSDB=false;
@@ -57,7 +60,9 @@ function checkphpversion()
     {
         list($match,$major,$minor,$release) = $matches;
         if ($major>=5 && $minor>=1) return; // 5.1.x or higher is ok.
-        die('Your server supports php '.$ver.'. Shaarli requires at last php 5.1, and thus cannot run. Sorry.');
+        header('Content-Type: text/plain; charset=utf-8');
+        echo 'Your server supports php '.$ver.'. Shaarli requires at last php 5.1, and thus cannot run. Sorry.';
+        exit;
     }
     // if cannot check php version... well, at your own risks.
 }
@@ -124,6 +129,8 @@ function check_auth($login,$password)
 // Returns true if the user is logged in.
 function isLoggedIn()
 { 
+    if (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'])
     {
@@ -196,7 +203,11 @@ if (isset($_POST['login']))
         ban_loginOk();
         // Optional redirect after login:
         if (isset($_GET['post'])) { header('Location: ?post='.urlencode($_GET['post']).(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); exit; }
-        if (isset($_POST['returnurl'])) { header('Location: '.$_POST['returnurl']); exit; }
+        if (isset($_POST['returnurl']))
+        { 
+            if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
+            header('Location: '.$_POST['returnurl']); exit; 
+        }
         header('Location: ?'); exit;
     }
     else
@@ -504,8 +515,20 @@ class linkdb implements Iterator, Countable, ArrayAccess
         }
         krsort($filtered);
         return $filtered;
+    }   
 
-    }      
+    // Returns the list of all tags
+    // Output: associative array key=tags, value=0
+    public function allTags()
+    {
+        $tags=array();
+        foreach($this->links as $link)
+            foreach(explode(' ',$link['tags']) as $tag)
+                if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
+        arsort($tags); // Sort tags by usage (most used tag first)
+        return $tags;
+    }
+    
 }
 
 // ------------------------------------------------------------------------------------------
@@ -513,16 +536,23 @@ class linkdb implements Iterator, Countable, ArrayAccess
 function showRSS()
 {
     global $LINKSDB;
+    
+    // Optionnaly filter the results:
+    $linksToDisplay=array();
+    if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
+    elseif (!empty($_GET['searchtags']))   $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']);
+    else $linksToDisplay = $LINKSDB;
+        
     header('Content-Type: application/xhtml+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>Shared links on '.$pageaddr.'</title><link>'.$pageaddr.'</link>';
     echo '<description>Shared links</description><language></language><copyright>'.$pageaddr.'</copyright>'."\n\n";
     $i=0;
-    $keys=array(); foreach($LINKSDB as $key=>$value) { $keys[]=$key; }  // No, I can't use array_keys().
+    $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; }  // No, I can't use array_keys().
     while ($i<50 && $i<count($keys))
     {
-        $link = $LINKSDB[$keys[$i]];
+        $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><pubDate>'.htmlspecialchars($rfc822date).'</pubDate>';
         echo '<description><![CDATA['.htmlspecialchars($link['description']).']]></description></item>'."\n";      
@@ -545,6 +575,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 (!ban_canLogin())
         { 
             $loginform='<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>';
@@ -563,6 +594,7 @@ function renderPage()
     // -------- User wants to logout.
     if (startswith($_SERVER["QUERY_STRING"],'do=logout'))
     { 
+        invalidateCaches(); 
         logout(); 
         header('Location: ?'); 
         exit; 
@@ -638,10 +670,10 @@ HTML;
         $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ?
         // The javascript code for the bookmarklet:
         $toolbar= <<<HTML
-<div id="headerform">
-    <a href="?do=import"><b>Import</b></a> - <small>Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)</small><br> 
-    <a href="?do=export"><b>Export</b></a> - <small>Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)</small><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> - <small>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.</small>
+<div id="headerform"><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>
 </div>
 HTML;
         $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>''); 
@@ -669,6 +701,7 @@ HTML;
         if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
         $LINKSDB[$linkdate] = $link;
         $LINKSDB->savedb(); // save to disk
+        invalidateCaches();
         
         // If we are called from the bookmarklet, we must close the popup:
         if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
@@ -697,6 +730,7 @@ HTML;
         $linkdate=$_POST['lf_linkdate'];
         unset($LINKSDB[$linkdate]);
         $LINKSDB->savedb(); // save to disk
+        invalidateCaches();
         // If we are called from the bookmarklet, we must close the popup:
         if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
         $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
@@ -723,6 +757,7 @@ HTML;
         // 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);
         
         $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)
@@ -750,9 +785,25 @@ HTML;
     
     // -------- Export as Netscape Bookmarks HTML file.
     if (startswith($_SERVER["QUERY_STRING"],'do=export'))
-    {    
+    {
+        if (empty($_GET['what']))
+        {
+            $toolbar= <<<HTML
+<div id="headerform"><br>
+    <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>
+</div>
+HTML;
+            $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>''); 
+            templatePage($data);
+            exit;
+        }
+        $exportWhat=$_GET['what'];
+        if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???');
+       
         header('Content-Type: text/html; charset=utf-8');
-        header('Content-disposition: attachment; filename=bookmarks_'.strval(date('Ymd_His')).'.html');
+        header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
         echo <<<HTML
 <!DOCTYPE NETSCAPE-Bookmark-file-1>
 <!-- This is an automatically generated file.
@@ -764,12 +815,17 @@ HTML;
 HTML;
         foreach($LINKSDB as $link)
         {
-            echo '<DT><A HREF="'.htmlspecialchars($link['url']).'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
-            if ($link['tags']!='') echo ' TAGS="'.htmlspecialchars(str_replace(' ',',',$link['tags'])).'"';
-            echo '>'.htmlspecialchars($link['title'])."</A>\n";
-            if ($link['description']!='') echo '<DD>'.htmlspecialchars($link['description'])."\n";
+            if ($exportWhat=='all' ||
+               ($exportWhat=='private' && $link['private']!=0) ||
+               ($exportWhat=='public' && $link['private']==0))
+            {
+                echo '<DT><A HREF="'.htmlspecialchars($link['url']).'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
+                if ($link['tags']!='') echo ' TAGS="'.htmlspecialchars(str_replace(' ',',',$link['tags'])).'"';
+                echo '>'.htmlspecialchars($link['title'])."</A>\n";
+                if ($link['description']!='') echo '<DD>'.htmlspecialchars($link['description'])."\n";
+            }
         }
-        echo '<!-- Shaarli bookmarks export on '.date('Y/m/d H:i:s')."-->\n";
+        echo '<!-- Shaarli '.$exportWhat.' bookmarks export on '.date('Y/m/d H:i:s')."-->\n";
         exit;
     }            
 
@@ -801,7 +857,9 @@ Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/
     <input type="hidden" name="token" value="{$token}">        
     <input type="file" name="filetoupload" size="80">
     <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
-    <input type="submit" name="import_file" value="Import" class="bigbutton">   
+    <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
+    <input type="checkbox" name="private">&nbsp;Import all links as private<br>   
+    <input type="checkbox" name="overwrite">&nbsp;Overwrite existing links    
 </form>
 </div>
 HTML;
@@ -831,6 +889,9 @@ function importFile()
     $filename=$_FILES['filetoupload']['name'];
     $filesize=$_FILES['filetoupload']['size'];    
     $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
+    $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ?
+    $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ?
+    $import_count=0;
 
     // Sniff file type:
     $type='unknown';
@@ -842,30 +903,35 @@ function importFile()
         // This is a standard Netscape-style bookmark file.
         // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.      
         // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
-        $before=count($LINKSDB); 
         foreach(explode('<DT>',$data) as $html) // explode is very fast
         {
             $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);  
             $d = explode('<DD>',$html);
             if (startswith($d[0],'<A '))
             {
-                $link['description'] = (isset($d[1]) ? trim($d[1]) : '');  // Get description (optional)
+                $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : '');  // Get description (optional)
                 preg_match('!<A .*?>(.*?)</A>!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : '');  // Get title
+                $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8');
                 preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER);  // Get all other attributes
                 foreach($matches as $m)
                 {
                     $attr=$m[1]; $value=$m[2];
-                    if ($attr=='HREF') $link['url']=$value;
+                    if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
                     elseif ($attr=='ADD_DATE') $link['linkdate']=date('Ymd_His',intval($value));
                     elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
-                    elseif ($attr=='TAGS') $link['tags']=str_replace(',',' ',$value);
+                    elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
                 }     
-                if ($link['linkdate']!='' && $link['url']!='')  $LINKSDB[$link['linkdate']] = $link;
+                if ($link['linkdate']!='' && $link['url']!='' && ($overwrite || empty($LINKSDB[$link['linkdate']])))
+                {
+                    if ($private==1) $link['private']=1;
+                    $LINKSDB[$link['linkdate']] = $link;
+                    $import_count++;
+                }
             }     
         }
-        $import_count = count($LINKSDB)-$before;
         $LINKSDB->savedb();
-        echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully imported: '.$import_count.' new links.");document.location=\'?\';</script>';            
+        invalidateCaches();
+        echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';            
     }
     else
     {
@@ -907,7 +973,7 @@ function templateEditForm($link,$link_is_new=false)
         <i>URL</i><br><input type="text" name="lf_url" value="{$url}" style="width:100%"><br>
         <i>Title</i><br><input type="text" name="lf_title" value="{$title}" style="width:100%"><br>
         <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%">{$description}</textarea><br>
-        <i>Tags</i><br><input type="text" name="lf_tags" value="{$tags}" style="width:100%"><br>
+        <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value="{$tags}" style="width:100%"><br>
         <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private">&nbsp;<i>Private</i><br>
         <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
         <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
@@ -1005,79 +1071,45 @@ function templatePage($data)
     global $STARTTIME;
     global $LINKSDB;
     $shaarli_version = shaarli_version;
-    $linkcount = count($LINKSDB); 
-    $menu=(isLoggedIn() ? ' <a href="?do=logout">Logout</a> &nbsp;<a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>' : ' <a href="?do=login">Login</a>');  
+    $linkcount = count($LINKSDB);
+    $open='';
+    if (OPEN_SHAARLI)
+    {
+        $menu=' <a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>';
+        $open='Open ';
+    }
+    else
+        $menu=(isLoggedIn() ? ' <a href="?do=logout">Logout</a> &nbsp;<a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>' : ' <a href="?do=login">Login</a>');  
     foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not).
     {
         if (!array_key_exists($k,$data)) $data[$k]='';
     }
+    $jsincludes=''; $jsincludes_bottom = '';
+    if (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'].'?ws=tags';  
+        $jsincludes_bottom = <<<JS
+<script language="JavaScript">             
+$(document).ready(function() 
+{
+    $('#lf_tags').autocomplete({source:'{$source}',minLength:0});
+});        
+</script>    
+JS;
+    }
     $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss');
     echo <<<HTML
 <html>
 <head>
-<title>Shaarli - Let's shaare your links...</title>
-<link rel="alternate" type="application/rss+xml" href="{$feedurl}">
-<style type="text/css">
-<!--
-/* CSS Reset from Yahoo to cope with browsers CSS inconsistencies. */
-/*
-Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html
-version: 2.8.2r1
-*/
-html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}
-
-body { font-family: "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif; font-size:10pt; background-color: #ffffff; } 
-input { border: 1px solid #aaa; background-color:#F0F0FF; padding: 2 5 2 5; -moz-box-shadow: inset 2px 2px 3px #aaaaaa; -webkit-box-shadow: inset 2px 2px 3px #aaaaaa; box-shadow: inset 2px 2px 3px #aaaaaa; } 
-textarea { border: 1px solid #aaa; background-color:#F0F0FF; padding: 2 5 2 5; -moz-box-shadow: inset 2px 2px 3px #B2B2C4; -webkit-box-shadow: inset 2px 2px 3px #B2B2C4; box-shadow: inset 2px 2px 3px #B2B2C4; } 
-/* I don't give a shit about IE. He can't understand selectors such as input[type='submit']. */
-
-.bigbutton {border-style:outset;border-width:2px;padding:3px 6px;background-color:rgb(212,212,212);font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;font-size:8pt;-moz-border-radius:0.5em;border-radius:0.5em;} 
-.smallbutton {border-style:outset;border-width:2px;padding:0px 4px;background-color:rgb(212,212,212);font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;font-size:8pt;-moz-border-radius:0.5em;border-radius:0.5em;} 
-#pageheader
-{
-color:#eee;
-border-bottom: 1px solid #aaa;    
-background-color: #6A6A6A;
-background-image: -webkit-gradient(linear, left top, left bottom, from(#6A6A6A), to(#303030)); /* Saf4+, Chrome */
-background-image: -webkit-linear-gradient(top, #6A6A6A, #303030); /* Chrome 10+, Saf5.1+ */
-background-image:    -moz-linear-gradient(top, #6A6A6A, #303030); /* FF3.6 */
-background-image:     -ms-linear-gradient(top, #6A6A6A, #303030); /* IE10 */
-background-image:      -o-linear-gradient(top, #6A6A6A, #303030); /* Opera 11.10+ */
-background-image:         linear-gradient(top, #6A6A6A, #303030);
-filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#6A6A6A', EndColorStr='#303030'); /* IE6-IE9 */
-padding-bottom: 5px;
-}
-#pageheader a:link { color:#bbb; text-decoration:none;}
-#pageheader a:visited { color:#bbb; text-decoration:none;}
-#pageheader a:hover { color:#FFFFC9; text-decoration:none;}
-#pageheader a:active { color:#bbb; text-decoration:none;} 
-.paging { background-color:#777; color:#ccc; text-align:center; padding:0 0 3 0;}
-.paging a:link { color:#ccc; text-decoration:none;}
-.paging a:visited { color:#ccc;  }
-.paging a:hover {  color:#FFFFC9;  }
-.paging a:active { color:#fff;  }
-#headerform { padding:5 5 5 15;  }
-#editlinkform {  padding:5 5 5 15px; width:80%; }
-#linklist li { padding:4 10 8 20; border-bottom: 1px solid #bbb;}
-#linklist li.private { background-color: #ccc; border-left:8px solid #888; }
-.linktitle { font-size:14pt; font-weight:bold; }
-.linktitle a { text-decoration: none; color:#0000EE; }
-.linktitle a:hover { text-decoration: underline; }
-.linktitle a:visited { color:#0000BB; }
-.linkdate { font-size:8pt; color:#888; }
-.linkurl { font-size:8pt; color:#4BAA74; }
-.linkdescription { color:#000; margin-top:0px; margin-bottom:0px; font-weight:normal; }
-.linktag { font-size:9pt; color:#777; background-color:#ddd; padding:0 6 0 6; -moz-box-shadow: inset 2px 2px 3px #ffffff; -webkit-box-shadow: inset 2px 2px 3px #ffffff; box-shadow: inset 2px 2px 3px ffffff;
-border-bottom:1px solid #aaa; border-right:1px solid #aaa;  }
-.linktag a { color:#777; text-decoration:none;  }
-.buttoneditform { display:inline; }
-#footer { font-size:8pt; text-align:center; border-top:1px solid #ddd; color: #888; }
--->
-</style>
+<title>{$open}Shaarli - Let's shaare your links...</title>
+<link rel="alternate" type="application/rss+xml" href="{$feedurl}" />
+<link type="text/css" rel="stylesheet" href="shaarli.css" />
+{$jsincludes}
 </head>
 <body {$data['onload']}>
 <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>Shaarli {$shaarli_version}</i></b> - <a href="?">Home</a>&nbsp;{$menu}&nbsp;<a href="{$feedurl}" style="padding-left:30px;">RSS Feed</a>
+    <b><i>{$open}Shaarli {$shaarli_version}</i></b> - <a href="?">Home</a>&nbsp;{$menu}&nbsp;<a href="{$feedurl}" style="padding-left:30px;">RSS Feed</a>
 {$data['pageheader']}    
 </div>
 {$data['body']}
@@ -1086,7 +1118,7 @@ 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>';
     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 '</body></html>';
+    echo $jsincludes_bottom.'</body></html>';
 }
 
 // -----------------------------------------------------------------------------------------------
@@ -1094,6 +1126,9 @@ HTML;
 // This function should NEVER be called if the file data/config.php exists.
 function install()
 {
+    // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
+    if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
+    
     if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
     {
         $tz=(empty($_POST['settimezone']) ? 'UTC':$_POST['settimezone']);
@@ -1101,7 +1136,11 @@ function install()
         $salt=sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
         $hash = sha1($_POST['setpassword'].$_POST['setlogin'].$salt);
         $config='<?php $GLOBALS[\'login\']='.var_export($_POST['setlogin'],true).'; $GLOBALS[\'hash\']='.var_export($hash,true).'; $GLOBALS[\'salt\']='.var_export($salt,true).'; date_default_timezone_set('.var_export($tz,true).'); ?>';
-        file_put_contents(CONFIG_FILE,$config);     
+        if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(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;
+        }
         echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>';        
         exit;            
    }
@@ -1114,11 +1153,9 @@ function install()
         $timezoneselect='Timezone: <select name="settimezone"><option value="" selected>(please select:)</option>'.$timezones.'</select><br><br>';
     }
     echo <<<HTML
-<html><title>Shaarli - Configuration</title><style type="text/css">
-body { font-family: "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif; font-size:10pt; background-color: #ffffff; } 
-input { border: 1px solid #aaa; background-color:#F0F0FF; padding: 2 5 2 5; -moz-box-shadow: inset 2px 2px 3px #aaaaaa; -webkit-box-shadow: inset 2px 2px 3px #aaaaaa; box-shadow: inset 2px 2px 3px #aaaaaa; } 
-.bigbutton {border-style:outset;border-width:2px;padding:3px 6px;background-color:rgb(212,212,212);font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;font-size:8pt;-moz-border-radius:0.5em;border-radius:0.5em;} 
-</style></head><body onload="document.configform.setlogin.focus();"><h1>Shaarli - Shaare your links...</h1>It looks like it's the first time you run Shaarli. Please chose a login/password and a timezone:<br>
+<html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" /></head>
+<body onload="document.configform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
+It looks like it's the first time you run Shaarli. Please chose a login/password and a timezone:<br>
 <form method="POST" action="" name="configform" style="border:1px solid black; padding:10 10 10 10;">
 Login: <input type="text" name="setlogin"><br><br>Password: <input type="password" name="setpassword"><br><br>
 {$timezoneselect}
@@ -1127,7 +1164,41 @@ HTML;
     exit;
 }
 
-$LINKSDB=new linkdb(isLoggedIn());  // Read links from database (and filter private links if used it not logged in).
+// Webservices (for use with jQuery/jQueryUI)
+// eg.  index.php?ws=tags&term=minecr
+function processWS()
+{
+    if (empty($_GET['ws']) || empty($_GET['term'])) return;
+    $term = $_GET['term'];
+    global $LINKSDB;
+    header('Content-Type: application/json; charset=utf-8');
+
+    // Search in tags
+    if ($_GET['ws']=='tags')
+    { 
+        $tags=explode(' ',$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;
+        }      
+        echo json_encode(array_keys($suggested));
+        exit;
+    }
+}
+
+// Invalidate caches when the database is changed or the user logs out.
+// (eg. tags cache).
+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"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
 if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=LINKS_PER_PAGE;
 if (startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
 renderPage();