aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
Diffstat (limited to 'index.php')
-rw-r--r--index.php983
1 files changed, 412 insertions, 571 deletions
diff --git a/index.php b/index.php
index 7aec94da..e78733bf 100644
--- a/index.php
+++ b/index.php
@@ -1,5 +1,5 @@
1<?php 1<?php
2// Shaarli 0.0.31 beta - Shaare your links... 2// Shaarli 0.0.32 beta - Shaare your links...
3// The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net 3// The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net
4// http://sebsauvage.net/wiki/doku.php?id=php:shaarli 4// http://sebsauvage.net/wiki/doku.php?id=php:shaarli
5// Licence: http://www.opensource.org/licenses/zlib-license.php 5// Licence: http://www.opensource.org/licenses/zlib-license.php
@@ -21,7 +21,7 @@ $GLOBALS['config']['ENABLE_THUMBNAILS'] = true; // Enable thumbnails in links.
21$GLOBALS['config']['CACHEDIR'] = 'cache'; // Cache directory for thumbnails for SLOW services (like flickr) 21$GLOBALS['config']['CACHEDIR'] = 'cache'; // Cache directory for thumbnails for SLOW services (like flickr)
22$GLOBALS['config']['ENABLE_LOCALCACHE'] = true; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce webspace usage. 22$GLOBALS['config']['ENABLE_LOCALCACHE'] = true; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce webspace usage.
23$GLOBALS['config']['PUBSUBHUB_URL'] = ''; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable. 23$GLOBALS['config']['PUBSUBHUB_URL'] = ''; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
24 // Note: You must have publisher.php in the same directory as Shaarli index.php 24 // Note: You must have publisher.php in the same directory as Shaarli index.php
25// ----------------------------------------------------------------------------------------------- 25// -----------------------------------------------------------------------------------------------
26// Program config (touch at your own risks !) 26// Program config (touch at your own risks !)
27$GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt'; // For updates check of Shaarli. 27$GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt'; // For updates check of Shaarli.
@@ -32,17 +32,21 @@ ini_set('post_max_size', '16M');
32ini_set('upload_max_filesize', '16M'); 32ini_set('upload_max_filesize', '16M');
33define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code. 33define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
34define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code. 34define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
35$STARTTIME = microtime(true); // Measure page execution time.
36checkphpversion(); 35checkphpversion();
37error_reporting(E_ALL^E_WARNING); // See all error except warnings. 36error_reporting(E_ALL^E_WARNING); // See all error except warnings.
38//error_reporting(-1); // See all errors (for debugging only) 37//error_reporting(-1); // See all errors (for debugging only)
38
39include "inc/rain.tpl.class.php"; //include Rain TPL
40raintpl::$tpl_dir = "tpl/"; // template directory
41raintpl::$cache_dir = "tmp/"; // cache directory
42
39ob_start(); 43ob_start();
40 44
41// Optionnal config file. 45// Optionnal config file.
42if (is_file($GLOBALS['config']['DATADIR'].'/options.php')) require($GLOBALS['config']['DATADIR'].'/options.php'); 46if (is_file($GLOBALS['config']['DATADIR'].'/options.php')) require($GLOBALS['config']['DATADIR'].'/options.php');
43 47
44// In case stupid admin has left magic_quotes enabled in php.ini: 48// In case stupid admin has left magic_quotes enabled in php.ini:
45if (get_magic_quotes_gpc()) 49if (get_magic_quotes_gpc())
46{ 50{
47 function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } 51 function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
48 $_POST = array_map('stripslashes_deep', $_POST); 52 $_POST = array_map('stripslashes_deep', $_POST);
@@ -54,24 +58,24 @@ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
54header("Cache-Control: no-store, no-cache, must-revalidate"); 58header("Cache-Control: no-store, no-cache, must-revalidate");
55header("Cache-Control: post-check=0, pre-check=0", false); 59header("Cache-Control: post-check=0, pre-check=0", false);
56header("Pragma: no-cache"); 60header("Pragma: no-cache");
57define('shaarli_version','0.0.31 beta'); 61define('shaarli_version','0.0.32 beta');
58if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); } 62if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); }
59if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files. 63if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
60if ($GLOBALS['config']['ENABLE_LOCALCACHE']) 64if ($GLOBALS['config']['ENABLE_LOCALCACHE'])
61{ 65{
62 if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); } 66 if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); }
63 if (!is_file($GLOBALS['config']['CACHEDIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['CACHEDIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files. 67 if (!is_file($GLOBALS['config']['CACHEDIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['CACHEDIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
64} 68}
65if (!is_file($GLOBALS['config']['CONFIG_FILE'])) install(); 69if (!is_file($GLOBALS['config']['CONFIG_FILE'])) install();
66require $GLOBALS['config']['CONFIG_FILE']; // Read login/password hash into $GLOBALS. 70require $GLOBALS['config']['CONFIG_FILE']; // Read login/password hash into $GLOBALS.
67// Small protection against dodgy config files: 71// Small protection against dodgy config files:
68if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']); 72if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.htmlspecialchars(indexUrl());
69if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get(); 73if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
70autoLocale(); // Sniff browser language and set date format accordingly. 74autoLocale(); // Sniff browser language and set date format accordingly.
71header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling. 75header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
72$LINKSDB=false; 76$LINKSDB=false;
73 77
74// Check php version 78// Check php version
75function checkphpversion() 79function checkphpversion()
76{ 80{
77 if (version_compare(PHP_VERSION, '5.1.0') < 0) 81 if (version_compare(PHP_VERSION, '5.1.0') < 0)
@@ -79,7 +83,7 @@ function checkphpversion()
79 header('Content-Type: text/plain; charset=utf-8'); 83 header('Content-Type: text/plain; charset=utf-8');
80 echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.'; 84 echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.';
81 exit; 85 exit;
82 } 86 }
83} 87}
84 88
85// Checks if an update is available for Shaarli. 89// Checks if an update is available for Shaarli.
@@ -89,14 +93,14 @@ function checkphpversion()
89function checkUpdate() 93function checkUpdate()
90{ 94{
91 if (!isLoggedIn()) return ''; // Do not check versions for visitors. 95 if (!isLoggedIn()) return ''; // Do not check versions for visitors.
92 96
93 // Get latest version number at most once a day. 97 // Get latest version number at most once a day.
94 if (!is_file($GLOBALS['config']['UPDATECHECK_FILENAME']) || (filemtime($GLOBALS['config']['UPDATECHECK_FILENAME'])<time()-($GLOBALS['config']['UPDATECHECK_INTERVAL']))) 98 if (!is_file($GLOBALS['config']['UPDATECHECK_FILENAME']) || (filemtime($GLOBALS['config']['UPDATECHECK_FILENAME'])<time()-($GLOBALS['config']['UPDATECHECK_INTERVAL'])))
95 { 99 {
96 $version=shaarli_version; 100 $version=shaarli_version;
97 list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2); 101 list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2);
98 if (strpos($httpstatus,'200 OK')!==false) $version=$data; 102 if (strpos($httpstatus,'200 OK')!==false) $version=$data;
99 // If failed, nevermind. We don't want to bother the user with that. 103 // If failed, nevermind. We don't want to bother the user with that.
100 file_put_contents($GLOBALS['config']['UPDATECHECK_FILENAME'],$version); // touch file date 104 file_put_contents($GLOBALS['config']['UPDATECHECK_FILENAME'],$version); // touch file date
101 } 105 }
102 // Compare versions: 106 // Compare versions:
@@ -121,7 +125,7 @@ function logm($message)
121 - only use the following characters: a-z A-Z 0-9 - _ @ 125 - only use the following characters: a-z A-Z 0-9 - _ @
122 - are NOT cryptographically secure (they CAN be forged) 126 - are NOT cryptographically secure (they CAN be forged)
123 In Shaarli, they are used as a tinyurl-like link to individual entries. 127 In Shaarli, they are used as a tinyurl-like link to individual entries.
124*/ 128*/
125function smallHash($text) 129function smallHash($text)
126{ 130{
127 $t = rtrim(base64_encode(hash('crc32',$text,true)),'='); 131 $t = rtrim(base64_encode(hash('crc32',$text,true)),'=');
@@ -137,11 +141,19 @@ function text2clickable($url)
137 $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector']; 141 $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'];
138 return preg_replace('!((?:https?|ftp)://\S+[[:alnum:]]/?)!si','<a href="'.$redir.'$1" rel="nofollow">$1</a>',$url); 142 return preg_replace('!((?:https?|ftp)://\S+[[:alnum:]]/?)!si','<a href="'.$redir.'$1" rel="nofollow">$1</a>',$url);
139} 143}
144
145// This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
146// even in the absence of <pre> (This is used in description to keep text formatting)
147function keepMultipleSpaces($text)
148{
149 return str_replace(' ',' &nbsp;',$text);
150
151}
140// ------------------------------------------------------------------------------------------ 152// ------------------------------------------------------------------------------------------
141// Sniff browser language to display dates in the right format automatically. 153// Sniff browser language to display dates in the right format automatically.
142// (Note that is may not work on your server if the corresponding local is not installed.) 154// (Note that is may not work on your server if the corresponding local is not installed.)
143function autoLocale() 155function autoLocale()
144{ 156{
145 $loc='en_US'; // Default if browser does not send HTTP_ACCEPT_LANGUAGE 157 $loc='en_US'; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
146 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3" 158 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
147 { // (It's a bit crude, but it works very well. Prefered language is always presented first.) 159 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
@@ -160,8 +172,8 @@ function pubsubhub()
160 { 172 {
161 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']); 173 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
162 $topic_url = array ( 174 $topic_url = array (
163 serverUrl().$_SERVER['SCRIPT_NAME'].'?do=atom', 175 indexUrl().'?do=atom',
164 serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss' 176 indexUrl().'?do=rss'
165 ); 177 );
166 $p->publish_update($topic_url); 178 $p->publish_update($topic_url);
167 } 179 }
@@ -187,7 +199,7 @@ function allIPs()
187} 199}
188 200
189// Check that user/password is correct. 201// Check that user/password is correct.
190function check_auth($login,$password) 202function check_auth($login,$password)
191{ 203{
192 $hash = sha1($password.$login.$GLOBALS['salt']); 204 $hash = sha1($password.$login.$GLOBALS['salt']);
193 if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash']) 205 if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash'])
@@ -205,9 +217,9 @@ function check_auth($login,$password)
205 217
206// Returns true if the user is logged in. 218// Returns true if the user is logged in.
207function isLoggedIn() 219function isLoggedIn()
208{ 220{
209 if ($GLOBALS['config']['OPEN_SHAARLI']) return true; 221 if ($GLOBALS['config']['OPEN_SHAARLI']) return true;
210 222
211 // If session does not exist on server side, or IP address has changed, or session has expired, logout. 223 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
212 if (empty($_SESSION['uid']) || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on']) 224 if (empty($_SESSION['uid']) || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on'])
213 { 225 {
@@ -216,7 +228,7 @@ function isLoggedIn()
216 } 228 }
217 if (!empty($_SESSION['longlastingsession'])) $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked. 229 if (!empty($_SESSION['longlastingsession'])) $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
218 else $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date. 230 else $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
219 231
220 return true; 232 return true;
221} 233}
222 234
@@ -260,7 +272,7 @@ function ban_canLogin()
260 if (isset($gb['BANS'][$ip])) 272 if (isset($gb['BANS'][$ip]))
261 { 273 {
262 // User is banned. Check if the ban has expired: 274 // User is banned. Check if the ban has expired:
263 if ($gb['BANS'][$ip]<=time()) 275 if ($gb['BANS'][$ip]<=time())
264 { // Ban expired, user can try to login again. 276 { // Ban expired, user can try to login again.
265 logm('Ban lifted.'); 277 logm('Ban lifted.');
266 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); 278 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
@@ -279,36 +291,36 @@ if (isset($_POST['login']))
279 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.'); 291 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
280 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password']))) 292 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
281 { // Login/password is ok. 293 { // Login/password is ok.
282 ban_loginOk(); 294 ban_loginOk();
283 // If user wants to keep the session cookie even after the browser closes: 295 // If user wants to keep the session cookie even after the browser closes:
284 if (!empty($_POST['longlastingsession'])) 296 if (!empty($_POST['longlastingsession']))
285 { 297 {
286 $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year) 298 $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year)
287 $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side. 299 $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side.
288 session_set_cookie_params($_SESSION['longlastingsession']); // Set session cookie expiration on client side 300 session_set_cookie_params($_SESSION['longlastingsession']); // Set session cookie expiration on client side
289 session_regenerate_id(true); // Send cookie with new expiration date to browser. 301 session_regenerate_id(true); // Send cookie with new expiration date to browser.
290 } 302 }
291 else // Standard session expiration (=when browser closes) 303 else // Standard session expiration (=when browser closes)
292 { 304 {
293 session_set_cookie_params(0); // 0 means "When browser closes" 305 session_set_cookie_params(0); // 0 means "When browser closes"
294 session_regenerate_id(true); 306 session_regenerate_id(true);
295 } 307 }
296 // Optional redirect after login: 308 // Optional redirect after login:
297 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; } 309 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; }
298 if (isset($_POST['returnurl'])) 310 if (isset($_POST['returnurl']))
299 { 311 {
300 if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen. 312 if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
301 header('Location: '.$_POST['returnurl']); exit; 313 header('Location: '.$_POST['returnurl']); exit;
302 } 314 }
303 header('Location: ?'); exit; 315 header('Location: ?'); exit;
304 } 316 }
305 else 317 else
306 { 318 {
307 ban_loginFailed(); 319 ban_loginFailed();
308 echo '<script language="JavaScript">alert("Wrong login/password.");document.location=\'?do=login\';</script>'; // Redirect to login screen. 320 echo '<script language="JavaScript">alert("Wrong login/password.");document.location=\'?do=login\';</script>'; // Redirect to login screen.
309 exit; 321 exit;
310 } 322 }
311} 323}
312 324
313// ------------------------------------------------------------------------------------------ 325// ------------------------------------------------------------------------------------------
314// Misc utility functions: 326// Misc utility functions:
@@ -318,15 +330,20 @@ if (isset($_POST['login']))
318// You can append $_SERVER['SCRIPT_NAME'] to get the current script URL. 330// You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
319function serverUrl() 331function serverUrl()
320{ 332{
321 $serverport = ($_SERVER["SERVER_PORT"]!='80' ? ':'.$_SERVER["SERVER_PORT"] : ''); 333 $serverport = ($_SERVER["SERVER_PORT"]=='80' || (!empty($_SERVER['HTTPS']) && $_SERVER["SERVER_PORT"]=='443') ? '' : ':'.$_SERVER["SERVER_PORT"]);
322 return 'http'.(!empty($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport; 334 return 'http'.(!empty($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport;
323} 335}
324 336
337function indexUrl()
338{
339 return serverUrl() . ($_SERVER["SCRIPT_NAME"] == '/index.php' ? '' : $_SERVER["SCRIPT_NAME"]);
340}
341
325// Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes. 342// Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
326function return_bytes($val) 343function return_bytes($val)
327{ 344{
328 $val = trim($val); $last=strtolower($val[strlen($val)-1]); 345 $val = trim($val); $last=strtolower($val[strlen($val)-1]);
329 switch($last) 346 switch($last)
330 { 347 {
331 case 'g': $val *= 1024; 348 case 'g': $val *= 1024;
332 case 'm': $val *= 1024; 349 case 'm': $val *= 1024;
@@ -396,7 +413,7 @@ function linkdate2locale($linkdate)
396} 413}
397 414
398// Parse HTTP response headers and return an associative array. 415// Parse HTTP response headers and return an associative array.
399function http_parse_headers_shaarli( $headers ) 416function http_parse_headers_shaarli( $headers )
400{ 417{
401 $res=array(); 418 $res=array();
402 foreach($headers as $header) 419 foreach($headers as $header)
@@ -444,9 +461,9 @@ function getHTTP($url,$timeout=30)
444 461
445// Extract title from an HTML document. 462// Extract title from an HTML document.
446// (Returns an empty string if not found.) 463// (Returns an empty string if not found.)
447function html_extract_title($html) 464function html_extract_title($html)
448{ 465{
449 return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ; 466 return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ;
450} 467}
451 468
452// ------------------------------------------------------------------------------------------ 469// ------------------------------------------------------------------------------------------
@@ -459,11 +476,11 @@ function getToken()
459{ 476{
460 $rnd = sha1(uniqid('',true).'_'.mt_rand()); // We generate a random string. 477 $rnd = sha1(uniqid('',true).'_'.mt_rand()); // We generate a random string.
461 $_SESSION['tokens'][$rnd]=1; // Store it on the server side. 478 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
462 return $rnd; 479 return $rnd;
463} 480}
464 481
465// Tells if a token is ok. Using this function will destroy the token. 482// Tells if a token is ok. Using this function will destroy the token.
466// true=token is ok. 483// true=token is ok.
467function tokenOk($token) 484function tokenOk($token)
468{ 485{
469 if (isset($_SESSION['tokens'][$token])) 486 if (isset($_SESSION['tokens'][$token]))
@@ -475,6 +492,58 @@ function tokenOk($token)
475} 492}
476 493
477// ------------------------------------------------------------------------------------------ 494// ------------------------------------------------------------------------------------------
495/* This class is in charge of building the final page.
496 (This is basically a wrapper around RainTPL which pre-fills some fields.)
497 p = new pageBuilder;
498 p.assign('myfield','myvalue');
499 p.renderPage('mytemplate');
500
501*/
502class pageBuilder
503{
504 private $tpl; // RainTPL template
505 function __construct()
506 {
507 $this->tpl=false;
508 }
509
510 private function initialize()
511 {
512 global $LINKSDB;
513 $this->tpl = new RainTPL;
514 $this->tpl->assign('newversion',checkUpdate());
515 $this->tpl->assign('linkcount',count($LINKSDB));
516 $this->tpl->assign('feedurl',htmlspecialchars(indexUrl()));
517 $searchcrits=''; // Search criteria
518 if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.$_GET['searchtags'];
519 elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.$_GET['searchterm'];
520 $this->tpl->assign('searchcrits',$searchcrits);
521 $this->tpl->assign('source',indexUrl());
522 $this->tpl->assign('version',shaarli_version);
523 $this->tpl->assign('pagetitle','Shaarli');
524 if (!empty($GLOBALS['title'])) $this->tpl->assign('pagetitle',$GLOBALS['title']);
525 if (!empty($GLOBALS['pagetitle'])) $this->tpl->assign('pagetitle',$GLOBALS['pagetitle']);
526 $this->tpl->assign('shaarlititle',empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title'] );
527 return;
528 }
529
530 // The following assign() method is basically the same as RainTPL (except that it's lazy)
531 public function assign($what,$where)
532 {
533 if ($this->tpl===false) $this->initialize(); // Lazy initialization
534 $this->tpl->assign($what,$where);
535 }
536
537 // Render a specific page (using a template).
538 // eg. pb.renderPage('picwall')
539 public function renderPage($page)
540 {
541 if ($this->tpl===false) $this->initialize(); // Lazy initialization
542 $this->tpl->draw($page);
543 }
544}
545
546// ------------------------------------------------------------------------------------------
478/* Data storage for links. 547/* Data storage for links.
479 This object behaves like an associative array. 548 This object behaves like an associative array.
480 Example: 549 Example:
@@ -482,14 +551,13 @@ function tokenOk($token)
482 echo $mylinks['20110826_161819']['title']; 551 echo $mylinks['20110826_161819']['title'];
483 foreach($mylinks as $link) 552 foreach($mylinks as $link)
484 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description']; 553 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
485 554
486 We implement 3 interfaces: 555 We implement 3 interfaces:
487 - ArrayAccess so that this object behaves like an associative array. 556 - ArrayAccess so that this object behaves like an associative array.
488 - Iterator so that this object can be used in foreach() loops. 557 - Iterator so that this object can be used in foreach() loops.
489 - Countable interface so that we can do a count() on this object. 558 - Countable interface so that we can do a count() on this object.
490*/ 559*/
491class linkdb implements Iterator, Countable, ArrayAccess 560class linkdb implements Iterator, Countable, ArrayAccess
492
493{ 561{
494 private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...) 562 private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
495 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate) 563 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
@@ -504,8 +572,8 @@ class linkdb implements Iterator, Countable, ArrayAccess
504 $this->loggedin = $isLoggedIn; 572 $this->loggedin = $isLoggedIn;
505 $this->checkdb(); // Make sure data file exists. 573 $this->checkdb(); // Make sure data file exists.
506 $this->readdb(); // Then read it. 574 $this->readdb(); // Then read it.
507 } 575 }
508 576
509 // ---- Countable interface implementation 577 // ---- Countable interface implementation
510 public function count() { return count($this->links); } 578 public function count() { return count($this->links); }
511 579
@@ -516,17 +584,17 @@ class linkdb implements Iterator, Countable, ArrayAccess
516 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.'); 584 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.');
517 if (empty($offset)) die('You must specify a key.'); 585 if (empty($offset)) die('You must specify a key.');
518 $this->links[$offset] = $value; 586 $this->links[$offset] = $value;
519 $this->urls[$value['url']]=$offset; 587 $this->urls[$value['url']]=$offset;
520 } 588 }
521 public function offsetExists($offset) { return array_key_exists($offset,$this->links); } 589 public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
522 public function offsetUnset($offset) 590 public function offsetUnset($offset)
523 { 591 {
524 if (!$this->loggedin) die('You are not authorized to delete a link.'); 592 if (!$this->loggedin) die('You are not authorized to delete a link.');
525 $url = $this->links[$offset]['url']; unset($this->urls[$url]); 593 $url = $this->links[$offset]['url']; unset($this->urls[$url]);
526 unset($this->links[$offset]); 594 unset($this->links[$offset]);
527 } 595 }
528 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; } 596 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
529 597
530 // ---- Iterator interface implementation 598 // ---- Iterator interface implementation
531 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first). 599 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
532 function key() { return $this->keys[$this->position]; } // current key 600 function key() { return $this->keys[$this->position]; } // current key
@@ -543,18 +611,18 @@ class linkdb implements Iterator, Countable, ArrayAccess
543 $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'); 611 $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');
544 $this->links[$link['linkdate']] = $link; 612 $this->links[$link['linkdate']] = $link;
545 $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'); 613 $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');
546 $this->links[$link['linkdate']] = $link; 614 $this->links[$link['linkdate']] = $link;
547 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk 615 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
548 } 616 }
549 } 617 }
550 618
551 // Read database from disk to memory 619 // Read database from disk to memory
552 private function readdb() 620 private function readdb()
553 { 621 {
554 // Read data 622 // Read data
555 $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() ); 623 $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
556 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439 624 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
557 625
558 // If user is not logged in, filter private links. 626 // If user is not logged in, filter private links.
559 if (!$this->loggedin) 627 if (!$this->loggedin)
560 { 628 {
@@ -562,21 +630,21 @@ class linkdb implements Iterator, Countable, ArrayAccess
562 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; } 630 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
563 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); } 631 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
564 } 632 }
565 633
566 // Keep the list of the mapping URLs-->linkdate up-to-date. 634 // Keep the list of the mapping URLs-->linkdate up-to-date.
567 $this->urls=array(); 635 $this->urls=array();
568 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; } 636 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
569 } 637 }
570 638
571 // Save database from memory to disk. 639 // Save database from memory to disk.
572 public function savedb() 640 public function savedb()
573 { 641 {
574 if (!$this->loggedin) die('You are not authorized to change the database.'); 642 if (!$this->loggedin) die('You are not authorized to change the database.');
575 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); 643 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
576 } 644 }
577 645
578 // Returns the link for a given URL (if it exists). false it does not exist. 646 // Returns the link for a given URL (if it exists). false it does not exist.
579 public function getLinkFromUrl($url) 647 public function getLinkFromUrl($url)
580 { 648 {
581 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]]; 649 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
582 return false; 650 return false;
@@ -584,14 +652,14 @@ class linkdb implements Iterator, Countable, ArrayAccess
584 652
585 // Case insentitive search among links (in url, title and description). Returns filtered list of links. 653 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
586 // eg. print_r($mydb->filterFulltext('hollandais')); 654 // eg. print_r($mydb->filterFulltext('hollandais'));
587 public function filterFulltext($searchterms) 655 public function filterFulltext($searchterms)
588 { 656 {
589 // FIXME: explode(' ',$searchterms) and perform a AND search. 657 // FIXME: explode(' ',$searchterms) and perform a AND search.
590 // FIXME: accept double-quotes to search for a string "as is" ? 658 // FIXME: accept double-quotes to search for a string "as is" ?
591 $filtered=array(); 659 $filtered=array();
592 $s = strtolower($searchterms); 660 $s = strtolower($searchterms);
593 foreach($this->links as $l) 661 foreach($this->links as $l)
594 { 662 {
595 $found= (strpos(strtolower($l['title']),$s)!==false) 663 $found= (strpos(strtolower($l['title']),$s)!==false)
596 || (strpos(strtolower($l['description']),$s)!==false) 664 || (strpos(strtolower($l['description']),$s)!==false)
597 || (strpos(strtolower($l['url']),$s)!==false) 665 || (strpos(strtolower($l['url']),$s)!==false)
@@ -601,7 +669,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
601 krsort($filtered); 669 krsort($filtered);
602 return $filtered; 670 return $filtered;
603 } 671 }
604 672
605 // Filter by tag. 673 // Filter by tag.
606 // You can specify one or more tags (tags can be separated by space or comma). 674 // You can specify one or more tags (tags can be separated by space or comma).
607 // eg. print_r($mydb->filterTags('linux programming')); 675 // eg. print_r($mydb->filterTags('linux programming'));
@@ -611,22 +679,22 @@ class linkdb implements Iterator, Countable, ArrayAccess
611 $searchtags=explode(' ',$t); 679 $searchtags=explode(' ',$t);
612 $filtered=array(); 680 $filtered=array();
613 foreach($this->links as $l) 681 foreach($this->links as $l)
614 { 682 {
615 $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags']))); 683 $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags'])));
616 if (count(array_intersect($linktags,$searchtags)) == count($searchtags)) 684 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
617 $filtered[$l['linkdate']] = $l; 685 $filtered[$l['linkdate']] = $l;
618 } 686 }
619 krsort($filtered); 687 krsort($filtered);
620 return $filtered; 688 return $filtered;
621 } 689 }
622 690
623 // Filter by smallHash. 691 // Filter by smallHash.
624 // Only 1 article is returned. 692 // Only 1 article is returned.
625 public function filterSmallHash($smallHash) 693 public function filterSmallHash($smallHash)
626 { 694 {
627 $filtered=array(); 695 $filtered=array();
628 foreach($this->links as $l) 696 foreach($this->links as $l)
629 { 697 {
630 if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow 698 if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
631 { 699 {
632 $filtered[$l['linkdate']] = $l; 700 $filtered[$l['linkdate']] = $l;
@@ -634,7 +702,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
634 } 702 }
635 } 703 }
636 return $filtered; 704 return $filtered;
637 } 705 }
638 706
639 // Returns the list of all tags 707 // Returns the list of all tags
640 // Output: associative array key=tags, value=0 708 // Output: associative array key=tags, value=0
@@ -646,7 +714,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
646 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1); 714 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
647 arsort($tags); // Sort tags by usage (most used tag first) 715 arsort($tags); // Sort tags by usage (most used tag first)
648 return $tags; 716 return $tags;
649 } 717 }
650} 718}
651 719
652// ------------------------------------------------------------------------------------------ 720// ------------------------------------------------------------------------------------------
@@ -654,15 +722,15 @@ class linkdb implements Iterator, Countable, ArrayAccess
654function showRSS() 722function showRSS()
655{ 723{
656 global $LINKSDB; 724 global $LINKSDB;
657 725
658 // Optionnaly filter the results: 726 // Optionnaly filter the results:
659 $linksToDisplay=array(); 727 $linksToDisplay=array();
660 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); 728 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
661 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); 729 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
662 else $linksToDisplay = $LINKSDB; 730 else $linksToDisplay = $LINKSDB;
663 731
664 header('Content-Type: application/rss+xml; charset=utf-8'); 732 header('Content-Type: application/rss+xml; charset=utf-8');
665 $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]); 733 $pageaddr=htmlspecialchars(indexUrl());
666 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">'; 734 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
667 echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>'; 735 echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>';
668 echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n"; 736 echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
@@ -678,16 +746,17 @@ function showRSS()
678 while ($i<50 && $i<count($keys)) 746 while ($i<50 && $i<count($keys))
679 { 747 {
680 $link = $linksToDisplay[$keys[$i]]; 748 $link = $linksToDisplay[$keys[$i]];
749 $guid = $pageaddr.'?'.smallHash($link['linkdate']);
681 $rfc822date = linkdate2rfc822($link['linkdate']); 750 $rfc822date = linkdate2rfc822($link['linkdate']);
682 $absurl = htmlspecialchars($link['url']); 751 $absurl = htmlspecialchars($link['url']);
683 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute 752 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
684 echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.$absurl.'</guid><link>'.$absurl.'</link>'; 753 echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.$guid.'</guid><link>'.$absurl.'</link>';
685 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date)."</pubDate>\n"; 754 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date)."</pubDate>\n";
686 if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification) 755 if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
687 { 756 {
688 foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.htmlspecialchars($pageaddr).'">'.htmlspecialchars($tag).'</category>'."\n"; } 757 foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.htmlspecialchars($pageaddr).'">'.htmlspecialchars($tag).'</category>'."\n"; }
689 } 758 }
690 echo '<description><![CDATA['.nl2br(text2clickable(htmlspecialchars($link['description']))).']]></description>'."\n</item>\n"; 759 echo '<description><![CDATA['.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description'])))).']]></description>'."\n</item>\n";
691 $i++; 760 $i++;
692 } 761 }
693 echo '</channel></rss>'; 762 echo '</channel></rss>';
@@ -699,15 +768,15 @@ function showRSS()
699function showATOM() 768function showATOM()
700{ 769{
701 global $LINKSDB; 770 global $LINKSDB;
702 771
703 // Optionnaly filter the results: 772 // Optionnaly filter the results:
704 $linksToDisplay=array(); 773 $linksToDisplay=array();
705 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); 774 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
706 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); 775 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
707 else $linksToDisplay = $LINKSDB; 776 else $linksToDisplay = $LINKSDB;
708 777
709 header('Content-Type: application/atom+xml; charset=utf-8'); 778 header('Content-Type: application/atom+xml; charset=utf-8');
710 $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]); 779 $pageaddr=htmlspecialchars(indexUrl());
711 $latestDate = ''; 780 $latestDate = '';
712 $entries=''; 781 $entries='';
713 $i=0; 782 $i=0;
@@ -715,19 +784,20 @@ function showATOM()
715 while ($i<50 && $i<count($keys)) 784 while ($i<50 && $i<count($keys))
716 { 785 {
717 $link = $linksToDisplay[$keys[$i]]; 786 $link = $linksToDisplay[$keys[$i]];
787 $guid = $pageaddr.'?'.smallHash($link['linkdate']);
718 $iso8601date = linkdate2iso8601($link['linkdate']); 788 $iso8601date = linkdate2iso8601($link['linkdate']);
719 $latestDate = max($latestDate,$iso8601date); 789 $latestDate = max($latestDate,$iso8601date);
720 $absurl = htmlspecialchars($link['url']); 790 $absurl = htmlspecialchars($link['url']);
721 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute 791 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
722 $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title><link href="'.$absurl.'" /><id>'.$absurl.'</id>'; 792 $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title><link href="'.$absurl.'" /><id>'.$guid.'</id>';
723 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>'; 793 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>';
724 $entries.='<summary>'.nl2br(text2clickable(htmlspecialchars($link['description'])))."</summary>\n"; 794 $entries.='<summary>'.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))))."</summary>\n";
725 if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification) 795 if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification)
726 { 796 {
727 foreach(explode(' ',$link['tags']) as $tag) 797 foreach(explode(' ',$link['tags']) as $tag)
728 { $entries.='<category scheme="'.htmlspecialchars($pageaddr,ENT_QUOTES).'" term="'.htmlspecialchars($tag,ENT_QUOTES).'" />'."\n"; } 798 { $entries.='<category scheme="'.htmlspecialchars($pageaddr,ENT_QUOTES).'" term="'.htmlspecialchars($tag,ENT_QUOTES).'" />'."\n"; }
729 } 799 }
730 $entries.="</entry>\n"; 800 $entries.="</entry>\n";
731 $i++; 801 $i++;
732 } 802 }
733 $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">'; 803 $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
@@ -749,92 +819,79 @@ function showATOM()
749} 819}
750 820
751// ------------------------------------------------------------------------------------------ 821// ------------------------------------------------------------------------------------------
752// Render HTML page: 822// Render HTML page (according to URL parameters and user rights)
753function renderPage() 823function renderPage()
754{ 824{
755 global $STARTTIME;
756 global $LINKSDB; 825 global $LINKSDB;
757 826
758 // Well... rendering the page would be 100x better with the excellent Smarty, but I don't want to tie this minimalist project to 100+ files.
759 // So I use a custom templating system.
760
761 // -------- Display login form. 827 // -------- Display login form.
762 if (startswith($_SERVER["QUERY_STRING"],'do=login')) 828 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login'))
763 { 829 {
764 if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; } // No need to login for open Shaarli 830 if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; } // No need to login for open Shaarli
765 if (!ban_canLogin()) 831 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful.
766 { 832 $PAGE = new pageBuilder;
767 $loginform='<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>'; 833 $PAGE->assign('token',$token);
768 $data = array('pageheader'=>$loginform,'body'=>'','onload'=>''); 834 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER']:''));
769 templatePage($data); 835 $PAGE->renderPage('loginform');
770 exit;
771 }
772 $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');
773 $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>';
774 $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>';
775 $onload = 'onload="document.loginform.login.focus();"';
776 $data = array('pageheader'=>$loginform,'body'=>'','onload'=>$onload);
777 templatePage($data);
778 exit; 836 exit;
779 } 837 }
780 // -------- User wants to logout. 838 // -------- User wants to logout.
781 if (startswith($_SERVER["QUERY_STRING"],'do=logout')) 839 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=logout'))
782 { 840 {
783 invalidateCaches(); 841 invalidateCaches();
784 logout(); 842 logout();
785 header('Location: ?'); 843 header('Location: ?');
786 exit; 844 exit;
787 } 845 }
788 846
789 // -------- Picture wall 847 // -------- Picture wall
790 if (startswith($_SERVER["QUERY_STRING"],'do=picwall')) 848 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=picwall'))
791 { 849 {
792 // Optionnaly filter the results: 850 // Optionnaly filter the results:
793 $linksToDisplay=array(); 851 $links=array();
794 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); 852 if (!empty($_GET['searchterm'])) $links = $LINKSDB->filterFulltext($_GET['searchterm']);
795 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); 853 elseif (!empty($_GET['searchtags'])) $links = $LINKSDB->filterTags(trim($_GET['searchtags']));
796 else $linksToDisplay = $LINKSDB; 854 else $links = $LINKSDB;
797 $body=''; 855 $body='';
798 856 $linksToDisplay=array();
799 foreach($linksToDisplay as $link) 857
858 // Get only links which have a thumbnail.
859 foreach($links as $link)
800 { 860 {
801 $href='?'.htmlspecialchars(smallhash($link['linkdate']),ENT_QUOTES); 861 $permalink='?'.htmlspecialchars(smallhash($link['linkdate']),ENT_QUOTES);
802 $thumb=thumbnail($link['url'],$href); 862 $thumb=thumbnail($link['url'],$permalink);
803 if ($thumb!='') 863 if ($thumb!='') // Only output links which have a thumbnail.
804 { 864 {
805 $body.='<div class="picwall_pictureframe">'.$thumb.'<a href="'.$href.'"><span class="info">'.htmlspecialchars($link['title']).'</span></a></div>'; 865 $link['thumbnail']=$thumb; // Thumbnail HTML code.
806 866 $link['permalink']=$permalink;
867 $linksToDisplay[]=$link; // Add to array.
807 } 868 }
808 } 869 }
809 $body = '<center><div id="picwall_container">'.$body.'<hr style="width:0;height:0;clear:both;"></div></center>'; 870 $PAGE = new pageBuilder;
810 $data = array('pageheader'=>'<br>&nbsp;','body'=>$body,'onload'=>''); 871 $PAGE->assign('linksToDisplay',$linksToDisplay);
811 templatePage($data); 872 $PAGE->renderPage('picwall');
812 exit; 873 exit;
813 874 }
814 }
815 875
816 // -------- Tag cloud 876 // -------- Tag cloud
817 if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud')) 877 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
818 { 878 {
819 $tags= $LINKSDB->allTags(); 879 $tags= $LINKSDB->allTags();
820 // We sort tags alphabetically, then choose a font size according to count. 880 // We sort tags alphabetically, then choose a font size according to count.
821 // First, find max value. 881 // First, find max value.
822 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value); 882 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
823 ksort($tags); 883 ksort($tags);
824 $cloud=''; 884 $tagList=array();
825 foreach($tags as $key=>$value) 885 foreach($tags as $key=>$value)
826 { 886 {
827 $size = max(40*$value/$maxcount,8); // Minimum size 8. 887 $tagList[$key] = array('count'=>$value,'size'=>max(40*$value/$maxcount,8));
828 $colorvalue = 128-ceil(127*$value/$maxcount);
829 $color='rgb('.$colorvalue.','.$colorvalue.','.$colorvalue.')';
830 $cloud.= '<span style="color:#99f; font-size:9pt; padding-left:5px; padding-right:2px;">'.$value.'</span><a href="?searchtags='.htmlspecialchars($key).'" style="font-size:'.$size.'pt; font-weight:bold; color:'.$color.';">'.htmlspecialchars($key).'</a> ';
831 } 888 }
832 $cloud='<div id="cloudtag">'.$cloud.'</div>'; 889 $PAGE = new pageBuilder;
833 $data = array('pageheader'=>'','body'=>$cloud,'onload'=>''); 890 $PAGE->assign('tags',$tagList);
834 templatePage($data); 891 $PAGE->renderPage('tagcloud');
835 exit; 892 exit;
836 } 893 }
837 894
838 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...) 895 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
839 if (isset($_GET['addtag'])) 896 if (isset($_GET['addtag']))
840 { 897 {
@@ -862,8 +919,8 @@ function renderPage()
862 } 919 }
863 header('Location: ?'.http_build_query($params)); 920 header('Location: ?'.http_build_query($params));
864 exit; 921 exit;
865 } 922 }
866 923
867 // -------- User wants to change the number of links per page (linksperpage=...) 924 // -------- User wants to change the number of links per page (linksperpage=...)
868 if (isset($_GET['linksperpage'])) 925 if (isset($_GET['linksperpage']))
869 { 926 {
@@ -871,57 +928,37 @@ function renderPage()
871 header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER'])); 928 header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']));
872 exit; 929 exit;
873 } 930 }
874 931
875 932
876 // -------- Handle other actions allowed for non-logged in users: 933 // -------- Handle other actions allowed for non-logged in users:
877 if (!isLoggedIn()) 934 if (!isLoggedIn())
878 { 935 {
879 // User tries to post new link but is not loggedin: 936 // User tries to post new link but is not loggedin:
880 // Show login screen, then redirect to ?post=... 937 // Show login screen, then redirect to ?post=...
881 if (isset($_GET['post'])) 938 if (isset($_GET['post']))
882 { 939 {
883 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. 940 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.
884 exit; 941 exit;
885 } 942 }
886 943 $PAGE = new pageBuilder;
887 // Show search form and display list of links. 944 buildLinkList($PAGE); // Compute list of links to display
888 $searchform=<<<HTML 945 $PAGE->renderPage('linklist');
889<div id="headerform" style="width:100%; white-space:nowrap;";> 946 exit; // Never remove this one ! All operations below are reserved for logged in user.
890 <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>
891 <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>
892</div>
893HTML;
894 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>'');
895 templatePage($data);
896 exit; // Never remove this one ! All operations below are reserved for logged in user.
897 } 947 }
898 948
899 // -------- All other functions are reserved for the registered user: 949 // -------- All other functions are reserved for the registered user:
900 950
901 // -------- Display the Tools menu if requested (import/export/bookmarklet...) 951 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
902 if (startswith($_SERVER["QUERY_STRING"],'do=tools')) 952 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=tools'))
903 { 953 {
904 $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ? 954 $PAGE = new pageBuilder;
905 // The javascript code for the bookmarklet: 955 $PAGE->assign('pageabsaddr',indexUrl());
906 $changepwd = ($GLOBALS['config']['OPEN_SHAARLI'] ? '' : '<a href="?do=changepasswd"><b>Change password</b> <span>: Change your password.</span></a><br><br>' ); 956 $PAGE->renderPage('tools');
907 $toolbar= <<<HTML
908<div id="toolsdiv">
909 {$changepwd}
910 <a href="?do=configure"><b>Configure your Shaarli</b> <span>: Change Title, timezone...</span></a><br><br>
911 <a href="?do=changetag"><b>Rename/delete tags</b> <span>: Rename or delete a tag in all links</span></a><br><br>
912 <a href="?do=import"><b>Import</b> <span>: Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)</span></a> <br><br>
913 <a href="?do=export"><b>Export</b> <span>: Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)</span></a><br><br>
914<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=390,width=600,toolbar=no,scrollbars=no,status=no');})();"><b>Shaare link</b></a> <a href="#" style="clear:none;"><span>&#x21D0; 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.</span></a><br><br>
915 <div class="clear"></div>
916 </div>
917HTML;
918 $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>'');
919 templatePage($data);
920 exit; 957 exit;
921 } 958 }
922 959
923 // -------- User wants to change his/her password. 960 // -------- User wants to change his/her password.
924 if (startswith($_SERVER["QUERY_STRING"],'do=changepasswd')) 961 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=changepasswd'))
925 { 962 {
926 if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.'); 963 if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.');
927 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) 964 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
@@ -938,32 +975,25 @@ HTML;
938 echo '<script language="JavaScript">alert("Your password has been changed.");document.location=\'?do=tools\';</script>'; 975 echo '<script language="JavaScript">alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
939 exit; 976 exit;
940 } 977 }
941 else 978 else // show the change password form.
942 { 979 {
943 $token = getToken(); 980 $PAGE = new pageBuilder;
944 $changepwdform= <<<HTML 981 $PAGE->assign('token',getToken());
945<form method="POST" action="" name="changepasswordform" id="changepasswordform"> 982 $PAGE->renderPage('changepassword');
946Old password: <input type="password" name="oldpassword">&nbsp; &nbsp; 983 exit;
947New password: <input type="password" name="setpassword">
948<input type="hidden" name="token" value="{$token}">
949<input type="submit" name="Save" value="Save password" class="bigbutton"></form>
950HTML;
951 $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.changepasswordform.oldpassword.focus();"');
952 templatePage($data);
953 exit;
954 } 984 }
955 } 985 }
956 986
957 // -------- User wants to change configuration 987 // -------- User wants to change configuration
958 if (startswith($_SERVER["QUERY_STRING"],'do=configure')) 988 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=configure'))
959 { 989 {
960 if (!empty($_POST['title']) ) 990 if (!empty($_POST['title']) )
961 { 991 {
962 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away ! 992 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
963 $tz = 'UTC'; 993 $tz = 'UTC';
964 if (!empty($_POST['continent']) && !empty($_POST['city'])) 994 if (!empty($_POST['continent']) && !empty($_POST['city']))
965 if (isTZvalid($_POST['continent'],$_POST['city'])) 995 if (isTZvalid($_POST['continent'],$_POST['city']))
966 $tz = $_POST['continent'].'/'.$_POST['city']; 996 $tz = $_POST['continent'].'/'.$_POST['city'];
967 $GLOBALS['timezone'] = $tz; 997 $GLOBALS['timezone'] = $tz;
968 $GLOBALS['title']=$_POST['title']; 998 $GLOBALS['title']=$_POST['title'];
969 $GLOBALS['redirector']=$_POST['redirector']; 999 $GLOBALS['redirector']=$_POST['redirector'];
@@ -971,49 +1001,33 @@ HTML;
971 echo '<script language="JavaScript">alert("Configuration was saved.");document.location=\'?do=tools\';</script>'; 1001 echo '<script language="JavaScript">alert("Configuration was saved.");document.location=\'?do=tools\';</script>';
972 exit; 1002 exit;
973 } 1003 }
974 else 1004 else // Show the configuration form.
975 { 1005 {
976 $token = getToken(); 1006 $PAGE = new pageBuilder;
977 $title = htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES); 1007 $PAGE->assign('token',getToken());
978 $redirector = htmlspecialchars( empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] , ENT_QUOTES); 1008 $PAGE->assign('title',htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES));
1009 $PAGE->assign('redirector',htmlspecialchars( empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] , ENT_QUOTES));
979 list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']); 1010 list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']);
980 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>'; 1011 $PAGE->assign('timezone_form',$timezone_form); // FIXME: put entire tz form generation in template ?
981 $changepwdform= <<<HTML 1012 $PAGE->assign('timezone_js',$timezone_js);
982${timezone_js}<form method="POST" action="" name="configform" id="configform"><input type="hidden" name="token" value="{$token}"> 1013 $PAGE->renderPage('configure');
983<table border="0" cellpadding="20"> 1014 exit;
984<tr><td><b>Page title:</b></td><td><input type="text" name="title" id="title" size="50" value="{$title}"></td></tr>
985{$timezone_html}
986<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>
987<tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
988</table>
989</form>
990HTML;
991 $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.configform.title.focus();"');
992 templatePage($data);
993 exit;
994 } 1015 }
995 } 1016 }
996 1017
997 // -------- User wants to rename a tag or delete it 1018 // -------- User wants to rename a tag or delete it
998 if (startswith($_SERVER["QUERY_STRING"],'do=changetag')) 1019 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=changetag'))
999 { 1020 {
1000 if (empty($_POST['fromtag'])) 1021 if (empty($_POST['fromtag']))
1001 { 1022 {
1002 $token = getToken(); 1023 $PAGE = new pageBuilder;
1003 $changetagform = <<<HTML 1024 $PAGE->assign('token',getToken());
1004<form method="POST" action="" name="changetag" id="changetag"> 1025 $PAGE->renderPage('changetag');
1005<input type="hidden" name="token" value="{$token}"> 1026 exit;
1006Tag: <input type="text" name="fromtag" id="fromtag">
1007<input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
1008&nbsp;&nbsp;or&nbsp; <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
1009<script language="JavaScript">function confirmDeleteTag() { var agree=confirm("Are you sure you want to delete this tag from all links ?"); if (agree) return true ; else return false ; }</script>
1010HTML;
1011 $data = array('pageheader'=>$changetagform,'body'=>'','onload'=>'onload="document.changetag.fromtag.focus();"');
1012 templatePage($data);
1013 exit;
1014 } 1027 }
1015 if (!tokenOk($_POST['token'])) die('Wrong token.'); 1028 if (!tokenOk($_POST['token'])) die('Wrong token.');
1016 1029
1030 // Delete a tag:
1017 if (!empty($_POST['deletetag']) && !empty($_POST['fromtag'])) 1031 if (!empty($_POST['deletetag']) && !empty($_POST['fromtag']))
1018 { 1032 {
1019 $needle=trim($_POST['fromtag']); 1033 $needle=trim($_POST['fromtag']);
@@ -1047,19 +1061,17 @@ HTML;
1047 invalidateCaches(); 1061 invalidateCaches();
1048 echo '<script language="JavaScript">alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>'; 1062 echo '<script language="JavaScript">alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
1049 exit; 1063 exit;
1050 } 1064 }
1051 } 1065 }
1052 1066
1053 // -------- User wants to add a link without using the bookmarklet: show form. 1067 // -------- User wants to add a link without using the bookmarklet: show form.
1054 if (startswith($_SERVER["QUERY_STRING"],'do=addlink')) 1068 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=addlink'))
1055 { 1069 {
1056 $onload = 'onload="document.addform.post.focus();"'; 1070 $PAGE = new pageBuilder;
1057 $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>'; 1071 $PAGE->renderPage('addlink');
1058 $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload);
1059 templatePage($data);
1060 exit; 1072 exit;
1061 } 1073 }
1062 1074
1063 // -------- User clicked the "Save" button when editing a link: Save link to database. 1075 // -------- User clicked the "Save" button when editing a link: Save link to database.
1064 if (isset($_POST['save_edit'])) 1076 if (isset($_POST['save_edit']))
1065 { 1077 {
@@ -1067,20 +1079,20 @@ HTML;
1067 $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces. 1079 $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces.
1068 $linkdate=$_POST['lf_linkdate']; 1080 $linkdate=$_POST['lf_linkdate'];
1069 $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0), 1081 $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
1070 'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags)); 1082 'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags));
1071 if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title. 1083 if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
1072 $LINKSDB[$linkdate] = $link; 1084 $LINKSDB[$linkdate] = $link;
1073 $LINKSDB->savedb(); // save to disk 1085 $LINKSDB->savedb(); // save to disk
1074 pubsubhub(); 1086 pubsubhub();
1075 invalidateCaches(); 1087 invalidateCaches();
1076 1088
1077 // If we are called from the bookmarklet, we must close the popup: 1089 // If we are called from the bookmarklet, we must close the popup:
1078 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; } 1090 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1079 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); 1091 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1080 header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on. 1092 header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on.
1081 exit; 1093 exit;
1082 } 1094 }
1083 1095
1084 // -------- User clicked the "Cancel" button when editing a link. 1096 // -------- User clicked the "Cancel" button when editing a link.
1085 if (isset($_POST['cancel_edit'])) 1097 if (isset($_POST['cancel_edit']))
1086 { 1098 {
@@ -1088,7 +1100,7 @@ HTML;
1088 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; } 1100 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1089 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); 1101 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1090 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on. 1102 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1091 exit; 1103 exit;
1092 } 1104 }
1093 1105
1094 // -------- User clicked the "Delete" button when editing a link : Delete link from database. 1106 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
@@ -1107,19 +1119,22 @@ HTML;
1107 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); 1119 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1108 header('Location: '.$returnurl); // After deleting the link, redirect to the page the user was on. 1120 header('Location: '.$returnurl); // After deleting the link, redirect to the page the user was on.
1109 exit; 1121 exit;
1110 } 1122 }
1111 1123
1112 // -------- User clicked the "EDIT" button on a link: Display link edit form. 1124 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1113 if (isset($_GET['edit_link'])) 1125 if (isset($_GET['edit_link']))
1114 { 1126 {
1115 $link = $LINKSDB[$_GET['edit_link']]; // Read database 1127 $link = $LINKSDB[$_GET['edit_link']]; // Read database
1116 if (!$link) { header('Location: ?'); exit; } // Link not found in database. 1128 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1117 list($editform,$onload)=templateEditForm($link); 1129 $PAGE = new pageBuilder;
1118 $data = array('pageheader'=>$editform,'body'=>'','onload'=>$onload); 1130 $PAGE->assign('link',$link);
1119 templatePage($data); 1131 $PAGE->assign('link_is_new',false);
1120 exit; 1132 $PAGE->assign('token',getToken()); // XSRF protection.
1133 $PAGE->assign('http_referer',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''));
1134 $PAGE->renderPage('editlink');
1135 exit;
1121 } 1136 }
1122 1137
1123 // -------- User want to post a new link: Display link edit form. 1138 // -------- User want to post a new link: Display link edit form.
1124 if (isset($_GET['post'])) 1139 if (isset($_GET['post']))
1125 { 1140 {
@@ -1129,51 +1144,48 @@ HTML;
1129 $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i); 1144 $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i);
1130 $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i); 1145 $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
1131 $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i); 1146 $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
1132 1147
1133 $link_is_new = false; 1148 $link_is_new = false;
1134 $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link) 1149 $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link)
1135 if (!$link) 1150 if (!$link)
1136 { 1151 {
1137 $link_is_new = true; // This is a new link 1152 $link_is_new = true; // This is a new link
1138 $linkdate = strval(date('Ymd_His')); 1153 $linkdate = strval(date('Ymd_His'));
1139 $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet). 1154 $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
1140 $description=''; $tags=''; $private=0; 1155 $description=''; $tags=''; $private=0;
1141 if (($url!='') && parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url; 1156 if (($url!='') && parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;
1142 // 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.) 1157 // 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.)
1143 if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http') 1158 if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
1144 { 1159 {
1145 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive. 1160 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
1146 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html 1161 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1147 if (strpos($status,'200 OK')!==false) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8'); 1162 if (strpos($status,'200 OK')!==false) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
1148 } 1163 }
1149 if ($url=='') $url='?'.smallHash($linkdate); // In case of empty URL, this is just a text (with a link that point to itself) 1164 if ($url=='') $url='?'.smallHash($linkdate); // In case of empty URL, this is just a text (with a link that point to itself)
1150 $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0); 1165 $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
1151 } 1166 }
1152 list($editform,$onload)=templateEditForm($link,$link_is_new); 1167
1153 $data = array('pageheader'=>$editform,'body'=>'','onload'=>$onload); 1168 $PAGE = new pageBuilder;
1154 templatePage($data); 1169 $PAGE->assign('link',$link);
1170 $PAGE->assign('link_is_new',$link_is_new);
1171 $PAGE->assign('token',getToken()); // XSRF protection.
1172 $PAGE->assign('http_referer',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''));
1173 $PAGE->renderPage('editlink');
1155 exit; 1174 exit;
1156 } 1175 }
1157 1176
1158 // -------- Export as Netscape Bookmarks HTML file. 1177 // -------- Export as Netscape Bookmarks HTML file.
1159 if (startswith($_SERVER["QUERY_STRING"],'do=export')) 1178 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=export'))
1160 { 1179 {
1161 if (empty($_GET['what'])) 1180 if (empty($_GET['what']))
1162 { 1181 {
1163 $toolbar= <<<HTML 1182 $PAGE = new pageBuilder;
1164<div id="toolsdiv"> 1183 $PAGE->renderPage('export');
1165 <a href="?do=export&what=all"><b>Export all</b> <span>: Export all links</span></a><br><br> 1184 exit;
1166 <a href="?do=export&what=public"><b>Export public</b> <span>: Export public links only</a><br><br>
1167 <a href="?do=export&what=private"><b>Export private</b> <span>: Export private links only</a><br><br style="clear:both;">
1168</div>
1169HTML;
1170 $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>'');
1171 templatePage($data);
1172 exit;
1173 } 1185 }
1174 $exportWhat=$_GET['what']; 1186 $exportWhat=$_GET['what'];
1175 if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???'); 1187 if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???');
1176 1188
1177 header('Content-Type: text/html; charset=utf-8'); 1189 header('Content-Type: text/html; charset=utf-8');
1178 header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html'); 1190 header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
1179 $currentdate=date('Y/m/d H:i:s'); 1191 $currentdate=date('Y/m/d H:i:s');
@@ -1182,7 +1194,7 @@ HTML;
1182<!-- This is an automatically generated file. 1194<!-- This is an automatically generated file.
1183 It will be read and overwritten. 1195 It will be read and overwritten.
1184 DO NOT EDIT! --> 1196 DO NOT EDIT! -->
1185<!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} --> 1197<!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1186<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> 1198<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1187<TITLE>Bookmarks</TITLE> 1199<TITLE>Bookmarks</TITLE>
1188<H1>Bookmarks</H1> 1200<H1>Bookmarks</H1>
@@ -1200,10 +1212,10 @@ HTML;
1200 } 1212 }
1201 } 1213 }
1202 exit; 1214 exit;
1203 } 1215 }
1204 1216
1205 // -------- User is uploading a file for import 1217 // -------- User is uploading a file for import
1206 if (startswith($_SERVER["QUERY_STRING"],'do=upload')) 1218 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=upload'))
1207 { 1219 {
1208 // If file is too big, some form field may be missing. 1220 // If file is too big, some form field may be missing.
1209 if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0)) 1221 if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0))
@@ -1211,47 +1223,28 @@ HTML;
1211 $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] ); 1223 $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] );
1212 echo '<script language="JavaScript">alert("The file you are trying to upload is probably bigger than what this webserver can accept ('.getMaxFileSize().' bytes). Please upload in smaller chunks.");document.location=\''.htmlspecialchars($returnurl).'\';</script>'; 1224 echo '<script language="JavaScript">alert("The file you are trying to upload is probably bigger than what this webserver can accept ('.getMaxFileSize().' bytes). Please upload in smaller chunks.");document.location=\''.htmlspecialchars($returnurl).'\';</script>';
1213 exit; 1225 exit;
1214 } 1226 }
1215 if (!tokenOk($_POST['token'])) die('Wrong token.'); 1227 if (!tokenOk($_POST['token'])) die('Wrong token.');
1216 importFile(); 1228 importFile();
1217 exit; 1229 exit;
1218 } 1230 }
1219 1231
1220 // -------- Show upload/import dialog: 1232 // -------- Show upload/import dialog:
1221 if (startswith($_SERVER["QUERY_STRING"],'do=import')) 1233 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=import'))
1222 { 1234 {
1223 $token = getToken(); 1235 $PAGE = new pageBuilder;
1224 $maxfilesize=getMaxFileSize(); 1236 $PAGE->assign('token',getToken());
1225 $onload = 'onload="document.uploadform.filetoupload.focus();"'; 1237 $PAGE->assign('maxfilesize',getMaxFileSize());
1226 $uploadform=<<<HTML 1238 $PAGE->renderPage('import');
1227<div id="uploaddiv">
1228Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
1229<form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform" id="uploadform">
1230 <input type="hidden" name="token" value="{$token}">
1231 <input type="file" name="filetoupload" size="80">
1232 <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
1233 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
1234 <input type="checkbox" name="private">&nbsp;Import all links as private<br>
1235 <input type="checkbox" name="overwrite">&nbsp;Overwrite existing links
1236</form>
1237</div>
1238HTML;
1239 $data = array('pageheader'=>$uploadform,'body'=>'','onload'=>$onload );
1240 templatePage($data);
1241 exit; 1239 exit;
1242 } 1240 }
1243 1241
1244 // -------- Otherwise, simply display search form and links: 1242 // -------- Otherwise, simply display search form and links:
1245 $searchform=<<<HTML 1243 $PAGE = new pageBuilder;
1246<div id="headerform" style="width:100%; white-space:nowrap;";> 1244 buildLinkList($PAGE); // Compute list of links to display
1247 <form method="GET" class="searchform" name="searchform"><input type="text" name="searchterm" style="width:30%" value=""> <input type="submit" value="Search" class="bigbutton"></form> 1245 $PAGE->renderPage('linklist');
1248 <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>
1249</div>
1250HTML;
1251 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>'');
1252 templatePage($data);
1253 exit; 1246 exit;
1254} 1247}
1255 1248
1256// ----------------------------------------------------------------------------------------------- 1249// -----------------------------------------------------------------------------------------------
1257// Process the import file form. 1250// Process the import file form.
@@ -1259,7 +1252,7 @@ function importFile()
1259{ 1252{
1260 global $LINKSDB; 1253 global $LINKSDB;
1261 $filename=$_FILES['filetoupload']['name']; 1254 $filename=$_FILES['filetoupload']['name'];
1262 $filesize=$_FILES['filetoupload']['size']; 1255 $filesize=$_FILES['filetoupload']['size'];
1263 $data=file_get_contents($_FILES['filetoupload']['tmp_name']); 1256 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
1264 $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ? 1257 $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ?
1265 $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ? 1258 $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ?
@@ -1268,15 +1261,15 @@ function importFile()
1268 // Sniff file type: 1261 // Sniff file type:
1269 $type='unknown'; 1262 $type='unknown';
1270 if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox). 1263 if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox).
1271 1264
1272 // Then import the bookmarks. 1265 // Then import the bookmarks.
1273 if ($type=='netscape') 1266 if ($type=='netscape')
1274 { 1267 {
1275 // This is a standard Netscape-style bookmark file. 1268 // This is a standard Netscape-style bookmark file.
1276 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others. 1269 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1277 foreach(explode('<DT>',$data) as $html) // explode is very fast 1270 foreach(explode('<DT>',$data) as $html) // explode is very fast
1278 { 1271 {
1279 $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0); 1272 $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
1280 $d = explode('<DD>',$html); 1273 $d = explode('<DD>',$html);
1281 if (startswith($d[0],'<A ')) 1274 if (startswith($d[0],'<A '))
1282 { 1275 {
@@ -1292,7 +1285,7 @@ function importFile()
1292 elseif ($attr=='ADD_DATE') $raw_add_date=intval($value); 1285 elseif ($attr=='ADD_DATE') $raw_add_date=intval($value);
1293 elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1); 1286 elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
1294 elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8'); 1287 elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
1295 } 1288 }
1296 if ($link['url']!='') 1289 if ($link['url']!='')
1297 { 1290 {
1298 if ($private==1) $link['private']=1; 1291 if ($private==1) $link['private']=1;
@@ -1300,7 +1293,7 @@ function importFile()
1300 if ($dblink==false) 1293 if ($dblink==false)
1301 { // Link not in database, let's import it... 1294 { // Link not in database, let's import it...
1302 if (empty($raw_add_date)) $raw_add_date=time(); // In case of shitty bookmark file with no ADD_DATE 1295 if (empty($raw_add_date)) $raw_add_date=time(); // In case of shitty bookmark file with no ADD_DATE
1303 1296
1304 // Make sure date/time is not already used by another link. 1297 // Make sure date/time is not already used by another link.
1305 // (Some bookmark files have several different links with the same ADD_DATE) 1298 // (Some bookmark files have several different links with the same ADD_DATE)
1306 // We increment date by 1 second until we find a date which is not used in db. 1299 // We increment date by 1 second until we find a date which is not used in db.
@@ -1321,98 +1314,51 @@ function importFile()
1321 } 1314 }
1322 1315
1323 } 1316 }
1324 } 1317 }
1325 } 1318 }
1326 $LINKSDB->savedb(); 1319 $LINKSDB->savedb();
1327 invalidateCaches(); 1320 invalidateCaches();
1328 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>'; 1321 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
1329 } 1322 }
1330 else 1323 else
1331 { 1324 {
1332 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>'; 1325 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
1333 } 1326 }
1334} 1327}
1335 1328
1336// ----------------------------------------------------------------------------------------------- 1329// -----------------------------------------------------------------------------------------------
1337/* Template for the edit link form 1330// Template for the list of links (<div id="linklist">)
1338 Input: $link : link to edit (assocative array item as returned by the LINKDB class) 1331// This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1339Output: An array : (string) : The html code of the edit link form. 1332function buildLinkList($PAGE)
1340 (string) : The proper onload to use in body.
1341 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
1342 echo $html;
1343*/
1344function templateEditForm($link,$link_is_new=false)
1345{ 1333{
1346 $url=htmlspecialchars($link['url']); 1334 global $LINKSDB; // Get the links database.
1347 $title=htmlspecialchars($link['title']);
1348 $tags=htmlspecialchars($link['tags']);
1349 $description=htmlspecialchars($link['description']);
1350 $private = ($link['private']==0 ? '' : 'checked="yes"');
1351
1352 // Automatically focus on empty fields:
1353 $onload='onload="document.linkform.lf_tags.focus();"';
1354 if ($description=='') $onload='onload="document.linkform.lf_description.focus();"';
1355 if ($title=='') $onload='onload="document.linkform.lf_title.focus();"';
1356
1357 // Do not show "Delete" button if this is a new link.
1358 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">';
1359 if ($link_is_new) $delete_button='';
1360
1361 $token=getToken(); // XSRF protection.
1362 $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');
1363 $editlinkform=<<<HTML
1364<div id="editlinkform">
1365 <form method="post" name="linkform">
1366 <input type="hidden" name="lf_linkdate" value="{$link['linkdate']}">
1367 <i>URL</i><br><input type="text" name="lf_url" value="{$url}" style="width:100%"><br>
1368 <i>Title</i><br><input type="text" name="lf_title" value="{$title}" style="width:100%"><br>
1369 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%">{$description}</textarea><br>
1370 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value="{$tags}" style="width:100%"><br>
1371 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private">&nbsp;<i>Private</i><br>
1372 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1373 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1374 {$delete_button}
1375 <input type="hidden" name="token" value="{$token}">
1376 {$returnurl_html}
1377 </form>
1378</div>
1379HTML;
1380 return array($editlinkform,$onload);
1381}
1382
1383
1384// -----------------------------------------------------------------------------------------------
1385// Template for the list of links.
1386// Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1387function templateLinkList()
1388{
1389 global $LINKSDB;
1390 1335
1391 // Search according to entered search terms: 1336 // ---- Filter link database according to parameters
1392 $linksToDisplay=array(); 1337 $linksToDisplay=array();
1393 $searched=''; 1338 $search_type='';
1339 $search_crits='';
1394 if (!empty($_GET['searchterm'])) // Fulltext search 1340 if (!empty($_GET['searchterm'])) // Fulltext search
1395 { 1341 {
1396 $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm'])); 1342 $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
1397 $searched=count($linksToDisplay).' results for <i>'.htmlspecialchars(trim($_GET['searchterm'])).'</i>:'; 1343 $search_crits=htmlspecialchars(trim($_GET['searchterm']));
1344 $search_type='fulltext';
1398 } 1345 }
1399 elseif (!empty($_GET['searchtags'])) // Search by tag 1346 elseif (!empty($_GET['searchtags'])) // Search by tag
1400 { 1347 {
1401 $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); 1348 $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
1402 $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> '; 1349 $search_crits=explode(' ',trim($_GET['searchtags']));
1403 $searched=''.count($linksToDisplay).' results for tags '.$tagshtml.':'; 1350 $search_type='tags';
1404 } 1351 }
1405 elseif (preg_match('/[a-zA-Z0-9-_@]{6}/',$_SERVER["QUERY_STRING"])) // Detect smallHashes in URL 1352 elseif (isset($_SERVER["QUERY_STRING"]) && preg_match('/[a-zA-Z0-9-_@]{6}(&.+?)?/',$_SERVER["QUERY_STRING"])) // Detect smallHashes in URL
1406 { 1353 {
1407 $linksToDisplay = $LINKSDB->filterSmallHash($_SERVER["QUERY_STRING"]); 1354 $linksToDisplay = $LINKSDB->filterSmallHash(substr(trim($_SERVER["QUERY_STRING"], '/'),0,6));
1355 $search_type='permalink';
1408 } 1356 }
1409 else 1357 else
1410 $linksToDisplay = $LINKSDB; // otherwise, display without filtering. 1358 $linksToDisplay = $LINKSDB; // otherwise, display without filtering.
1411 if ($searched!='') $searched='<div id="searchcriteria">'.$searched.'</div>'; 1359
1412 $linklist=''; 1360
1413 $actions=''; 1361 // ---- Handle paging.
1414
1415 // Handle paging.
1416 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ??? 1362 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1417 "Warning: array_keys() expects parameter 1 to be array, object given in ... " 1363 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1418 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); ) 1364 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
@@ -1422,72 +1368,62 @@ function templateLinkList()
1422 // If there is only a single link, we change on-the-fly the title of the page. 1368 // If there is only a single link, we change on-the-fly the title of the page.
1423 if (count($linksToDisplay)==1) $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title']; 1369 if (count($linksToDisplay)==1) $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title'];
1424 1370
1371 // Select articles according to paging.
1425 $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']); 1372 $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
1426 $pagecount = ($pagecount==0 ? 1 : $pagecount); 1373 $pagecount = ($pagecount==0 ? 1 : $pagecount);
1427 $page=( empty($_GET['page']) ? 1 : intval($_GET['page'])); 1374 $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
1428 $page = ( $page<1 ? 1 : $page ); 1375 $page = ( $page<1 ? 1 : $page );
1429 $page = ( $page>$pagecount ? $pagecount : $page ); 1376 $page = ( $page>$pagecount ? $pagecount : $page );
1430 $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index. 1377 $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
1431 $end = $i+$_SESSION['LINKS_PER_PAGE']; 1378 $end = $i+$_SESSION['LINKS_PER_PAGE'];
1432 $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector']; // optional redirector URL 1379 $linkDisp=array(); // Links to display
1433 $token = ''; if (isLoggedIn()) $token=getToken();
1434
1435 while ($i<$end && $i<count($keys)) 1380 while ($i<$end && $i<count($keys))
1436 { 1381 {
1437 $link = $linksToDisplay[$keys[$i]]; 1382 $link = $linksToDisplay[$keys[$i]];
1438 $description=text2clickable(htmlspecialchars($link['description'])); 1383 $link['description']=nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))));
1439 $title=$link['title']; 1384 $title=$link['title'];
1440 $classLi = $i%2!=0 ? '' : 'class="publicLinkHightLight"'; 1385 $classLi = $i%2!=0 ? '' : 'publicLinkHightLight';
1441 $classprivate = ($link['private']==0 ? $classLi : 'class="private"'); 1386 $link['class'] = ($link['private']==0 ? $classLi : 'private');
1442 if (isLoggedIn()) 1387 $link['localdate']=linkdate2locale($link['linkdate']);
1443 { 1388 $link['taglist']=explode(' ',$link['tags']);
1444 $actions=' <form method="GET" class="buttoneditform"><input type="hidden" name="edit_link" value="'.$link['linkdate'].'"><input type="image" alt="Edit" src="images/edit_icon.png" title="Edit" class="button_edit"></form>'; 1389 $linkDisp[$keys[$i]] = $link;
1445 $actions.=' <form method="POST" class="buttoneditform"><input type="hidden" name="lf_linkdate" value="'.$link['linkdate'].'">';
1446 $actions.='<input type="hidden" name="token" value="'.$token.'"><input type="hidden" name="delete_link"><input type="image" alt="Delete" src="images/delete_icon.png" title="Delete" class="button_delete" onClick="return confirmDeleteLink();"></form>';
1447 }
1448 $tags='';
1449 if ($link['tags']!='')
1450 {
1451 foreach(explode(' ',$link['tags']) as $tag) { $tags.='<span class="linktag" title="Add tag"><a href="?addtag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).'</a></span> '; }
1452 $tags='<div class="linktaglist">'.$tags.'</div>';
1453 }
1454 $linklist.='<li '.$classprivate.'><div class="thumbnail">'.thumbnail($link['url']).'</div>';
1455 $linklist.='<div class="linkcontainer"><span class="linktitle"><a href="'.$redir.htmlspecialchars($link['url']).'">'.htmlspecialchars($title).'</a></span>'.$actions.'<br>';
1456 if ($description!='') $linklist.='<div class="linkdescription">'.nl2br($description).'</div><br>';
1457 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $linklist.='<span class="linkdate" title="Permalink"><a href="?'.smallHash($link['linkdate']).'">'.htmlspecialchars(linkdate2locale($link['linkdate'])).' - permalink</a> - </span>';
1458 else $linklist.='<span class="linkdate" title="Short link here"><a href="?'.smallHash($link['linkdate']).'">permalink</a> - </span>';
1459 $linklist.='<span class="linkurl" title="Short link">'.htmlspecialchars($link['url']).'</span><br>'.$tags."</div></li>\n";
1460 $i++; 1390 $i++;
1461 } 1391 }
1462 1392
1463 // Show paging. 1393 // Compute paging navigation
1464 $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] ); 1394 $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] );
1465 $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] ); 1395 $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] );
1466 $paging=''; 1396 $paging='';
1467 if ($i!=count($keys)) $paging.='<a href="?page='.($page+1).$searchterm.$searchtags.'">&#x25C4;Older</a>'; 1397 $previous_page_url=''; if ($i!=count($keys)) $previous_page_url='?page='.($page+1).$searchterm.$searchtags;
1468 $paging.= '<span style="color:#fff; padding:0 20 0 20;">page '.$page.' / '.$pagecount.'</span>'; 1398 $next_page_url='';if ($page>1) $next_page_url='?page='.($page-1).$searchterm.$searchtags;
1469 if ($page>1) $paging.='<a href="?page='.($page-1).$searchterm.$searchtags.'">Newer&#x25BA;</a>'; 1399
1470 $linksperpage = <<<HTML 1400 $token = ''; if (isLoggedIn()) $token=getToken();
1471<div style="float:right; padding-right:5px;"> 1401
1472Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a> 1402 // Fill all template fields.
1473 <form method="GET" style="display:inline;" class="linksperpage"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div> 1403 $PAGE->assign('previous_page_url',$previous_page_url);
1474HTML; 1404 $PAGE->assign('next_page_url',$next_page_url);
1475 $paging = '<div class="paging">'.$linksperpage.$paging.'</div>'; 1405 $PAGE->assign('page_current',$page);
1476 $linklist='<div id="linklist">'.$paging.$searched.'<ul>'.$linklist.'</ul>'.$paging.'</div>'; 1406 $PAGE->assign('page_max',$pagecount);
1477 return $linklist; 1407 $PAGE->assign('result_count',count($linksToDisplay));
1408 $PAGE->assign('search_type',$search_type);
1409 $PAGE->assign('search_crits',$search_crits);
1410 $PAGE->assign('redirector',empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector']); // optional redirector URL
1411 $PAGE->assign('token',$token);
1412 $PAGE->assign('links',$linkDisp);
1413 return;
1478} 1414}
1479 1415
1480// Returns the HTML code to display a thumbnail for a link 1416// Returns the HTML code to display a thumbnail for a link
1481// with a link to the original URL. 1417// with a link to the original URL.
1482// Understands various services (youtube.com...) 1418// Understands various services (youtube.com...)
1483// Input: $url = url for which the thumbnail must be found. 1419// Input: $url = url for which the thumbnail must be found.
1484// $href = if provided, this URL will be followed instead of $url 1420// $href = if provided, this URL will be followed instead of $url
1485function thumbnail($url,$href=false) 1421function thumbnail($url,$href=false)
1486{ 1422{
1487 if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return ''; 1423 if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return '';
1488 1424
1489 if ($href==false) $href=$url; 1425 if ($href==false) $href=$url;
1490 1426
1491 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link. 1427 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1492 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg ) 1428 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1493 // ^^^^^^^^^^^ ^^^^^^^^^^^ 1429 // ^^^^^^^^^^^ ^^^^^^^^^^^
@@ -1501,7 +1437,7 @@ function thumbnail($url,$href=false)
1501 { 1437 {
1502 $path = parse_url($url,PHP_URL_PATH); 1438 $path = parse_url($url,PHP_URL_PATH);
1503 return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi'.htmlspecialchars($path).'/default.jpg" width="120" height="90"></a>'; 1439 return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi'.htmlspecialchars($path).'/default.jpg" width="120" height="90"></a>';
1504 } 1440 }
1505 if ($domain=='imgur.com') 1441 if ($domain=='imgur.com')
1506 { 1442 {
1507 $path = parse_url($url,PHP_URL_PATH); 1443 $path = parse_url($url,PHP_URL_PATH);
@@ -1514,7 +1450,7 @@ function thumbnail($url,$href=false)
1514 { 1450 {
1515 $pi = pathinfo(parse_url($url,PHP_URL_PATH)); 1451 $pi = pathinfo(parse_url($url,PHP_URL_PATH));
1516 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>'; 1452 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>';
1517 } 1453 }
1518 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com') 1454 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1519 { 1455 {
1520 if (strpos($url,'dailymotion.com/video/')!==false) 1456 if (strpos($url,'dailymotion.com/video/')!==false)
@@ -1522,7 +1458,7 @@ function thumbnail($url,$href=false)
1522 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url); 1458 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1523 return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>'; 1459 return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
1524 } 1460 }
1525 } 1461 }
1526 if (endsWith($domain,'.imageshack.us')) 1462 if (endsWith($domain,'.imageshack.us'))
1527 { 1463 {
1528 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION)); 1464 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
@@ -1536,9 +1472,9 @@ function thumbnail($url,$href=false)
1536 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL. 1472 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1537 // So we deport the thumbnail generation in order not to slow down page generation 1473 // So we deport the thumbnail generation in order not to slow down page generation
1538 // (and we also cache the thumbnail) 1474 // (and we also cache the thumbnail)
1539 1475
1540 if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return ''; // If local cache is disabled, no thumbnails for services which require the use a local cache. 1476 if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return ''; // If local cache is disabled, no thumbnails for services which require the use a local cache.
1541 1477
1542 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com') 1478 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1543 || $domain=='vimeo.com' 1479 || $domain=='vimeo.com'
1544 || $domain=='ted.com' || endsWith($domain,'.ted.com') 1480 || $domain=='ted.com' || endsWith($domain,'.ted.com')
@@ -1546,7 +1482,7 @@ function thumbnail($url,$href=false)
1546 { 1482 {
1547 if ($domain=='vimeo.com') 1483 if ($domain=='vimeo.com')
1548 { // Make sure this vimeo url points to a video (/xxx... where xxx is numeric) 1484 { // Make sure this vimeo url points to a video (/xxx... where xxx is numeric)
1549 $path = parse_url($url,PHP_URL_PATH); 1485 $path = parse_url($url,PHP_URL_PATH);
1550 if (!preg_match('!/\d+.+?!',$path)) return ''; // This is not a single video URL. 1486 if (!preg_match('!/\d+.+?!',$path)) return ''; // This is not a single video URL.
1551 } 1487 }
1552 if ($domain=='ted.com' || endsWith($domain,'.ted.com')) 1488 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
@@ -1565,140 +1501,45 @@ function thumbnail($url,$href=false)
1565 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif') 1501 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1566 { 1502 {
1567 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation) 1503 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
1568 return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>'; 1504 return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';
1569 } 1505 }
1570 return ''; // No thumbnail. 1506 return ''; // No thumbnail.
1571 1507
1572} 1508}
1573 1509
1574// ----------------------------------------------------------------------------------------------- 1510// -----------------------------------------------------------------------------------------------
1575// Template for the whole page.
1576/* Input: $data (associative array).
1577 Keys: 'body' : body of HTML document
1578 'pageheader' : html code to show in page header (top of page)
1579 'onload' : optional onload javascript for the <body>
1580*/
1581function templatePage($data)
1582{
1583 global $STARTTIME;
1584 global $LINKSDB;
1585 $shaarli_version = shaarli_version;
1586
1587 $newversion=checkUpdate();
1588 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>';
1589 $linkcount = count($LINKSDB);
1590
1591 $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']);
1592 $searchcrits=''; // Search criteria
1593 if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.$_GET['searchtags'];
1594 elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.$_GET['searchterm'];
1595 $filtered_feed= ($searchcrits=='' ? '' : 'Filtered ');
1596
1597 $open='';
1598 if ($GLOBALS['config']['OPEN_SHAARLI'])
1599 {
1600 $menu='<a href="?do=tools">Tools</a><a href="?do=addlink"><b>Add link</b></a>';
1601 $open='Open ';
1602 }
1603 else
1604 $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>');
1605 $menu='<a href="?">Home</a>'.$menu.'<a href="'.$feedurl.'?do=rss'.$searchcrits.'">RSS Feed</a><a href="'.$feedurl.'?do=atom'.$searchcrits.'" style="padding-left:10px;">ATOM Feed</a><a href="?do=tagcloud">Tag cloud</a><a href="?do=picwall'.$searchcrits.'">Picture wall</a>';
1606 # If we are in the bookmarklet popup, do not display menu.
1607 if (!empty($_GET['source']) && $_GET['source']=='bookmarklet') $menu='';
1608
1609 foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not).
1610 {
1611 if (!array_key_exists($k,$data)) $data[$k]='';
1612 }
1613 $jsincludes=''; $jsincludes_bottom = '';
1614 if ($GLOBALS['config']['OPEN_SHAARLI'] || isLoggedIn())
1615 {
1616 $source = serverUrl().$_SERVER['SCRIPT_NAME'];
1617 $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>';
1618 $jsincludes_bottom = <<<JS
1619<script language="JavaScript">
1620$(document).ready(function()
1621{
1622 $('#lf_tags').autocomplete({source:'{$source}?ws=tags',minLength:1});
1623 $('#searchtags').autocomplete({source:'{$source}?ws=tags',minLength:1});
1624 $('#fromtag').autocomplete({source:'{$source}?ws=singletag',minLength:1});
1625});
1626</script>
1627JS;
1628 }
1629
1630 $version=shaarli_version;
1631
1632 $title = htmlspecialchars( $GLOBALS['title'] );
1633 $pagetitle = htmlspecialchars( empty($GLOBALS['pagetitle']) ? $title : $GLOBALS['pagetitle'] );
1634
1635 echo <<<HTML
1636<html>
1637<head>
1638<title>{$pagetitle}</title>
1639<link rel="alternate" type="application/rss+xml" href="{$feedurl}?do=rss{$searchcrits}" title="{$filtered_feed}RSS Feed" />
1640<link rel="alternate" type="application/atom+xml" href="{$feedurl}?do=atom{$searchcrits}" title="{$filtered_feed}ATOM Feed" />
1641<link href="./images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
1642<link type="text/css" rel="stylesheet" href="shaarli.css?version={$version}" />
1643<link type="text/css" rel="stylesheet" href="user.css?version={$version}" />
1644{$jsincludes}
1645</head>
1646<body {$data['onload']}>{$newversion}
1647<div id="pageheader"><div id="logo" title="Share your links !" onclick="document.location='?';"></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>
1648 <span id="shaarli_title"><a href="?">{$title}</a></span>{$menu}<div class="clear"></div>
1649{$data['pageheader']}
1650</div>
1651{$data['body']}
1652
1653HTML;
1654 $exectime = round(microtime(true)-$STARTTIME,4);
1655 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 <a href="http://sebsauvage.net" target="_blank">sebsauvage.net</a>. Theme by <a href="http://blog.idleman.fr" target="_blank">idleman.fr</a>.<br>Who gives a shit that this page was generated in '.$exectime.' seconds&nbsp;?</div>';
1656 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>';
1657 echo $jsincludes_bottom.'</body></html>';
1658}
1659
1660// -----------------------------------------------------------------------------------------------
1661// Installation 1511// Installation
1662// This function should NEVER be called if the file data/config.php exists. 1512// This function should NEVER be called if the file data/config.php exists.
1663function install() 1513function install()
1664{ 1514{
1665 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. 1515 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1666 if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); 1516 if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1667 1517
1668 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) 1518 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1669 { 1519 {
1670 $tz = 'UTC'; 1520 $tz = 'UTC';
1671 if (!empty($_POST['continent']) && !empty($_POST['city'])) 1521 if (!empty($_POST['continent']) && !empty($_POST['city']))
1672 if (isTZvalid($_POST['continent'],$_POST['city'])) 1522 if (isTZvalid($_POST['continent'],$_POST['city']))
1673 $tz = $_POST['continent'].'/'.$_POST['city']; 1523 $tz = $_POST['continent'].'/'.$_POST['city'];
1674 $GLOBALS['timezone'] = $tz; 1524 $GLOBALS['timezone'] = $tz;
1675 // Everything is ok, let's create config file. 1525 // Everything is ok, let's create config file.
1676 $GLOBALS['login'] = $_POST['setlogin']; 1526 $GLOBALS['login'] = $_POST['setlogin'];
1677 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. 1527 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
1678 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']); 1528 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
1679 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']) : $_POST['title'] ); 1529 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.htmlspecialchars(indexUrl()) : $_POST['title'] );
1680 writeConfig(); 1530 writeConfig();
1681 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>'; 1531 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>';
1682 exit; 1532 exit;
1683 } 1533 }
1684 1534
1685 // Display config form: 1535 // Display config form:
1686 list($timezone_form,$timezone_js) = templateTZform(); 1536 list($timezone_form,$timezone_js) = templateTZform();
1687 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>'; 1537 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
1688 echo <<<HTML 1538
1689<html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" />${timezone_js}</head> 1539 $PAGE = new pageBuilder;
1690<body onload="document.installform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1> 1540 $PAGE->assign('timezone_html',$timezone_html);
1691It looks like it's the first time you run Shaarli. Please configure it:<br> 1541 $PAGE->assign('timezone_js',$timezone_js);
1692<form method="POST" action="" name="installform" id="installform" style="border:1px solid black; padding:10 10 10 10;"> 1542 $PAGE->renderPage('install');
1693<table border="0" cellpadding="20">
1694<tr><td><b>Login:</b></td><td><input type="text" name="setlogin" size="30"></td></tr>
1695<tr><td><b>Password:</b></td><td><input type="password" name="setpassword" size="30"></td></tr>
1696{$timezone_html}
1697<tr><td><b>Page title:</b></td><td><input type="text" name="title" size="30"></td></tr>
1698<tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
1699</table>
1700</form></body></html>
1701HTML;
1702 exit; 1543 exit;
1703} 1544}
1704 1545
@@ -1714,7 +1555,7 @@ function templateTZform($ptz=false)
1714 // Try to split the provided timezone. 1555 // Try to split the provided timezone.
1715 if ($ptz==false) { $l=timezone_identifiers_list(); $ptz=$l[0]; } 1556 if ($ptz==false) { $l=timezone_identifiers_list(); $ptz=$l[0]; }
1716 $spos=strpos($ptz,'/'); $pcontinent=substr($ptz,0,$spos); $pcity=substr($ptz,$spos+1); 1557 $spos=strpos($ptz,'/'); $pcontinent=substr($ptz,0,$spos); $pcity=substr($ptz,$spos+1);
1717 1558
1718 // Display config form: 1559 // Display config form:
1719 $timezone_form = ''; 1560 $timezone_form = '';
1720 $timezone_js = ''; 1561 $timezone_js = '';
@@ -1722,7 +1563,7 @@ function templateTZform($ptz=false)
1722 // We split the list in continents/cities. 1563 // We split the list in continents/cities.
1723 $continents = array(); 1564 $continents = array();
1724 $cities = array(); 1565 $cities = array();
1725 foreach(timezone_identifiers_list() as $tz) 1566 foreach(timezone_identifiers_list() as $tz)
1726 { 1567 {
1727 if ($tz=='UTC') $tz='UTC/UTC'; 1568 if ($tz=='UTC') $tz='UTC/UTC';
1728 $spos = strpos($tz,'/'); 1569 $spos = strpos($tz,'/');
@@ -1737,12 +1578,12 @@ function templateTZform($ptz=false)
1737 $continents_html = ''; 1578 $continents_html = '';
1738 $continents = array_keys($continents); 1579 $continents = array_keys($continents);
1739 foreach($continents as $continent) 1580 foreach($continents as $continent)
1740 $continents_html.='<option value="'.$continent.'"'.($pcontinent==$continent?'selected':'').'>'.$continent.'</option>'; 1581 $continents_html.='<option value="'.$continent.'"'.($pcontinent==$continent?'selected':'').'>'.$continent.'</option>';
1741 $cities_html = $cities[$pcontinent]; 1582 $cities_html = $cities[$pcontinent];
1742 $timezone_form = "Continent: <select name=\"continent\" id=\"continent\" onChange=\"onChangecontinent();\">${continents_html}</select><br /><br />"; 1583 $timezone_form = "Continent: <select name=\"continent\" id=\"continent\" onChange=\"onChangecontinent();\">${continents_html}</select><br /><br />";
1743 $timezone_form .= "City: <select name=\"city\" id=\"city\">${cities[$pcontinent]}</select><br /><br />"; 1584 $timezone_form .= "City: <select name=\"city\" id=\"city\">${cities[$pcontinent]}</select><br /><br />";
1744 $timezone_js = "<script language=\"JavaScript\">"; 1585 $timezone_js = "<script language=\"JavaScript\">";
1745 $timezone_js .= "function onChangecontinent(){document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];}"; 1586 $timezone_js .= "function onChangecontinent(){document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];}";
1746 $timezone_js .= "var citiescontinent = ".json_encode($cities).";" ; 1587 $timezone_js .= "var citiescontinent = ".json_encode($cities).";" ;
1747 $timezone_js .= "</script>" ; 1588 $timezone_js .= "</script>" ;
1748 return array($timezone_form,$timezone_js); 1589 return array($timezone_form,$timezone_js);
@@ -1776,32 +1617,32 @@ function processWS()
1776 1617
1777 // Search in tags (case insentitive, cumulative search) 1618 // Search in tags (case insentitive, cumulative search)
1778 if ($_GET['ws']=='tags') 1619 if ($_GET['ws']=='tags')
1779 { 1620 {
1780 $tags=explode(' ',str_replace(',',' ',$term)); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d") 1621 $tags=explode(' ',str_replace(',',' ',$term)); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
1781 $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags 1622 $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags
1782 $suggested=array(); 1623 $suggested=array();
1783 /* To speed up things, we store list of tags in session */ 1624 /* To speed up things, we store list of tags in session */
1784 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags(); 1625 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1785 foreach($_SESSION['tags'] as $key=>$value) 1626 foreach($_SESSION['tags'] as $key=>$value)
1786 { 1627 {
1787 if (startsWith($key,$last,$case=false) && !in_array($key,$tags)) $suggested[$addtags.$key.' ']=0; 1628 if (startsWith($key,$last,$case=false) && !in_array($key,$tags)) $suggested[$addtags.$key.' ']=0;
1788 } 1629 }
1789 echo json_encode(array_keys($suggested)); 1630 echo json_encode(array_keys($suggested));
1790 exit; 1631 exit;
1791 } 1632 }
1792 1633
1793 // Search a single tag (case sentitive, single tag search) 1634 // Search a single tag (case sentitive, single tag search)
1794 if ($_GET['ws']=='singletag') 1635 if ($_GET['ws']=='singletag')
1795 { 1636 {
1796 /* To speed up things, we store list of tags in session */ 1637 /* To speed up things, we store list of tags in session */
1797 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags(); 1638 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1798 foreach($_SESSION['tags'] as $key=>$value) 1639 foreach($_SESSION['tags'] as $key=>$value)
1799 { 1640 {
1800 if (startsWith($key,$term,$case=true)) $suggested[$key]=0; 1641 if (startsWith($key,$term,$case=true)) $suggested[$key]=0;
1801 } 1642 }
1802 echo json_encode(array_keys($suggested)); 1643 echo json_encode(array_keys($suggested));
1803 exit; 1644 exit;
1804 } 1645 }
1805} 1646}
1806 1647
1807// Re-write configuration file according to globals. 1648// Re-write configuration file according to globals.
@@ -1815,7 +1656,7 @@ function writeConfig()
1815 $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; '; 1656 $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; ';
1816 $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).';'; 1657 $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).';';
1817 $config .= '$GLOBALS[\'redirector\']='.var_export($GLOBALS['redirector'],true).'; '; 1658 $config .= '$GLOBALS[\'redirector\']='.var_export($GLOBALS['redirector'],true).'; ';
1818 $config .= ' ?>'; 1659 $config .= ' ?>';
1819 if (!file_put_contents($GLOBALS['config']['CONFIG_FILE'],$config) || strcmp(file_get_contents($GLOBALS['config']['CONFIG_FILE']),$config)!=0) 1660 if (!file_put_contents($GLOBALS['config']['CONFIG_FILE'],$config) || strcmp(file_get_contents($GLOBALS['config']['CONFIG_FILE']),$config)!=0)
1820 { 1661 {
1821 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>'; 1662 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>';
@@ -1836,14 +1677,14 @@ function genThumbnail()
1836{ 1677{
1837 // Make sure the parameters in the URL were generated by us. 1678 // Make sure the parameters in the URL were generated by us.
1838 $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']); 1679 $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']);
1839 if ($sign!=$_GET['hmac']) die('Naughty boy !'); 1680 if ($sign!=$_GET['hmac']) die('Naughty boy !');
1840 1681
1841 // Let's see if we don't already have the image for this URL in the cache. 1682 // Let's see if we don't already have the image for this URL in the cache.
1842 $thumbname=hash('sha1',$_GET['url']).'.jpg'; 1683 $thumbname=hash('sha1',$_GET['url']).'.jpg';
1843 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname)) 1684 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname))
1844 { // We have the thumbnail, just serve it: 1685 { // We have the thumbnail, just serve it:
1845 header('Content-Type: image/jpeg'); 1686 header('Content-Type: image/jpeg');
1846 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname); 1687 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname);
1847 return; 1688 return;
1848 } 1689 }
1849 // We may also serve a blank image (if service did not respond) 1690 // We may also serve a blank image (if service did not respond)
@@ -1851,16 +1692,16 @@ function genThumbnail()
1851 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname)) 1692 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname))
1852 { 1693 {
1853 header('Content-Type: image/gif'); 1694 header('Content-Type: image/gif');
1854 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname); 1695 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname);
1855 return; 1696 return;
1856 } 1697 }
1857 1698
1858 // Otherwise, generate the thumbnail. 1699 // Otherwise, generate the thumbnail.
1859 $url = $_GET['url']; 1700 $url = $_GET['url'];
1860 $domain = parse_url($url,PHP_URL_HOST); 1701 $domain = parse_url($url,PHP_URL_HOST);
1861 1702
1862 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')) 1703 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
1863 { 1704 {
1864 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way. 1705 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1865 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page. 1706 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1866 // All images in Flickr are in the form: 1707 // All images in Flickr are in the form:
@@ -1875,7 +1716,7 @@ function genThumbnail()
1875 if (endswith(parse_url($url,PHP_URL_PATH),'.jpg')) 1716 if (endswith(parse_url($url,PHP_URL_PATH),'.jpg'))
1876 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg 1717 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1877 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches); 1718 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
1878 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg'; 1719 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1879 } 1720 }
1880 else // this is a flickr page (html) 1721 else // this is a flickr page (html)
1881 { 1722 {
@@ -1883,7 +1724,7 @@ function genThumbnail()
1883 if (strpos($httpstatus,'200 OK')!==false) 1724 if (strpos($httpstatus,'200 OK')!==false)
1884 { 1725 {
1885 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!',$data,$matches); 1726 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!',$data,$matches);
1886 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg'; 1727 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1887 } 1728 }
1888 } 1729 }
1889 if ($imageurl!='') 1730 if ($imageurl!='')
@@ -1896,7 +1737,7 @@ function genThumbnail()
1896 echo $data; 1737 echo $data;
1897 return; 1738 return;
1898 } 1739 }
1899 } 1740 }
1900 } 1741 }
1901 1742
1902 elseif ($domain=='vimeo.com' ) 1743 elseif ($domain=='vimeo.com' )
@@ -1917,8 +1758,8 @@ function genThumbnail()
1917 header('Content-Type: image/jpeg'); 1758 header('Content-Type: image/jpeg');
1918 echo $data; 1759 echo $data;
1919 return; 1760 return;
1920 } 1761 }
1921 } 1762 }
1922 } 1763 }
1923 1764
1924 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com')) 1765 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
@@ -1942,14 +1783,14 @@ function genThumbnail()
1942 if (resizeImage($filepath)) 1783 if (resizeImage($filepath))
1943 { 1784 {
1944 header('Content-Type: image/jpeg'); 1785 header('Content-Type: image/jpeg');
1945 echo file_get_contents($filepath); 1786 echo file_get_contents($filepath);
1946 return; 1787 return;
1947 } 1788 }
1948 } 1789 }
1949 } 1790 }
1950 } 1791 }
1951 } 1792 }
1952 1793
1953 else 1794 else
1954 { 1795 {
1955 // For all other domains, we try to download the image and make a thumbnail. 1796 // For all other domains, we try to download the image and make a thumbnail.
@@ -1961,7 +1802,7 @@ function genThumbnail()
1961 if (resizeImage($filepath)) 1802 if (resizeImage($filepath))
1962 { 1803 {
1963 header('Content-Type: image/jpeg'); 1804 header('Content-Type: image/jpeg');
1964 echo file_get_contents($filepath); 1805 echo file_get_contents($filepath);
1965 return; 1806 return;
1966 } 1807 }
1967 } 1808 }
@@ -2014,11 +1855,11 @@ function invalidateCaches()
2014 unset($_SESSION['tags']); 1855 unset($_SESSION['tags']);
2015} 1856}
2016 1857
2017if (startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database. 1858if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database.
2018$LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 1859$LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
2019if (startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI) 1860if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
2020if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE']; 1861if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE'];
2021if (startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; } 1862if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
2022if (startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; } 1863if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; }
2023renderPage(); 1864renderPage();
2024?> \ No newline at end of file 1865?>