]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
2 // Shaarli 0.0.25 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.25 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 // -------- Tag cloud
742 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tagcloud' ))
744 $tags = $LINKSDB- > allTags ();
745 // We sort tags alphabetically, then choose a font size according to count.
746 // First, find max value.
747 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
750 foreach ( $tags as $key => $value )
752 $size = max ( 40 * $value / $maxcount , 8 ); // Minimum size 8.
753 $colorvalue = 128 - ceil ( 127 * $value / $maxcount );
754 $color = 'rgb(' . $colorvalue . ',' . $colorvalue . ',' . $colorvalue . ')' ;
755 $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> ' ;
757 $cloud = '<div id="cloudtag">' . $cloud . '</div>' ;
758 $data = array ( 'pageheader' => '' , 'body' => $cloud , 'onload' => '' );
763 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
764 if ( isset ( $_GET [ 'addtag' ]))
766 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
767 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
768 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
769 $params [ 'searchtags' ] = ( empty ( $params [ 'searchtags' ]) ? trim ( $_GET [ 'addtag' ]) : trim ( $params [ 'searchtags' ]). ' ' . urlencode ( trim ( $_GET [ 'addtag' ])));
770 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
771 header ( 'Location: ?' . http_build_query ( $params ));
775 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
776 if ( isset ( $_GET [ 'removetag' ]))
778 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
779 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?' ); exit ; } // In case browser does not send HTTP_REFERER
780 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
781 if ( isset ( $params [ 'searchtags' ]))
783 $tags = explode ( ' ' , $params [ 'searchtags' ]);
784 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
785 if ( count ( $tags )== 0 ) unset ( $params [ 'searchtags' ]); else $params [ 'searchtags' ] = implode ( ' ' , $tags );
786 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
788 header ( 'Location: ?' . http_build_query ( $params ));
792 // -------- User wants to change the number of links per page (linksperpage=...)
793 if ( isset ( $_GET [ 'linksperpage' ]))
795 if ( is_numeric ( $_GET [ 'linksperpage' ])) { $_SESSION
[ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET
[ 'linksperpage' ])); }
796 header ( 'Location: ' .( empty ( $_SERVER [ 'HTTP_REFERER' ])? '?' : $_SERVER [ 'HTTP_REFERER' ]));
801 // -------- Handle other actions allowed for non-logged in users:
804 // User tries to post new link but is not loggedin:
805 // Show login screen, then redirect to ?post=...
806 if ( isset ( $_GET [ 'post' ]))
808 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.
812 // Show search form and display list of links.
814 <div id="headerform" style="width:100%; white-space:nowrap;";>
815 <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>
816 <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>
819 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => '' );
821 exit ; // Never remove this one ! All operations below are reserved for logged in user.
824 // -------- All other functions are reserved for the registered user:
826 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
827 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tools' ))
829 $pageabsaddr = serverUrl (). $_SERVER [ "SCRIPT_NAME" ]; // Why doesn't php have a built-in function for that ?
830 // The javascript code for the bookmarklet:
831 $changepwd = ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] ? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
833 <div id="headerform"><br>
835 <a href="?do=configure"><b>Configure your Shaarli</b></a> - Change Title, timezone...<br><br>
836 <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
837 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
838 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
839 <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>
842 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
847 // -------- User wants to change his/her password.
848 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changepasswd' ))
850 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
851 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
853 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
855 // Make sure old password is correct.
856 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
857 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
859 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
860 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
862 echo '<script language="JavaScript">alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
868 $changepwdform = <<<HTML
869 <form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
870 Old password: <input type="password" name="oldpassword">
871 New password: <input type="password" name="setpassword">
872 <input type="hidden" name="token" value=" {$token} ">
873 <input type="submit" name="Save" value="Save password" class="bigbutton"></form>
875 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.changepasswordform.oldpassword.focus();"' );
881 // -------- User wants to change configuration
882 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=configure' ))
884 if (! empty ( $_POST [ 'title' ]) )
886 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
888 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
889 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
890 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
891 $GLOBALS [ 'timezone' ] = $tz ;
892 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
893 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
895 echo '<script language="JavaScript">alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
901 $title = htmlspecialchars ( empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] , ENT_QUOTES
);
902 $redirector = htmlspecialchars ( empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] , ENT_QUOTES
);
903 list ( $timezone_form , $timezone_js ) = templateTZform ( $GLOBALS [ 'timezone' ]);
904 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
905 $changepwdform = <<<HTML
906 ${timezone_js} <form method="POST" action="" name="configform" id="configform"><input type="hidden" name="token" value=" {$token} ">
907 <table border="0" cellpadding="20">
908 <tr><td><b>Page title:</b></td><td><input type="text" name="title" id="title" size="50" value=" {$title} "></td></tr>
910 <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>
911 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
915 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.configform.title.focus();"' );
921 // -------- User wants to rename a tag or delete it
922 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changetag' ))
924 if ( empty ( $_POST [ 'fromtag' ]))
927 $changetagform = <<<HTML
928 <form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
929 <input type="hidden" name="token" value=" {$token} ">
930 Tag: <input type="text" name="fromtag" id="fromtag">
931 <input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
932 or <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
933 <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>
935 $data = array ( 'pageheader' => $changetagform , 'body' => '' , 'onload' => 'onload="document.changetag.fromtag.focus();"' );
939 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
941 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
943 $needle = trim ( $_POST [ 'fromtag' ]);
944 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
945 foreach ( $linksToAlter as $key => $value )
947 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
948 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
949 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
950 $LINKSDB [ $key ]= $value ;
952 $LINKSDB- > savedb (); // save to disk
954 echo '<script language="JavaScript">alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
959 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
961 $needle = trim ( $_POST [ 'fromtag' ]);
962 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
963 foreach ( $linksToAlter as $key => $value )
965 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
966 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Remplace tags value.
967 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
968 $LINKSDB [ $key ]= $value ;
970 $LINKSDB- > savedb (); // save to disk
972 echo '<script language="JavaScript">alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
977 // -------- User wants to add a link without using the bookmarklet: show form.
978 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=addlink' ))
980 $onload = 'onload="document.addform.post.focus();"' ;
981 $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>' ;
982 $data = array ( 'pageheader' => $addform , 'body' => '' , 'onload' => $onload );
987 // -------- User clicked the "Save" button when editing a link: Save link to database.
988 if ( isset ( $_POST [ 'save_edit' ]))
990 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
991 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
992 $linkdate = $_POST [ 'lf_linkdate' ];
993 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => trim ( $_POST [ 'lf_url' ]), 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
994 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
995 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
996 $LINKSDB [ $linkdate ] = $link ;
997 $LINKSDB- > savedb (); // save to disk
1000 // If we are called from the bookmarklet, we must close the popup:
1001 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1002 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1003 header ( 'Location: ' . $returnurl ); // After saving the link, redirect to the page the user was on.
1007 // -------- User clicked the "Cancel" button when editing a link.
1008 if ( isset ( $_POST [ 'cancel_edit' ]))
1010 // If we are called from the bookmarklet, we must close the popup;
1011 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1012 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1013 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1017 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
1018 if ( isset ( $_POST [ 'delete_link' ]))
1020 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1021 // We do not need to ask for confirmation:
1022 // - confirmation is handled by javascript
1023 // - we are protected from XSRF by the token.
1024 $linkdate = $_POST [ 'lf_linkdate' ];
1025 unset ( $LINKSDB [ $linkdate ]);
1026 $LINKSDB- > savedb (); // save to disk
1028 // If we are called from the bookmarklet, we must close the popup:
1029 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1030 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1031 header ( 'Location: ' . $returnurl ); // After deleting the link, redirect to the page the user was on.
1035 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1036 if ( isset ( $_GET [ 'edit_link' ]))
1038 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1039 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1040 list ( $editform , $onload )= templateEditForm ( $link );
1041 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
1042 templatePage ( $data );
1046 // -------- User want to post a new link: Display link edit form.
1047 if ( isset ( $_GET [ 'post' ]))
1051 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
1052 $i = strpos ( $url , '&utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
1053 $i = strpos ( $url , '?utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
1054 $i = strpos ( $url , '#xtor=RSS-' ); if ( $i ) $url = substr ( $url , 0 , $i );
1056 $link_is_new = false ;
1057 $link = $LINKSDB- > getLinkFromUrl ( $url ); // Check if URL is not already in database (in this case, we will edit the existing link)
1060 $link_is_new = true ; // This is a new link
1061 $linkdate = strval ( date ( 'Ymd_His' ));
1062 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] ); // Get title if it was provided in URL (by the bookmarklet).
1063 $description = '' ; $tags = '' ; $private = 0 ;
1064 if (( $url != '' ) && parse_url ( $url , PHP_URL_SCHEME
)== '' ) $url = 'http://' . $url ;
1065 // 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.)
1066 if ( empty ( $title ) && parse_url ( $url , PHP_URL_SCHEME
)== 'http' )
1068 list ( $status , $headers , $data ) = getHTTP ( $url , 4 ); // Short timeout to keep the application responsive.
1069 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1070 if ( strpos ( $status , '200 OK' )) $title = html_entity_decode ( html_extract_title ( $data ), ENT_QUOTES
, 'UTF-8' );
1072 if ( $url == '' ) $url = '?' . smallHash ( $linkdate ); // In case of empty URL, this is just a text (with a link that point to itself)
1073 $link = array ( 'linkdate' => $linkdate , 'title' => $title , 'url' => $url , 'description' => $description , 'tags' => $tags , 'private' => 0 );
1075 list ( $editform , $onload )= templateEditForm ( $link , $link_is_new );
1076 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
1077 templatePage ( $data );
1081 // -------- Export as Netscape Bookmarks HTML file.
1082 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=export' ))
1084 if ( empty ( $_GET [ 'what' ]))
1087 <div id="headerform"><br>
1088 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
1089 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
1090 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
1093 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
1094 templatePage ( $data );
1097 $exportWhat = $_GET [ 'what' ];
1098 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export ???' );
1100 header ( 'Content-Type: text/html; charset=utf-8' );
1101 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1103 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1104 <!-- This is an automatically generated file.
1105 It will be read and overwritten.
1107 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1108 <TITLE>Bookmarks</TITLE>
1111 foreach ( $LINKSDB as $link )
1113 if ( $exportWhat == 'all' ||
1114 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1115 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1117 echo '<DT><A HREF="' . htmlspecialchars ( $link [ 'url' ]). '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1118 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . htmlspecialchars ( str_replace ( ' ' , ',' , $link [ 'tags' ])). '"' ;
1119 echo '>' . htmlspecialchars ( $link [ 'title' ]). "</A> \n " ;
1120 if ( $link [ 'description' ]!= '' ) echo '<DD>' . htmlspecialchars ( $link [ 'description' ]). " \n " ;
1123 echo '<!-- Shaarli ' . $exportWhat . ' bookmarks export on ' . date ( 'Y/m/d H:i:s' ). "--> \n " ;
1127 // -------- User is uploading a file for import
1128 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1130 // If file is too big, some form field may be missing.
1131 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1133 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1134 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>' ;
1137 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1142 // -------- Show upload/import dialog:
1143 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=import' ))
1145 $token = getToken ();
1146 $maxfilesize = getMaxFileSize ();
1147 $onload = 'onload="document.uploadform.filetoupload.focus();"' ;
1149 <div id="headerform">
1150 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
1151 <form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
1152 <input type="hidden" name="token" value=" {$token} ">
1153 <input type="file" name="filetoupload" size="80">
1154 <input type="hidden" name="MAX_FILE_SIZE" value=" {$maxfilesize} ">
1155 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
1156 <input type="checkbox" name="private"> Import all links as private<br>
1157 <input type="checkbox" name="overwrite"> Overwrite existing links
1161 $data = array ( 'pageheader' => $uploadform , 'body' => '' , 'onload' => $onload );
1162 templatePage ( $data );
1166 // -------- Otherwise, simply display search form and links:
1168 <div id="headerform" style="width:100%; white-space:nowrap;";>
1169 <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>
1170 <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>
1173 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => '' );
1174 templatePage ( $data );
1178 // -----------------------------------------------------------------------------------------------
1179 // Process the import file form.
1180 function importFile ()
1183 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1184 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1185 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1186 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private ?
1187 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones ?
1192 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1194 // Then import the bookmarks.
1195 if ( $type == 'netscape' )
1197 // This is a standard Netscape-style bookmark file.
1198 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1199 // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
1200 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1202 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1203 $d = explode ( '<DD>' , $html );
1204 if ( startswith ( $d [ 0 ], '<A ' ))
1206 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1207 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1208 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1209 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1210 foreach ( $matches as $m )
1212 $attr = $m [ 1 ]; $value = $m [ 2 ];
1213 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1214 elseif ( $attr == 'ADD_DATE' ) $link [ 'linkdate' ]= date ( 'Ymd_His' , intval ( $value ));
1215 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1216 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1218 if ( $link [ 'linkdate' ]!= '' && $link [ 'url' ]!= '' && ( $overwrite || empty ( $LINKSDB [ $link [ 'linkdate' ]])))
1220 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1221 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1228 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1232 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1236 // -----------------------------------------------------------------------------------------------
1237 /* Template for the edit link form
1238 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
1239 Output: An array : (string) : The html code of the edit link form.
1240 (string) : The proper onload to use in body.
1241 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
1244 function templateEditForm ( $link , $link_is_new = false )
1246 $url = htmlspecialchars ( $link [ 'url' ]);
1247 $title = htmlspecialchars ( $link [ 'title' ]);
1248 $tags = htmlspecialchars ( $link [ 'tags' ]);
1249 $description = htmlspecialchars ( $link [ 'description' ]);
1250 $private = ( $link [ 'private' ]== 0 ? '' : 'checked="yes"' );
1252 // Automatically focus on empty fields:
1253 $onload = 'onload="document.linkform.lf_tags.focus();"' ;
1254 if ( $description == '' ) $onload = 'onload="document.linkform.lf_description.focus();"' ;
1255 if ( $title == '' ) $onload = 'onload="document.linkform.lf_title.focus();"' ;
1257 // Do not show "Delete" button if this is a new link.
1258 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">' ;
1259 if ( $link_is_new ) $delete_button = '' ;
1261 $token = getToken (); // XSRF protection.
1262 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
1263 $editlinkform = <<<HTML
1264 <div id="editlinkform">
1265 <form method="post" name="linkform">
1266 <input type="hidden" name="lf_linkdate" value=" {$link['linkdate']} ">
1267 <i>URL</i><br><input type="text" name="lf_url" value=" {$url} " style="width:100%"><br>
1268 <i>Title</i><br><input type="text" name="lf_title" value=" {$title} " style="width:100%"><br>
1269 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%"> {$description} </textarea><br>
1270 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value=" {$tags} " style="width:100%"><br>
1271 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private"> <i>Private</i><br>
1272 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1273 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1275 <input type="hidden" name="token" value=" {$token} ">
1280 return array ( $editlinkform , $onload );
1284 // -----------------------------------------------------------------------------------------------
1285 // Template for the list of links.
1286 // Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1287 function templateLinkList ()
1291 // Search according to entered search terms:
1292 $linksToDisplay = array ();
1294 if (! empty ( $_GET [ 'searchterm' ])) // Fulltext search
1296 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1297 $searched = count ( $linksToDisplay ). ' results for <i>' . htmlspecialchars ( trim ( $_GET [ 'searchterm' ])). '</i>:' ;
1299 elseif (! empty ( $_GET [ 'searchtags' ])) // Search by tag
1301 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1302 $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> ' ;
1303 $searched = '' . count ( $linksToDisplay ). ' results for tags ' . $tagshtml . ':' ;
1305 elseif ( preg_match ( '/[a-zA-Z0-9-_@] {6} /' , $_SERVER [ "QUERY_STRING" ])) // Detect smallHashes in URL
1307 $linksToDisplay = $LINKSDB- > filterSmallHash ( $_SERVER [ "QUERY_STRING" ]);
1310 $linksToDisplay = $LINKSDB ; // otherwise, display without filtering.
1311 if ( $searched != '' ) $searched = '<div id="searchcriteria">' . $searched . '</div>' ;
1316 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1317 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1318 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1320 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks php.
1322 // If there is only a single link, we change on-the-fly the title of the page.
1323 if ( count ( $linksToDisplay )== 1 ) $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1325 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1326 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1327 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1328 $page = ( $page < 1 ? 1 : $page );
1329 $page = ( $page > $pagecount ? $pagecount : $page );
1330 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1331 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1332 $redir = empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ]; // optional redirector URL
1334 while ( $i < $end && $i < count ( $keys ))
1336 $link = $linksToDisplay [ $keys [ $i ]];
1337 $description = text2clickable ( htmlspecialchars ( $link [ 'description' ]));
1338 $title = $link [ 'title' ];
1339 $classprivate = ( $link [ 'private' ]== 0 ? '' : 'class="private"' );
1340 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>' ;
1342 if ( $link [ 'tags' ]!= '' )
1344 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { $tags
.= '<span class="linktag" title="Add tag"><a href="?addtag=' . htmlspecialchars ( $tag
). '">' . htmlspecialchars ( $tag
). '</a></span> ' ; }
1345 $tags = '<div class="linktaglist">' . $tags . '</div>' ;
1347 $linklist .= '<li ' . $classprivate . '>' . thumbnail ( $link [ 'url' ]);
1348 $linklist .= '<div class="linkcontainer"><span class="linktitle"><a href="' . $redir . htmlspecialchars ( $link [ 'url' ]). '">' . htmlspecialchars ( $title ). '</a></span>' . $actions . '<br>' ;
1349 if ( $description != '' ) $linklist .= '<div class="linkdescription">' . nl2br ( $description ). '</div><br>' ;
1350 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $linklist .= '<span class="linkdate" title="Short link here"><a href="?' . smallHash ( $link [ 'linkdate' ]). '">' . htmlspecialchars ( linkdate2locale ( $link [ 'linkdate' ])). ' </a> - </span>' ;
1351 else $linklist .= '<span class="linkdate" title="Short link here"><a href="?' . smallHash ( $link [ 'linkdate' ]). '">link</a> - </span>' ;
1352 $linklist .= '<span class="linkurl" title="Short link">' . htmlspecialchars ( $link [ 'url' ]). '</span><br>' . $tags . "</div></li> \n " ;
1357 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1358 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1360 if ( $i != count ( $keys )) $paging .= '<a href="?page=' .( $page +
1 ). $searchterm . $searchtags . '">◄Older</a>' ;
1361 $paging .= '<span style="color:#fff; padding:0 20 0 20;">page ' . $page . ' / ' . $pagecount . '</span>' ;
1362 if ( $page > 1 ) $paging .= '<a href="?page=' .( $page-1 ). $searchterm . $searchtags . '">Newer►</a>' ;
1363 $linksperpage = <<<HTML
1364 <div style="float:right; padding-right:5px;">
1365 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1366 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1368 $paging = '<div class="paging">' . $linksperpage . $paging . '</div>' ;
1369 $linklist = '<div id="linklist">' . $paging . $searched . '<ul>' . $linklist . '</ul>' . $paging . '</div>' ;
1373 // Returns the HTML code to display a thumbnail for a link.
1374 // Understands various services (youtube.com...)
1375 function thumbnail ( $url )
1377 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return '' ;
1379 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1380 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1381 // ^^^^^^^^^^^ ^^^^^^^^^^^
1382 $domain = parse_url ( $url , PHP_URL_HOST
);
1383 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1385 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1386 if (! empty ( $params [ 'v' ])) return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="http://img.youtube.com/vi/' . htmlspecialchars ( $params [ 'v' ]). '/default.jpg" width="120" height="90"></a></div>' ;
1388 if ( $domain == 'imgur.com' )
1390 $path = parse_url ( $url , PHP_URL_PATH
);
1391 if ( substr_count ( $path , '/' )== 1 ) return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( substr ( $path , 1 )). 's.jpg" width="90" height="90"></a></div>' ;
1392 if ( strpos ( $path , '/gallery/' )== 0 ) return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com' . htmlspecialchars ( substr ( $path , 8 )). 's.jpg" width="90" height="90"></a></div>' ;
1394 if ( $domain == 'i.imgur.com' )
1396 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1397 if (! empty ( $pi [ 'filename' ])) return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( $pi [ 'filename' ]). 's.jpg" width="90" height="90"></a></div>' ;
1399 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1401 if ( strpos ( $url , 'dailymotion.com/video/' ))
1403 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1404 return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a></div>' ;
1407 if ( endsWith ( $domain , '.imageshack.us' ))
1409 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1410 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1412 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1413 return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a></div>' ;
1418 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1419 // So we deport the thumbnail generation in order not to slow down page generation
1420 // (and we also cache the thumbnail)
1422 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return '' ; // If local cache is disabled, no thumbnails for services which require the use a local cache.
1424 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ) || $domain == 'vimeo.com' )
1426 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1427 return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="?do=genthumbnail&hmac=' . htmlspecialchars ( $sign ). '&url=' . urlencode ( $url ). '" width="120" style="height:auto;"></a></div>' ;
1430 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1431 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1432 // But using the extension will do.
1433 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1434 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1436 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1437 return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="?do=genthumbnail&hmac=' . htmlspecialchars ( $sign ). '&url=' . urlencode ( $url ). '" width="120" style="height:auto;"></a></div>' ;
1439 return '' ; // No thumbnail.
1443 // -----------------------------------------------------------------------------------------------
1444 // Template for the whole page.
1445 /* Input: $data (associative array).
1446 Keys: 'body' : body of HTML document
1447 'pageheader' : html code to show in page header (top of page)
1448 'onload' : optional onload javascript for the <body>
1450 function templatePage ( $data )
1454 $shaarli_version = shaarli_version
;
1456 $newversion = checkUpdate ();
1457 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>' ;
1458 $linkcount = count ( $LINKSDB );
1460 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ])
1462 $menu = ' <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' ;
1466 $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>' );
1468 foreach ( array ( 'pageheader' , 'body' , 'onload' ) as $k ) // make sure all required fields exist (put an empty string if not).
1470 if (! array_key_exists ( $k , $data )) $data [ $k ]= '' ;
1472 $jsincludes = '' ; $jsincludes_bottom = '' ;
1473 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] || isLoggedIn ())
1475 $source = serverUrl (). $_SERVER [ 'SCRIPT_NAME' ];
1476 $jsincludes = '<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>' ;
1477 $jsincludes_bottom = <<<JS
1478 <script language="JavaScript">
1479 $(document).ready(function()
1481 $('#lf_tags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1482 $('#searchtags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1483 $('#fromtag').autocomplete( {source:'{$source} ?ws=singletag',minLength:1});
1488 $feedurl = htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]);
1490 if (! empty ( $_GET [ 'searchtags' ])) $feedsearch .= '&searchtags=' . $_GET [ 'searchtags' ];
1491 elseif (! empty ( $_GET [ 'searchterm' ])) $feedsearch .= '&searchterm=' . $_GET [ 'searchterm' ];
1492 $filtered_feed = ( $feedsearch == '' ? '' : 'Filtered ' );
1493 $version = shaarli_version
;
1495 $title = htmlspecialchars ( $GLOBALS [ 'title' ] );
1496 $pagetitle = htmlspecialchars ( empty ( $GLOBALS [ 'pagetitle' ]) ? $title : $GLOBALS [ 'pagetitle' ] );
1500 <title> {$pagetitle} </title>
1501 <link rel="alternate" type="application/rss+xml" href=" {$feedurl} ?do=rss {$feedsearch} " title=" {$filtered_feed} RSS Feed" />
1502 <link rel="alternate" type="application/atom+xml" href=" {$feedurl} ?do=atom {$feedsearch} " title=" {$filtered_feed} ATOM Feed" />
1503 <link type="text/css" rel="stylesheet" href="shaarli.css?version= {$version} " />
1506 <body {$data['onload']} > {$newversion}
1507 <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>
1508 <span id="shaarli_title"><a href="?"> {$title} </a></span> - <a href="?">Home</a> {$menu} <a href=" {$feedurl} ?do=rss {$feedsearch} " style="padding-left:30px;">RSS Feed</a> <a href=" {$feedurl} ?do=atom {$feedsearch} " style="padding-left:10px;">ATOM Feed</a>
1509 <a href="?do=tagcloud">Tag cloud</a>
1510 {$data['pageheader']}
1515 $exectime = round ( microtime ( true )- $STARTTIME , 4 );
1516 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>' ;
1517 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>' ;
1518 echo $jsincludes_bottom . '</body></html>' ;
1521 // -----------------------------------------------------------------------------------------------
1523 // This function should NEVER be called if the file data/config.php exists.
1526 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1527 if ( endsWith ( $_SERVER [ 'SERVER_NAME' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1529 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1532 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1533 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1534 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1535 $GLOBALS [ 'timezone' ] = $tz ;
1536 // Everything is ok, let's create config file.
1537 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
1538 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1539 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1540 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]) : $_POST [ 'title' ] );
1542 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location= \' ?do=login \' ;</script>' ;
1546 // Display config form:
1547 list ( $timezone_form , $timezone_js ) = templateTZform ();
1548 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
1550 <html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" /> ${timezone_js} </head>
1551 <body onload="document.installform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
1552 It looks like it's the first time you run Shaarli. Please configure it:<br>
1553 <form method="POST" action="" name="installform" id="installform" style="border:1px solid black; padding:10 10 10 10;">
1554 <table border="0" cellpadding="20">
1555 <tr><td><b>Login:</b></td><td><input type="text" name="setlogin" size="30"></td></tr>
1556 <tr><td><b>Password:</b></td><td><input type="password" name="setpassword" size="30"></td></tr>
1558 <tr><td><b>Page title:</b></td><td><input type="text" name="title" size="30"></td></tr>
1559 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
1561 </form></body></html>
1566 // Generates the timezone selection form and javascript.
1567 // Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1568 // Output: array(html,js)
1569 // Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1570 // Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1571 function templateTZform ( $ptz = false )
1573 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1575 // Try to split the provided timezone.
1576 if ( $ptz == false ) { $l
= timezone_identifiers_list (); $ptz
= $l
[ 0 ]; }
1577 $spos = strpos ( $ptz , '/' ); $pcontinent = substr ( $ptz , 0 , $spos ); $pcity = substr ( $ptz , $spos +
1 );
1579 // Display config form:
1580 $timezone_form = '' ;
1582 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1583 // We split the list in continents/cities.
1584 $continents = array ();
1586 foreach ( timezone_identifiers_list () as $tz )
1588 if ( $tz == 'UTC' ) $tz = 'UTC/UTC' ;
1589 $spos = strpos ( $tz , '/' );
1592 $continent = substr ( $tz , 0 , $spos ); $city = substr ( $tz , $spos +
1 );
1593 $continents [ $continent ]= 1 ;
1594 if (! isset ( $cities [ $continent ])) $cities [ $continent ]= array ();
1595 $cities [ $continent ].= '<option value="' . $city . '"' .( $pcity == $city ? 'selected' : '' ). '>' . $city . '</option>' ;
1598 $continents_html = '' ;
1599 $continents = array_keys ( $continents );
1600 foreach ( $continents as $continent )
1601 $continents_html .= '<option value="' . $continent . '"' .( $pcontinent == $continent ? 'selected' : '' ). '>' . $continent . '</option>' ;
1602 $cities_html = $cities [ $pcontinent ];
1603 $timezone_form = "Continent: <select name= \" continent \" id= \" continent \" onChange= \" onChangecontinent(); \" > ${continents_html} </select><br /><br />" ;
1604 $timezone_form .= "City: <select name= \" city \" id= \" city \" > ${cities[$pcontinent]} </select><br /><br />" ;
1605 $timezone_js = "<script language= \" JavaScript \" >" ;
1606 $timezone_js .= "function onChangecontinent() {document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];} " ;
1607 $timezone_js .= "var citiescontinent = " . json_encode ( $cities ). ";" ;
1608 $timezone_js .= "</script>" ;
1609 return array ( $timezone_form , $timezone_js );
1611 return array ( '' , '' );
1614 // Tells if a timezone is valid or not.
1615 // If not valid, returns false.
1616 // If system does not support timezone list, returns false.
1617 function isTZvalid ( $continent , $city )
1619 $tz = $continent . '/' . $city ;
1620 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1622 if ( in_array ( $tz , timezone_identifiers_list ())) // it's a valid timezone ?
1629 // Webservices (for use with jQuery/jQueryUI)
1630 // eg. index.php?ws=tags&term=minecr
1631 function processWS ()
1633 if ( empty ( $_GET [ 'ws' ]) || empty ( $_GET [ 'term' ])) return ;
1634 $term = $_GET [ 'term' ];
1636 header ( 'Content-Type: application/json; charset=utf-8' );
1638 // Search in tags (case insentitive, cumulative search)
1639 if ( $_GET [ 'ws' ]== 'tags' )
1641 $tags = explode ( ' ' , str_replace ( ',' , ' ' , $term )); $last = array_pop ( $tags ); // Get the last term ("a b c d" ==> "a b c", "d")
1642 $addtags = '' ; if ( $tags ) $addtags = implode ( ' ' , $tags ). ' ' ; // We will pre-pend previous tags
1644 /* To speed up things, we store list of tags in session */
1645 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1646 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1648 if ( startsWith ( $key , $last , $case = false ) && ! in_array ( $key , $tags )) $suggested [ $addtags . $key . ' ' ]= 0 ;
1650 echo json_encode ( array_keys ( $suggested ));
1654 // Search a single tag (case sentitive, single tag search)
1655 if ( $_GET [ 'ws' ]== 'singletag' )
1657 /* To speed up things, we store list of tags in session */
1658 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1659 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1661 if ( startsWith ( $key , $term , $case = true )) $suggested [ $key ]= 0 ;
1663 echo json_encode ( array_keys ( $suggested ));
1668 // Re-write configuration file according to globals.
1669 // Requires some $GLOBALS to be set (login,hash,salt,title).
1670 // If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1671 // (otherwise, the function simply returns.)
1672 function writeConfig ()
1674 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]) && ! isLoggedIn ()) die ( 'You are not authorized to alter config.' ); // Only logged in user can alter config.
1675 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
1676 $config = '<?php $GLOBALS [ \' login \' ]=' . var_export ( $GLOBALS [ 'login' ], true ). '; $GLOBALS [ \' hash \' ]=' . var_export ( $GLOBALS [ 'hash' ], true ). '; $GLOBALS [ \' salt \' ]=' . var_export ( $GLOBALS [ 'salt' ], true ). '; ' ;
1677 $config .= ' $GLOBALS [ \' timezone \' ]=' . var_export ( $GLOBALS [ 'timezone' ], true ). '; date_default_timezone_set(' . var_export ( $GLOBALS [ 'timezone' ], true ). '); $GLOBALS [ \' title \' ]=' . var_export ( $GLOBALS [ 'title' ], true ). ';' ;
1678 $config .= ' $GLOBALS [ \' redirector \' ]=' . var_export ( $GLOBALS [ 'redirector' ], true ). '; ' ;
1680 if (! file_put_contents ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ], $config ) || strcmp ( file_get_contents ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]), $config )!= 0 )
1682 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>' ;
1687 /* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
1688 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1689 The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
1690 This function is called by passing the url:
1691 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1692 [URL] is the URL of the link (eg. a flickr page)
1693 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1694 The function below will fetch the image from the webservice and store it in the cache.
1696 function genThumbnail ()
1698 // Make sure the parameters in the URL were generated by us.
1699 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
1700 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy !' );
1702 // Let's see if we don't already have the image for this URL in the cache.
1703 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
1704 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
1705 { // We have the thumbnail, just serve it:
1706 header ( 'Content-Type: image/jpeg' );
1707 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
1710 // We may also serve a blank image (if service did not respond)
1711 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
1712 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
1714 header ( 'Content-Type: image/gif' );
1715 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
1719 // Otherwise, generate the thumbnail.
1720 $url = $_GET [ 'url' ];
1721 $domain = parse_url ( $url , PHP_URL_HOST
);
1723 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
1725 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1726 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1727 // All images in Flickr are in the form:
1728 // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
1729 // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
1730 // We want the 240x120 format, which is _m.jpg.
1731 // We search for the first image in the page which does not have the _s size,
1732 // when use the _m to get the thumbnail.
1734 // Is this a link to an image, or to a flickr page ?
1736 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
1737 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1738 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
1739 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1741 else // this is a flickr page (html)
1743 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 20 ); // Get the flickr html page.
1744 if ( strpos ( $httpstatus , '200 OK' ))
1746 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!' , $data , $matches );
1747 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1751 { // Let's download the image.
1752 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 ); // Image is 240x120, so 10 seconds to download should be enough.
1753 if ( strpos ( $httpstatus , '200 OK' ))
1755 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
1756 header ( 'Content-Type: image/jpeg' );
1763 if ( $domain == 'vimeo.com' )
1765 // This is more complex: we have to perform a HTTP request, then parse the result.
1766 // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
1767 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
1768 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://vimeo.com/api/v2/video/' . htmlspecialchars ( $vid ). '.php' , 5 );
1769 if ( strpos ( $httpstatus , '200 OK' ))
1771 $t = unserialize ( $data );
1772 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
1773 // Then we download the image and serve it to our client.
1774 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 );
1775 if ( strpos ( $httpstatus , '200 OK' ))
1777 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
1778 header ( 'Content-Type: image/jpeg' );
1785 // For all other domains, we try to download the image and make a thumbnail.
1786 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 30 ); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1787 if ( strpos ( $httpstatus , '200 OK' ))
1789 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
1790 file_put_contents ( $filepath , $data ); // Save image to cache.
1791 if ( resizeImage ( $filepath ))
1793 header ( 'Content-Type: image/jpeg' );
1794 echo file_get_contents ( $filepath );
1800 // Otherwise, return an empty image (8x8 transparent gif)
1801 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
1802 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
1803 header ( 'Content-Type: image/gif' );
1807 // Make a thumbnail of the image (to width: 120 pixels)
1808 // Returns true if success, false otherwise.
1809 function resizeImage ( $filepath )
1811 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
1813 // Trick: some stupid people rename GIF as JPEG... or else.
1814 // So we really try to open each image type whatever the extension is.
1815 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
1817 if ( strpos ( $header , 'GIF8' )== 0 ) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
1818 if ( strpos ( $header , 'PNG' )== 1 ) $im = imagecreatefrompng ( $filepath );
1819 if ( strpos ( $header , 'JFIF' )) $im = imagecreatefromjpeg ( $filepath );
1820 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
1823 $ystart = 0 ; $yheight = $h ;
1824 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
1825 $nw = 120 ; // Desired width
1826 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
1828 $im2 = imagecreatetruecolor ( $nw , $nh );
1829 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
1830 imageinterlace ( $im2 , true ); // For progressive JPEG.
1831 $tempname = $filepath . '_TEMP.jpg' ;
1832 imagejpeg ( $im2 , $tempname , 90 );
1835 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
1839 // Invalidate caches when the database is changed or the user logs out.
1840 // (eg. tags cache).
1841 function invalidateCaches ()
1843 unset ( $_SESSION [ 'tags' ]);
1846 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
1847 $LINKSDB = new linkdb ( isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]); // Read links from database (and filter private links if used it not logged in).
1848 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'ws=' )) { processWS (); exit ; } // Webservices (for jQuery/jQueryUI)
1849 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];
1850 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
1851 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }