<?php
-// Shaarli 0.0.8 beta - Shaare your links...
+// Shaarli 0.0.13 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.2.x
+// Requires: php 5.1.x
// -----------------------------------------------------------------------------------------------
// User config:
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
+
// -----------------------------------------------------------------------------------------------
// Program config (touch at your own risks !)
-//error_reporting(E_ALL^E_WARNING); // See all error except warnings.
-error_reporting(-1); // See all errors (for debugging only)
+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 ONE the following line in .htaccess (depending on your host):\n\nphp_flag magic_quotes_gpc Off\nor\nSetEnv MAGIC_QUOTES 0"; exit;
+}
+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();
// Prevent caching: (yes, it's ugly)
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.8 beta');
+define('shaarli_version','0.0.13 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();
header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
$LINKSDB=false;
+// Check php version
+function checkphpversion()
+{
+ $ver=phpversion();
+ if (preg_match('!(\d+)\.(\d+)\.(\d+)!',$ver,$matches)) // (because phpversion() sometimes returns strings like "5.2.4-2ubuntu5.2")
+ {
+ list($match,$major,$minor,$release) = $matches;
+ if ($major>=5 && $minor>=1) return; // 5.1.x or higher is ok.
+ 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.
+}
+
// -----------------------------------------------------------------------------------------------
// Log to text file
function logm($message)
// 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'])
{
/* GET an URL.
Input: $url : url to get (http://...)
$timeout : Network timeout (will wait this many seconds for an anwser before giving up).
- Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK")
+ Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
[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/');
*/
function getHTTP($url,$timeout=30)
{
- //FIXME: trap error correctly (unresolved host, unsupported protocol, etc.)
- $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.
- 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);
- return array($httpStatus,$responseHeaders,$data);
+ try
+ {
+ $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.
+ 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);
+ return array($httpStatus,$responseHeaders,$data);
+ }
+ catch (Exception $e) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
+ {
+ return array($e->getMessage(),'','');
+ }
}
// Extract title from an HTML document.
}
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;
+ }
+
}
// ------------------------------------------------------------------------------------------
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";
// -------- 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>';
// -------- User wants to logout.
if (startswith($_SERVER["QUERY_STRING"],'do=logout'))
{
+ invalidateCaches();
logout();
header('Location: ?');
exit;
if (isset($_GET['addtag']))
{
// Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
+ if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
- $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags'].' '.$_GET['addtag']));
+ $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags'].' '.urlencode($_GET['addtag'])));
unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
header('Location: ?'.http_build_query($params));
exit;
if (isset($_GET['removetag']))
{
// Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
+ if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?'); exit; } // In case browser does not send HTTP_REFERER
parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
if (isset($params['searchtags']))
{
if (isset($_GET['linksperpage']))
{
if (is_numeric($_GET['linksperpage'])) { $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); }
- header('Location: '.$_SERVER['HTTP_REFERER']);
+ header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']));
exit;
}
$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)+'&title='%20+%20encodeURIComponent(title)+'&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)+'&title='%20+%20encodeURIComponent(title)+'&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'=>'');
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; }
- header('Location: '.$_POST['returnurl']); // After saving the link, redirect to the page the user was on.
+ $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
+ header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on.
exit;
}
$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'] : '?' );
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 charset specified in either 1) HTTP response headers or 2) <head> in html
- if (strpos($status,'200 OK')) $title=html_extract_title($data);
+ // 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');
}
$link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
}
// -------- 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.
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;
}
<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"> Import all links as private
</form>
</div>
HTML;
$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 ?
// Sniff file type:
$type='unknown';
elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
elseif ($attr=='TAGS') $link['tags']=str_replace(',',' ',$value);
}
- if ($link['linkdate']!='' && $link['url']!='') $LINKSDB[$link['linkdate']] = $link;
+ if ($link['linkdate']!='' && $link['url']!='' && empty($LINKSDB[$link['linkdate']]))
+ {
+ if ($private==1) $link['private']=1;
+ $LINKSDB[$link['linkdate']] = $link;
+ }
}
}
$import_count = count($LINKSDB)-$before;
$LINKSDB->savedb();
+ invalidateCaches();
echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully imported: '.$import_count.' new links.");document.location=\'?\';</script>';
}
else
<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"> <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;">
$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">'.str_replace("\n",'<br>',htmlspecialchars($description)).'</div><br>';
+ if ($description!='') $linklist.='<div class="linkdescription">'.nl2br(htmlspecialchars($description)).'</div><br>';
$linklist.='<span class="linkdate">'.htmlspecialchars(linkdate2locale($link['linkdate'])).' - </span><span class="linkurl">'.htmlspecialchars($link['url']).'</span><br>'.$tags."</li>\n";
$i++;
}
global $STARTTIME;
global $LINKSDB;
$shaarli_version = shaarli_version;
- $linkcount = count($LINKSDB);
- $menu=(isLoggedIn() ? ' <a href="?do=logout">Logout</a> <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' : ' <a href="?do=login">Login</a>');
+ $linkcount = count($LINKSDB);
+ $open='';
+ if (OPEN_SHAARLI)
+ {
+ $menu=' <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>';
+ $open='Open ';
+ }
+ else
+ $menu=(isLoggedIn() ? ' <a href="?do=logout">Logout</a> <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' : ' <a href="?do=login">Login</a>');
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>
+<title>{$open}Shaarli - Let's shaare your links...</title>
<link rel="alternate" type="application/rss+xml" href="{$feedurl}">
+{$jsincludes}
<style type="text/css">
<!--
/* CSS Reset from Yahoo to cope with browsers CSS inconsistencies. */
.linktag a { color:#777; text-decoration:none; }
.buttoneditform { display:inline; }
#footer { font-size:8pt; text-align:center; border-top:1px solid #ddd; color: #888; }
+
+/* Minimal customisation for jQuery widgets */
+.ui-autocomplete { background-color:#fff; padding-left:5px;}
+.ui-state-hover { background-color: #604dff; color:#fff; }
+
-->
</style>
</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> {$menu} <a href="{$feedurl}" style="padding-left:30px;">RSS Feed</a>
+ <b><i>{$open}Shaarli {$shaarli_version}</i></b> - <a href="?">Home</a> {$menu} <a href="{$feedurl}" style="padding-left:30px;">RSS Feed</a>
{$data['pageheader']}
</div>
{$data['body']}
$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 ?</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>';
}
// -----------------------------------------------------------------------------------------------
// This function should NEVER be called if the file data/config.php exists.
function install()
{
- // FIXME: check version of php ?
- if (isset($_POST['setlogin']) && isset($_POST['setpassword']) && isset($_POST['settimezone']))
+ if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
{
- if ($_POST['setlogin']!='' && $_POST['setpassword']!='' && in_array($_POST['settimezone'],timezone_identifiers_list()))
- { // Everything is ok, let's create config file.
- $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($_POST['settimezone'],true).'); ?>';
- file_put_contents(CONFIG_FILE,$config);
- 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;
+ $tz=(empty($_POST['settimezone']) ? 'UTC':$_POST['settimezone']);
+ // Everything is ok, let's create config file.
+ $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).'); ?>';
+ 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;
+ }
// Display config form:
- $timezones='';
- foreach(timezone_identifiers_list() as $tz) $timezones.='<option value="'.htmlspecialchars($tz).'">'.htmlspecialchars($tz)."</option>\n";
+ $timezoneselect='';
+ if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
+ {
+ $timezones='';
+ foreach(timezone_identifiers_list() as $tz) $timezones.='<option value="'.htmlspecialchars($tz).'">'.htmlspecialchars($tz)."</option>\n";
+ $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; }
</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>
<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>
-Timezone: <select name="settimezone"><option value="0" selected>(please select:)</option>{$timezones}</select><br><br>
+{$timezoneselect}
<input type="submit" name="Save" value="Save config" class="bigbutton"></form></body></html>
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();