]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
520d7d30af41cfc17f721334279d7a15fabb3c7d
2 // Shaarli 0.0.14 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
20 // -----------------------------------------------------------------------------------------------
21 // Program config (touch at your own risks !)
22 ini_set ( 'max_input_time' , '60' ); // High execution time in case of problematic imports/exports.
23 ini_set ( 'memory_limit' , '128M' ); // Try to set max upload file size and read (May not work on some hosts).
24 ini_set ( 'post_max_size' , '16M' );
25 ini_set ( 'upload_max_filesize' , '16M' );
26 define ( 'PHPPREFIX' , '<?php /* ' ); // Prefix to encapsulate data in php code.
27 define ( 'PHPSUFFIX' , ' */ ?>' ); // Suffix to encapsulate data in php code.
28 $STARTTIME = microtime ( true ); // Measure page execution time.
30 error_reporting ( E_ALL^E_WARNING
); // See all error except warnings.
31 //error_reporting(-1); // See all errors (for debugging only)
33 // In case stupid admin has left magic_quotes enabled in php.ini:
34 if ( get_magic_quotes_gpc ())
36 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
37 $_POST = array_map ( 'stripslashes_deep' , $_POST );
38 $_GET = array_map ( 'stripslashes_deep' , $_GET );
39 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
41 // Prevent caching: (yes, it's ugly)
42 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
43 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
44 header ( "Cache-Control: post-check=0, pre-check=0" , false );
45 header ( "Pragma: no-cache" );
46 define ( 'shaarli_version' , '0.0.14 beta' );
47 if (! is_dir ( DATADIR
)) { mkdir ( DATADIR
, 0705 ); chmod ( DATADIR
, 0705 ); }
48 if (! is_file ( DATADIR
. '/.htaccess' )) { file_put_contents ( DATADIR
. '/.htaccess' , "Allow from none \n Deny from all \n " ); } // Protect data files.
49 if (! is_file ( CONFIG_FILE
)) install ();
50 require CONFIG_FILE
; // Read login/password hash into $GLOBALS.
51 autoLocale (); // Sniff browser language and set date format accordingly.
52 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
56 function checkphpversion ()
59 if ( preg_match ( '!(\d+)\.(\d+)\.(\d+)!' , $ver , $matches )) // (because phpversion() sometimes returns strings like "5.2.4-2ubuntu5.2")
61 list ( $match , $major , $minor , $release ) = $matches ;
62 if ( $major >= 5 && $minor >= 1 ) return ; // 5.1.x or higher is ok.
63 header ( 'Content-Type: text/plain; charset=utf-8' );
64 echo 'Your server supports php ' . $ver . '. Shaarli requires at last php 5.1, and thus cannot run. Sorry.' ;
67 // if cannot check php version... well, at your own risks.
70 // -----------------------------------------------------------------------------------------------
72 function logm ( $message )
74 if (! file_exists ( DATADIR
. '/log.txt' )) { $logFile
= fopen ( DATADIR
. '/log.txt' , 'w' ); }
75 else { $logFile
= fopen ( DATADIR
. '/log.txt' , 'a' ); }
76 fwrite ( $logFile , strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " );
80 // ------------------------------------------------------------------------------------------
81 // Sniff browser language to display dates in the right format automatically.
82 // (Note that is may not work on your server if the corresponding local is not installed.)
85 $loc = 'en_US' ; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
86 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
87 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
88 if ( preg_match ( '/([a-z] {2} (-[a-z] {2} )?)/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) $loc = $matches [ 1 ];
90 setlocale ( LC_TIME
, $loc ); // LC_TIME = Set local for date/time format only.
93 // ------------------------------------------------------------------------------------------
95 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
96 ini_set ( 'session.use_cookies' , 1 ); // Use cookies to store session.
97 ini_set ( 'session.use_only_cookies' , 1 ); // Force cookies for session (phpsessionID forbidden in URL)
98 ini_set ( 'session.use_trans_sid' , false ); // Prevent php to use sessionID in URL if cookies are disabled.
99 session_name ( 'shaarli' );
102 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
105 $ip = $_SERVER [ "REMOTE_ADDR" ];
106 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
107 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
108 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
112 // Check that user/password is correct.
113 function check_auth ( $login , $password )
115 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
116 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
117 { // Login/password is correct.
118 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // generate unique random number (different than phpsessionid)
119 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
120 $_SESSION [ 'username' ]= $login ;
121 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
122 logm ( 'Login successful' );
125 logm ( 'Login failed for user ' . $login );
129 // Returns true if the user is logged in.
130 function isLoggedIn ()
132 if ( OPEN_SHAARLI
) return true ;
134 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
135 if ( empty ( $_SESSION [ 'uid' ]) || $_SESSION [ 'ip' ]!= allIPs () || time ()>= $_SESSION [ 'expires_on' ])
140 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // User accessed a page : Update his/her session expiration date.
145 function logout () { unset ( $_SESSION
[ 'uid' ]); unset ( $_SESSION
[ 'ip' ]); unset ( $_SESSION
[ 'username' ]);}
148 // ------------------------------------------------------------------------------------------
149 // Brute force protection system
150 // Several consecutive failed logins will ban the IP address for 30 minutes.
151 if (! is_file ( IPBANS_FILENAME
)) file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>" );
152 include IPBANS_FILENAME
;
153 // Signal a failed login. Will ban the IP if too many failures:
154 function ban_loginFailed ()
156 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
157 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
158 $gb [ 'FAILURES' ][ $ip ] ++
;
159 if ( $gb [ 'FAILURES' ][ $ip ]>( BAN_AFTER
- 1 ))
161 $gb [ 'BANS' ][ $ip ]= time () +BAN_DURATION
;
162 logm ( 'IP address banned from login' );
164 $GLOBALS [ 'IPBANS' ] = $gb ;
165 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
168 // Signals a successful login. Resets failed login counter.
169 function ban_loginOk ()
171 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
172 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
173 $GLOBALS [ 'IPBANS' ] = $gb ;
174 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
177 // Checks if the user CAN login. If 'true', the user can try to login.
178 function ban_canLogin ()
180 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
181 if ( isset ( $gb [ 'BANS' ][ $ip ]))
183 // User is banned. Check if the ban has expired:
184 if ( $gb [ 'BANS' ][ $ip ]<= time ())
185 { // Ban expired, user can try to login again.
187 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
188 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
189 return true ; // Ban has expired, user can login.
191 return false ; // User is banned.
193 return true ; // User is not banned.
196 // ------------------------------------------------------------------------------------------
197 // Process login form: Check if login/password is correct.
198 if ( isset ( $_POST [ 'login' ]))
200 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
201 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
202 { // Login/password is ok.
204 // Optional redirect after login:
205 if ( isset ( $_GET [ 'post' ])) { header ( 'Location: ?post=' . urlencode ( $_GET
[ 'post' ]).(! empty ( $_GET
[ 'source' ])? '&source=' . urlencode ( $_GET
[ 'source' ]): '' )); exit ; }
206 if ( isset ( $_POST [ 'returnurl' ])) { header ( 'Location: ' . $_POST
[ 'returnurl' ]); exit ; }
207 header ( 'Location: ?' ); exit ;
212 echo '<script language="JavaScript">alert("Wrong login/password.");document.location= \' ?do=login \' ;</script>' ; // Redirect to login screen.
217 // ------------------------------------------------------------------------------------------
218 // Misc utility functions:
220 // Returns the server URL (including port and http/https), without path.
221 // eg. "http://myserver.com:8080"
222 // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
225 $serverport = ( $_SERVER [ "SERVER_PORT" ]!= '80' ? ':' . $_SERVER [ "SERVER_PORT" ] : '' );
226 return 'http' .(! empty ( $_SERVER [ 'HTTPS' ])? 's' : '' ). '://' . $_SERVER [ "SERVER_NAME" ]. $serverport ;
229 // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
230 function return_bytes ( $val )
232 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
235 case 'g' : $val *= 1024 ;
236 case 'm' : $val *= 1024 ;
237 case 'k' : $val *= 1024 ;
242 // Try to determine max file size for uploads (POST).
243 // Returns an integer (in bytes)
244 function getMaxFileSize ()
246 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
247 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
248 // Return the smaller of two:
249 $maxsize = min ( $size1 , $size2 );
250 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
254 // Tells if a string start with a substring or not.
255 function startsWith ( $haystack , $needle , $case = true )
257 if ( $case ){ return ( strcmp ( substr ( $haystack
, 0 , strlen ( $needle
)), $needle
)=== 0 );}
258 return ( strcasecmp ( substr ( $haystack , 0 , strlen ( $needle )), $needle )=== 0 );
261 // Tells if a string ends with a substring or not.
262 function endsWith ( $haystack , $needle , $case = true )
264 if ( $case ){ return ( strcmp ( substr ( $haystack
, strlen ( $haystack
) - strlen ( $needle
)), $needle
)=== 0 );}
265 return ( strcasecmp ( substr ( $haystack , strlen ( $haystack ) - strlen ( $needle )), $needle )=== 0 );
268 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
269 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
270 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
271 function linkdate2timestamp ( $linkdate )
274 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
275 return mktime ( $h , $m , $s , $M , $D , $Y );
278 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
279 (used to build the pubDate attribute in RSS feed.) */
280 function linkdate2rfc822 ( $linkdate )
282 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
285 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
286 (used to display link date on screen)
287 The date format is automatically chose according to locale/languages sniffed from browser headers (see autoLocale()). */
288 function linkdate2locale ( $linkdate )
290 return utf8_encode ( strftime ( '%c' , linkdate2timestamp ( $linkdate ))); // %c is for automatic date format according to locale.
291 // Note that if you use a local which is not installed on your webserver,
292 // the date will not be displayed in the chosen locale, but probably in US notation.
295 // Parse HTTP response headers and return an associative array.
296 function http_parse_headers ( $headers )
299 foreach ( $headers as $header )
301 $i = strpos ( $header , ': ' );
304 $key = substr ( $header , 0 , $i );
305 $value = substr ( $header , $i +
2 , strlen ( $header )- $i-2 );
313 Input: $url : url to get (http://...)
314 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
315 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
316 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
318 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
319 if (strpos($httpstatus,'200 OK'))
320 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
322 echo 'There was an error: '.htmlspecialchars($httpstatus)
324 function getHTTP ( $url , $timeout = 30 )
328 $options = array ( 'http' => array ( 'method' => 'GET' , 'timeout' => $timeout )); // Force network timeout
329 $context = stream_context_create ( $options );
330 $data = file_get_contents ( $url , false , $context ,- 1 , 2000000 ); // We download at most 2 Mb from source.
331 if (! $data ) { $lasterror
= error_get_last (); return array ( $lasterror
[ 'message' ], array (), '' ); }
332 $httpStatus = $http_response_header [ 0 ]; // eg. "HTTP/1.1 200 OK"
333 $responseHeaders = http_parse_headers ( $http_response_header );
334 return array ( $httpStatus , $responseHeaders , $data );
336 catch ( Exception
$e ) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
338 return array ( $e- > getMessage (), '' , '' );
342 // Extract title from an HTML document.
343 // (Returns an empty string if not found.)
344 function html_extract_title ( $html )
346 return preg_match ( '!<title>(.*?)</title>!i' , $html , $matches ) ? $matches [ 1 ] : '' ;
349 // ------------------------------------------------------------------------------------------
350 // Token management for XSRF protection
351 // Token should be used in any form which acts on data (create,update,delete,import...).
352 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
357 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // We generate a random string.
358 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
362 // Tells if a token is ok. Using this function will destroy the token.
364 function tokenOk ( $token )
366 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
368 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
369 return true ; // Token is ok.
371 return false ; // Wrong token, or already used.
374 // ------------------------------------------------------------------------------------------
375 /* Data storage for links.
376 This object behaves like an associative array.
378 $mylinks = new linkdb();
379 echo $mylinks['20110826_161819']['title'];
380 foreach($mylinks as $link)
381 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
383 We implement 3 interfaces:
384 - ArrayAccess so that this object behaves like an associative array.
385 - Iterator so that this object can be used in foreach() loops.
386 - Countable interface so that we can do a count() on this object.
388 class linkdb
implements Iterator
, Countable
, ArrayAccess
391 private $links ; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
392 private $urls ; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
393 private $keys ; // List of linkdate keys (for the Iterator interface implementation)
394 private $position ; // Position in the $this->keys array. (for the Iterator interface implementation.)
395 private $loggedin ; // Is the used logged in ? (used to filter private links)
398 function __construct ( $isLoggedIn )
399 // Input : $isLoggedIn : is the used logged in ?
401 $this- > loggedin
= $isLoggedIn ;
402 $this- > checkdb (); // Make sure data file exists.
403 $this- > readdb (); // Then read it.
406 // ---- Countable interface implementation
407 public function count () { return count ( $this
-> links
); }
409 // ---- ArrayAccess interface implementation
410 public function offsetSet ( $offset , $value )
412 if (! $this- > loggedin
) die ( 'You are not authorized to add a link.' );
413 if ( empty ( $value [ 'linkdate' ]) || empty ( $value [ 'url' ])) die ( 'Internal Error: A link should always have a linkdate and url.' );
414 if ( empty ( $offset )) die ( 'You must specify a key.' );
415 $this- > links
[ $offset ] = $value ;
416 $this- > urls
[ $value [ 'url' ]]= $offset ;
418 public function offsetExists ( $offset ) { return array_key_exists ( $offset
, $this
-> links
); }
419 public function offsetUnset ( $offset )
421 if (! $this- > loggedin
) die ( 'You are not authorized to delete a link.' );
422 $url = $this- > links
[ $offset ][ 'url' ]; unset ( $this- > urls
[ $url ]);
423 unset ( $this- > links
[ $offset ]);
425 public function offsetGet ( $offset ) { return isset ( $this
-> links
[ $offset
]) ? $this
-> links
[ $offset
] : null ; }
427 // ---- Iterator interface implementation
428 function rewind () { $this
-> keys
= array_keys ( $this
-> links
); rsort ( $this
-> keys
); $this
-> position
= 0 ; } // Start over for iteration, ordered by date (latest first).
429 function key () { return $this
-> keys
[ $this
-> position
]; } // current key
430 function current () { return $this
-> links
[ $this
-> keys
[ $this
-> position
]]; } // current value
431 function next () { ++$this
-> position
; } // go to next item
432 function valid () { return isset ( $this
-> keys
[ $this
-> position
]); } // Check if current position is valid.
435 private function checkdb () // Check if db directory and file exists.
437 if (! file_exists ( DATASTORE
)) // Create a dummy database for example.
439 $this- > links
= array ();
440 $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' );
441 $this- > links
[ $link [ 'linkdate' ]] = $link ;
442 $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' );
443 $this- > links
[ $link [ 'linkdate' ]] = $link ;
444 file_put_contents ( DATASTORE
, PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
); // Write database to disk
448 // Read database from disk to memory
449 private function readdb ()
452 $this- > links
=( file_exists ( DATASTORE
) ? unserialize ( gzinflate ( base64_decode ( substr ( file_get_contents ( DATASTORE
), strlen ( PHPPREFIX
),- strlen ( PHPSUFFIX
))))) : array () );
454 // If user is not logged in, filter private links.
455 if (! $this- > loggedin
)
458 foreach ( $this- > links
as $link ) { if ( $link
[ 'private' ]!= 0 ) $toremove
[]= $link
[ 'linkdate' ]; }
459 foreach ( $toremove as $linkdate ) { unset ( $this
-> links
[ $linkdate
]); }
462 // Keep the list of the mapping URLs-->linkdate up-to-date.
464 foreach ( $this- > links
as $link ) { $this
-> urls
[ $link
[ 'url' ]]= $link
[ 'linkdate' ]; }
467 // Save database from memory to disk.
468 public function savedb ()
470 if (! $this- > loggedin
) die ( 'You are not authorized to change the database.' );
471 file_put_contents ( DATASTORE
, PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
);
474 // Returns the link for a given URL (if it exists). false it does not exist.
475 public function getLinkFromUrl ( $url )
477 if ( isset ( $this- > urls
[ $url ])) return $this- > links
[ $this- > urls
[ $url ]];
481 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
482 // eg. print_r($mydb->filterTags('hollandais'));
483 public function filterFulltext ( $searchterms )
485 // FIXME: explode(' ',$searchterms) and perform a AND search.
486 // FIXME: accept double-quotes to search for a string "as is" ?
488 $s = strtolower ( $searchterms );
489 foreach ( $this- > links
as $l )
491 $found = strpos ( strtolower ( $l [ 'title' ]), $s ) || strpos ( strtolower ( $l [ 'description' ]), $s ) || strpos ( strtolower ( $l [ 'url' ]), $s ) || strpos ( strtolower ( $l [ 'tags' ]), $s );
492 if ( $found ) $filtered [ $l [ 'linkdate' ]] = $l ;
499 // You can specify one or more tags (tags can be separated by space or comma).
500 // eg. print_r($mydb->filterTags('linux programming'));
501 public function filterTags ( $tags )
503 $t = str_replace ( ',' , ' ' , strtolower ( $tags ));
504 $searchtags = explode ( ' ' , $t );
506 foreach ( $this- > links
as $l )
508 $linktags = explode ( ' ' , strtolower ( $l [ 'tags' ]));
509 if ( count ( array_intersect ( $linktags , $searchtags )) == count ( $searchtags ))
510 $filtered [ $l [ 'linkdate' ]] = $l ;
516 // Returns the list of all tags
517 // Output: associative array key=tags, value=0
518 public function allTags ()
521 foreach ( $this- > links
as $link )
522 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
523 if (! empty ( $tag )) $tags [ $tag ]=( empty ( $tags [ $tag ]) ? 1 : $tags [ $tag ] +
1 );
524 arsort ( $tags ); // Sort tags by usage (most used tag first)
530 // ------------------------------------------------------------------------------------------
531 // Ouput the last 50 links in RSS 2.0 format.
536 // Optionnaly filter the results:
537 $linksToDisplay = array ();
538 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
539 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( $_GET [ 'searchtags' ]);
540 else $linksToDisplay = $LINKSDB ;
542 header ( 'Content-Type: application/xhtml+xml; charset=utf-8' );
543 $pageaddr = htmlspecialchars ( serverUrl (). $_SERVER [ "SCRIPT_NAME" ]);
544 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
545 echo '<channel><title>Shared links on ' . $pageaddr . '</title><link>' . $pageaddr . '</link>' ;
546 echo '<description>Shared links</description><language></language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
548 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
549 while ( $i < 50 && $i < count ( $keys ))
551 $link = $linksToDisplay [ $keys [ $i ]];
552 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
553 echo '<item><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><guid>' . htmlspecialchars ( $link [ 'url' ]). '</guid><link>' . htmlspecialchars ( $link [ 'url' ]). '</link><pubDate>' . htmlspecialchars ( $rfc822date ). '</pubDate>' ;
554 echo '<description><![CDATA[' . htmlspecialchars ( $link [ 'description' ]). ']]></description></item>' . " \n " ;
557 echo '</channel></rss>' ;
561 // ------------------------------------------------------------------------------------------
563 function renderPage ()
568 // 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.
569 // So I use a custom templating system.
571 // -------- Display login form.
572 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=login' ))
574 if ( OPEN_SHAARLI
) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
577 $loginform = '<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>' ;
578 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => '' );
582 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
583 $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>' ;
584 $onload = 'onload="document.loginform.login.focus();"' ;
585 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => $onload );
590 // -------- User wants to logout.
591 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
595 header ( 'Location: ?' );
599 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
600 if ( isset ( $_GET [ 'addtag' ]))
602 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
603 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
604 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
605 $params [ 'searchtags' ] = ( empty ( $params [ 'searchtags' ]) ? trim ( $_GET [ 'addtag' ]) : trim ( $params [ 'searchtags' ]. ' ' . urlencode ( $_GET [ 'addtag' ])));
606 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
607 header ( 'Location: ?' . http_build_query ( $params ));
611 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
612 if ( isset ( $_GET [ 'removetag' ]))
614 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
615 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?' ); exit ; } // In case browser does not send HTTP_REFERER
616 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
617 if ( isset ( $params [ 'searchtags' ]))
619 $tags = explode ( ' ' , $params [ 'searchtags' ]);
620 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
621 if ( count ( $tags )== 0 ) unset ( $params [ 'searchtags' ]); else $params [ 'searchtags' ] = implode ( ' ' , $tags );
622 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
624 header ( 'Location: ?' . http_build_query ( $params ));
628 // -------- User wants to change the number of links per page (linksperpage=...)
629 if ( isset ( $_GET [ 'linksperpage' ]))
631 if ( is_numeric ( $_GET [ 'linksperpage' ])) { $_SESSION
[ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET
[ 'linksperpage' ])); }
632 header ( 'Location: ' .( empty ( $_SERVER [ 'HTTP_REFERER' ])? '?' : $_SERVER [ 'HTTP_REFERER' ]));
637 // -------- Handle other actions allowed for non-logged in users:
640 // User tries to post new link but is not loggedin:
641 // Show login screen, then redirect to ?post=...
642 if ( isset ( $_GET [ 'post' ]))
644 header ( 'Location: ?do=login&post=' . urlencode ( $_GET [ 'post' ]).( isset ( $_GET [ 'source' ])? '&source=' . urlencode ( $_GET [ 'source' ]): '' )); // Redirect to login page, then back to post link.
648 // Show search form and display list of links.
650 <div id="headerform" style="width:100%; white-space:nowrap;";>
651 <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>
652 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
655 $onload = 'document.searchform.searchterm.focus();' ;
656 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => $onload );
658 exit ; // Never remove this one !
661 // -------- All other functions are reserved for the registered user:
663 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
664 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tools' ))
666 $pageabsaddr = serverUrl (). $_SERVER [ "SCRIPT_NAME" ]; // Why doesn't php have a built-in function for that ?
667 // The javascript code for the bookmarklet:
669 <div id="headerform"><br>
670 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
671 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
672 <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>
675 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
680 // -------- User wants to add a link without using the bookmarklet: show form.
681 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=addlink' ))
683 $onload = 'document.addform.post.focus();' ;
684 $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>' ;
685 $data = array ( 'pageheader' => $addform , 'body' => '' , 'onload' => $onload );
690 // -------- User clicked the "Save" button when editing a link: Save link to database.
691 if ( isset ( $_POST [ 'save_edit' ]))
693 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
694 $linkdate = $_POST [ 'lf_linkdate' ];
695 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => trim ( $_POST [ 'lf_url' ]), 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
696 'linkdate' => $linkdate , 'tags' => trim ( $_POST [ 'lf_tags' ]));
697 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
698 $LINKSDB [ $linkdate ] = $link ;
699 $LINKSDB- > savedb (); // save to disk
702 // If we are called from the bookmarklet, we must close the popup:
703 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
704 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
705 header ( 'Location: ' . $returnurl ); // After saving the link, redirect to the page the user was on.
709 // -------- User clicked the "Cancel" button when editing a link.
710 if ( isset ( $_POST [ 'cancel_edit' ]))
712 // If we are called from the bookmarklet, we must close the popup;
713 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
714 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
715 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
719 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
720 if ( isset ( $_POST [ 'delete_link' ]))
722 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
723 // We do not need to ask for confirmation:
724 // - confirmation is handled by javascript
725 // - we are protected from XSRF by the token.
726 $linkdate = $_POST [ 'lf_linkdate' ];
727 unset ( $LINKSDB [ $linkdate ]);
728 $LINKSDB- > savedb (); // save to disk
730 // If we are called from the bookmarklet, we must close the popup:
731 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
732 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
733 header ( 'Location: ' . $returnurl ); // After deleting the link, redirect to the page the user was on.
737 // -------- User clicked the "EDIT" button on a link: Display link edit form.
738 if ( isset ( $_GET [ 'edit_link' ]))
740 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
741 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
742 list ( $editform , $onload )= templateEditForm ( $link );
743 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
748 // -------- User want to post a new link: Display link edit form.
749 if ( isset ( $_GET [ 'post' ]))
753 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
754 $i = strpos ( $url , '&utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
755 $i = strpos ( $url , '?utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
757 $link_is_new = false ;
758 $link = $LINKSDB- > getLinkFromUrl ( $url ); // Check if URL is not already in database (in this case, we will edit the existing link)
761 $link_is_new = true ; // This is a new link
762 $linkdate = strval ( date ( 'Ymd_His' ));
763 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] ); // Get title if it was provided in URL (by the bookmarklet).
764 $description = '' ; $tags = '' ; $private = 0 ;
765 if ( parse_url ( $url , PHP_URL_SCHEME
)== '' ) $url = 'http://' . $url ;
766 // 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.)
767 if ( empty ( $title ) && parse_url ( $url , PHP_URL_SCHEME
)== 'http' )
769 list ( $status , $headers , $data ) = getHTTP ( $url , 4 ); // Short timeout to keep the application responsive.
770 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
771 if ( strpos ( $status , '200 OK' )) $title = html_entity_decode ( html_extract_title ( $data ), ENT_QUOTES
, 'UTF-8' );
773 $link = array ( 'linkdate' => $linkdate , 'title' => $title , 'url' => $url , 'description' => $description , 'tags' => $tags , 'private' => 0 );
775 list ( $editform , $onload )= templateEditForm ( $link , $link_is_new );
776 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
781 // -------- Export as Netscape Bookmarks HTML file.
782 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=export' ))
784 if ( empty ( $_GET [ 'what' ]))
787 <div id="headerform"><br>
788 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
789 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
790 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
793 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
797 $exportWhat = $_GET [ 'what' ];
798 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export ???' );
800 header ( 'Content-Type: text/html; charset=utf-8' );
801 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
803 <!DOCTYPE NETSCAPE-Bookmark-file-1>
804 <!-- This is an automatically generated file.
805 It will be read and overwritten.
807 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
808 <TITLE>Bookmarks</TITLE>
811 foreach ( $LINKSDB as $link )
813 if ( $exportWhat == 'all' ||
814 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
815 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
817 echo '<DT><A HREF="' . htmlspecialchars ( $link [ 'url' ]). '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
818 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . htmlspecialchars ( str_replace ( ' ' , ',' , $link [ 'tags' ])). '"' ;
819 echo '>' . htmlspecialchars ( $link [ 'title' ]). "</A> \n " ;
820 if ( $link [ 'description' ]!= '' ) echo '<DD>' . htmlspecialchars ( $link [ 'description' ]). " \n " ;
823 echo '<!-- Shaarli ' . $exportWhat . ' bookmarks export on ' . date ( 'Y/m/d H:i:s' ). "--> \n " ;
827 // -------- User is uploading a file for import
828 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
830 // If file is too big, some form field may be missing.
831 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
833 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
834 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>' ;
837 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
842 // -------- Show upload/import dialog:
843 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=import' ))
846 $maxfilesize = getMaxFileSize ();
847 $onload = 'onload="document.uploadform.filetoupload.focus();"' ;
849 <div id="headerform">
850 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
851 <form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
852 <input type="hidden" name="token" value=" {$token} ">
853 <input type="file" name="filetoupload" size="80">
854 <input type="hidden" name="MAX_FILE_SIZE" value=" {$maxfilesize} ">
855 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
856 <input type="checkbox" name="private"> Import all links as private
860 $data = array ( 'pageheader' => $uploadform , 'body' => '' , 'onload' => $onload );
865 // -------- Otherwise, simply display search form and links:
867 <div id="headerform" style="width:100%; white-space:nowrap;";>
868 <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>
869 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
872 $onload = 'document.searchform.searchterm.focus();' ;
873 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => $onload );
878 // -----------------------------------------------------------------------------------------------
879 // Process the import file form.
880 function importFile ()
883 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
884 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
885 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
886 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private ?
890 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
892 // Then import the bookmarks.
893 if ( $type == 'netscape' )
895 // This is a standard Netscape-style bookmark file.
896 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
897 // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
898 $before = count ( $LINKSDB );
899 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
901 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
902 $d = explode ( '<DD>' , $html );
903 if ( startswith ( $d [ 0 ], '<A ' ))
905 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? trim ( $d [ 1 ]) : '' ); // Get description (optional)
906 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
907 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
908 foreach ( $matches as $m )
910 $attr = $m [ 1 ]; $value = $m [ 2 ];
911 if ( $attr == 'HREF' ) $link [ 'url' ]= $value ;
912 elseif ( $attr == 'ADD_DATE' ) $link [ 'linkdate' ]= date ( 'Ymd_His' , intval ( $value ));
913 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
914 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= str_replace ( ',' , ' ' , $value );
916 if ( $link [ 'linkdate' ]!= '' && $link [ 'url' ]!= '' && empty ( $LINKSDB [ $link [ 'linkdate' ]]))
918 if ( $private == 1 ) $link [ 'private' ]= 1 ;
919 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
923 $import_count = count ( $LINKSDB )- $before ;
926 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) was successfully imported: ' . $import_count . ' new links.");document.location= \' ? \' ;</script>' ;
930 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
934 // -----------------------------------------------------------------------------------------------
935 /* Template for the edit link form
936 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
937 Output: An array : (string) : The html code of the edit link form.
938 (string) : The proper onload to use in body.
939 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
942 function templateEditForm ( $link , $link_is_new = false )
944 $url = htmlspecialchars ( $link [ 'url' ]);
945 $title = htmlspecialchars ( $link [ 'title' ]);
946 $tags = htmlspecialchars ( $link [ 'tags' ]);
947 $description = htmlspecialchars ( $link [ 'description' ]);
948 $private = ( $link [ 'private' ]== 0 ? '' : 'checked="yes"' );
950 // Automatically focus on empty fields:
951 $onload = 'onload="document.linkform.lf_tags.focus();"' ;
952 if ( $description == '' ) $onload = 'onload="document.linkform.lf_description.focus();"' ;
953 if ( $title == '' ) $onload = 'onload="document.linkform.lf_title.focus();"' ;
955 // Do not show "Delete" button if this is a new link.
956 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">' ;
957 if ( $link_is_new ) $delete_button = '' ;
959 $token = getToken (); // XSRF protection.
960 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
961 $editlinkform = <<<HTML
962 <div id="editlinkform">
963 <form method="post" name="linkform">
964 <input type="hidden" name="lf_linkdate" value=" {$link['linkdate']} ">
965 <i>URL</i><br><input type="text" name="lf_url" value=" {$url} " style="width:100%"><br>
966 <i>Title</i><br><input type="text" name="lf_title" value=" {$title} " style="width:100%"><br>
967 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%"> {$description} </textarea><br>
968 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value=" {$tags} " style="width:100%"><br>
969 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private"> <i>Private</i><br>
970 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
971 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
973 <input type="hidden" name="token" value=" {$token} ">
978 return array ( $editlinkform , $onload );
982 // -----------------------------------------------------------------------------------------------
983 // Template for the list of links.
984 // Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
985 function templateLinkList ()
989 // Search according to entered search terms:
990 $linksToDisplay = array ();
992 if (! empty ( $_GET [ 'searchterm' ])) // Fulltext search
994 $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
995 $searched = ' <b>' . count ( $linksToDisplay ). ' results for <i>' . htmlspecialchars ( $_GET [ 'searchterm' ]). '</i></b>:' ;
997 elseif (! empty ( $_GET [ 'searchtags' ])) // Search by tag
999 $linksToDisplay = $LINKSDB- > filterTags ( $_GET [ 'searchtags' ]);
1000 $tagshtml = '' ; foreach ( explode ( ' ' , $_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> ' ;
1001 $searched = ' <b>' . count ( $linksToDisplay ). ' results for tags ' . $tagshtml . ':</b>' ;
1004 $linksToDisplay = $LINKSDB ; // otherwise, display without filtering.
1010 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1011 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1012 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1014 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks php.
1015 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1016 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1017 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1018 $page = ( $page < 1 ? 1 : $page );
1019 $page = ( $page > $pagecount ? $pagecount : $page );
1020 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1021 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1022 while ( $i < $end && $i < count ( $keys ))
1024 $link = $linksToDisplay [ $keys [ $i ]];
1025 $description = $link [ 'description' ];
1026 $title = $link [ 'title' ];
1027 $classprivate = ( $link [ 'private' ]== 0 ? '' : 'class="private"' );
1028 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>' ;
1030 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> ' ; }
1031 $linklist .= '<li ' . $classprivate . '><span class="linktitle"><a href="' . htmlspecialchars ( $link [ 'url' ]). '">' . htmlspecialchars ( $title ). '</a></span>' . $actions . '<br>' ;
1032 if ( $description != '' ) $linklist .= '<div class="linkdescription">' . nl2br ( htmlspecialchars ( $description )). '</div><br>' ;
1033 $linklist .= '<span class="linkdate">' . htmlspecialchars ( linkdate2locale ( $link [ 'linkdate' ])). ' - </span><span class="linkurl">' . htmlspecialchars ( $link [ 'url' ]). '</span><br>' . $tags . "</li> \n " ;
1038 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1039 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1041 if ( $i != count ( $keys )) $paging .= '<a href="?page=' .( $page +
1 ). $searchterm . $searchtags . '">◄Older</a>' ;
1042 $paging .= '<span style="color:#fff; padding:0 20 0 20;">page ' . $page . ' / ' . $pagecount . '</span>' ;
1043 if ( $page > 1 ) $paging .= '<a href="?page=' .( $page-1 ). $searchterm . $searchtags . '">Newer►</a>' ;
1044 $linksperpage = <<<HTML
1045 <div style="float:right; padding-right:5px;">
1046 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1047 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1049 $paging = '<div class="paging">' . $linksperpage . $paging . '</div>' ;
1050 $linklist = '<div id="linklist">' . $paging . $searched . '<ul>' . $linklist . '</ul>' . $paging . '</div>' ;
1054 // -----------------------------------------------------------------------------------------------
1055 // Template for the whole page.
1056 /* Input: $data (associative array).
1057 Keys: 'body' : body of HTML document
1058 'pageheader' : html code to show in page header (top of page)
1059 'onload' : optional onload javascript for the <body>
1061 function templatePage ( $data )
1065 $shaarli_version = shaarli_version
;
1066 $linkcount = count ( $LINKSDB );
1070 $menu = ' <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' ;
1074 $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>' );
1075 foreach ( array ( 'pageheader' , 'body' , 'onload' ) as $k ) // make sure all required fields exist (put an empty string if not).
1077 if (! array_key_exists ( $k , $data )) $data [ $k ]= '' ;
1079 $jsincludes = '' ; $jsincludes_bottom = '' ;
1080 if ( OPEN_SHAARLI
|| isLoggedIn ())
1082 $jsincludes = '<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>' ;
1083 $source = serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]. '?ws=tags' ;
1084 $jsincludes_bottom = <<<JS
1085 <script language="JavaScript">
1086 $(document).ready(function()
1088 $('#lf_tags').autocomplete( {source:'{$source} ',minLength:0});
1093 $feedurl = htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]. '?do=rss' );
1097 <title> {$open} Shaarli - Let's shaare your links...</title>
1098 <link rel="alternate" type="application/rss+xml" href=" {$feedurl} ">
1100 <style type="text/css">
1102 /* CSS Reset from Yahoo to cope with browsers CSS inconsistencies. */
1104 Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html
1107 html {color:#000;background:#FFF;} body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td {margin:0;padding:0;} table {border-collapse:collapse;border-spacing:0;} fieldset,img {border:0;} address,caption,cite,code,dfn,em,strong,th,var,optgroup {font-style:inherit;font-weight:inherit;} del,ins {text-decoration:none;} li {list-style:none;} caption,th {text-align:left;} h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal;} q:before,q:after {content:'';} abbr,acronym {border:0;font-variant:normal;} sup {vertical-align:baseline;} sub {vertical-align:baseline;} legend {color:#000;} input,button,textarea,select,optgroup,option {font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;} input,button,textarea,select {*font-size:100%;}
1109 body { font-family: "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif; font-size:10pt; background-color: #ffffff; }
1110 input { border: 1px solid #aaa; background-color:#F0F0FF; padding: 2 5 2 5; -moz-box-shadow: inset 2px 2px 3px #aaaaaa; -webkit-box-shadow: inset 2px 2px 3px #aaaaaa; box-shadow: inset 2px 2px 3px #aaaaaa; }
1111 textarea { border: 1px solid #aaa; background-color:#F0F0FF; padding: 2 5 2 5; -moz-box-shadow: inset 2px 2px 3px #B2B2C4; -webkit-box-shadow: inset 2px 2px 3px #B2B2C4; box-shadow: inset 2px 2px 3px #B2B2C4; }
1112 /* I don't give a shit about IE. He can't understand selectors such as input[type='submit']. */
1114 .bigbutton {border-style:outset;border-width:2px;padding:3px 6px;background-color:rgb(212,212,212);font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;font-size:8pt;-moz-border-radius:0.5em;border-radius:0.5em;}
1115 .smallbutton {border-style:outset;border-width:2px;padding:0px 4px;background-color:rgb(212,212,212);font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;font-size:8pt;-moz-border-radius:0.5em;border-radius:0.5em;}
1119 border-bottom: 1px solid #aaa;
1120 background-color: #6A6A6A;
1121 background-image: -webkit-gradient(linear, left top, left bottom, from(#6A6A6A), to(#303030)); /* Saf4+, Chrome */
1122 background-image: -webkit-linear-gradient(top, #6A6A6A, #303030); /* Chrome 10+, Saf5.1+ */
1123 background-image: -moz-linear-gradient(top, #6A6A6A, #303030); /* FF3.6 */
1124 background-image: -ms-linear-gradient(top, #6A6A6A, #303030); /* IE10 */
1125 background-image: -o-linear-gradient(top, #6A6A6A, #303030); /* Opera 11.10+ */
1126 background-image: linear-gradient(top, #6A6A6A, #303030);
1127 filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#6A6A6A', EndColorStr='#303030'); /* IE6-IE9 */
1128 padding-bottom: 5px;
1130 #pageheader a:link { color:#bbb; text-decoration:none;}
1131 #pageheader a:visited { color:#bbb; text-decoration:none;}
1132 #pageheader a:hover { color:#FFFFC9; text-decoration:none;}
1133 #pageheader a:active { color:#bbb; text-decoration:none;}
1134 .paging { background-color:#777; color:#ccc; text-align:center; padding:0 0 3 0;}
1135 .paging a:link { color:#ccc; text-decoration:none;}
1136 .paging a:visited { color:#ccc; }
1137 .paging a:hover { color:#FFFFC9; }
1138 .paging a:active { color:#fff; }
1139 #headerform { padding:5 5 5 15; }
1140 #editlinkform { padding:5 5 5 15px; width:80%; }
1141 #linklist li { padding:4 10 8 20; border-bottom: 1px solid #bbb;}
1142 #linklist li.private { background-color: #ccc; border-left:8px solid #888; }
1143 .linktitle { font-size:14pt; font-weight:bold; }
1144 .linktitle a { text-decoration: none; color:#0000EE; }
1145 .linktitle a:hover { text-decoration: underline; }
1146 .linktitle a:visited { color:#0000BB; }
1147 .linkdate { font-size:8pt; color:#888; }
1148 .linkurl { font-size:8pt; color:#4BAA74; }
1149 .linkdescription { color:#000; margin-top:0px; margin-bottom:0px; font-weight:normal; }
1150 .linktag { font-size:9pt; color:#777; background-color:#ddd; padding:0 6 0 6; -moz-box-shadow: inset 2px 2px 3px #ffffff; -webkit-box-shadow: inset 2px 2px 3px #ffffff; box-shadow: inset 2px 2px 3px ffffff;
1151 border-bottom:1px solid #aaa; border-right:1px solid #aaa; }
1152 .linktag a { color:#777; text-decoration:none; }
1153 .buttoneditform { display:inline; }
1154 #footer { font-size:8pt; text-align:center; border-top:1px solid #ddd; color: #888; }
1156 /* Minimal customisation for jQuery widgets */
1157 .ui-autocomplete { background-color:#fff; padding-left:5px;}
1158 .ui-state-hover { background-color: #604dff; color:#fff; }
1163 <body {$data['onload']} >
1164 <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>
1165 <b><i> {$open} Shaarli {$shaarli_version} </i></b> - <a href="?">Home</a> {$menu} <a href=" {$feedurl} " style="padding-left:30px;">RSS Feed</a>
1166 {$data['pageheader']}
1171 $exectime = round ( microtime ( true )- $STARTTIME , 4 );
1172 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>' ;
1173 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>' ;
1174 echo $jsincludes_bottom . '</body></html>' ;
1177 // -----------------------------------------------------------------------------------------------
1179 // This function should NEVER be called if the file data/config.php exists.
1182 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1184 $tz =( empty ( $_POST [ 'settimezone' ]) ? 'UTC' : $_POST [ 'settimezone' ]);
1185 // Everything is ok, let's create config file.
1186 $salt = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1187 $hash = sha1 ( $_POST [ 'setpassword' ]. $_POST [ 'setlogin' ]. $salt );
1188 $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 ). '); ?>' ;
1189 if (! file_put_contents ( CONFIG_FILE
, $config ) || strcmp ( file_get_contents ( CONFIG_FILE
), $config )!= 0 )
1191 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>' ;
1194 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location= \' ?do=login \' ;</script>' ;
1197 // Display config form:
1199 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1202 foreach ( timezone_identifiers_list () as $tz ) $timezones .= '<option value="' . htmlspecialchars ( $tz ). '">' . htmlspecialchars ( $tz ). "</option> \n " ;
1203 $timezoneselect = 'Timezone: <select name="settimezone"><option value="" selected>(please select:)</option>' . $timezones . '</select><br><br>' ;
1206 <html><title>Shaarli - Configuration</title><style type="text/css">
1207 body { font-family: "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif; font-size:10pt; background-color: #ffffff; }
1208 input { border: 1px solid #aaa; background-color:#F0F0FF; padding: 2 5 2 5; -moz-box-shadow: inset 2px 2px 3px #aaaaaa; -webkit-box-shadow: inset 2px 2px 3px #aaaaaa; box-shadow: inset 2px 2px 3px #aaaaaa; }
1209 .bigbutton {border-style:outset;border-width:2px;padding:3px 6px;background-color:rgb(212,212,212);font-family:Tahoma,Verdana,Arial,Helvetica,sans-serif;font-size:8pt;-moz-border-radius:0.5em;border-radius:0.5em;}
1210 </style></head><body onload="document.configform.setlogin.focus();"><h1>Shaarli - Shaare your links...</h1>It looks like it's the first time you run Shaarli. Please chose a login/password and a timezone:<br>
1211 <form method="POST" action="" name="configform" style="border:1px solid black; padding:10 10 10 10;">
1212 Login: <input type="text" name="setlogin"><br><br>Password: <input type="password" name="setpassword"><br><br>
1214 <input type="submit" name="Save" value="Save config" class="bigbutton"></form></body></html>
1219 // Webservices (for use with jQuery/jQueryUI)
1220 // eg. index.php?ws=tags&term=minecr
1221 function processWS ()
1223 if ( empty ( $_GET [ 'ws' ]) || empty ( $_GET [ 'term' ])) return ;
1224 $term = $_GET [ 'term' ];
1226 header ( 'Content-Type: application/json; charset=utf-8' );
1229 if ( $_GET [ 'ws' ]== 'tags' )
1231 $tags = explode ( ' ' , $term ); $last = array_pop ( $tags ); // Get the last term ("a b c d" ==> "a b c", "d")
1232 $addtags = '' ; if ( $tags ) $addtags = implode ( ' ' , $tags ). ' ' ; // We will pre-pend previous tags
1234 /* To speed up things, we store list of tags in session */
1235 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1236 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1238 if ( startsWith ( $key , $last , $case = false )) $suggested [ $addtags . $key . ' ' ]= 0 ;
1240 echo json_encode ( array_keys ( $suggested ));
1245 // Invalidate caches when the database is changed or the user logs out.
1246 // (eg. tags cache).
1247 function invalidateCaches ()
1249 unset ( $_SESSION [ 'tags' ]);
1252 $LINKSDB = new linkdb ( isLoggedIn () || OPEN_SHAARLI
); // Read links from database (and filter private links if used it not logged in).
1253 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'ws=' )) { processWS (); exit ; } // Webservices (for jQuery/jQueryUI)
1254 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= LINKS_PER_PAGE
;
1255 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }