]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
801108b808c95af1cbfb16d74f2f2d2c81311e24
2 // Shaarli 0.0.27 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
8 // (but autocomplete fields will only work if you have php 5.2.x)
9 // -----------------------------------------------------------------------------------------------
11 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ; // Data subdirectory
12 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ; // Configuration file (user login/password)
13 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ; // Data storage file.
14 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ; // Default links per page.
15 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ; // File storage for failures and bans.
16 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ; // Ban IP after this many failures.
17 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ; // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
18 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ; // If true, anyone can add/edit/delete links without having to login
19 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ; // If true, the moment when links were saved are not shown to users that are not logged in.
20 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ; // Enable thumbnails in links.
21 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ; // Cache directory for thumbnails for SLOW services (like flickr)
22 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce webspace usage.
24 // -----------------------------------------------------------------------------------------------
25 // Program config (touch at your own risks !)
26 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ; // For updates check of Shaarli.
27 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
28 ini_set ( 'max_input_time' , '60' ); // High execution time in case of problematic imports/exports.
29 ini_set ( 'memory_limit' , '128M' ); // Try to set max upload file size and read (May not work on some hosts).
30 ini_set ( 'post_max_size' , '16M' );
31 ini_set ( 'upload_max_filesize' , '16M' );
32 define ( 'PHPPREFIX' , '<?php /* ' ); // Prefix to encapsulate data in php code.
33 define ( 'PHPSUFFIX' , ' */ ?>' ); // Suffix to encapsulate data in php code.
34 $STARTTIME = microtime ( true ); // Measure page execution time.
36 error_reporting ( E_ALL^E_WARNING
); // See all error except warnings.
37 //error_reporting(-1); // See all errors (for debugging only)
40 // Optionnal config file.
41 if ( is_file ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/options.php' )) require ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/options.php' );
43 // In case stupid admin has left magic_quotes enabled in php.ini:
44 if ( get_magic_quotes_gpc ())
46 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
47 $_POST = array_map ( 'stripslashes_deep' , $_POST );
48 $_GET = array_map ( 'stripslashes_deep' , $_GET );
49 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
51 // Prevent caching: (yes, it's ugly)
52 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
53 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
54 header ( "Cache-Control: post-check=0, pre-check=0" , false );
55 header ( "Pragma: no-cache" );
56 define ( 'shaarli_version' , '0.0.27 beta' );
57 if (! is_dir ( $GLOBALS [ 'config' ][ 'DATADIR' ])) { mkdir ( $GLOBALS
[ 'config' ][ 'DATADIR' ], 0705 ); chmod ( $GLOBALS
[ 'config' ][ 'DATADIR' ], 0705 ); }
58 if (! is_file ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/.htaccess' )) { file_put_contents ( $GLOBALS
[ 'config' ][ 'DATADIR' ]. '/.htaccess' , "Allow from none \n Deny from all \n " ); } // Protect data files.
59 if ( $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ])
61 if (! is_dir ( $GLOBALS [ 'config' ][ 'CACHEDIR' ])) { mkdir ( $GLOBALS
[ 'config' ][ 'CACHEDIR' ], 0705 ); chmod ( $GLOBALS
[ 'config' ][ 'CACHEDIR' ], 0705 ); }
62 if (! is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/.htaccess' )) { file_put_contents ( $GLOBALS
[ 'config' ][ 'CACHEDIR' ]. '/.htaccess' , "Allow from none \n Deny from all \n " ); } // Protect data files.
64 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) install ();
65 require $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]; // Read login/password hash into $GLOBALS.
66 // Small protection against dodgy config files:
67 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]);
68 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
69 autoLocale (); // Sniff browser language and set date format accordingly.
70 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
74 function checkphpversion ()
76 if ( version_compare ( PHP_VERSION
, '5.1.0' ) < 0 )
78 header ( 'Content-Type: text/plain; charset=utf-8' );
79 echo 'Your server supports php ' . PHP_VERSION
. '. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.' ;
84 // Checks if an update is available for Shaarli.
85 // (at most once a day, and only for registered user.)
86 // Output: '' = no new version.
87 // other= the available version.
88 function checkUpdate ()
90 if (! isLoggedIn ()) return '' ; // Do not check versions for visitors.
92 // Get latest version number at most once a day.
93 if (! is_file ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]) || ( filemtime ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ])< time ()-( $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ])))
95 $version = shaarli_version
;
96 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://sebsauvage.net/files/shaarli_version.txt' , 2 );
97 if ( strpos ( $httpstatus , '200 OK' )) $version = $data ;
98 // If failed, nevermind. We don't want to bother the user with that.
99 file_put_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ], $version ); // touch file date
102 $newestversion = file_get_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]);
103 if ( version_compare ( $newestversion , shaarli_version
)== 1 ) return $newestversion ;
107 // -----------------------------------------------------------------------------------------------
109 function logm ( $message )
111 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
112 file_put_contents ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' , $t , FILE_APPEND
);
115 /* Returns the small hash of a string
116 eg. smallHash('20111006_131924') --> yZH23w
118 - are unique (well, as unique as crc32, at last)
119 - are always 6 characters long.
120 - only use the following characters: a-z A-Z 0-9 - _ @
121 - are NOT cryptographically secure (they CAN be forged)
122 In Shaarli, they are used as a tinyurl-like link to individual entries.
124 function smallHash ( $text )
126 $t = rtrim ( base64_encode ( hash ( 'crc32' , $text , true )), '=' );
127 $t = str_replace ( '+' , '-' , $t ); // Get rid of characters which need encoding in URLs.
128 $t = str_replace ( '/' , '_' , $t );
129 $t = str_replace ( '=' , '@' , $t );
133 // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
134 function text2clickable ( $url )
136 $redir = empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ];
137 return preg_replace ( '!((?:https?|ftp)://\S+[[:alnum:]]/?)!si' , '<a href="' . $redir . ' $1" rel="nofollow"> $1 </a>' , $url );
139 // ------------------------------------------------------------------------------------------
140 // Sniff browser language to display dates in the right format automatically.
141 // (Note that is may not work on your server if the corresponding local is not installed.)
142 function autoLocale ()
144 $loc = 'en_US' ; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
145 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
146 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
147 if ( preg_match ( '/([a-z] {2} (-[a-z] {2} )?)/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) $loc = $matches [ 1 ];
149 setlocale ( LC_TIME
, $loc ); // LC_TIME = Set local for date/time format only.
152 // ------------------------------------------------------------------------------------------
153 // Session management
154 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
155 ini_set ( 'session.use_cookies' , 1 ); // Use cookies to store session.
156 ini_set ( 'session.use_only_cookies' , 1 ); // Force cookies for session (phpsessionID forbidden in URL)
157 ini_set ( 'session.use_trans_sid' , false ); // Prevent php to use sessionID in URL if cookies are disabled.
158 session_name ( 'shaarli' );
161 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
164 $ip = $_SERVER [ "REMOTE_ADDR" ];
165 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
166 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
167 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
171 // Check that user/password is correct.
172 function check_auth ( $login , $password )
174 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
175 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
176 { // Login/password is correct.
177 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // generate unique random number (different than phpsessionid)
178 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
179 $_SESSION [ 'username' ]= $login ;
180 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
181 logm ( 'Login successful' );
184 logm ( 'Login failed for user ' . $login );
188 // Returns true if the user is logged in.
189 function isLoggedIn ()
191 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) return true ;
193 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
194 if ( empty ( $_SESSION [ 'uid' ]) || $_SESSION [ 'ip' ]!= allIPs () || time ()>= $_SESSION [ 'expires_on' ])
199 if (! empty ( $_SESSION [ 'longlastingsession' ])) $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
200 else $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
206 function logout () { if ( isset ( $_SESSION
)) { unset ( $_SESSION
[ 'uid' ]); unset ( $_SESSION
[ 'ip' ]); unset ( $_SESSION
[ 'username' ]);} }
209 // ------------------------------------------------------------------------------------------
210 // Brute force protection system
211 // Several consecutive failed logins will ban the IP address for 30 minutes.
212 if (! is_file ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ])) file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>" );
213 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
214 // Signal a failed login. Will ban the IP if too many failures:
215 function ban_loginFailed ()
217 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
218 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
219 $gb [ 'FAILURES' ][ $ip ] ++
;
220 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
222 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
223 logm ( 'IP address banned from login' );
225 $GLOBALS [ 'IPBANS' ] = $gb ;
226 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
229 // Signals a successful login. Resets failed login counter.
230 function ban_loginOk ()
232 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
233 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
234 $GLOBALS [ 'IPBANS' ] = $gb ;
235 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
238 // Checks if the user CAN login. If 'true', the user can try to login.
239 function ban_canLogin ()
241 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
242 if ( isset ( $gb [ 'BANS' ][ $ip ]))
244 // User is banned. Check if the ban has expired:
245 if ( $gb [ 'BANS' ][ $ip ]<= time ())
246 { // Ban expired, user can try to login again.
248 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
249 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
250 return true ; // Ban has expired, user can login.
252 return false ; // User is banned.
254 return true ; // User is not banned.
257 // ------------------------------------------------------------------------------------------
258 // Process login form: Check if login/password is correct.
259 if ( isset ( $_POST [ 'login' ]))
261 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
262 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
263 { // Login/password is ok.
265 // If user wants to keep the session cookie even after the browser closes:
266 if (! empty ( $_POST [ 'longlastingsession' ]))
268 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
269 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
270 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ]); // Set session cookie expiration on client side
271 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
273 else // Standard session expiration (=when browser closes)
275 session_set_cookie_params ( 0 ); // 0 means "When browser closes"
276 session_regenerate_id ( true );
278 // Optional redirect after login:
279 if ( isset ( $_GET [ 'post' ])) { header ( 'Location: ?post=' . urlencode ( $_GET
[ 'post' ]).(! empty ( $_GET
[ 'title' ])? '&title=' . urlencode ( $_GET
[ 'title' ]): '' ).(! empty ( $_GET
[ 'source' ])? '&source=' . urlencode ( $_GET
[ 'source' ]): '' )); exit ; }
280 if ( isset ( $_POST [ 'returnurl' ]))
282 if ( endsWith ( $_POST [ 'returnurl' ], '?do=login' )) { header ( 'Location: ?' ); exit ; } // Prevent loops over login screen.
283 header ( 'Location: ' . $_POST [ 'returnurl' ]); exit ;
285 header ( 'Location: ?' ); exit ;
290 echo '<script language="JavaScript">alert("Wrong login/password.");document.location= \' ?do=login \' ;</script>' ; // Redirect to login screen.
295 // ------------------------------------------------------------------------------------------
296 // Misc utility functions:
298 // Returns the server URL (including port and http/https), without path.
299 // eg. "http://myserver.com:8080"
300 // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
303 $serverport = ( $_SERVER [ "SERVER_PORT" ]!= '80' ? ':' . $_SERVER [ "SERVER_PORT" ] : '' );
304 return 'http' .(! empty ( $_SERVER [ 'HTTPS' ])? 's' : '' ). '://' . $_SERVER [ "SERVER_NAME" ]. $serverport ;
307 // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
308 function return_bytes ( $val )
310 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
313 case 'g' : $val *= 1024 ;
314 case 'm' : $val *= 1024 ;
315 case 'k' : $val *= 1024 ;
320 // Try to determine max file size for uploads (POST).
321 // Returns an integer (in bytes)
322 function getMaxFileSize ()
324 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
325 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
326 // Return the smaller of two:
327 $maxsize = min ( $size1 , $size2 );
328 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
332 // Tells if a string start with a substring or not.
333 function startsWith ( $haystack , $needle , $case = true )
335 if ( $case ){ return ( strcmp ( substr ( $haystack
, 0 , strlen ( $needle
)), $needle
)=== 0 );}
336 return ( strcasecmp ( substr ( $haystack , 0 , strlen ( $needle )), $needle )=== 0 );
339 // Tells if a string ends with a substring or not.
340 function endsWith ( $haystack , $needle , $case = true )
342 if ( $case ){ return ( strcmp ( substr ( $haystack
, strlen ( $haystack
) - strlen ( $needle
)), $needle
)=== 0 );}
343 return ( strcasecmp ( substr ( $haystack , strlen ( $haystack ) - strlen ( $needle )), $needle )=== 0 );
346 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
347 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
348 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
349 function linkdate2timestamp ( $linkdate )
352 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
353 return mktime ( $h , $m , $s , $M , $D , $Y );
356 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
357 (used to build the pubDate attribute in RSS feed.) */
358 function linkdate2rfc822 ( $linkdate )
360 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
363 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
364 (used to build the updated tags in ATOM feed.) */
365 function linkdate2iso8601 ( $linkdate )
367 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
370 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
371 (used to display link date on screen)
372 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
373 function linkdate2locale ( $linkdate )
375 return utf8_encode ( strftime ( '%c' , linkdate2timestamp ( $linkdate ))); // %c is for automatic date format according to locale.
376 // Note that if you use a local which is not installed on your webserver,
377 // the date will not be displayed in the chosen locale, but probably in US notation.
380 // Parse HTTP response headers and return an associative array.
381 function http_parse_headers ( $headers )
384 foreach ( $headers as $header )
386 $i = strpos ( $header , ': ' );
389 $key = substr ( $header , 0 , $i );
390 $value = substr ( $header , $i +
2 , strlen ( $header )- $i-2 );
398 Input: $url : url to get (http://...)
399 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
400 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
401 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
403 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
404 if (strpos($httpstatus,'200 OK'))
405 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
407 echo 'There was an error: '.htmlspecialchars($httpstatus)
409 function getHTTP ( $url , $timeout = 30 )
413 $options = array ( 'http' => array ( 'method' => 'GET' , 'timeout' => $timeout )); // Force network timeout
414 $context = stream_context_create ( $options );
415 $data = file_get_contents ( $url , false , $context ,- 1 , 4000000 ); // We download at most 4 Mb from source.
416 if (! $data ) { $lasterror
= error_get_last (); return array ( $lasterror
[ 'message' ], array (), '' ); }
417 $httpStatus = $http_response_header [ 0 ]; // eg. "HTTP/1.1 200 OK"
418 $responseHeaders = http_parse_headers ( $http_response_header );
419 return array ( $httpStatus , $responseHeaders , $data );
421 catch ( Exception
$e ) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
423 return array ( $e- > getMessage (), '' , '' );
427 // Extract title from an HTML document.
428 // (Returns an empty string if not found.)
429 function html_extract_title ( $html )
431 return preg_match ( '!<title>(.*)</title>!is' , $html , $matches ) ? trim ( str_replace ( " \n " , ' ' , $matches [ 1 ])) : '' ;
434 // ------------------------------------------------------------------------------------------
435 // Token management for XSRF protection
436 // Token should be used in any form which acts on data (create,update,delete,import...).
437 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
442 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // We generate a random string.
443 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
447 // Tells if a token is ok. Using this function will destroy the token.
449 function tokenOk ( $token )
451 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
453 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
454 return true ; // Token is ok.
456 return false ; // Wrong token, or already used.
459 // ------------------------------------------------------------------------------------------
460 /* Data storage for links.
461 This object behaves like an associative array.
463 $mylinks = new linkdb();
464 echo $mylinks['20110826_161819']['title'];
465 foreach($mylinks as $link)
466 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
468 We implement 3 interfaces:
469 - ArrayAccess so that this object behaves like an associative array.
470 - Iterator so that this object can be used in foreach() loops.
471 - Countable interface so that we can do a count() on this object.
473 class linkdb
implements Iterator
, Countable
, ArrayAccess
476 private $links ; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
477 private $urls ; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
478 private $keys ; // List of linkdate keys (for the Iterator interface implementation)
479 private $position ; // Position in the $this->keys array. (for the Iterator interface implementation.)
480 private $loggedin ; // Is the used logged in ? (used to filter private links)
483 function __construct ( $isLoggedIn )
484 // Input : $isLoggedIn : is the used logged in ?
486 $this- > loggedin
= $isLoggedIn ;
487 $this- > checkdb (); // Make sure data file exists.
488 $this- > readdb (); // Then read it.
491 // ---- Countable interface implementation
492 public function count () { return count ( $this
-> links
); }
494 // ---- ArrayAccess interface implementation
495 public function offsetSet ( $offset , $value )
497 if (! $this- > loggedin
) die ( 'You are not authorized to add a link.' );
498 if ( empty ( $value [ 'linkdate' ]) || empty ( $value [ 'url' ])) die ( 'Internal Error: A link should always have a linkdate and url.' );
499 if ( empty ( $offset )) die ( 'You must specify a key.' );
500 $this- > links
[ $offset ] = $value ;
501 $this- > urls
[ $value [ 'url' ]]= $offset ;
503 public function offsetExists ( $offset ) { return array_key_exists ( $offset
, $this
-> links
); }
504 public function offsetUnset ( $offset )
506 if (! $this- > loggedin
) die ( 'You are not authorized to delete a link.' );
507 $url = $this- > links
[ $offset ][ 'url' ]; unset ( $this- > urls
[ $url ]);
508 unset ( $this- > links
[ $offset ]);
510 public function offsetGet ( $offset ) { return isset ( $this
-> links
[ $offset
]) ? $this
-> links
[ $offset
] : null ; }
512 // ---- Iterator interface implementation
513 function rewind () { $this
-> keys
= array_keys ( $this
-> links
); rsort ( $this
-> keys
); $this
-> position
= 0 ; } // Start over for iteration, ordered by date (latest first).
514 function key () { return $this
-> keys
[ $this
-> position
]; } // current key
515 function current () { return $this
-> links
[ $this
-> keys
[ $this
-> position
]]; } // current value
516 function next () { ++$this
-> position
; } // go to next item
517 function valid () { return isset ( $this
-> keys
[ $this
-> position
]); } // Check if current position is valid.
520 private function checkdb () // Check if db directory and file exists.
522 if (! file_exists ( $GLOBALS [ 'config' ][ 'DATASTORE' ])) // Create a dummy database for example.
524 $this- > links
= array ();
525 $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' );
526 $this- > links
[ $link [ 'linkdate' ]] = $link ;
527 $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' );
528 $this- > links
[ $link [ 'linkdate' ]] = $link ;
529 file_put_contents ( $GLOBALS [ 'config' ][ 'DATASTORE' ], PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
); // Write database to disk
533 // Read database from disk to memory
534 private function readdb ()
537 $this- > links
=( file_exists ( $GLOBALS [ 'config' ][ 'DATASTORE' ]) ? unserialize ( gzinflate ( base64_decode ( substr ( file_get_contents ( $GLOBALS [ 'config' ][ 'DATASTORE' ]), strlen ( PHPPREFIX
),- strlen ( PHPSUFFIX
))))) : array () );
538 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
540 // If user is not logged in, filter private links.
541 if (! $this- > loggedin
)
544 foreach ( $this- > links
as $link ) { if ( $link
[ 'private' ]!= 0 ) $toremove
[]= $link
[ 'linkdate' ]; }
545 foreach ( $toremove as $linkdate ) { unset ( $this
-> links
[ $linkdate
]); }
548 // Keep the list of the mapping URLs-->linkdate up-to-date.
550 foreach ( $this- > links
as $link ) { $this
-> urls
[ $link
[ 'url' ]]= $link
[ 'linkdate' ]; }
553 // Save database from memory to disk.
554 public function savedb ()
556 if (! $this- > loggedin
) die ( 'You are not authorized to change the database.' );
557 file_put_contents ( $GLOBALS [ 'config' ][ 'DATASTORE' ], PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
);
560 // Returns the link for a given URL (if it exists). false it does not exist.
561 public function getLinkFromUrl ( $url )
563 if ( isset ( $this- > urls
[ $url ])) return $this- > links
[ $this- > urls
[ $url ]];
567 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
568 // eg. print_r($mydb->filterFulltext('hollandais'));
569 public function filterFulltext ( $searchterms )
571 // FIXME: explode(' ',$searchterms) and perform a AND search.
572 // FIXME: accept double-quotes to search for a string "as is" ?
574 $s = strtolower ( $searchterms );
575 foreach ( $this- > links
as $l )
577 $found = strpos ( strtolower ( $l [ 'title' ]), $s ) || strpos ( strtolower ( $l [ 'description' ]), $s ) || strpos ( strtolower ( $l [ 'url' ]), $s ) || strpos ( strtolower ( $l [ 'tags' ]), $s );
578 if ( $found ) $filtered [ $l [ 'linkdate' ]] = $l ;
585 // You can specify one or more tags (tags can be separated by space or comma).
586 // eg. print_r($mydb->filterTags('linux programming'));
587 public function filterTags ( $tags , $casesensitive = false )
589 $t = str_replace ( ',' , ' ' ,( $casesensitive ? $tags : strtolower ( $tags )));
590 $searchtags = explode ( ' ' , $t );
592 foreach ( $this- > links
as $l )
594 $linktags = explode ( ' ' ,( $casesensitive ? $l [ 'tags' ]: strtolower ( $l [ 'tags' ])));
595 if ( count ( array_intersect ( $linktags , $searchtags )) == count ( $searchtags ))
596 $filtered [ $l [ 'linkdate' ]] = $l ;
602 // Filter by smallHash.
603 // Only 1 article is returned.
604 public function filterSmallHash ( $smallHash )
607 foreach ( $this- > links
as $l )
609 if ( $smallHash == smallHash ( $l [ 'linkdate' ])) // Yes, this is ugly and slow
611 $filtered [ $l [ 'linkdate' ]] = $l ;
618 // Returns the list of all tags
619 // Output: associative array key=tags, value=0
620 public function allTags ()
623 foreach ( $this- > links
as $link )
624 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
625 if (! empty ( $tag )) $tags [ $tag ]=( empty ( $tags [ $tag ]) ? 1 : $tags [ $tag ] +
1 );
626 arsort ( $tags ); // Sort tags by usage (most used tag first)
631 // ------------------------------------------------------------------------------------------
632 // Ouput the last 50 links in RSS 2.0 format.
637 // Optionnaly filter the results:
638 $linksToDisplay = array ();
639 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
640 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
641 else $linksToDisplay = $LINKSDB ;
643 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
644 $pageaddr = htmlspecialchars ( serverUrl (). $_SERVER [ "SCRIPT_NAME" ]);
645 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
646 echo '<channel><title>' . htmlspecialchars ( $GLOBALS [ 'title' ]). '</title><link>' . $pageaddr . '</link>' ;
647 echo '<description>Shared links</description><language></language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
649 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
650 while ( $i < 50 && $i < count ( $keys ))
652 $link = $linksToDisplay [ $keys [ $i ]];
653 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
654 echo '<item><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><guid>' . htmlspecialchars ( $link [ 'url' ]). '</guid><link>' . htmlspecialchars ( $link [ 'url' ]). '</link>' ;
655 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . htmlspecialchars ( $rfc822date ). '</pubDate>' ;
656 echo '<description><![CDATA[' . nl2br ( htmlspecialchars ( $link [ 'description' ])). ']]></description></item>' . " \n " ;
659 echo '</channel></rss>' ;
663 // ------------------------------------------------------------------------------------------
664 // Ouput the last 50 links in ATOM format.
669 // Optionnaly filter the results:
670 $linksToDisplay = array ();
671 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
672 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
673 else $linksToDisplay = $LINKSDB ;
675 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
676 $pageaddr = htmlspecialchars ( serverUrl (). $_SERVER [ "SCRIPT_NAME" ]);
680 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
681 while ( $i < 50 && $i < count ( $keys ))
683 $link = $linksToDisplay [ $keys [ $i ]];
684 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
685 $latestDate = max ( $latestDate , $iso8601date );
686 $entries .= '<entry><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><link href="' . htmlspecialchars ( $link [ 'url' ]). '"/><id>' . htmlspecialchars ( $link [ 'url' ]). '</id>' ;
687 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . htmlspecialchars ( $iso8601date ). '</updated>' ;
688 $entries .= '<summary>' . nl2br ( htmlspecialchars ( $link [ 'description' ])). '</summary></entry>' . " \n " ;
691 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
692 $feed .= '<title>' . htmlspecialchars ( $GLOBALS [ 'title' ]). '</title>' ;
693 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . htmlspecialchars ( $latestDate ). '</updated>' ;
694 $feed .= '<link href="' . htmlspecialchars ( $pageaddr ). '" />' ;
695 $feed .= '<author><uri>' . htmlspecialchars ( $pageaddr ). '</uri></author>' ;
696 $feed .= '<id>' . htmlspecialchars ( $pageaddr ). '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
703 // ------------------------------------------------------------------------------------------
705 function renderPage ()
710 // 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.
711 // So I use a custom templating system.
713 // -------- Display login form.
714 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=login' ))
716 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
719 $loginform = '<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>' ;
720 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => '' );
724 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
725 $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"><br>' ;
726 $loginform .= '<input style="margin:10 0 0 40;" type="checkbox" name="longlastingsession" id="longlastingsession"><label for="longlastingsession"> Stay signed in (Do not check on public computers)</label><input type="hidden" name="token" value="' . getToken (). '">' . $returnurl_html . '</form></div>' ;
727 $onload = 'onload="document.loginform.login.focus();"' ;
728 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => $onload );
732 // -------- User wants to logout.
733 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
737 header ( 'Location: ?' );
741 // -------- Picture wall
742 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=picwall' ))
744 // Optionnaly filter the results:
745 $linksToDisplay = array ();
746 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
747 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
748 else $linksToDisplay = $LINKSDB ;
750 foreach ( $linksToDisplay as $link )
752 $thumb = thumbnail ( $link [ 'url' ]);
755 $url = htmlspecialchars ( $link [ 'url' ], ENT_QUOTES
);
756 $body .= '<div class="picwall_pictureframe">' . $thumb . '<a href="' . $url . '"><span class="info">' . htmlspecialchars ( $link [ 'title' ]). '</span></a></div>' ;
760 $body = '<center><div id="picwall_container">' . $body . '<hr style="width:0;height:0;clear:both;"></div></center>' ;
761 $data = array ( 'pageheader' => '<br> ' , 'body' => $body , 'onload' => '' );
767 // -------- Tag cloud
768 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tagcloud' ))
770 $tags = $LINKSDB- > allTags ();
771 // We sort tags alphabetically, then choose a font size according to count.
772 // First, find max value.
773 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
776 foreach ( $tags as $key => $value )
778 $size = max ( 40 * $value / $maxcount , 8 ); // Minimum size 8.
779 $colorvalue = 128 - ceil ( 127 * $value / $maxcount );
780 $color = 'rgb(' . $colorvalue . ',' . $colorvalue . ',' . $colorvalue . ')' ;
781 $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> ' ;
783 $cloud = '<div id="cloudtag">' . $cloud . '</div>' ;
784 $data = array ( 'pageheader' => '' , 'body' => $cloud , 'onload' => '' );
789 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
790 if ( isset ( $_GET [ 'addtag' ]))
792 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
793 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
794 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
795 $params [ 'searchtags' ] = ( empty ( $params [ 'searchtags' ]) ? trim ( $_GET [ 'addtag' ]) : trim ( $params [ 'searchtags' ]). ' ' . urlencode ( trim ( $_GET [ 'addtag' ])));
796 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
797 header ( 'Location: ?' . http_build_query ( $params ));
801 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
802 if ( isset ( $_GET [ 'removetag' ]))
804 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
805 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?' ); exit ; } // In case browser does not send HTTP_REFERER
806 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
807 if ( isset ( $params [ 'searchtags' ]))
809 $tags = explode ( ' ' , $params [ 'searchtags' ]);
810 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
811 if ( count ( $tags )== 0 ) unset ( $params [ 'searchtags' ]); else $params [ 'searchtags' ] = implode ( ' ' , $tags );
812 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
814 header ( 'Location: ?' . http_build_query ( $params ));
818 // -------- User wants to change the number of links per page (linksperpage=...)
819 if ( isset ( $_GET [ 'linksperpage' ]))
821 if ( is_numeric ( $_GET [ 'linksperpage' ])) { $_SESSION
[ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET
[ 'linksperpage' ])); }
822 header ( 'Location: ' .( empty ( $_SERVER [ 'HTTP_REFERER' ])? '?' : $_SERVER [ 'HTTP_REFERER' ]));
827 // -------- Handle other actions allowed for non-logged in users:
830 // User tries to post new link but is not loggedin:
831 // Show login screen, then redirect to ?post=...
832 if ( isset ( $_GET [ 'post' ]))
834 header ( 'Location: ?do=login&post=' . urlencode ( $_GET [ 'post' ]).( isset ( $_GET [ 'title' ])? '&title=' . urlencode ( $_GET [ 'title' ]): '' ).( isset ( $_GET [ 'source' ])? '&source=' . urlencode ( $_GET [ 'source' ]): '' )); // Redirect to login page, then back to post link.
838 // Show search form and display list of links.
840 <div id="headerform" style="width:100%; white-space:nowrap;";>
841 <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>
842 <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>
845 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => '' );
847 exit ; // Never remove this one ! All operations below are reserved for logged in user.
850 // -------- All other functions are reserved for the registered user:
852 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
853 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tools' ))
855 $pageabsaddr = serverUrl (). $_SERVER [ "SCRIPT_NAME" ]; // Why doesn't php have a built-in function for that ?
856 // The javascript code for the bookmarklet:
857 $changepwd = ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] ? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
859 <div id="headerform"><br>
861 <a href="?do=configure"><b>Configure your Shaarli</b></a> - Change Title, timezone...<br><br>
862 <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
863 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
864 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
865 <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>
868 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
873 // -------- User wants to change his/her password.
874 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changepasswd' ))
876 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
877 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
879 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
881 // Make sure old password is correct.
882 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
883 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
885 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
886 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
888 echo '<script language="JavaScript">alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
894 $changepwdform = <<<HTML
895 <form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
896 Old password: <input type="password" name="oldpassword">
897 New password: <input type="password" name="setpassword">
898 <input type="hidden" name="token" value=" {$token} ">
899 <input type="submit" name="Save" value="Save password" class="bigbutton"></form>
901 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.changepasswordform.oldpassword.focus();"' );
907 // -------- User wants to change configuration
908 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=configure' ))
910 if (! empty ( $_POST [ 'title' ]) )
912 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
914 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
915 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
916 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
917 $GLOBALS [ 'timezone' ] = $tz ;
918 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
919 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
921 echo '<script language="JavaScript">alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
927 $title = htmlspecialchars ( empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] , ENT_QUOTES
);
928 $redirector = htmlspecialchars ( empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] , ENT_QUOTES
);
929 list ( $timezone_form , $timezone_js ) = templateTZform ( $GLOBALS [ 'timezone' ]);
930 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
931 $changepwdform = <<<HTML
932 ${timezone_js} <form method="POST" action="" name="configform" id="configform"><input type="hidden" name="token" value=" {$token} ">
933 <table border="0" cellpadding="20">
934 <tr><td><b>Page title:</b></td><td><input type="text" name="title" id="title" size="50" value=" {$title} "></td></tr>
936 <tr><td valign="top"><b>Redirector</b></td><td><input type="text" name="redirector" id="redirector" size="50" value=" {$redirector} "><br>(e.g. <i>http://anonym.to/?</i> will mask the HTTP_REFERER)</td></tr>
937 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
941 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.configform.title.focus();"' );
947 // -------- User wants to rename a tag or delete it
948 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changetag' ))
950 if ( empty ( $_POST [ 'fromtag' ]))
953 $changetagform = <<<HTML
954 <form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
955 <input type="hidden" name="token" value=" {$token} ">
956 Tag: <input type="text" name="fromtag" id="fromtag">
957 <input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
958 or <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
959 <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>
961 $data = array ( 'pageheader' => $changetagform , 'body' => '' , 'onload' => 'onload="document.changetag.fromtag.focus();"' );
965 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
967 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
969 $needle = trim ( $_POST [ 'fromtag' ]);
970 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
971 foreach ( $linksToAlter as $key => $value )
973 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
974 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
975 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
976 $LINKSDB [ $key ]= $value ;
978 $LINKSDB- > savedb (); // save to disk
980 echo '<script language="JavaScript">alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
985 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
987 $needle = trim ( $_POST [ 'fromtag' ]);
988 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
989 foreach ( $linksToAlter as $key => $value )
991 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
992 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Remplace tags value.
993 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
994 $LINKSDB [ $key ]= $value ;
996 $LINKSDB- > savedb (); // save to disk
998 echo '<script language="JavaScript">alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1003 // -------- User wants to add a link without using the bookmarklet: show form.
1004 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=addlink' ))
1006 $onload = 'onload="document.addform.post.focus();"' ;
1007 $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>' ;
1008 $data = array ( 'pageheader' => $addform , 'body' => '' , 'onload' => $onload );
1009 templatePage ( $data );
1013 // -------- User clicked the "Save" button when editing a link: Save link to database.
1014 if ( isset ( $_POST [ 'save_edit' ]))
1016 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
1017 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
1018 $linkdate = $_POST [ 'lf_linkdate' ];
1019 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => trim ( $_POST [ 'lf_url' ]), 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1020 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
1021 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
1022 $LINKSDB [ $linkdate ] = $link ;
1023 $LINKSDB- > savedb (); // save to disk
1026 // If we are called from the bookmarklet, we must close the popup:
1027 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1028 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1029 header ( 'Location: ' . $returnurl ); // After saving the link, redirect to the page the user was on.
1033 // -------- User clicked the "Cancel" button when editing a link.
1034 if ( isset ( $_POST [ 'cancel_edit' ]))
1036 // If we are called from the bookmarklet, we must close the popup;
1037 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1038 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1039 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1043 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
1044 if ( isset ( $_POST [ 'delete_link' ]))
1046 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1047 // We do not need to ask for confirmation:
1048 // - confirmation is handled by javascript
1049 // - we are protected from XSRF by the token.
1050 $linkdate = $_POST [ 'lf_linkdate' ];
1051 unset ( $LINKSDB [ $linkdate ]);
1052 $LINKSDB- > savedb (); // save to disk
1054 // If we are called from the bookmarklet, we must close the popup:
1055 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1056 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1057 header ( 'Location: ' . $returnurl ); // After deleting the link, redirect to the page the user was on.
1061 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1062 if ( isset ( $_GET [ 'edit_link' ]))
1064 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1065 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1066 list ( $editform , $onload )= templateEditForm ( $link );
1067 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
1068 templatePage ( $data );
1072 // -------- User want to post a new link: Display link edit form.
1073 if ( isset ( $_GET [ 'post' ]))
1077 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
1078 $i = strpos ( $url , '&utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
1079 $i = strpos ( $url , '?utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
1080 $i = strpos ( $url , '#xtor=RSS-' ); if ( $i ) $url = substr ( $url , 0 , $i );
1082 $link_is_new = false ;
1083 $link = $LINKSDB- > getLinkFromUrl ( $url ); // Check if URL is not already in database (in this case, we will edit the existing link)
1086 $link_is_new = true ; // This is a new link
1087 $linkdate = strval ( date ( 'Ymd_His' ));
1088 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] ); // Get title if it was provided in URL (by the bookmarklet).
1089 $description = '' ; $tags = '' ; $private = 0 ;
1090 if (( $url != '' ) && parse_url ( $url , PHP_URL_SCHEME
)== '' ) $url = 'http://' . $url ;
1091 // 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.)
1092 if ( empty ( $title ) && parse_url ( $url , PHP_URL_SCHEME
)== 'http' )
1094 list ( $status , $headers , $data ) = getHTTP ( $url , 4 ); // Short timeout to keep the application responsive.
1095 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1096 if ( strpos ( $status , '200 OK' )) $title = html_entity_decode ( html_extract_title ( $data ), ENT_QUOTES
, 'UTF-8' );
1098 if ( $url == '' ) $url = '?' . smallHash ( $linkdate ); // In case of empty URL, this is just a text (with a link that point to itself)
1099 $link = array ( 'linkdate' => $linkdate , 'title' => $title , 'url' => $url , 'description' => $description , 'tags' => $tags , 'private' => 0 );
1101 list ( $editform , $onload )= templateEditForm ( $link , $link_is_new );
1102 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
1103 templatePage ( $data );
1107 // -------- Export as Netscape Bookmarks HTML file.
1108 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=export' ))
1110 if ( empty ( $_GET [ 'what' ]))
1113 <div id="headerform"><br>
1114 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
1115 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
1116 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
1119 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
1120 templatePage ( $data );
1123 $exportWhat = $_GET [ 'what' ];
1124 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export ???' );
1126 header ( 'Content-Type: text/html; charset=utf-8' );
1127 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1129 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1130 <!-- This is an automatically generated file.
1131 It will be read and overwritten.
1133 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1134 <TITLE>Bookmarks</TITLE>
1137 foreach ( $LINKSDB as $link )
1139 if ( $exportWhat == 'all' ||
1140 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1141 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1143 echo '<DT><A HREF="' . htmlspecialchars ( $link [ 'url' ]). '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1144 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . htmlspecialchars ( str_replace ( ' ' , ',' , $link [ 'tags' ])). '"' ;
1145 echo '>' . htmlspecialchars ( $link [ 'title' ]). "</A> \n " ;
1146 if ( $link [ 'description' ]!= '' ) echo '<DD>' . htmlspecialchars ( $link [ 'description' ]). " \n " ;
1149 echo '<!-- Shaarli ' . $exportWhat . ' bookmarks export on ' . date ( 'Y/m/d H:i:s' ). "--> \n " ;
1153 // -------- User is uploading a file for import
1154 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1156 // If file is too big, some form field may be missing.
1157 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1159 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1160 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>' ;
1163 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1168 // -------- Show upload/import dialog:
1169 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=import' ))
1171 $token = getToken ();
1172 $maxfilesize = getMaxFileSize ();
1173 $onload = 'onload="document.uploadform.filetoupload.focus();"' ;
1175 <div id="headerform">
1176 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
1177 <form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
1178 <input type="hidden" name="token" value=" {$token} ">
1179 <input type="file" name="filetoupload" size="80">
1180 <input type="hidden" name="MAX_FILE_SIZE" value=" {$maxfilesize} ">
1181 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
1182 <input type="checkbox" name="private"> Import all links as private<br>
1183 <input type="checkbox" name="overwrite"> Overwrite existing links
1187 $data = array ( 'pageheader' => $uploadform , 'body' => '' , 'onload' => $onload );
1188 templatePage ( $data );
1192 // -------- Otherwise, simply display search form and links:
1194 <div id="headerform" style="width:100%; white-space:nowrap;";>
1195 <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>
1196 <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>
1199 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => '' );
1200 templatePage ( $data );
1204 // -----------------------------------------------------------------------------------------------
1205 // Process the import file form.
1206 function importFile ()
1209 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1210 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1211 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1212 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private ?
1213 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones ?
1218 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1220 // Then import the bookmarks.
1221 if ( $type == 'netscape' )
1223 // This is a standard Netscape-style bookmark file.
1224 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1225 // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
1226 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1228 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1229 $d = explode ( '<DD>' , $html );
1230 if ( startswith ( $d [ 0 ], '<A ' ))
1232 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1233 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1234 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1235 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1236 foreach ( $matches as $m )
1238 $attr = $m [ 1 ]; $value = $m [ 2 ];
1239 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1240 elseif ( $attr == 'ADD_DATE' ) $link [ 'linkdate' ]= date ( 'Ymd_His' , intval ( $value ));
1241 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1242 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1244 if ( $link [ 'linkdate' ]!= '' && $link [ 'url' ]!= '' && ( $overwrite || empty ( $LINKSDB [ $link [ 'linkdate' ]])))
1246 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1247 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1254 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1258 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1262 // -----------------------------------------------------------------------------------------------
1263 /* Template for the edit link form
1264 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
1265 Output: An array : (string) : The html code of the edit link form.
1266 (string) : The proper onload to use in body.
1267 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
1270 function templateEditForm ( $link , $link_is_new = false )
1272 $url = htmlspecialchars ( $link [ 'url' ]);
1273 $title = htmlspecialchars ( $link [ 'title' ]);
1274 $tags = htmlspecialchars ( $link [ 'tags' ]);
1275 $description = htmlspecialchars ( $link [ 'description' ]);
1276 $private = ( $link [ 'private' ]== 0 ? '' : 'checked="yes"' );
1278 // Automatically focus on empty fields:
1279 $onload = 'onload="document.linkform.lf_tags.focus();"' ;
1280 if ( $description == '' ) $onload = 'onload="document.linkform.lf_description.focus();"' ;
1281 if ( $title == '' ) $onload = 'onload="document.linkform.lf_title.focus();"' ;
1283 // Do not show "Delete" button if this is a new link.
1284 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">' ;
1285 if ( $link_is_new ) $delete_button = '' ;
1287 $token = getToken (); // XSRF protection.
1288 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
1289 $editlinkform = <<<HTML
1290 <div id="editlinkform">
1291 <form method="post" name="linkform">
1292 <input type="hidden" name="lf_linkdate" value=" {$link['linkdate']} ">
1293 <i>URL</i><br><input type="text" name="lf_url" value=" {$url} " style="width:100%"><br>
1294 <i>Title</i><br><input type="text" name="lf_title" value=" {$title} " style="width:100%"><br>
1295 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%"> {$description} </textarea><br>
1296 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value=" {$tags} " style="width:100%"><br>
1297 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private"> <i>Private</i><br>
1298 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1299 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1301 <input type="hidden" name="token" value=" {$token} ">
1306 return array ( $editlinkform , $onload );
1310 // -----------------------------------------------------------------------------------------------
1311 // Template for the list of links.
1312 // Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1313 function templateLinkList ()
1317 // Search according to entered search terms:
1318 $linksToDisplay = array ();
1320 if (! empty ( $_GET [ 'searchterm' ])) // Fulltext search
1322 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1323 $searched = count ( $linksToDisplay ). ' results for <i>' . htmlspecialchars ( trim ( $_GET [ 'searchterm' ])). '</i>:' ;
1325 elseif (! empty ( $_GET [ 'searchtags' ])) // Search by tag
1327 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1328 $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> ' ;
1329 $searched = '' . count ( $linksToDisplay ). ' results for tags ' . $tagshtml . ':' ;
1331 elseif ( preg_match ( '/[a-zA-Z0-9-_@] {6} /' , $_SERVER [ "QUERY_STRING" ])) // Detect smallHashes in URL
1333 $linksToDisplay = $LINKSDB- > filterSmallHash ( $_SERVER [ "QUERY_STRING" ]);
1336 $linksToDisplay = $LINKSDB ; // otherwise, display without filtering.
1337 if ( $searched != '' ) $searched = '<div id="searchcriteria">' . $searched . '</div>' ;
1342 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1343 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1344 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1346 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks php.
1348 // If there is only a single link, we change on-the-fly the title of the page.
1349 if ( count ( $linksToDisplay )== 1 ) $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1351 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1352 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1353 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1354 $page = ( $page < 1 ? 1 : $page );
1355 $page = ( $page > $pagecount ? $pagecount : $page );
1356 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1357 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1358 $redir = empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ]; // optional redirector URL
1360 while ( $i < $end && $i < count ( $keys ))
1362 $link = $linksToDisplay [ $keys [ $i ]];
1363 $description = text2clickable ( htmlspecialchars ( $link [ 'description' ]));
1364 $title = $link [ 'title' ];
1365 $classprivate = ( $link [ 'private' ]== 0 ? '' : 'class="private"' );
1366 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>' ;
1368 if ( $link [ 'tags' ]!= '' )
1370 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { $tags
.= '<span class="linktag" title="Add tag"><a href="?addtag=' . htmlspecialchars ( $tag
). '">' . htmlspecialchars ( $tag
). '</a></span> ' ; }
1371 $tags = '<div class="linktaglist">' . $tags . '</div>' ;
1373 $linklist .= '<li ' . $classprivate . '><div class="thumbnail">' . thumbnail ( $link [ 'url' ]). '</div>' ;
1374 $linklist .= '<div class="linkcontainer"><span class="linktitle"><a href="' . $redir . htmlspecialchars ( $link [ 'url' ]). '">' . htmlspecialchars ( $title ). '</a></span>' . $actions . '<br>' ;
1375 if ( $description != '' ) $linklist .= '<div class="linkdescription">' . nl2br ( $description ). '</div><br>' ;
1376 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $linklist .= '<span class="linkdate" title="Permalink"><a href="?' . smallHash ( $link [ 'linkdate' ]). '">' . htmlspecialchars ( linkdate2locale ( $link [ 'linkdate' ])). ' - permalink</a> - </span>' ;
1377 else $linklist .= '<span class="linkdate" title="Short link here"><a href="?' . smallHash ( $link [ 'linkdate' ]). '">permalink</a> - </span>' ;
1378 $linklist .= '<span class="linkurl" title="Short link">' . htmlspecialchars ( $link [ 'url' ]). '</span><br>' . $tags . "</div></li> \n " ;
1383 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1384 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1386 if ( $i != count ( $keys )) $paging .= '<a href="?page=' .( $page +
1 ). $searchterm . $searchtags . '">◄Older</a>' ;
1387 $paging .= '<span style="color:#fff; padding:0 20 0 20;">page ' . $page . ' / ' . $pagecount . '</span>' ;
1388 if ( $page > 1 ) $paging .= '<a href="?page=' .( $page-1 ). $searchterm . $searchtags . '">Newer►</a>' ;
1389 $linksperpage = <<<HTML
1390 <div style="float:right; padding-right:5px;">
1391 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1392 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1394 $paging = '<div class="paging">' . $linksperpage . $paging . '</div>' ;
1395 $linklist = '<div id="linklist">' . $paging . $searched . '<ul>' . $linklist . '</ul>' . $paging . '</div>' ;
1399 // Returns the HTML code to display a thumbnail for a link.
1400 // Understands various services (youtube.com...)
1401 function thumbnail ( $url )
1403 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return '' ;
1405 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1406 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1407 // ^^^^^^^^^^^ ^^^^^^^^^^^
1408 $domain = parse_url ( $url , PHP_URL_HOST
);
1409 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1411 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1412 if (! empty ( $params [ 'v' ])) return '<a href="' . htmlspecialchars ( $url ). '"><img src="http://img.youtube.com/vi/' . htmlspecialchars ( $params [ 'v' ]). '/default.jpg" width="120" height="90"></a>' ;
1414 if ( $domain == 'imgur.com' )
1416 $path = parse_url ( $url , PHP_URL_PATH
);
1417 if ( strpos ( $path , '/r/' )== 0 ) return '<a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( basename ( $path )). 's.jpg" width="90" height="90"></a>' ;
1418 if ( strpos ( $path , '/gallery/' )== 0 ) return '<a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com' . htmlspecialchars ( substr ( $path , 8 )). 's.jpg" width="90" height="90"></a>' ;
1419 if ( substr_count ( $path , '/' )== 1 ) return '<a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( substr ( $path , 1 )). 's.jpg" width="90" height="90"></a>' ;
1421 if ( $domain == 'i.imgur.com' )
1423 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1424 if (! empty ( $pi [ 'filename' ])) return '<a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( $pi [ 'filename' ]). 's.jpg" width="90" height="90"></a>' ;
1426 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1428 if ( strpos ( $url , 'dailymotion.com/video/' ))
1430 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1431 return '<a href="' . htmlspecialchars ( $url ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a>' ;
1434 if ( endsWith ( $domain , '.imageshack.us' ))
1436 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1437 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1439 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1440 return '<a href="' . htmlspecialchars ( $url ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a>' ;
1445 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1446 // So we deport the thumbnail generation in order not to slow down page generation
1447 // (and we also cache the thumbnail)
1449 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return '' ; // If local cache is disabled, no thumbnails for services which require the use a local cache.
1451 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ) || $domain == 'vimeo.com' )
1453 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1454 return '<a href="' . htmlspecialchars ( $url ). '"><img src="?do=genthumbnail&hmac=' . htmlspecialchars ( $sign ). '&url=' . urlencode ( $url ). '" width="120" style="height:auto;"></a>' ;
1457 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1458 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1459 // But using the extension will do.
1460 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1461 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1463 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1464 return '<a href="' . htmlspecialchars ( $url ). '"><img src="?do=genthumbnail&hmac=' . htmlspecialchars ( $sign ). '&url=' . urlencode ( $url ). '" width="120" style="height:auto;"></a>' ;
1466 return '' ; // No thumbnail.
1470 // -----------------------------------------------------------------------------------------------
1471 // Template for the whole page.
1472 /* Input: $data (associative array).
1473 Keys: 'body' : body of HTML document
1474 'pageheader' : html code to show in page header (top of page)
1475 'onload' : optional onload javascript for the <body>
1477 function templatePage ( $data )
1481 $shaarli_version = shaarli_version
;
1483 $newversion = checkUpdate ();
1484 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>' ;
1485 $linkcount = count ( $LINKSDB );
1487 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ])
1489 $menu = ' <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' ;
1493 $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>' );
1495 foreach ( array ( 'pageheader' , 'body' , 'onload' ) as $k ) // make sure all required fields exist (put an empty string if not).
1497 if (! array_key_exists ( $k , $data )) $data [ $k ]= '' ;
1499 $jsincludes = '' ; $jsincludes_bottom = '' ;
1500 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] || isLoggedIn ())
1502 $source = serverUrl (). $_SERVER [ 'SCRIPT_NAME' ];
1503 $jsincludes = '<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>' ;
1504 $jsincludes_bottom = <<<JS
1505 <script language="JavaScript">
1506 $(document).ready(function()
1508 $('#lf_tags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1509 $('#searchtags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1510 $('#fromtag').autocomplete( {source:'{$source} ?ws=singletag',minLength:1});
1515 $feedurl = htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]);
1516 $searchcrits = '' ; // Search criteria
1517 if (! empty ( $_GET [ 'searchtags' ])) $searchcrits .= '&searchtags=' . $_GET [ 'searchtags' ];
1518 elseif (! empty ( $_GET [ 'searchterm' ])) $searchcrits .= '&searchterm=' . $_GET [ 'searchterm' ];
1519 $filtered_feed = ( $searchcrits == '' ? '' : 'Filtered ' );
1520 $version = shaarli_version
;
1522 $title = htmlspecialchars ( $GLOBALS [ 'title' ] );
1523 $pagetitle = htmlspecialchars ( empty ( $GLOBALS [ 'pagetitle' ]) ? $title : $GLOBALS [ 'pagetitle' ] );
1527 <title> {$pagetitle} </title>
1528 <link rel="alternate" type="application/rss+xml" href=" {$feedurl} ?do=rss {$searchcrits} " title=" {$filtered_feed} RSS Feed" />
1529 <link rel="alternate" type="application/atom+xml" href=" {$feedurl} ?do=atom {$searchcrits} " title=" {$filtered_feed} ATOM Feed" />
1530 <link type="text/css" rel="stylesheet" href="shaarli.css?version= {$version} " />
1533 <body {$data['onload']} > {$newversion}
1534 <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>
1535 <span id="shaarli_title"><a href="?"> {$title} </a></span> - <a href="?">Home</a> {$menu} <a href=" {$feedurl} ?do=rss {$searchcrits} " style="padding-left:30px;">RSS Feed</a> <a href=" {$feedurl} ?do=atom {$searchcrits} " style="padding-left:10px;">ATOM Feed</a>
1536 <a href="?do=tagcloud">Tag cloud</a> <a href="?do=picwall {$searchcrits} ">Picture wall</a>
1537 {$data['pageheader']}
1542 $exectime = round ( microtime ( true )- $STARTTIME , 4 );
1543 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>' ;
1544 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>' ;
1545 echo $jsincludes_bottom . '</body></html>' ;
1548 // -----------------------------------------------------------------------------------------------
1550 // This function should NEVER be called if the file data/config.php exists.
1553 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1554 if ( endsWith ( $_SERVER [ 'SERVER_NAME' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1556 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1559 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1560 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1561 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1562 $GLOBALS [ 'timezone' ] = $tz ;
1563 // Everything is ok, let's create config file.
1564 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
1565 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1566 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1567 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]) : $_POST [ 'title' ] );
1569 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location= \' ?do=login \' ;</script>' ;
1573 // Display config form:
1574 list ( $timezone_form , $timezone_js ) = templateTZform ();
1575 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
1577 <html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" /> ${timezone_js} </head>
1578 <body onload="document.installform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
1579 It looks like it's the first time you run Shaarli. Please configure it:<br>
1580 <form method="POST" action="" name="installform" id="installform" style="border:1px solid black; padding:10 10 10 10;">
1581 <table border="0" cellpadding="20">
1582 <tr><td><b>Login:</b></td><td><input type="text" name="setlogin" size="30"></td></tr>
1583 <tr><td><b>Password:</b></td><td><input type="password" name="setpassword" size="30"></td></tr>
1585 <tr><td><b>Page title:</b></td><td><input type="text" name="title" size="30"></td></tr>
1586 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
1588 </form></body></html>
1593 // Generates the timezone selection form and javascript.
1594 // Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1595 // Output: array(html,js)
1596 // Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1597 // Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1598 function templateTZform ( $ptz = false )
1600 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1602 // Try to split the provided timezone.
1603 if ( $ptz == false ) { $l
= timezone_identifiers_list (); $ptz
= $l
[ 0 ]; }
1604 $spos = strpos ( $ptz , '/' ); $pcontinent = substr ( $ptz , 0 , $spos ); $pcity = substr ( $ptz , $spos +
1 );
1606 // Display config form:
1607 $timezone_form = '' ;
1609 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1610 // We split the list in continents/cities.
1611 $continents = array ();
1613 foreach ( timezone_identifiers_list () as $tz )
1615 if ( $tz == 'UTC' ) $tz = 'UTC/UTC' ;
1616 $spos = strpos ( $tz , '/' );
1619 $continent = substr ( $tz , 0 , $spos ); $city = substr ( $tz , $spos +
1 );
1620 $continents [ $continent ]= 1 ;
1621 if (! isset ( $cities [ $continent ])) $cities [ $continent ]= array ();
1622 $cities [ $continent ].= '<option value="' . $city . '"' .( $pcity == $city ? 'selected' : '' ). '>' . $city . '</option>' ;
1625 $continents_html = '' ;
1626 $continents = array_keys ( $continents );
1627 foreach ( $continents as $continent )
1628 $continents_html .= '<option value="' . $continent . '"' .( $pcontinent == $continent ? 'selected' : '' ). '>' . $continent . '</option>' ;
1629 $cities_html = $cities [ $pcontinent ];
1630 $timezone_form = "Continent: <select name= \" continent \" id= \" continent \" onChange= \" onChangecontinent(); \" > ${continents_html} </select><br /><br />" ;
1631 $timezone_form .= "City: <select name= \" city \" id= \" city \" > ${cities[$pcontinent]} </select><br /><br />" ;
1632 $timezone_js = "<script language= \" JavaScript \" >" ;
1633 $timezone_js .= "function onChangecontinent() {document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];} " ;
1634 $timezone_js .= "var citiescontinent = " . json_encode ( $cities ). ";" ;
1635 $timezone_js .= "</script>" ;
1636 return array ( $timezone_form , $timezone_js );
1638 return array ( '' , '' );
1641 // Tells if a timezone is valid or not.
1642 // If not valid, returns false.
1643 // If system does not support timezone list, returns false.
1644 function isTZvalid ( $continent , $city )
1646 $tz = $continent . '/' . $city ;
1647 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1649 if ( in_array ( $tz , timezone_identifiers_list ())) // it's a valid timezone ?
1656 // Webservices (for use with jQuery/jQueryUI)
1657 // eg. index.php?ws=tags&term=minecr
1658 function processWS ()
1660 if ( empty ( $_GET [ 'ws' ]) || empty ( $_GET [ 'term' ])) return ;
1661 $term = $_GET [ 'term' ];
1663 header ( 'Content-Type: application/json; charset=utf-8' );
1665 // Search in tags (case insentitive, cumulative search)
1666 if ( $_GET [ 'ws' ]== 'tags' )
1668 $tags = explode ( ' ' , str_replace ( ',' , ' ' , $term )); $last = array_pop ( $tags ); // Get the last term ("a b c d" ==> "a b c", "d")
1669 $addtags = '' ; if ( $tags ) $addtags = implode ( ' ' , $tags ). ' ' ; // We will pre-pend previous tags
1671 /* To speed up things, we store list of tags in session */
1672 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1673 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1675 if ( startsWith ( $key , $last , $case = false ) && ! in_array ( $key , $tags )) $suggested [ $addtags . $key . ' ' ]= 0 ;
1677 echo json_encode ( array_keys ( $suggested ));
1681 // Search a single tag (case sentitive, single tag search)
1682 if ( $_GET [ 'ws' ]== 'singletag' )
1684 /* To speed up things, we store list of tags in session */
1685 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1686 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1688 if ( startsWith ( $key , $term , $case = true )) $suggested [ $key ]= 0 ;
1690 echo json_encode ( array_keys ( $suggested ));
1695 // Re-write configuration file according to globals.
1696 // Requires some $GLOBALS to be set (login,hash,salt,title).
1697 // If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1698 // (otherwise, the function simply returns.)
1699 function writeConfig ()
1701 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]) && ! isLoggedIn ()) die ( 'You are not authorized to alter config.' ); // Only logged in user can alter config.
1702 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
1703 $config = '<?php $GLOBALS [ \' login \' ]=' . var_export ( $GLOBALS [ 'login' ], true ). '; $GLOBALS [ \' hash \' ]=' . var_export ( $GLOBALS [ 'hash' ], true ). '; $GLOBALS [ \' salt \' ]=' . var_export ( $GLOBALS [ 'salt' ], true ). '; ' ;
1704 $config .= ' $GLOBALS [ \' timezone \' ]=' . var_export ( $GLOBALS [ 'timezone' ], true ). '; date_default_timezone_set(' . var_export ( $GLOBALS [ 'timezone' ], true ). '); $GLOBALS [ \' title \' ]=' . var_export ( $GLOBALS [ 'title' ], true ). ';' ;
1705 $config .= ' $GLOBALS [ \' redirector \' ]=' . var_export ( $GLOBALS [ 'redirector' ], true ). '; ' ;
1707 if (! file_put_contents ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ], $config ) || strcmp ( file_get_contents ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]), $config )!= 0 )
1709 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>' ;
1714 /* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
1715 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1716 The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
1717 This function is called by passing the url:
1718 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1719 [URL] is the URL of the link (eg. a flickr page)
1720 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1721 The function below will fetch the image from the webservice and store it in the cache.
1723 function genThumbnail ()
1725 // Make sure the parameters in the URL were generated by us.
1726 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
1727 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy !' );
1729 // Let's see if we don't already have the image for this URL in the cache.
1730 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
1731 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
1732 { // We have the thumbnail, just serve it:
1733 header ( 'Content-Type: image/jpeg' );
1734 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
1737 // We may also serve a blank image (if service did not respond)
1738 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
1739 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
1741 header ( 'Content-Type: image/gif' );
1742 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
1746 // Otherwise, generate the thumbnail.
1747 $url = $_GET [ 'url' ];
1748 $domain = parse_url ( $url , PHP_URL_HOST
);
1750 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
1752 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1753 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1754 // All images in Flickr are in the form:
1755 // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
1756 // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
1757 // We want the 240x120 format, which is _m.jpg.
1758 // We search for the first image in the page which does not have the _s size,
1759 // when use the _m to get the thumbnail.
1761 // Is this a link to an image, or to a flickr page ?
1763 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
1764 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1765 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
1766 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1768 else // this is a flickr page (html)
1770 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 20 ); // Get the flickr html page.
1771 if ( strpos ( $httpstatus , '200 OK' ))
1773 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!' , $data , $matches );
1774 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1778 { // Let's download the image.
1779 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 ); // Image is 240x120, so 10 seconds to download should be enough.
1780 if ( strpos ( $httpstatus , '200 OK' ))
1782 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
1783 header ( 'Content-Type: image/jpeg' );
1790 if ( $domain == 'vimeo.com' )
1792 // This is more complex: we have to perform a HTTP request, then parse the result.
1793 // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
1794 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
1795 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://vimeo.com/api/v2/video/' . htmlspecialchars ( $vid ). '.php' , 5 );
1796 if ( strpos ( $httpstatus , '200 OK' ))
1798 $t = unserialize ( $data );
1799 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
1800 // Then we download the image and serve it to our client.
1801 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 );
1802 if ( strpos ( $httpstatus , '200 OK' ))
1804 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
1805 header ( 'Content-Type: image/jpeg' );
1812 // For all other domains, we try to download the image and make a thumbnail.
1813 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 30 ); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1814 if ( strpos ( $httpstatus , '200 OK' ))
1816 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
1817 file_put_contents ( $filepath , $data ); // Save image to cache.
1818 if ( resizeImage ( $filepath ))
1820 header ( 'Content-Type: image/jpeg' );
1821 echo file_get_contents ( $filepath );
1827 // Otherwise, return an empty image (8x8 transparent gif)
1828 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
1829 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
1830 header ( 'Content-Type: image/gif' );
1834 // Make a thumbnail of the image (to width: 120 pixels)
1835 // Returns true if success, false otherwise.
1836 function resizeImage ( $filepath )
1838 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
1840 // Trick: some stupid people rename GIF as JPEG... or else.
1841 // So we really try to open each image type whatever the extension is.
1842 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
1844 if ( strpos ( $header , 'GIF8' )== 0 ) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
1845 if ( strpos ( $header , 'PNG' )== 1 ) $im = imagecreatefrompng ( $filepath );
1846 if ( strpos ( $header , 'JFIF' )) $im = imagecreatefromjpeg ( $filepath );
1847 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
1850 $ystart = 0 ; $yheight = $h ;
1851 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
1852 $nw = 120 ; // Desired width
1853 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
1855 $im2 = imagecreatetruecolor ( $nw , $nh );
1856 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
1857 imageinterlace ( $im2 , true ); // For progressive JPEG.
1858 $tempname = $filepath . '_TEMP.jpg' ;
1859 imagejpeg ( $im2 , $tempname , 90 );
1862 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
1866 // Invalidate caches when the database is changed or the user logs out.
1867 // (eg. tags cache).
1868 function invalidateCaches ()
1870 unset ( $_SESSION [ 'tags' ]);
1873 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
1874 $LINKSDB = new linkdb ( isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]); // Read links from database (and filter private links if used it not logged in).
1875 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'ws=' )) { processWS (); exit ; } // Webservices (for jQuery/jQueryUI)
1876 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];
1877 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
1878 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }