]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
2 // Shaarli 0.0.17 beta - Shaare your links...
3 // The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net
4 // http://sebsauvage.net/wiki/doku.php?id=php:shaarli
5 // Licence: http://www.opensource.org/licenses/zlib-license.php
9 // -----------------------------------------------------------------------------------------------
11 define ( 'DATADIR' , 'data' ); // Data subdirectory
12 define ( 'CONFIG_FILE' , DATADIR
. '/config.php' ); // Configuration file (user login/password)
13 define ( 'DATASTORE' , DATADIR
. '/datastore.php' ); // Data storage file.
14 define ( 'LINKS_PER_PAGE' , 20 ); // Default links per page.
15 define ( 'IPBANS_FILENAME' , DATADIR
. '/ipbans.php' ); // File storage for failures and bans.
16 define ( 'BAN_AFTER' , 4 ); // Ban IP after this many failures.
17 define ( 'BAN_DURATION' , 1800 ); // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
18 define ( 'OPEN_SHAARLI' , false ); // If true, anyone can add/edit/delete links without having to login
19 define ( 'HIDE_TIMESTAMPS' , false ); // If true, the moment when links were saved are not shown to users that are not logged in.
21 // -----------------------------------------------------------------------------------------------
22 // Program config (touch at your own risks !)
23 define ( 'UPDATECHECK_FILENAME' , DATADIR
. '/lastupdatecheck.txt' ); // For updates check of Shaarli.
24 define ( 'UPDATECHECK_INTERVAL' , 86400 ); // Updates check frequency for Shaarli. 86400 seconds=24 hours
25 ini_set ( 'max_input_time' , '60' ); // High execution time in case of problematic imports/exports.
26 ini_set ( 'memory_limit' , '128M' ); // Try to set max upload file size and read (May not work on some hosts).
27 ini_set ( 'post_max_size' , '16M' );
28 ini_set ( 'upload_max_filesize' , '16M' );
29 define ( 'PHPPREFIX' , '<?php /* ' ); // Prefix to encapsulate data in php code.
30 define ( 'PHPSUFFIX' , ' */ ?>' ); // Suffix to encapsulate data in php code.
31 $STARTTIME = microtime ( true ); // Measure page execution time.
33 error_reporting ( E_ALL^E_WARNING
); // See all error except warnings.
34 //error_reporting(-1); // See all errors (for debugging only)
37 // In case stupid admin has left magic_quotes enabled in php.ini:
38 if ( get_magic_quotes_gpc ())
40 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
41 $_POST = array_map ( 'stripslashes_deep' , $_POST );
42 $_GET = array_map ( 'stripslashes_deep' , $_GET );
43 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
45 // Prevent caching: (yes, it's ugly)
46 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
47 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
48 header ( "Cache-Control: post-check=0, pre-check=0" , false );
49 header ( "Pragma: no-cache" );
50 define ( 'shaarli_version' , '0.0.17 beta' );
51 if (! is_dir ( DATADIR
)) { mkdir ( DATADIR
, 0705 ); chmod ( DATADIR
, 0705 ); }
52 if (! is_file ( DATADIR
. '/.htaccess' )) { file_put_contents ( DATADIR
. '/.htaccess' , "Allow from none \n Deny from all \n " ); } // Protect data files.
53 if (! is_file ( CONFIG_FILE
)) install ();
54 require CONFIG_FILE
; // Read login/password hash into $GLOBALS.
55 autoLocale (); // Sniff browser language and set date format accordingly.
56 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
60 function checkphpversion ()
62 if ( version_compare ( PHP_VERSION
, '5.1.0' ) < 0 )
64 header ( 'Content-Type: text/plain; charset=utf-8' );
65 echo 'Your server supports php ' . PHP_VERSION
. '. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.' ;
70 // Checks if an update is available for Shaarli.
71 // (at most once a day, and only for registered user.)
72 // Output: '' = no new version.
73 // other= the available version.
74 function checkUpdate ()
76 if (! isLoggedIn ()) return '' ; // Do not check versions for visitors.
78 // Get latest version number at most once a day.
79 if (! is_file ( UPDATECHECK_FILENAME
) || ( filemtime ( UPDATECHECK_FILENAME
)< time ()-( UPDATECHECK_INTERVAL
)))
81 $version = shaarli_version
;
82 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://sebsauvage.net/files/shaarli_version.txt' , 2 );
83 if ( strpos ( $httpstatus , '200 OK' )) $version = $data ;
84 // If failed, nevermind. We don't want to bother the user with that.
85 file_put_contents ( UPDATECHECK_FILENAME
, $version ); // touch file date
88 $newestversion = file_get_contents ( UPDATECHECK_FILENAME
);
89 if ( $newestversion != shaarli_version
) return $newestversion ;
93 // -----------------------------------------------------------------------------------------------
95 function logm ( $message )
97 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
98 file_put_contents ( DATADIR
. '/log.txt' , $t , FILE_APPEND
);
101 // ------------------------------------------------------------------------------------------
102 // Sniff browser language to display dates in the right format automatically.
103 // (Note that is may not work on your server if the corresponding local is not installed.)
104 function autoLocale ()
106 $loc = 'en_US' ; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
107 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
108 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
109 if ( preg_match ( '/([a-z] {2} (-[a-z] {2} )?)/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) $loc = $matches [ 1 ];
111 setlocale ( LC_TIME
, $loc ); // LC_TIME = Set local for date/time format only.
114 // ------------------------------------------------------------------------------------------
115 // Session management
116 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
117 ini_set ( 'session.use_cookies' , 1 ); // Use cookies to store session.
118 ini_set ( 'session.use_only_cookies' , 1 ); // Force cookies for session (phpsessionID forbidden in URL)
119 ini_set ( 'session.use_trans_sid' , false ); // Prevent php to use sessionID in URL if cookies are disabled.
120 session_name ( 'shaarli' );
123 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
126 $ip = $_SERVER [ "REMOTE_ADDR" ];
127 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
128 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
129 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
133 // Check that user/password is correct.
134 function check_auth ( $login , $password )
136 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
137 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
138 { // Login/password is correct.
139 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // generate unique random number (different than phpsessionid)
140 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
141 $_SESSION [ 'username' ]= $login ;
142 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
143 logm ( 'Login successful' );
146 logm ( 'Login failed for user ' . $login );
150 // Returns true if the user is logged in.
151 function isLoggedIn ()
153 if ( OPEN_SHAARLI
) return true ;
155 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
156 if ( empty ( $_SESSION [ 'uid' ]) || $_SESSION [ 'ip' ]!= allIPs () || time ()>= $_SESSION [ 'expires_on' ])
161 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // User accessed a page : Update his/her session expiration date.
166 function logout () { unset ( $_SESSION
[ 'uid' ]); unset ( $_SESSION
[ 'ip' ]); unset ( $_SESSION
[ 'username' ]);}
169 // ------------------------------------------------------------------------------------------
170 // Brute force protection system
171 // Several consecutive failed logins will ban the IP address for 30 minutes.
172 if (! is_file ( IPBANS_FILENAME
)) file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>" );
173 include IPBANS_FILENAME
;
174 // Signal a failed login. Will ban the IP if too many failures:
175 function ban_loginFailed ()
177 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
178 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
179 $gb [ 'FAILURES' ][ $ip ] ++
;
180 if ( $gb [ 'FAILURES' ][ $ip ]>( BAN_AFTER
- 1 ))
182 $gb [ 'BANS' ][ $ip ]= time () +BAN_DURATION
;
183 logm ( 'IP address banned from login' );
185 $GLOBALS [ 'IPBANS' ] = $gb ;
186 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
189 // Signals a successful login. Resets failed login counter.
190 function ban_loginOk ()
192 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
193 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
194 $GLOBALS [ 'IPBANS' ] = $gb ;
195 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
198 // Checks if the user CAN login. If 'true', the user can try to login.
199 function ban_canLogin ()
201 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
202 if ( isset ( $gb [ 'BANS' ][ $ip ]))
204 // User is banned. Check if the ban has expired:
205 if ( $gb [ 'BANS' ][ $ip ]<= time ())
206 { // Ban expired, user can try to login again.
208 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
209 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
210 return true ; // Ban has expired, user can login.
212 return false ; // User is banned.
214 return true ; // User is not banned.
217 // ------------------------------------------------------------------------------------------
218 // Process login form: Check if login/password is correct.
219 if ( isset ( $_POST [ 'login' ]))
221 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
222 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
223 { // Login/password is ok.
225 // Optional redirect after login:
226 if ( isset ( $_GET [ 'post' ])) { header ( 'Location: ?post=' . urlencode ( $_GET
[ 'post' ]).(! empty ( $_GET
[ 'source' ])? '&source=' . urlencode ( $_GET
[ 'source' ]): '' )); exit ; }
227 if ( isset ( $_POST [ 'returnurl' ]))
229 if ( endsWith ( $_POST [ 'returnurl' ], '?do=login' )) { header ( 'Location: ?' ); exit ; } // Prevent loops over login screen.
230 header ( 'Location: ' . $_POST [ 'returnurl' ]); exit ;
232 header ( 'Location: ?' ); exit ;
237 echo '<script language="JavaScript">alert("Wrong login/password.");document.location= \' ?do=login \' ;</script>' ; // Redirect to login screen.
242 // ------------------------------------------------------------------------------------------
243 // Misc utility functions:
245 // Returns the server URL (including port and http/https), without path.
246 // eg. "http://myserver.com:8080"
247 // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
250 $serverport = ( $_SERVER [ "SERVER_PORT" ]!= '80' ? ':' . $_SERVER [ "SERVER_PORT" ] : '' );
251 return 'http' .(! empty ( $_SERVER [ 'HTTPS' ])? 's' : '' ). '://' . $_SERVER [ "SERVER_NAME" ]. $serverport ;
254 // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
255 function return_bytes ( $val )
257 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
260 case 'g' : $val *= 1024 ;
261 case 'm' : $val *= 1024 ;
262 case 'k' : $val *= 1024 ;
267 // Try to determine max file size for uploads (POST).
268 // Returns an integer (in bytes)
269 function getMaxFileSize ()
271 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
272 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
273 // Return the smaller of two:
274 $maxsize = min ( $size1 , $size2 );
275 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
279 // Tells if a string start with a substring or not.
280 function startsWith ( $haystack , $needle , $case = true )
282 if ( $case ){ return ( strcmp ( substr ( $haystack
, 0 , strlen ( $needle
)), $needle
)=== 0 );}
283 return ( strcasecmp ( substr ( $haystack , 0 , strlen ( $needle )), $needle )=== 0 );
286 // Tells if a string ends with a substring or not.
287 function endsWith ( $haystack , $needle , $case = true )
289 if ( $case ){ return ( strcmp ( substr ( $haystack
, strlen ( $haystack
) - strlen ( $needle
)), $needle
)=== 0 );}
290 return ( strcasecmp ( substr ( $haystack , strlen ( $haystack ) - strlen ( $needle )), $needle )=== 0 );
293 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
294 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
295 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
296 function linkdate2timestamp ( $linkdate )
299 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
300 return mktime ( $h , $m , $s , $M , $D , $Y );
303 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
304 (used to build the pubDate attribute in RSS feed.) */
305 function linkdate2rfc822 ( $linkdate )
307 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
310 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
311 (used to display link date on screen)
312 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
313 function linkdate2locale ( $linkdate )
315 return utf8_encode ( strftime ( '%c' , linkdate2timestamp ( $linkdate ))); // %c is for automatic date format according to locale.
316 // Note that if you use a local which is not installed on your webserver,
317 // the date will not be displayed in the chosen locale, but probably in US notation.
320 // Parse HTTP response headers and return an associative array.
321 function http_parse_headers ( $headers )
324 foreach ( $headers as $header )
326 $i = strpos ( $header , ': ' );
329 $key = substr ( $header , 0 , $i );
330 $value = substr ( $header , $i +
2 , strlen ( $header )- $i-2 );
338 Input: $url : url to get (http://...)
339 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
340 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
341 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
343 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
344 if (strpos($httpstatus,'200 OK'))
345 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
347 echo 'There was an error: '.htmlspecialchars($httpstatus)
349 function getHTTP ( $url , $timeout = 30 )
353 $options = array ( 'http' => array ( 'method' => 'GET' , 'timeout' => $timeout )); // Force network timeout
354 $context = stream_context_create ( $options );
355 $data = file_get_contents ( $url , false , $context ,- 1 , 2000000 ); // We download at most 2 Mb from source.
356 if (! $data ) { $lasterror
= error_get_last (); return array ( $lasterror
[ 'message' ], array (), '' ); }
357 $httpStatus = $http_response_header [ 0 ]; // eg. "HTTP/1.1 200 OK"
358 $responseHeaders = http_parse_headers ( $http_response_header );
359 return array ( $httpStatus , $responseHeaders , $data );
361 catch ( Exception
$e ) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
363 return array ( $e- > getMessage (), '' , '' );
367 // Extract title from an HTML document.
368 // (Returns an empty string if not found.)
369 function html_extract_title ( $html )
371 return preg_match ( '!<title>(.*?)</title>!i' , $html , $matches ) ? $matches [ 1 ] : '' ;
374 // ------------------------------------------------------------------------------------------
375 // Token management for XSRF protection
376 // Token should be used in any form which acts on data (create,update,delete,import...).
377 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
382 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // We generate a random string.
383 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
387 // Tells if a token is ok. Using this function will destroy the token.
389 function tokenOk ( $token )
391 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
393 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
394 return true ; // Token is ok.
396 return false ; // Wrong token, or already used.
399 // ------------------------------------------------------------------------------------------
400 /* Data storage for links.
401 This object behaves like an associative array.
403 $mylinks = new linkdb();
404 echo $mylinks['20110826_161819']['title'];
405 foreach($mylinks as $link)
406 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
408 We implement 3 interfaces:
409 - ArrayAccess so that this object behaves like an associative array.
410 - Iterator so that this object can be used in foreach() loops.
411 - Countable interface so that we can do a count() on this object.
413 class linkdb
implements Iterator
, Countable
, ArrayAccess
416 private $links ; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
417 private $urls ; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
418 private $keys ; // List of linkdate keys (for the Iterator interface implementation)
419 private $position ; // Position in the $this->keys array. (for the Iterator interface implementation.)
420 private $loggedin ; // Is the used logged in ? (used to filter private links)
423 function __construct ( $isLoggedIn )
424 // Input : $isLoggedIn : is the used logged in ?
426 $this- > loggedin
= $isLoggedIn ;
427 $this- > checkdb (); // Make sure data file exists.
428 $this- > readdb (); // Then read it.
431 // ---- Countable interface implementation
432 public function count () { return count ( $this
-> links
); }
434 // ---- ArrayAccess interface implementation
435 public function offsetSet ( $offset , $value )
437 if (! $this- > loggedin
) die ( 'You are not authorized to add a link.' );
438 if ( empty ( $value [ 'linkdate' ]) || empty ( $value [ 'url' ])) die ( 'Internal Error: A link should always have a linkdate and url.' );
439 if ( empty ( $offset )) die ( 'You must specify a key.' );
440 $this- > links
[ $offset ] = $value ;
441 $this- > urls
[ $value [ 'url' ]]= $offset ;
443 public function offsetExists ( $offset ) { return array_key_exists ( $offset
, $this
-> links
); }
444 public function offsetUnset ( $offset )
446 if (! $this- > loggedin
) die ( 'You are not authorized to delete a link.' );
447 $url = $this- > links
[ $offset ][ 'url' ]; unset ( $this- > urls
[ $url ]);
448 unset ( $this- > links
[ $offset ]);
450 public function offsetGet ( $offset ) { return isset ( $this
-> links
[ $offset
]) ? $this
-> links
[ $offset
] : null ; }
452 // ---- Iterator interface implementation
453 function rewind () { $this
-> keys
= array_keys ( $this
-> links
); rsort ( $this
-> keys
); $this
-> position
= 0 ; } // Start over for iteration, ordered by date (latest first).
454 function key () { return $this
-> keys
[ $this
-> position
]; } // current key
455 function current () { return $this
-> links
[ $this
-> keys
[ $this
-> position
]]; } // current value
456 function next () { ++$this
-> position
; } // go to next item
457 function valid () { return isset ( $this
-> keys
[ $this
-> position
]); } // Check if current position is valid.
460 private function checkdb () // Check if db directory and file exists.
462 if (! file_exists ( DATASTORE
)) // Create a dummy database for example.
464 $this- > links
= array ();
465 $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' );
466 $this- > links
[ $link [ 'linkdate' ]] = $link ;
467 $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' );
468 $this- > links
[ $link [ 'linkdate' ]] = $link ;
469 file_put_contents ( DATASTORE
, PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
); // Write database to disk
473 // Read database from disk to memory
474 private function readdb ()
477 $this- > links
=( file_exists ( DATASTORE
) ? unserialize ( gzinflate ( base64_decode ( substr ( file_get_contents ( DATASTORE
), strlen ( PHPPREFIX
),- strlen ( PHPSUFFIX
))))) : array () );
478 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
480 // If user is not logged in, filter private links.
481 if (! $this- > loggedin
)
484 foreach ( $this- > links
as $link ) { if ( $link
[ 'private' ]!= 0 ) $toremove
[]= $link
[ 'linkdate' ]; }
485 foreach ( $toremove as $linkdate ) { unset ( $this
-> links
[ $linkdate
]); }
488 // Keep the list of the mapping URLs-->linkdate up-to-date.
490 foreach ( $this- > links
as $link ) { $this
-> urls
[ $link
[ 'url' ]]= $link
[ 'linkdate' ]; }
493 // Save database from memory to disk.
494 public function savedb ()
496 if (! $this- > loggedin
) die ( 'You are not authorized to change the database.' );
497 file_put_contents ( DATASTORE
, PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
);
500 // Returns the link for a given URL (if it exists). false it does not exist.
501 public function getLinkFromUrl ( $url )
503 if ( isset ( $this- > urls
[ $url ])) return $this- > links
[ $this- > urls
[ $url ]];
507 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
508 // eg. print_r($mydb->filterFulltext('hollandais'));
509 public function filterFulltext ( $searchterms )
511 // FIXME: explode(' ',$searchterms) and perform a AND search.
512 // FIXME: accept double-quotes to search for a string "as is" ?
514 $s = strtolower ( $searchterms );
515 foreach ( $this- > links
as $l )
517 $found = strpos ( strtolower ( $l [ 'title' ]), $s ) || strpos ( strtolower ( $l [ 'description' ]), $s ) || strpos ( strtolower ( $l [ 'url' ]), $s ) || strpos ( strtolower ( $l [ 'tags' ]), $s );
518 if ( $found ) $filtered [ $l [ 'linkdate' ]] = $l ;
525 // You can specify one or more tags (tags can be separated by space or comma).
526 // eg. print_r($mydb->filterTags('linux programming'));
527 public function filterTags ( $tags , $casesensitive = false )
529 $t = str_replace ( ',' , ' ' ,( $casesensitive ? $tags : strtolower ( $tags )));
530 $searchtags = explode ( ' ' , $t );
532 foreach ( $this- > links
as $l )
534 $linktags = explode ( ' ' ,( $casesensitive ? $l [ 'tags' ]: strtolower ( $l [ 'tags' ])));
535 if ( count ( array_intersect ( $linktags , $searchtags )) == count ( $searchtags ))
536 $filtered [ $l [ 'linkdate' ]] = $l ;
542 // Returns the list of all tags
543 // Output: associative array key=tags, value=0
544 public function allTags ()
547 foreach ( $this- > links
as $link )
548 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
549 if (! empty ( $tag )) $tags [ $tag ]=( empty ( $tags [ $tag ]) ? 1 : $tags [ $tag ] +
1 );
550 arsort ( $tags ); // Sort tags by usage (most used tag first)
555 // ------------------------------------------------------------------------------------------
556 // Ouput the last 50 links in RSS 2.0 format.
561 // Optionnaly filter the results:
562 $linksToDisplay = array ();
563 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
564 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
565 else $linksToDisplay = $LINKSDB ;
567 header ( 'Content-Type: application/xhtml+xml; charset=utf-8' );
568 $pageaddr = htmlspecialchars ( serverUrl (). $_SERVER [ "SCRIPT_NAME" ]);
569 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
570 echo '<channel><title>Shared links on ' . $pageaddr . '</title><link>' . $pageaddr . '</link>' ;
571 echo '<description>Shared links</description><language></language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
573 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
574 while ( $i < 50 && $i < count ( $keys ))
576 $link = $linksToDisplay [ $keys [ $i ]];
577 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
578 echo '<item><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><guid>' . htmlspecialchars ( $link [ 'url' ]). '</guid><link>' . htmlspecialchars ( $link [ 'url' ]). '</link>' ;
579 if (! HIDE_TIMESTAMPS
|| isLoggedIn ()) echo '<pubDate>' . htmlspecialchars ( $rfc822date ). '</pubDate>' ;
580 echo '<description><![CDATA[' . htmlspecialchars ( $link [ 'description' ]). ']]></description></item>' . " \n " ;
583 echo '</channel></rss>' ;
587 // ------------------------------------------------------------------------------------------
589 function renderPage ()
594 // 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.
595 // So I use a custom templating system.
597 // -------- Display login form.
598 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=login' ))
600 if ( OPEN_SHAARLI
) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
603 $loginform = '<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>' ;
604 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => '' );
608 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
609 $loginform = '<div id="headerform"><form method="post" name="loginform">Login: <input type="text" name="login"> Password : <input type="password" name="password"> <input type="submit" value="Login" class="bigbutton"><input type="hidden" name="token" value="' . getToken (). '">' . $returnurl_html . '</form></div>' ;
610 $onload = 'onload="document.loginform.login.focus();"' ;
611 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => $onload );
616 // -------- User wants to logout.
617 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
621 header ( 'Location: ?' );
625 // -------- Tag cloud
626 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tagcloud' ))
628 $tags = $LINKSDB- > allTags ();
629 // We sort tags alphabetically, then choose a font size according to count.
630 // First, find max value.
631 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
634 foreach ( $tags as $key => $value )
636 $size = max ( 40 * $value / $maxcount , 8 ); // Minimum size 8.
637 $colorvalue = 128 - ceil ( 127 * $value / $maxcount );
638 $color = 'rgb(' . $colorvalue . ',' . $colorvalue . ',' . $colorvalue . ')' ;
639 $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> ' ;
641 $cloud = '<div id="cloudtag">' . $cloud . '</div>' ;
642 $data = array ( 'pageheader' => '' , 'body' => $cloud , 'onload' => '' );
647 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
648 if ( isset ( $_GET [ 'addtag' ]))
650 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
651 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
652 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
653 $params [ 'searchtags' ] = ( empty ( $params [ 'searchtags' ]) ? trim ( $_GET [ 'addtag' ]) : trim ( $params [ 'searchtags' ]). ' ' . urlencode ( trim ( $_GET [ 'addtag' ])));
654 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
655 header ( 'Location: ?' . http_build_query ( $params ));
659 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
660 if ( isset ( $_GET [ 'removetag' ]))
662 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
663 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?' ); exit ; } // In case browser does not send HTTP_REFERER
664 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
665 if ( isset ( $params [ 'searchtags' ]))
667 $tags = explode ( ' ' , $params [ 'searchtags' ]);
668 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
669 if ( count ( $tags )== 0 ) unset ( $params [ 'searchtags' ]); else $params [ 'searchtags' ] = implode ( ' ' , $tags );
670 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
672 header ( 'Location: ?' . http_build_query ( $params ));
676 // -------- User wants to change the number of links per page (linksperpage=...)
677 if ( isset ( $_GET [ 'linksperpage' ]))
679 if ( is_numeric ( $_GET [ 'linksperpage' ])) { $_SESSION
[ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET
[ 'linksperpage' ])); }
680 header ( 'Location: ' .( empty ( $_SERVER [ 'HTTP_REFERER' ])? '?' : $_SERVER [ 'HTTP_REFERER' ]));
685 // -------- Handle other actions allowed for non-logged in users:
688 // User tries to post new link but is not loggedin:
689 // Show login screen, then redirect to ?post=...
690 if ( isset ( $_GET [ 'post' ]))
692 header ( 'Location: ?do=login&post=' . urlencode ( $_GET [ 'post' ]).( isset ( $_GET [ 'source' ])? '&source=' . urlencode ( $_GET [ 'source' ]): '' )); // Redirect to login page, then back to post link.
696 // Show search form and display list of links.
698 <div id="headerform" style="width:100%; white-space:nowrap;";>
699 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
700 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
703 $onload = 'onload="document.searchform.searchterm.focus();"' ;
704 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => $onload );
706 exit ; // Never remove this one !
709 // -------- All other functions are reserved for the registered user:
711 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
712 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tools' ))
714 $pageabsaddr = serverUrl (). $_SERVER [ "SCRIPT_NAME" ]; // Why doesn't php have a built-in function for that ?
715 // The javascript code for the bookmarklet:
716 $changepwd = ( OPEN_SHAARLI
? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
718 <div id="headerform"><br>
720 <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
721 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
722 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
723 <a class="smallbutton" style="color:black;" onclick="alert('Drag this link to your bookmarks toolbar, or right-click it and choose Bookmark This Link...');return false;" href="javascript:javascript:(function() {var%20url%20=%20location.href;var%20title%20=%20document.title%20||%20url;window.open('{$pageabsaddr} ?post='%20+%20encodeURIComponent(url)+'&title='%20+%20encodeURIComponent(title)+'&source=bookmarklet','_blank','menubar=no,height=400,width=608,toolbar=no,scrollbars=no,status=no');})();">Shaare link</a> - Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....). Then click "Shaare link" button in any page you want to share.<br><br>
726 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
731 // -------- User wants to change his/her password.
732 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changepasswd' ))
734 if ( OPEN_SHAARLI
) die ( 'You are not supposed to change a password on an Open Shaarli.' );
735 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
737 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
739 // Make sure old password is correct.
740 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
741 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
744 $salt = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
745 $hash = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $salt );
746 $config = '<?php $GLOBALS [ \' login \' ]=' . var_export ( $GLOBALS [ 'login' ], true ). '; $GLOBALS [ \' hash \' ]=' . var_export ( $hash , true ). '; $GLOBALS [ \' salt \' ]=' . var_export ( $salt , true ). '; date_default_timezone_set(' . var_export ( date_default_timezone_get (), true ). '); ?>' ;
747 if (! file_put_contents ( CONFIG_FILE
, $config ) || strcmp ( file_get_contents ( CONFIG_FILE
), $config )!= 0 )
749 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>' ;
752 echo '<script language="JavaScript">alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
758 $changepwdform = <<<HTML
759 <form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
760 Old password: <input type="password" name="oldpassword">
761 New password: <input type="password" name="setpassword">
762 <input type="hidden" name="token" value=" {$token} ">
763 <input type="submit" name="Save" value="Save password" class="bigbutton"></form>
765 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.changepasswordform.oldpassword.focus();"' );
771 // -------- User wants to rename a tag or delete it
772 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changetag' ))
774 if ( empty ( $_POST [ 'fromtag' ]))
777 $changetagform = <<<HTML
778 <form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
779 <input type="hidden" name="token" value=" {$token} ">
780 Tag: <input type="text" name="fromtag" id="fromtag">
781 <input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
782 or <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
783 <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>
785 $data = array ( 'pageheader' => $changetagform , 'body' => '' , 'onload' => 'onload="document.changetag.fromtag.focus();"' );
789 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
791 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
793 $needle = trim ( $_POST [ 'fromtag' ]);
794 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
795 foreach ( $linksToAlter as $key => $value )
797 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
798 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
799 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
800 $LINKSDB [ $key ]= $value ;
802 $LINKSDB- > savedb (); // save to disk
804 echo '<script language="JavaScript">alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
809 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
811 $needle = trim ( $_POST [ 'fromtag' ]);
812 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
813 foreach ( $linksToAlter as $key => $value )
815 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
816 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Remplace tags value.
817 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
818 $LINKSDB [ $key ]= $value ;
820 $LINKSDB- > savedb (); // save to disk
822 echo '<script language="JavaScript">alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
827 // -------- User wants to add a link without using the bookmarklet: show form.
828 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=addlink' ))
830 $onload = 'onload="document.addform.post.focus();"' ;
831 $addform = '<div id="headerform"><form method="GET" action="" name="addform"><input type="text" name="post" style="width:70%;"> <input type="submit" value="Add link" class="bigbutton"></div>' ;
832 $data = array ( 'pageheader' => $addform , 'body' => '' , 'onload' => $onload );
837 // -------- User clicked the "Save" button when editing a link: Save link to database.
838 if ( isset ( $_POST [ 'save_edit' ]))
840 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
841 $linkdate = $_POST [ 'lf_linkdate' ];
842 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => trim ( $_POST [ 'lf_url' ]), 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
843 'linkdate' => $linkdate , 'tags' => trim ( $_POST [ 'lf_tags' ]));
844 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
845 $LINKSDB [ $linkdate ] = $link ;
846 $LINKSDB- > savedb (); // save to disk
849 // If we are called from the bookmarklet, we must close the popup:
850 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
851 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
852 header ( 'Location: ' . $returnurl ); // After saving the link, redirect to the page the user was on.
856 // -------- User clicked the "Cancel" button when editing a link.
857 if ( isset ( $_POST [ 'cancel_edit' ]))
859 // If we are called from the bookmarklet, we must close the popup;
860 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
861 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
862 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
866 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
867 if ( isset ( $_POST [ 'delete_link' ]))
869 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
870 // We do not need to ask for confirmation:
871 // - confirmation is handled by javascript
872 // - we are protected from XSRF by the token.
873 $linkdate = $_POST [ 'lf_linkdate' ];
874 unset ( $LINKSDB [ $linkdate ]);
875 $LINKSDB- > savedb (); // save to disk
877 // If we are called from the bookmarklet, we must close the popup:
878 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
879 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
880 header ( 'Location: ' . $returnurl ); // After deleting the link, redirect to the page the user was on.
884 // -------- User clicked the "EDIT" button on a link: Display link edit form.
885 if ( isset ( $_GET [ 'edit_link' ]))
887 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
888 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
889 list ( $editform , $onload )= templateEditForm ( $link );
890 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
895 // -------- User want to post a new link: Display link edit form.
896 if ( isset ( $_GET [ 'post' ]))
900 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
901 $i = strpos ( $url , '&utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
902 $i = strpos ( $url , '?utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
903 $i = strpos ( $url , '#xtor=RSS-' ); if ( $i ) $url = substr ( $url , 0 , $i );
905 $link_is_new = false ;
906 $link = $LINKSDB- > getLinkFromUrl ( $url ); // Check if URL is not already in database (in this case, we will edit the existing link)
909 $link_is_new = true ; // This is a new link
910 $linkdate = strval ( date ( 'Ymd_His' ));
911 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] ); // Get title if it was provided in URL (by the bookmarklet).
912 $description = '' ; $tags = '' ; $private = 0 ;
913 if ( parse_url ( $url , PHP_URL_SCHEME
)== '' ) $url = 'http://' . $url ;
914 // 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.)
915 if ( empty ( $title ) && parse_url ( $url , PHP_URL_SCHEME
)== 'http' )
917 list ( $status , $headers , $data ) = getHTTP ( $url , 4 ); // Short timeout to keep the application responsive.
918 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
919 if ( strpos ( $status , '200 OK' )) $title = html_entity_decode ( html_extract_title ( $data ), ENT_QUOTES
, 'UTF-8' );
921 $link = array ( 'linkdate' => $linkdate , 'title' => $title , 'url' => $url , 'description' => $description , 'tags' => $tags , 'private' => 0 );
923 list ( $editform , $onload )= templateEditForm ( $link , $link_is_new );
924 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
929 // -------- Export as Netscape Bookmarks HTML file.
930 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=export' ))
932 if ( empty ( $_GET [ 'what' ]))
935 <div id="headerform"><br>
936 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
937 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
938 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
941 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
945 $exportWhat = $_GET [ 'what' ];
946 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export ???' );
948 header ( 'Content-Type: text/html; charset=utf-8' );
949 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
951 <!DOCTYPE NETSCAPE-Bookmark-file-1>
952 <!-- This is an automatically generated file.
953 It will be read and overwritten.
955 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
956 <TITLE>Bookmarks</TITLE>
959 foreach ( $LINKSDB as $link )
961 if ( $exportWhat == 'all' ||
962 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
963 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
965 echo '<DT><A HREF="' . htmlspecialchars ( $link [ 'url' ]). '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
966 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . htmlspecialchars ( str_replace ( ' ' , ',' , $link [ 'tags' ])). '"' ;
967 echo '>' . htmlspecialchars ( $link [ 'title' ]). "</A> \n " ;
968 if ( $link [ 'description' ]!= '' ) echo '<DD>' . htmlspecialchars ( $link [ 'description' ]). " \n " ;
971 echo '<!-- Shaarli ' . $exportWhat . ' bookmarks export on ' . date ( 'Y/m/d H:i:s' ). "--> \n " ;
975 // -------- User is uploading a file for import
976 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
978 // If file is too big, some form field may be missing.
979 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
981 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
982 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>' ;
985 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
990 // -------- Show upload/import dialog:
991 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=import' ))
994 $maxfilesize = getMaxFileSize ();
995 $onload = 'onload="document.uploadform.filetoupload.focus();"' ;
997 <div id="headerform">
998 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
999 <form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
1000 <input type="hidden" name="token" value=" {$token} ">
1001 <input type="file" name="filetoupload" size="80">
1002 <input type="hidden" name="MAX_FILE_SIZE" value=" {$maxfilesize} ">
1003 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
1004 <input type="checkbox" name="private"> Import all links as private<br>
1005 <input type="checkbox" name="overwrite"> Overwrite existing links
1009 $data = array ( 'pageheader' => $uploadform , 'body' => '' , 'onload' => $onload );
1010 templatePage ( $data );
1014 // -------- Otherwise, simply display search form and links:
1016 <div id="headerform" style="width:100%; white-space:nowrap;";>
1017 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
1018 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
1021 $onload = 'onload="document.searchform.searchterm.focus();"' ;
1022 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => $onload );
1023 templatePage ( $data );
1027 // -----------------------------------------------------------------------------------------------
1028 // Process the import file form.
1029 function importFile ()
1032 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1033 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1034 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1035 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private ?
1036 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones ?
1041 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1043 // Then import the bookmarks.
1044 if ( $type == 'netscape' )
1046 // This is a standard Netscape-style bookmark file.
1047 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1048 // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
1049 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1051 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1052 $d = explode ( '<DD>' , $html );
1053 if ( startswith ( $d [ 0 ], '<A ' ))
1055 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1056 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1057 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1058 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1059 foreach ( $matches as $m )
1061 $attr = $m [ 1 ]; $value = $m [ 2 ];
1062 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1063 elseif ( $attr == 'ADD_DATE' ) $link [ 'linkdate' ]= date ( 'Ymd_His' , intval ( $value ));
1064 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1065 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1067 if ( $link [ 'linkdate' ]!= '' && $link [ 'url' ]!= '' && ( $overwrite || empty ( $LINKSDB [ $link [ 'linkdate' ]])))
1069 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1070 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1077 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1081 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1085 // -----------------------------------------------------------------------------------------------
1086 /* Template for the edit link form
1087 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
1088 Output: An array : (string) : The html code of the edit link form.
1089 (string) : The proper onload to use in body.
1090 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
1093 function templateEditForm ( $link , $link_is_new = false )
1095 $url = htmlspecialchars ( $link [ 'url' ]);
1096 $title = htmlspecialchars ( $link [ 'title' ]);
1097 $tags = htmlspecialchars ( $link [ 'tags' ]);
1098 $description = htmlspecialchars ( $link [ 'description' ]);
1099 $private = ( $link [ 'private' ]== 0 ? '' : 'checked="yes"' );
1101 // Automatically focus on empty fields:
1102 $onload = 'onload="document.linkform.lf_tags.focus();"' ;
1103 if ( $description == '' ) $onload = 'onload="document.linkform.lf_description.focus();"' ;
1104 if ( $title == '' ) $onload = 'onload="document.linkform.lf_title.focus();"' ;
1106 // Do not show "Delete" button if this is a new link.
1107 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">' ;
1108 if ( $link_is_new ) $delete_button = '' ;
1110 $token = getToken (); // XSRF protection.
1111 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
1112 $editlinkform = <<<HTML
1113 <div id="editlinkform">
1114 <form method="post" name="linkform">
1115 <input type="hidden" name="lf_linkdate" value=" {$link['linkdate']} ">
1116 <i>URL</i><br><input type="text" name="lf_url" value=" {$url} " style="width:100%"><br>
1117 <i>Title</i><br><input type="text" name="lf_title" value=" {$title} " style="width:100%"><br>
1118 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%"> {$description} </textarea><br>
1119 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value=" {$tags} " style="width:100%"><br>
1120 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private"> <i>Private</i><br>
1121 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1122 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1124 <input type="hidden" name="token" value=" {$token} ">
1129 return array ( $editlinkform , $onload );
1133 // -----------------------------------------------------------------------------------------------
1134 // Template for the list of links.
1135 // Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1136 function templateLinkList ()
1140 // Search according to entered search terms:
1141 $linksToDisplay = array ();
1143 if (! empty ( $_GET [ 'searchterm' ])) // Fulltext search
1145 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1146 $searched = ' <b>' . count ( $linksToDisplay ). ' results for <i>' . htmlspecialchars ( trim ( $_GET [ 'searchterm' ])). '</i></b>:' ;
1148 elseif (! empty ( $_GET [ 'searchtags' ])) // Search by tag
1150 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1151 $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> ' ;
1152 $searched = ' <b>' . count ( $linksToDisplay ). ' results for tags ' . $tagshtml . ':</b>' ;
1155 $linksToDisplay = $LINKSDB ; // otherwise, display without filtering.
1161 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1162 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1163 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1165 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks php.
1166 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1167 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1168 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1169 $page = ( $page < 1 ? 1 : $page );
1170 $page = ( $page > $pagecount ? $pagecount : $page );
1171 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1172 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1173 while ( $i < $end && $i < count ( $keys ))
1175 $link = $linksToDisplay [ $keys [ $i ]];
1176 $description = $link [ 'description' ];
1177 $title = $link [ 'title' ];
1178 $classprivate = ( $link [ 'private' ]== 0 ? '' : 'class="private"' );
1179 if ( isLoggedIn ()) $actions = ' <form method="GET" class="buttoneditform"><input type="hidden" name="edit_link" value="' . $link [ 'linkdate' ]. '"><input type="submit" value="Edit" class="smallbutton"></form>' ;
1181 if ( $link [ 'tags' ]!= '' ) foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { $tags
.= '<span class="linktag" title="Add tag"><a href="?addtag=' . htmlspecialchars ( $tag
). '">' . htmlspecialchars ( $tag
). '</a></span> ' ; }
1182 $linklist .= '<li ' . $classprivate . '><span class="linktitle"><a href="' . htmlspecialchars ( $link [ 'url' ]). '">' . htmlspecialchars ( $title ). '</a></span>' . $actions . '<br>' ;
1183 if ( $description != '' ) $linklist .= '<div class="linkdescription">' . nl2br ( htmlspecialchars ( $description )). '</div><br>' ;
1184 if (! HIDE_TIMESTAMPS
|| isLoggedIn ()) $linklist .= '<span class="linkdate">' . htmlspecialchars ( linkdate2locale ( $link [ 'linkdate' ])). ' - </span>' ;
1185 $linklist .= '<span class="linkurl">' . htmlspecialchars ( $link [ 'url' ]). '</span><br>' . $tags . "</li> \n " ;
1190 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1191 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1193 if ( $i != count ( $keys )) $paging .= '<a href="?page=' .( $page +
1 ). $searchterm . $searchtags . '">◄Older</a>' ;
1194 $paging .= '<span style="color:#fff; padding:0 20 0 20;">page ' . $page . ' / ' . $pagecount . '</span>' ;
1195 if ( $page > 1 ) $paging .= '<a href="?page=' .( $page-1 ). $searchterm . $searchtags . '">Newer►</a>' ;
1196 $linksperpage = <<<HTML
1197 <div style="float:right; padding-right:5px;">
1198 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1199 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1201 $paging = '<div class="paging">' . $linksperpage . $paging . '</div>' ;
1202 $linklist = '<div id="linklist">' . $paging . $searched . '<ul>' . $linklist . '</ul>' . $paging . '</div>' ;
1206 // -----------------------------------------------------------------------------------------------
1207 // Template for the whole page.
1208 /* Input: $data (associative array).
1209 Keys: 'body' : body of HTML document
1210 'pageheader' : html code to show in page header (top of page)
1211 'onload' : optional onload javascript for the <body>
1213 function templatePage ( $data )
1217 $shaarli_version = shaarli_version
;
1219 $newversion = checkUpdate ();
1220 if ( $newversion != '' ) $newversion = '<div id="newversion"><span style="text-decoration:blink;">●</span> Shaarli ' . htmlspecialchars ( $newversion ). ' is <a href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli#download">available</a>.</div>' ;
1221 $linkcount = count ( $LINKSDB );
1225 $menu = ' <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' ;
1229 $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>' );
1231 foreach ( array ( 'pageheader' , 'body' , 'onload' ) as $k ) // make sure all required fields exist (put an empty string if not).
1233 if (! array_key_exists ( $k , $data )) $data [ $k ]= '' ;
1235 $jsincludes = '' ; $jsincludes_bottom = '' ;
1236 if ( OPEN_SHAARLI
|| isLoggedIn ())
1238 $jsincludes = '<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>' ;
1239 $source = serverUrl (). $_SERVER [ 'SCRIPT_NAME' ];
1240 $jsincludes_bottom = <<<JS
1241 <script language="JavaScript">
1242 $(document).ready(function()
1244 $('#lf_tags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1245 $('#searchtags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1246 $('#fromtag').autocomplete( {source:'{$source} ?ws=singletag',minLength:1});
1251 $feedurl = htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]. '?do=rss' );
1252 if (! empty ( $_GET [ 'searchtags' ])) $feedurl .= '&searchtags=' . $_GET [ 'searchtags' ];
1253 elseif (! empty ( $_GET [ 'searchterm' ])) $feedurl .= '&searchterm=' . $_GET [ 'searchterm' ];
1258 <title> {$open} Shaarli - Let's shaare your links...</title>
1259 <link rel="alternate" type="application/rss+xml" href=" {$feedurl} " />
1260 <link type="text/css" rel="stylesheet" href="shaarli.css" />
1263 <body {$data['onload']} > {$newversion}
1264 <div id="pageheader"><div style="float:right; font-style:italic; color:#bbb; text-align:right; padding:0 5 0 0;">Shaare your links...<br> {$linkcount} links</div>
1265 <b><i> {$open} Shaarli {$shaarli_version} </i></b> - <a href="?">Home</a> {$menu} <a href=" {$feedurl} " style="padding-left:30px;">RSS Feed</a>
1266 <a href="?do=tagcloud">Tag cloud</a>
1267 {$data['pageheader']}
1272 $exectime = round ( microtime ( true )- $STARTTIME , 4 );
1273 echo '<div id="footer"><b><a href="http://sebsauvage.net/wiki/doku.php?id=php:shaarli">Shaarli ' . shaarli_version
. '</a></b> - The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net<br>Who gives a shit that this page was generated in ' . $exectime . ' seconds ?</div>' ;
1274 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>' ;
1275 echo $jsincludes_bottom . '</body></html>' ;
1278 // -----------------------------------------------------------------------------------------------
1280 // This function should NEVER be called if the file data/config.php exists.
1283 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1284 if ( endsWith ( $_SERVER [ 'SERVER_NAME' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1286 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1288 $tz =( empty ( $_POST [ 'settimezone' ]) ? 'UTC' : $_POST [ 'settimezone' ]);
1289 // Everything is ok, let's create config file.
1290 $salt = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1291 $hash = sha1 ( $_POST [ 'setpassword' ]. $_POST [ 'setlogin' ]. $salt );
1292 $config = '<?php $GLOBALS [ \' login \' ]=' . var_export ( $_POST [ 'setlogin' ], true ). '; $GLOBALS [ \' hash \' ]=' . var_export ( $hash , true ). '; $GLOBALS [ \' salt \' ]=' . var_export ( $salt , true ). '; date_default_timezone_set(' . var_export ( $tz , true ). '); ?>' ;
1293 if (! file_put_contents ( CONFIG_FILE
, $config ) || strcmp ( file_get_contents ( CONFIG_FILE
), $config )!= 0 )
1295 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>' ;
1298 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location= \' ?do=login \' ;</script>' ;
1301 // Display config form:
1303 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1306 foreach ( timezone_identifiers_list () as $tz ) $timezones .= '<option value="' . htmlspecialchars ( $tz ). '">' . htmlspecialchars ( $tz ). "</option> \n " ;
1307 $timezoneselect = 'Timezone: <select name="settimezone"><option value="" selected>(please select:)</option>' . $timezones . '</select><br><br>' ;
1310 <html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" /></head>
1311 <body onload="document.configform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
1312 It looks like it's the first time you run Shaarli. Please chose a login/password and a timezone:<br>
1313 <form method="POST" action="" name="configform" style="border:1px solid black; padding:10 10 10 10;">
1314 Login: <input type="text" name="setlogin"><br><br>Password: <input type="password" name="setpassword"><br><br>
1316 <input type="submit" name="Save" value="Save config" class="bigbutton"></form></body></html>
1321 // Webservices (for use with jQuery/jQueryUI)
1322 // eg. index.php?ws=tags&term=minecr
1323 function processWS ()
1325 if ( empty ( $_GET [ 'ws' ]) || empty ( $_GET [ 'term' ])) return ;
1326 $term = $_GET [ 'term' ];
1328 header ( 'Content-Type: application/json; charset=utf-8' );
1330 // Search in tags (case insentitive, cumulative search)
1331 if ( $_GET [ 'ws' ]== 'tags' )
1333 $tags = explode ( ' ' , $term ); $last = array_pop ( $tags ); // Get the last term ("a b c d" ==> "a b c", "d")
1334 $addtags = '' ; if ( $tags ) $addtags = implode ( ' ' , $tags ). ' ' ; // We will pre-pend previous tags
1336 /* To speed up things, we store list of tags in session */
1337 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1338 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1340 if ( startsWith ( $key , $last , $case = false )) $suggested [ $addtags . $key . ' ' ]= 0 ;
1342 echo json_encode ( array_keys ( $suggested ));
1346 // Search a single tag (case sentitive, single tag search)
1347 if ( $_GET [ 'ws' ]== 'singletag' )
1349 /* To speed up things, we store list of tags in session */
1350 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1351 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1353 if ( startsWith ( $key , $term , $case = true )) $suggested [ $key ]= 0 ;
1355 echo json_encode ( array_keys ( $suggested ));
1360 // Invalidate caches when the database is changed or the user logs out.
1361 // (eg. tags cache).
1362 function invalidateCaches ()
1364 unset ( $_SESSION [ 'tags' ]);
1367 $LINKSDB = new linkdb ( isLoggedIn () || OPEN_SHAARLI
); // Read links from database (and filter private links if used it not logged in).
1368 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'ws=' )) { processWS (); exit ; } // Webservices (for jQuery/jQueryUI)
1369 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= LINKS_PER_PAGE
;
1370 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }