]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
2 // Shaarli 0.0.24 beta - Shaare your links...
3 // The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net
4 // http://sebsauvage.net/wiki/doku.php?id=php:shaarli
5 // Licence: http://www.opensource.org/licenses/zlib-license.php
9 // -----------------------------------------------------------------------------------------------
11 define ( 'DATADIR' , 'data' ); // Data subdirectory
12 define ( 'CONFIG_FILE' , DATADIR
. '/config.php' ); // Configuration file (user login/password)
13 define ( 'DATASTORE' , DATADIR
. '/datastore.php' ); // Data storage file.
14 define ( 'LINKS_PER_PAGE' , 20 ); // Default links per page.
15 define ( 'IPBANS_FILENAME' , DATADIR
. '/ipbans.php' ); // File storage for failures and bans.
16 define ( 'BAN_AFTER' , 4 ); // Ban IP after this many failures.
17 define ( 'BAN_DURATION' , 1800 ); // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
18 define ( 'OPEN_SHAARLI' , false ); // If true, anyone can add/edit/delete links without having to login
19 define ( 'HIDE_TIMESTAMPS' , false ); // If true, the moment when links were saved are not shown to users that are not logged in.
20 define ( 'ENABLE_THUMBNAILS' , true ); // Enable thumbnails in links.
21 define ( 'CACHEDIR' , 'cache' ); // Cache directory for thumbnails for SLOW services (like flickr)
23 // -----------------------------------------------------------------------------------------------
24 // Program config (touch at your own risks !)
25 define ( 'UPDATECHECK_FILENAME' , DATADIR
. '/lastupdatecheck.txt' ); // For updates check of Shaarli.
26 define ( 'UPDATECHECK_INTERVAL' , 86400 ); // Updates check frequency for Shaarli. 86400 seconds=24 hours
27 ini_set ( 'max_input_time' , '60' ); // High execution time in case of problematic imports/exports.
28 ini_set ( 'memory_limit' , '128M' ); // Try to set max upload file size and read (May not work on some hosts).
29 ini_set ( 'post_max_size' , '16M' );
30 ini_set ( 'upload_max_filesize' , '16M' );
31 define ( 'PHPPREFIX' , '<?php /* ' ); // Prefix to encapsulate data in php code.
32 define ( 'PHPSUFFIX' , ' */ ?>' ); // Suffix to encapsulate data in php code.
33 $STARTTIME = microtime ( true ); // Measure page execution time.
35 error_reporting ( E_ALL^E_WARNING
); // See all error except warnings.
36 //error_reporting(-1); // See all errors (for debugging only)
39 // In case stupid admin has left magic_quotes enabled in php.ini:
40 if ( get_magic_quotes_gpc ())
42 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
43 $_POST = array_map ( 'stripslashes_deep' , $_POST );
44 $_GET = array_map ( 'stripslashes_deep' , $_GET );
45 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
47 // Prevent caching: (yes, it's ugly)
48 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
49 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
50 header ( "Cache-Control: post-check=0, pre-check=0" , false );
51 header ( "Pragma: no-cache" );
52 define ( 'shaarli_version' , '0.0.24 beta' );
53 if (! is_dir ( DATADIR
)) { mkdir ( DATADIR
, 0705 ); chmod ( DATADIR
, 0705 ); }
54 if (! is_dir ( CACHEDIR
)) { mkdir ( CACHEDIR
, 0705 ); chmod ( CACHEDIR
, 0705 ); }
55 if (! is_file ( DATADIR
. '/.htaccess' )) { file_put_contents ( DATADIR
. '/.htaccess' , "Allow from none \n Deny from all \n " ); } // Protect data files.
56 if (! is_file ( CACHEDIR
. '/.htaccess' )) { file_put_contents ( CACHEDIR
. '/.htaccess' , "Allow from none \n Deny from all \n " ); } // Protect data files.
57 if (! is_file ( CONFIG_FILE
)) install ();
58 require CONFIG_FILE
; // Read login/password hash into $GLOBALS.
59 // Small protection against dodgy config files:
60 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]);
61 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
62 autoLocale (); // Sniff browser language and set date format accordingly.
63 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
67 function checkphpversion ()
69 if ( version_compare ( PHP_VERSION
, '5.1.0' ) < 0 )
71 header ( 'Content-Type: text/plain; charset=utf-8' );
72 echo 'Your server supports php ' . PHP_VERSION
. '. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.' ;
77 // Checks if an update is available for Shaarli.
78 // (at most once a day, and only for registered user.)
79 // Output: '' = no new version.
80 // other= the available version.
81 function checkUpdate ()
83 if (! isLoggedIn ()) return '' ; // Do not check versions for visitors.
85 // Get latest version number at most once a day.
86 if (! is_file ( UPDATECHECK_FILENAME
) || ( filemtime ( UPDATECHECK_FILENAME
)< time ()-( UPDATECHECK_INTERVAL
)))
88 $version = shaarli_version
;
89 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://sebsauvage.net/files/shaarli_version.txt' , 2 );
90 if ( strpos ( $httpstatus , '200 OK' )) $version = $data ;
91 // If failed, nevermind. We don't want to bother the user with that.
92 file_put_contents ( UPDATECHECK_FILENAME
, $version ); // touch file date
95 $newestversion = file_get_contents ( UPDATECHECK_FILENAME
);
96 if ( version_compare ( $newestversion , shaarli_version
)== 1 ) return $newestversion ;
100 // -----------------------------------------------------------------------------------------------
102 function logm ( $message )
104 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
105 file_put_contents ( DATADIR
. '/log.txt' , $t , FILE_APPEND
);
108 /* Returns the small hash of a string
109 eg. smallHash('20111006_131924') --> yZH23w
111 - are unique (well, as unique as crc32, at last)
112 - are always 6 characters long.
113 - only use the following characters: a-z A-Z 0-9 - _ @
114 - are NOT cryptographically secure (they CAN be forged)
115 In Shaarli, they are used as a tinyurl-like link to individual entries.
117 function smallHash ( $text )
119 $t = rtrim ( base64_encode ( hash ( 'crc32' , $text , true )), '=' );
120 $t = str_replace ( '+' , '-' , $t ); // Get rid of characters which need encoding in URLs.
121 $t = str_replace ( '/' , '_' , $t );
122 $t = str_replace ( '=' , '@' , $t );
126 // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
127 function text2clickable ( $url )
129 return preg_replace ( '!((?:https?|ftp)://\S+[[:alnum:]]/?)!si' , '<a href=" $1" rel="nofollow"> $1 </a> ' , $url );
131 // ------------------------------------------------------------------------------------------
132 // Sniff browser language to display dates in the right format automatically.
133 // (Note that is may not work on your server if the corresponding local is not installed.)
134 function autoLocale ()
136 $loc = 'en_US' ; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
137 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
138 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
139 if ( preg_match ( '/([a-z] {2} (-[a-z] {2} )?)/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) $loc = $matches [ 1 ];
141 setlocale ( LC_TIME
, $loc ); // LC_TIME = Set local for date/time format only.
144 // ------------------------------------------------------------------------------------------
145 // Session management
146 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
147 ini_set ( 'session.use_cookies' , 1 ); // Use cookies to store session.
148 ini_set ( 'session.use_only_cookies' , 1 ); // Force cookies for session (phpsessionID forbidden in URL)
149 ini_set ( 'session.use_trans_sid' , false ); // Prevent php to use sessionID in URL if cookies are disabled.
150 session_name ( 'shaarli' );
153 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
156 $ip = $_SERVER [ "REMOTE_ADDR" ];
157 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
158 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
159 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
163 // Check that user/password is correct.
164 function check_auth ( $login , $password )
166 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
167 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
168 { // Login/password is correct.
169 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // generate unique random number (different than phpsessionid)
170 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
171 $_SESSION [ 'username' ]= $login ;
172 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
173 logm ( 'Login successful' );
176 logm ( 'Login failed for user ' . $login );
180 // Returns true if the user is logged in.
181 function isLoggedIn ()
183 if ( OPEN_SHAARLI
) return true ;
185 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
186 if ( empty ( $_SESSION [ 'uid' ]) || $_SESSION [ 'ip' ]!= allIPs () || time ()>= $_SESSION [ 'expires_on' ])
191 if (! empty ( $_SESSION [ 'longlastingsession' ])) $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
192 else $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
198 function logout () { if ( isset ( $_SESSION
)) { unset ( $_SESSION
[ 'uid' ]); unset ( $_SESSION
[ 'ip' ]); unset ( $_SESSION
[ 'username' ]);} }
201 // ------------------------------------------------------------------------------------------
202 // Brute force protection system
203 // Several consecutive failed logins will ban the IP address for 30 minutes.
204 if (! is_file ( IPBANS_FILENAME
)) file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>" );
205 include IPBANS_FILENAME
;
206 // Signal a failed login. Will ban the IP if too many failures:
207 function ban_loginFailed ()
209 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
210 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
211 $gb [ 'FAILURES' ][ $ip ] ++
;
212 if ( $gb [ 'FAILURES' ][ $ip ]>( BAN_AFTER
- 1 ))
214 $gb [ 'BANS' ][ $ip ]= time () +BAN_DURATION
;
215 logm ( 'IP address banned from login' );
217 $GLOBALS [ 'IPBANS' ] = $gb ;
218 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
221 // Signals a successful login. Resets failed login counter.
222 function ban_loginOk ()
224 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
225 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
226 $GLOBALS [ 'IPBANS' ] = $gb ;
227 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
230 // Checks if the user CAN login. If 'true', the user can try to login.
231 function ban_canLogin ()
233 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
234 if ( isset ( $gb [ 'BANS' ][ $ip ]))
236 // User is banned. Check if the ban has expired:
237 if ( $gb [ 'BANS' ][ $ip ]<= time ())
238 { // Ban expired, user can try to login again.
240 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
241 file_put_contents ( IPBANS_FILENAME
, "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
242 return true ; // Ban has expired, user can login.
244 return false ; // User is banned.
246 return true ; // User is not banned.
249 // ------------------------------------------------------------------------------------------
250 // Process login form: Check if login/password is correct.
251 if ( isset ( $_POST [ 'login' ]))
253 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
254 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
255 { // Login/password is ok.
257 // If user wants to keep the session cookie even after the browser closes:
258 if (! empty ( $_POST [ 'longlastingsession' ]))
260 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
261 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
262 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ]); // Set session cookie expiration on client side
263 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
265 else // Standard session expiration (=when browser closes)
267 session_set_cookie_params ( 0 ); // 0 means "When browser closes"
268 session_regenerate_id ( true );
270 // Optional redirect after login:
271 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 ; }
272 if ( isset ( $_POST [ 'returnurl' ]))
274 if ( endsWith ( $_POST [ 'returnurl' ], '?do=login' )) { header ( 'Location: ?' ); exit ; } // Prevent loops over login screen.
275 header ( 'Location: ' . $_POST [ 'returnurl' ]); exit ;
277 header ( 'Location: ?' ); exit ;
282 echo '<script language="JavaScript">alert("Wrong login/password.");document.location= \' ?do=login \' ;</script>' ; // Redirect to login screen.
287 // ------------------------------------------------------------------------------------------
288 // Misc utility functions:
290 // Returns the server URL (including port and http/https), without path.
291 // eg. "http://myserver.com:8080"
292 // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
295 $serverport = ( $_SERVER [ "SERVER_PORT" ]!= '80' ? ':' . $_SERVER [ "SERVER_PORT" ] : '' );
296 return 'http' .(! empty ( $_SERVER [ 'HTTPS' ])? 's' : '' ). '://' . $_SERVER [ "SERVER_NAME" ]. $serverport ;
299 // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
300 function return_bytes ( $val )
302 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
305 case 'g' : $val *= 1024 ;
306 case 'm' : $val *= 1024 ;
307 case 'k' : $val *= 1024 ;
312 // Try to determine max file size for uploads (POST).
313 // Returns an integer (in bytes)
314 function getMaxFileSize ()
316 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
317 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
318 // Return the smaller of two:
319 $maxsize = min ( $size1 , $size2 );
320 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
324 // Tells if a string start with a substring or not.
325 function startsWith ( $haystack , $needle , $case = true )
327 if ( $case ){ return ( strcmp ( substr ( $haystack
, 0 , strlen ( $needle
)), $needle
)=== 0 );}
328 return ( strcasecmp ( substr ( $haystack , 0 , strlen ( $needle )), $needle )=== 0 );
331 // Tells if a string ends with a substring or not.
332 function endsWith ( $haystack , $needle , $case = true )
334 if ( $case ){ return ( strcmp ( substr ( $haystack
, strlen ( $haystack
) - strlen ( $needle
)), $needle
)=== 0 );}
335 return ( strcasecmp ( substr ( $haystack , strlen ( $haystack ) - strlen ( $needle )), $needle )=== 0 );
338 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
339 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
340 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
341 function linkdate2timestamp ( $linkdate )
344 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
345 return mktime ( $h , $m , $s , $M , $D , $Y );
348 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
349 (used to build the pubDate attribute in RSS feed.) */
350 function linkdate2rfc822 ( $linkdate )
352 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
355 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
356 (used to build the updated tags in ATOM feed.) */
357 function linkdate2iso8601 ( $linkdate )
359 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
362 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
363 (used to display link date on screen)
364 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
365 function linkdate2locale ( $linkdate )
367 return utf8_encode ( strftime ( '%c' , linkdate2timestamp ( $linkdate ))); // %c is for automatic date format according to locale.
368 // Note that if you use a local which is not installed on your webserver,
369 // the date will not be displayed in the chosen locale, but probably in US notation.
372 // Parse HTTP response headers and return an associative array.
373 function http_parse_headers ( $headers )
376 foreach ( $headers as $header )
378 $i = strpos ( $header , ': ' );
381 $key = substr ( $header , 0 , $i );
382 $value = substr ( $header , $i +
2 , strlen ( $header )- $i-2 );
390 Input: $url : url to get (http://...)
391 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
392 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
393 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
395 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
396 if (strpos($httpstatus,'200 OK'))
397 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
399 echo 'There was an error: '.htmlspecialchars($httpstatus)
401 function getHTTP ( $url , $timeout = 30 )
405 $options = array ( 'http' => array ( 'method' => 'GET' , 'timeout' => $timeout )); // Force network timeout
406 $context = stream_context_create ( $options );
407 $data = file_get_contents ( $url , false , $context ,- 1 , 4000000 ); // We download at most 4 Mb from source.
408 if (! $data ) { $lasterror
= error_get_last (); return array ( $lasterror
[ 'message' ], array (), '' ); }
409 $httpStatus = $http_response_header [ 0 ]; // eg. "HTTP/1.1 200 OK"
410 $responseHeaders = http_parse_headers ( $http_response_header );
411 return array ( $httpStatus , $responseHeaders , $data );
413 catch ( Exception
$e ) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
415 return array ( $e- > getMessage (), '' , '' );
419 // Extract title from an HTML document.
420 // (Returns an empty string if not found.)
421 function html_extract_title ( $html )
423 return preg_match ( '!<title>(.*?)</title>!i' , $html , $matches ) ? $matches [ 1 ] : '' ;
426 // ------------------------------------------------------------------------------------------
427 // Token management for XSRF protection
428 // Token should be used in any form which acts on data (create,update,delete,import...).
429 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
434 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // We generate a random string.
435 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
439 // Tells if a token is ok. Using this function will destroy the token.
441 function tokenOk ( $token )
443 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
445 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
446 return true ; // Token is ok.
448 return false ; // Wrong token, or already used.
451 // ------------------------------------------------------------------------------------------
452 /* Data storage for links.
453 This object behaves like an associative array.
455 $mylinks = new linkdb();
456 echo $mylinks['20110826_161819']['title'];
457 foreach($mylinks as $link)
458 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
460 We implement 3 interfaces:
461 - ArrayAccess so that this object behaves like an associative array.
462 - Iterator so that this object can be used in foreach() loops.
463 - Countable interface so that we can do a count() on this object.
465 class linkdb
implements Iterator
, Countable
, ArrayAccess
468 private $links ; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
469 private $urls ; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
470 private $keys ; // List of linkdate keys (for the Iterator interface implementation)
471 private $position ; // Position in the $this->keys array. (for the Iterator interface implementation.)
472 private $loggedin ; // Is the used logged in ? (used to filter private links)
475 function __construct ( $isLoggedIn )
476 // Input : $isLoggedIn : is the used logged in ?
478 $this- > loggedin
= $isLoggedIn ;
479 $this- > checkdb (); // Make sure data file exists.
480 $this- > readdb (); // Then read it.
483 // ---- Countable interface implementation
484 public function count () { return count ( $this
-> links
); }
486 // ---- ArrayAccess interface implementation
487 public function offsetSet ( $offset , $value )
489 if (! $this- > loggedin
) die ( 'You are not authorized to add a link.' );
490 if ( empty ( $value [ 'linkdate' ]) || empty ( $value [ 'url' ])) die ( 'Internal Error: A link should always have a linkdate and url.' );
491 if ( empty ( $offset )) die ( 'You must specify a key.' );
492 $this- > links
[ $offset ] = $value ;
493 $this- > urls
[ $value [ 'url' ]]= $offset ;
495 public function offsetExists ( $offset ) { return array_key_exists ( $offset
, $this
-> links
); }
496 public function offsetUnset ( $offset )
498 if (! $this- > loggedin
) die ( 'You are not authorized to delete a link.' );
499 $url = $this- > links
[ $offset ][ 'url' ]; unset ( $this- > urls
[ $url ]);
500 unset ( $this- > links
[ $offset ]);
502 public function offsetGet ( $offset ) { return isset ( $this
-> links
[ $offset
]) ? $this
-> links
[ $offset
] : null ; }
504 // ---- Iterator interface implementation
505 function rewind () { $this
-> keys
= array_keys ( $this
-> links
); rsort ( $this
-> keys
); $this
-> position
= 0 ; } // Start over for iteration, ordered by date (latest first).
506 function key () { return $this
-> keys
[ $this
-> position
]; } // current key
507 function current () { return $this
-> links
[ $this
-> keys
[ $this
-> position
]]; } // current value
508 function next () { ++$this
-> position
; } // go to next item
509 function valid () { return isset ( $this
-> keys
[ $this
-> position
]); } // Check if current position is valid.
512 private function checkdb () // Check if db directory and file exists.
514 if (! file_exists ( DATASTORE
)) // Create a dummy database for example.
516 $this- > links
= array ();
517 $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' );
518 $this- > links
[ $link [ 'linkdate' ]] = $link ;
519 $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' );
520 $this- > links
[ $link [ 'linkdate' ]] = $link ;
521 file_put_contents ( DATASTORE
, PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
); // Write database to disk
525 // Read database from disk to memory
526 private function readdb ()
529 $this- > links
=( file_exists ( DATASTORE
) ? unserialize ( gzinflate ( base64_decode ( substr ( file_get_contents ( DATASTORE
), strlen ( PHPPREFIX
),- strlen ( PHPSUFFIX
))))) : array () );
530 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
532 // If user is not logged in, filter private links.
533 if (! $this- > loggedin
)
536 foreach ( $this- > links
as $link ) { if ( $link
[ 'private' ]!= 0 ) $toremove
[]= $link
[ 'linkdate' ]; }
537 foreach ( $toremove as $linkdate ) { unset ( $this
-> links
[ $linkdate
]); }
540 // Keep the list of the mapping URLs-->linkdate up-to-date.
542 foreach ( $this- > links
as $link ) { $this
-> urls
[ $link
[ 'url' ]]= $link
[ 'linkdate' ]; }
545 // Save database from memory to disk.
546 public function savedb ()
548 if (! $this- > loggedin
) die ( 'You are not authorized to change the database.' );
549 file_put_contents ( DATASTORE
, PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
);
552 // Returns the link for a given URL (if it exists). false it does not exist.
553 public function getLinkFromUrl ( $url )
555 if ( isset ( $this- > urls
[ $url ])) return $this- > links
[ $this- > urls
[ $url ]];
559 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
560 // eg. print_r($mydb->filterFulltext('hollandais'));
561 public function filterFulltext ( $searchterms )
563 // FIXME: explode(' ',$searchterms) and perform a AND search.
564 // FIXME: accept double-quotes to search for a string "as is" ?
566 $s = strtolower ( $searchterms );
567 foreach ( $this- > links
as $l )
569 $found = strpos ( strtolower ( $l [ 'title' ]), $s ) || strpos ( strtolower ( $l [ 'description' ]), $s ) || strpos ( strtolower ( $l [ 'url' ]), $s ) || strpos ( strtolower ( $l [ 'tags' ]), $s );
570 if ( $found ) $filtered [ $l [ 'linkdate' ]] = $l ;
577 // You can specify one or more tags (tags can be separated by space or comma).
578 // eg. print_r($mydb->filterTags('linux programming'));
579 public function filterTags ( $tags , $casesensitive = false )
581 $t = str_replace ( ',' , ' ' ,( $casesensitive ? $tags : strtolower ( $tags )));
582 $searchtags = explode ( ' ' , $t );
584 foreach ( $this- > links
as $l )
586 $linktags = explode ( ' ' ,( $casesensitive ? $l [ 'tags' ]: strtolower ( $l [ 'tags' ])));
587 if ( count ( array_intersect ( $linktags , $searchtags )) == count ( $searchtags ))
588 $filtered [ $l [ 'linkdate' ]] = $l ;
594 // Filter by smallHash.
595 // Only 1 article is returned.
596 public function filterSmallHash ( $smallHash )
599 foreach ( $this- > links
as $l )
601 if ( $smallHash == smallHash ( $l [ 'linkdate' ])) // Yes, this is ugly and slow
603 $filtered [ $l [ 'linkdate' ]] = $l ;
610 // Returns the list of all tags
611 // Output: associative array key=tags, value=0
612 public function allTags ()
615 foreach ( $this- > links
as $link )
616 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
617 if (! empty ( $tag )) $tags [ $tag ]=( empty ( $tags [ $tag ]) ? 1 : $tags [ $tag ] +
1 );
618 arsort ( $tags ); // Sort tags by usage (most used tag first)
623 // ------------------------------------------------------------------------------------------
624 // Ouput the last 50 links in RSS 2.0 format.
629 // Optionnaly filter the results:
630 $linksToDisplay = array ();
631 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
632 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
633 else $linksToDisplay = $LINKSDB ;
635 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
636 $pageaddr = htmlspecialchars ( serverUrl (). $_SERVER [ "SCRIPT_NAME" ]);
637 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
638 echo '<channel><title>' . htmlspecialchars ( $GLOBALS [ 'title' ]). '</title><link>' . $pageaddr . '</link>' ;
639 echo '<description>Shared links</description><language></language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
641 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
642 while ( $i < 50 && $i < count ( $keys ))
644 $link = $linksToDisplay [ $keys [ $i ]];
645 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
646 echo '<item><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><guid>' . htmlspecialchars ( $link [ 'url' ]). '</guid><link>' . htmlspecialchars ( $link [ 'url' ]). '</link>' ;
647 if (! HIDE_TIMESTAMPS
|| isLoggedIn ()) echo '<pubDate>' . htmlspecialchars ( $rfc822date ). '</pubDate>' ;
648 echo '<description><![CDATA[' . nl2br ( htmlspecialchars ( $link [ 'description' ])). ']]></description></item>' . " \n " ;
651 echo '</channel></rss>' ;
655 // ------------------------------------------------------------------------------------------
656 // Ouput the last 50 links in ATOM format.
661 // Optionnaly filter the results:
662 $linksToDisplay = array ();
663 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
664 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
665 else $linksToDisplay = $LINKSDB ;
667 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
668 $pageaddr = htmlspecialchars ( serverUrl (). $_SERVER [ "SCRIPT_NAME" ]);
672 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
673 while ( $i < 50 && $i < count ( $keys ))
675 $link = $linksToDisplay [ $keys [ $i ]];
676 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
677 $latestDate = max ( $latestDate , $iso8601date );
678 $entries .= '<entry><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><link href="' . htmlspecialchars ( $link [ 'url' ]). '"/><id>' . htmlspecialchars ( $link [ 'url' ]). '</id>' ;
679 if (! HIDE_TIMESTAMPS
|| isLoggedIn ()) $entries .= '<updated>' . htmlspecialchars ( $iso8601date ). '</updated>' ;
680 $entries .= '<summary>' . nl2br ( htmlspecialchars ( $link [ 'description' ])). '</summary></entry>' . " \n " ;
683 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
684 $feed .= '<title>' . htmlspecialchars ( $GLOBALS [ 'title' ]). '</title>' ;
685 if (! HIDE_TIMESTAMPS
|| isLoggedIn ()) $feed .= '<updated>' . htmlspecialchars ( $latestDate ). '</updated>' ;
686 $feed .= '<link href="' . htmlspecialchars ( $pageaddr ). '" />' ;
687 $feed .= '<author><uri>' . htmlspecialchars ( $pageaddr ). '</uri></author>' ;
688 $feed .= '<id>' . htmlspecialchars ( $pageaddr ). '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
695 // ------------------------------------------------------------------------------------------
697 function renderPage ()
702 // 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.
703 // So I use a custom templating system.
705 // -------- Display login form.
706 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=login' ))
708 if ( OPEN_SHAARLI
) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
711 $loginform = '<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>' ;
712 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => '' );
716 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
717 $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>' ;
718 $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>' ;
719 $onload = 'onload="document.loginform.login.focus();"' ;
720 $data = array ( 'pageheader' => $loginform , 'body' => '' , 'onload' => $onload );
724 // -------- User wants to logout.
725 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
729 header ( 'Location: ?' );
733 // -------- Tag cloud
734 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tagcloud' ))
736 $tags = $LINKSDB- > allTags ();
737 // We sort tags alphabetically, then choose a font size according to count.
738 // First, find max value.
739 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
742 foreach ( $tags as $key => $value )
744 $size = max ( 40 * $value / $maxcount , 8 ); // Minimum size 8.
745 $colorvalue = 128 - ceil ( 127 * $value / $maxcount );
746 $color = 'rgb(' . $colorvalue . ',' . $colorvalue . ',' . $colorvalue . ')' ;
747 $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> ' ;
749 $cloud = '<div id="cloudtag">' . $cloud . '</div>' ;
750 $data = array ( 'pageheader' => '' , 'body' => $cloud , 'onload' => '' );
755 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
756 if ( isset ( $_GET [ 'addtag' ]))
758 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
759 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
760 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
761 $params [ 'searchtags' ] = ( empty ( $params [ 'searchtags' ]) ? trim ( $_GET [ 'addtag' ]) : trim ( $params [ 'searchtags' ]). ' ' . urlencode ( trim ( $_GET [ 'addtag' ])));
762 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
763 header ( 'Location: ?' . http_build_query ( $params ));
767 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
768 if ( isset ( $_GET [ 'removetag' ]))
770 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
771 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?' ); exit ; } // In case browser does not send HTTP_REFERER
772 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
773 if ( isset ( $params [ 'searchtags' ]))
775 $tags = explode ( ' ' , $params [ 'searchtags' ]);
776 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
777 if ( count ( $tags )== 0 ) unset ( $params [ 'searchtags' ]); else $params [ 'searchtags' ] = implode ( ' ' , $tags );
778 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
780 header ( 'Location: ?' . http_build_query ( $params ));
784 // -------- User wants to change the number of links per page (linksperpage=...)
785 if ( isset ( $_GET [ 'linksperpage' ]))
787 if ( is_numeric ( $_GET [ 'linksperpage' ])) { $_SESSION
[ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET
[ 'linksperpage' ])); }
788 header ( 'Location: ' .( empty ( $_SERVER [ 'HTTP_REFERER' ])? '?' : $_SERVER [ 'HTTP_REFERER' ]));
793 // -------- Handle other actions allowed for non-logged in users:
796 // User tries to post new link but is not loggedin:
797 // Show login screen, then redirect to ?post=...
798 if ( isset ( $_GET [ 'post' ]))
800 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.
804 // Show search form and display list of links.
806 <div id="headerform" style="width:100%; white-space:nowrap;";>
807 <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>
808 <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>
811 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => '' );
813 exit ; // Never remove this one ! All operations below are reserved for logged in user.
816 // -------- All other functions are reserved for the registered user:
818 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
819 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tools' ))
821 $pageabsaddr = serverUrl (). $_SERVER [ "SCRIPT_NAME" ]; // Why doesn't php have a built-in function for that ?
822 // The javascript code for the bookmarklet:
823 $changepwd = ( OPEN_SHAARLI
? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
825 <div id="headerform"><br>
827 <a href="?do=configure"><b>Configure your Shaarli</b></a> - Change Title, timezone...<br><br>
828 <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
829 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
830 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
831 <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>
834 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
839 // -------- User wants to change his/her password.
840 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changepasswd' ))
842 if ( OPEN_SHAARLI
) die ( 'You are not supposed to change a password on an Open Shaarli.' );
843 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
845 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
847 // Make sure old password is correct.
848 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
849 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
851 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
852 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
854 echo '<script language="JavaScript">alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
860 $changepwdform = <<<HTML
861 <form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
862 Old password: <input type="password" name="oldpassword">
863 New password: <input type="password" name="setpassword">
864 <input type="hidden" name="token" value=" {$token} ">
865 <input type="submit" name="Save" value="Save password" class="bigbutton"></form>
867 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.changepasswordform.oldpassword.focus();"' );
873 // -------- User wants to change configuration
874 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=configure' ))
876 if (! empty ( $_POST [ 'title' ]) )
878 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
880 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
881 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
882 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
883 $GLOBALS [ 'timezone' ] = $tz ;
884 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
886 echo '<script language="JavaScript">alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
892 $title = htmlspecialchars ( empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] , ENT_QUOTES
);
893 list ( $timezone_form , $timezone_js ) = templateTZform ( $GLOBALS [ 'timezone' ]);
894 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
895 $changepwdform = <<<HTML
896 ${timezone_js} <form method="POST" action="" name="configform" id="configform"><input type="hidden" name="token" value=" {$token} ">
897 <table border="0" cellpadding="20">
898 <tr><td><b>Page title:</b></td><td><input type="text" name="title" id="title" size="50" value=" {$title} "></td></tr>
900 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
904 $data = array ( 'pageheader' => $changepwdform , 'body' => '' , 'onload' => 'onload="document.configform.title.focus();"' );
910 // -------- User wants to rename a tag or delete it
911 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changetag' ))
913 if ( empty ( $_POST [ 'fromtag' ]))
916 $changetagform = <<<HTML
917 <form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
918 <input type="hidden" name="token" value=" {$token} ">
919 Tag: <input type="text" name="fromtag" id="fromtag">
920 <input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
921 or <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
922 <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>
924 $data = array ( 'pageheader' => $changetagform , 'body' => '' , 'onload' => 'onload="document.changetag.fromtag.focus();"' );
928 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
930 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
932 $needle = trim ( $_POST [ 'fromtag' ]);
933 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
934 foreach ( $linksToAlter as $key => $value )
936 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
937 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
938 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
939 $LINKSDB [ $key ]= $value ;
941 $LINKSDB- > savedb (); // save to disk
943 echo '<script language="JavaScript">alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
948 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
950 $needle = trim ( $_POST [ 'fromtag' ]);
951 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
952 foreach ( $linksToAlter as $key => $value )
954 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
955 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Remplace tags value.
956 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
957 $LINKSDB [ $key ]= $value ;
959 $LINKSDB- > savedb (); // save to disk
961 echo '<script language="JavaScript">alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
966 // -------- User wants to add a link without using the bookmarklet: show form.
967 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=addlink' ))
969 $onload = 'onload="document.addform.post.focus();"' ;
970 $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>' ;
971 $data = array ( 'pageheader' => $addform , 'body' => '' , 'onload' => $onload );
976 // -------- User clicked the "Save" button when editing a link: Save link to database.
977 if ( isset ( $_POST [ 'save_edit' ]))
979 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
980 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
981 $linkdate = $_POST [ 'lf_linkdate' ];
982 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => trim ( $_POST [ 'lf_url' ]), 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
983 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
984 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
985 $LINKSDB [ $linkdate ] = $link ;
986 $LINKSDB- > savedb (); // save to disk
989 // If we are called from the bookmarklet, we must close the popup:
990 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
991 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
992 header ( 'Location: ' . $returnurl ); // After saving the link, redirect to the page the user was on.
996 // -------- User clicked the "Cancel" button when editing a link.
997 if ( isset ( $_POST [ 'cancel_edit' ]))
999 // If we are called from the bookmarklet, we must close the popup;
1000 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1001 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1002 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1006 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
1007 if ( isset ( $_POST [ 'delete_link' ]))
1009 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1010 // We do not need to ask for confirmation:
1011 // - confirmation is handled by javascript
1012 // - we are protected from XSRF by the token.
1013 $linkdate = $_POST [ 'lf_linkdate' ];
1014 unset ( $LINKSDB [ $linkdate ]);
1015 $LINKSDB- > savedb (); // save to disk
1017 // If we are called from the bookmarklet, we must close the popup:
1018 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1019 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1020 header ( 'Location: ' . $returnurl ); // After deleting the link, redirect to the page the user was on.
1024 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1025 if ( isset ( $_GET [ 'edit_link' ]))
1027 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1028 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1029 list ( $editform , $onload )= templateEditForm ( $link );
1030 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
1031 templatePage ( $data );
1035 // -------- User want to post a new link: Display link edit form.
1036 if ( isset ( $_GET [ 'post' ]))
1040 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
1041 $i = strpos ( $url , '&utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
1042 $i = strpos ( $url , '?utm_source=' ); if ( $i ) $url = substr ( $url , 0 , $i );
1043 $i = strpos ( $url , '#xtor=RSS-' ); if ( $i ) $url = substr ( $url , 0 , $i );
1045 $link_is_new = false ;
1046 $link = $LINKSDB- > getLinkFromUrl ( $url ); // Check if URL is not already in database (in this case, we will edit the existing link)
1049 $link_is_new = true ; // This is a new link
1050 $linkdate = strval ( date ( 'Ymd_His' ));
1051 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] ); // Get title if it was provided in URL (by the bookmarklet).
1052 $description = '' ; $tags = '' ; $private = 0 ;
1053 if (( $url != '' ) && parse_url ( $url , PHP_URL_SCHEME
)== '' ) $url = 'http://' . $url ;
1054 // 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.)
1055 if ( empty ( $title ) && parse_url ( $url , PHP_URL_SCHEME
)== 'http' )
1057 list ( $status , $headers , $data ) = getHTTP ( $url , 4 ); // Short timeout to keep the application responsive.
1058 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1059 if ( strpos ( $status , '200 OK' )) $title = html_entity_decode ( html_extract_title ( $data ), ENT_QUOTES
, 'UTF-8' );
1061 if ( $url == '' ) $url = '?' . smallHash ( $linkdate ); // In case of empty URL, this is just a text (with a link that point to itself)
1062 $link = array ( 'linkdate' => $linkdate , 'title' => $title , 'url' => $url , 'description' => $description , 'tags' => $tags , 'private' => 0 );
1064 list ( $editform , $onload )= templateEditForm ( $link , $link_is_new );
1065 $data = array ( 'pageheader' => $editform , 'body' => '' , 'onload' => $onload );
1066 templatePage ( $data );
1070 // -------- Export as Netscape Bookmarks HTML file.
1071 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=export' ))
1073 if ( empty ( $_GET [ 'what' ]))
1076 <div id="headerform"><br>
1077 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
1078 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
1079 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
1082 $data = array ( 'pageheader' => $toolbar , 'body' => '' , 'onload' => '' );
1083 templatePage ( $data );
1086 $exportWhat = $_GET [ 'what' ];
1087 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export ???' );
1089 header ( 'Content-Type: text/html; charset=utf-8' );
1090 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1092 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1093 <!-- This is an automatically generated file.
1094 It will be read and overwritten.
1096 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1097 <TITLE>Bookmarks</TITLE>
1100 foreach ( $LINKSDB as $link )
1102 if ( $exportWhat == 'all' ||
1103 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1104 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1106 echo '<DT><A HREF="' . htmlspecialchars ( $link [ 'url' ]). '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1107 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . htmlspecialchars ( str_replace ( ' ' , ',' , $link [ 'tags' ])). '"' ;
1108 echo '>' . htmlspecialchars ( $link [ 'title' ]). "</A> \n " ;
1109 if ( $link [ 'description' ]!= '' ) echo '<DD>' . htmlspecialchars ( $link [ 'description' ]). " \n " ;
1112 echo '<!-- Shaarli ' . $exportWhat . ' bookmarks export on ' . date ( 'Y/m/d H:i:s' ). "--> \n " ;
1116 // -------- User is uploading a file for import
1117 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1119 // If file is too big, some form field may be missing.
1120 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1122 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1123 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>' ;
1126 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1131 // -------- Show upload/import dialog:
1132 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=import' ))
1134 $token = getToken ();
1135 $maxfilesize = getMaxFileSize ();
1136 $onload = 'onload="document.uploadform.filetoupload.focus();"' ;
1138 <div id="headerform">
1139 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
1140 <form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
1141 <input type="hidden" name="token" value=" {$token} ">
1142 <input type="file" name="filetoupload" size="80">
1143 <input type="hidden" name="MAX_FILE_SIZE" value=" {$maxfilesize} ">
1144 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
1145 <input type="checkbox" name="private"> Import all links as private<br>
1146 <input type="checkbox" name="overwrite"> Overwrite existing links
1150 $data = array ( 'pageheader' => $uploadform , 'body' => '' , 'onload' => $onload );
1151 templatePage ( $data );
1155 // -------- Otherwise, simply display search form and links:
1157 <div id="headerform" style="width:100%; white-space:nowrap;";>
1158 <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>
1159 <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>
1162 $data = array ( 'pageheader' => $searchform , 'body' => templateLinkList (), 'onload' => '' );
1163 templatePage ( $data );
1167 // -----------------------------------------------------------------------------------------------
1168 // Process the import file form.
1169 function importFile ()
1172 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1173 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1174 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1175 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private ?
1176 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones ?
1181 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1183 // Then import the bookmarks.
1184 if ( $type == 'netscape' )
1186 // This is a standard Netscape-style bookmark file.
1187 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1188 // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
1189 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1191 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1192 $d = explode ( '<DD>' , $html );
1193 if ( startswith ( $d [ 0 ], '<A ' ))
1195 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1196 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1197 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1198 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1199 foreach ( $matches as $m )
1201 $attr = $m [ 1 ]; $value = $m [ 2 ];
1202 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1203 elseif ( $attr == 'ADD_DATE' ) $link [ 'linkdate' ]= date ( 'Ymd_His' , intval ( $value ));
1204 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1205 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1207 if ( $link [ 'linkdate' ]!= '' && $link [ 'url' ]!= '' && ( $overwrite || empty ( $LINKSDB [ $link [ 'linkdate' ]])))
1209 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1210 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1217 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1221 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1225 // -----------------------------------------------------------------------------------------------
1226 /* Template for the edit link form
1227 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
1228 Output: An array : (string) : The html code of the edit link form.
1229 (string) : The proper onload to use in body.
1230 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
1233 function templateEditForm ( $link , $link_is_new = false )
1235 $url = htmlspecialchars ( $link [ 'url' ]);
1236 $title = htmlspecialchars ( $link [ 'title' ]);
1237 $tags = htmlspecialchars ( $link [ 'tags' ]);
1238 $description = htmlspecialchars ( $link [ 'description' ]);
1239 $private = ( $link [ 'private' ]== 0 ? '' : 'checked="yes"' );
1241 // Automatically focus on empty fields:
1242 $onload = 'onload="document.linkform.lf_tags.focus();"' ;
1243 if ( $description == '' ) $onload = 'onload="document.linkform.lf_description.focus();"' ;
1244 if ( $title == '' ) $onload = 'onload="document.linkform.lf_title.focus();"' ;
1246 // Do not show "Delete" button if this is a new link.
1247 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">' ;
1248 if ( $link_is_new ) $delete_button = '' ;
1250 $token = getToken (); // XSRF protection.
1251 $returnurl_html = ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? '<input type="hidden" name="returnurl" value="' . htmlspecialchars ( $_SERVER [ 'HTTP_REFERER' ]). '">' : '' );
1252 $editlinkform = <<<HTML
1253 <div id="editlinkform">
1254 <form method="post" name="linkform">
1255 <input type="hidden" name="lf_linkdate" value=" {$link['linkdate']} ">
1256 <i>URL</i><br><input type="text" name="lf_url" value=" {$url} " style="width:100%"><br>
1257 <i>Title</i><br><input type="text" name="lf_title" value=" {$title} " style="width:100%"><br>
1258 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%"> {$description} </textarea><br>
1259 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value=" {$tags} " style="width:100%"><br>
1260 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private"> <i>Private</i><br>
1261 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1262 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1264 <input type="hidden" name="token" value=" {$token} ">
1269 return array ( $editlinkform , $onload );
1273 // -----------------------------------------------------------------------------------------------
1274 // Template for the list of links.
1275 // Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1276 function templateLinkList ()
1280 // Search according to entered search terms:
1281 $linksToDisplay = array ();
1283 if (! empty ( $_GET [ 'searchterm' ])) // Fulltext search
1285 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1286 $searched = ' <b>' . count ( $linksToDisplay ). ' results for <i>' . htmlspecialchars ( trim ( $_GET [ 'searchterm' ])). '</i></b>:' ;
1288 elseif (! empty ( $_GET [ 'searchtags' ])) // Search by tag
1290 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1291 $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> ' ;
1292 $searched = ' <b>' . count ( $linksToDisplay ). ' results for tags ' . $tagshtml . ':</b>' ;
1294 elseif ( preg_match ( '/[a-zA-Z0-9-_@] {6} /' , $_SERVER [ "QUERY_STRING" ])) // Detect smallHashes in URL
1296 $linksToDisplay = $LINKSDB- > filterSmallHash ( $_SERVER [ "QUERY_STRING" ]);
1299 $linksToDisplay = $LINKSDB ; // otherwise, display without filtering.
1305 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1306 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1307 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1309 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks php.
1310 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1311 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1312 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1313 $page = ( $page < 1 ? 1 : $page );
1314 $page = ( $page > $pagecount ? $pagecount : $page );
1315 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1316 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1317 while ( $i < $end && $i < count ( $keys ))
1319 $link = $linksToDisplay [ $keys [ $i ]];
1320 $description = text2clickable ( htmlspecialchars ( $link [ 'description' ]));
1321 $title = $link [ 'title' ];
1322 $classprivate = ( $link [ 'private' ]== 0 ? '' : 'class="private"' );
1323 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>' ;
1325 if ( $link [ 'tags' ]!= '' ) foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { $tags
.= '<span class="linktag" title="Add tag"><a href="?addtag=' . htmlspecialchars ( $tag
). '">' . htmlspecialchars ( $tag
). '</a></span> ' ; }
1326 $linklist .= '<li ' . $classprivate . '>' . thumbnail ( $link [ 'url' ]);
1327 $linklist .= '<div class="linkcontainer"><span class="linktitle"><a href="' . htmlspecialchars ( $link [ 'url' ]). '">' . htmlspecialchars ( $title ). '</a></span>' . $actions . '<br>' ;
1328 if ( $description != '' ) $linklist .= '<div class="linkdescription">' . nl2br ( $description ). '</div><br>' ;
1329 if (! HIDE_TIMESTAMPS
|| isLoggedIn ()) $linklist .= '<span class="linkdate" title="Short link here"><a href="?' . smallHash ( $link [ 'linkdate' ]). '">' . htmlspecialchars ( linkdate2locale ( $link [ 'linkdate' ])). ' </a> - </span>' ;
1330 else $linklist .= '<span class="linkdate" title="Short link here"><a href="?' . smallHash ( $link [ 'linkdate' ]). '">link</a> - </span>' ;
1331 $linklist .= '<span class="linkurl" title="Short link">' . htmlspecialchars ( $link [ 'url' ]). '</span><br>' . $tags . "</div></li> \n " ;
1336 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1337 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1339 if ( $i != count ( $keys )) $paging .= '<a href="?page=' .( $page +
1 ). $searchterm . $searchtags . '">◄Older</a>' ;
1340 $paging .= '<span style="color:#fff; padding:0 20 0 20;">page ' . $page . ' / ' . $pagecount . '</span>' ;
1341 if ( $page > 1 ) $paging .= '<a href="?page=' .( $page-1 ). $searchterm . $searchtags . '">Newer►</a>' ;
1342 $linksperpage = <<<HTML
1343 <div style="float:right; padding-right:5px;">
1344 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1345 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1347 $paging = '<div class="paging">' . $linksperpage . $paging . '</div>' ;
1348 $linklist = '<div id="linklist">' . $paging . $searched . '<ul>' . $linklist . '</ul>' . $paging . '</div>' ;
1352 // Returns the HTML code to display a thumbnail for a link.
1353 // Understands various services (youtube.com...)
1354 function thumbnail ( $url )
1356 if (! ENABLE_THUMBNAILS
) return '' ;
1358 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1359 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/2.jpg )
1360 // ^^^^^^^^^^^ ^^^^^^^^^^^
1361 $domain = parse_url ( $url , PHP_URL_HOST
);
1362 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1364 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1365 if (! empty ( $params [ 'v' ])) return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="http://img.youtube.com/vi/' . htmlspecialchars ( $params [ 'v' ]). '/2.jpg" width="120" height="90"></a></div>' ;
1367 if ( $domain == 'imgur.com' )
1369 $path = parse_url ( $url , PHP_URL_PATH
);
1370 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>' ;
1371 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>' ;
1373 if ( $domain == 'i.imgur.com' )
1375 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1376 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>' ;
1378 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1380 if ( strpos ( $url , 'dailymotion.com/video/' ))
1382 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1383 return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a></div>' ;
1386 if ( endsWith ( $domain , '.imageshack.us' ))
1388 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1389 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1391 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1392 return '<div class="thumbnail"><a href="' . htmlspecialchars ( $url ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a></div>' ;
1396 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1397 // So we deport the thumbnail generation in order not to slow down page generation
1398 // (and we also cache the thumbnail)
1399 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ) || $domain == 'vimeo.com' )
1401 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1402 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>' ;
1405 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1406 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1407 // But using the extension will do.
1408 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1409 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1411 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1412 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>' ;
1414 return '' ; // No thumbnail.
1418 // -----------------------------------------------------------------------------------------------
1419 // Template for the whole page.
1420 /* Input: $data (associative array).
1421 Keys: 'body' : body of HTML document
1422 'pageheader' : html code to show in page header (top of page)
1423 'onload' : optional onload javascript for the <body>
1425 function templatePage ( $data )
1429 $shaarli_version = shaarli_version
;
1431 $newversion = checkUpdate ();
1432 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>' ;
1433 $linkcount = count ( $LINKSDB );
1437 $menu = ' <a href="?do=tools">Tools</a> <a href="?do=addlink"><b>Add link</b></a>' ;
1441 $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>' );
1443 foreach ( array ( 'pageheader' , 'body' , 'onload' ) as $k ) // make sure all required fields exist (put an empty string if not).
1445 if (! array_key_exists ( $k , $data )) $data [ $k ]= '' ;
1447 $jsincludes = '' ; $jsincludes_bottom = '' ;
1448 if ( OPEN_SHAARLI
|| isLoggedIn ())
1450 $jsincludes = '<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>' ;
1451 $source = serverUrl (). $_SERVER [ 'SCRIPT_NAME' ];
1452 $jsincludes_bottom = <<<JS
1453 <script language="JavaScript">
1454 $(document).ready(function()
1456 $('#lf_tags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1457 $('#searchtags').autocomplete( {source:'{$source} ?ws=tags',minLength:1});
1458 $('#fromtag').autocomplete( {source:'{$source} ?ws=singletag',minLength:1});
1463 $feedurl = htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]);
1465 if (! empty ( $_GET [ 'searchtags' ])) $feedsearch .= '&searchtags=' . $_GET [ 'searchtags' ];
1466 elseif (! empty ( $_GET [ 'searchterm' ])) $feedsearch .= '&searchterm=' . $_GET [ 'searchterm' ];
1467 $version = shaarli_version
;
1469 $title = htmlspecialchars ( $GLOBALS [ 'title' ] );
1473 <title> {$title} </title>
1474 <link rel="alternate" type="application/rss+xml" href=" {$feedurl} " />
1475 <link type="text/css" rel="stylesheet" href="shaarli.css?version= {$version} " />
1478 <body {$data['onload']} > {$newversion}
1479 <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>
1480 <b><i> {$title} </i></b> - <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>
1481 <a href="?do=tagcloud">Tag cloud</a>
1482 {$data['pageheader']}
1487 $exectime = round ( microtime ( true )- $STARTTIME , 4 );
1488 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>' ;
1489 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>' ;
1490 echo $jsincludes_bottom . '</body></html>' ;
1493 // -----------------------------------------------------------------------------------------------
1495 // This function should NEVER be called if the file data/config.php exists.
1498 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1499 if ( endsWith ( $_SERVER [ 'SERVER_NAME' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1501 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1504 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1505 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1506 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1507 $GLOBALS [ 'timezone' ] = $tz ;
1508 // Everything is ok, let's create config file.
1509 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
1510 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1511 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1512 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . htmlspecialchars ( serverUrl (). $_SERVER [ 'SCRIPT_NAME' ]) : $_POST [ 'title' ] );
1514 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location= \' ?do=login \' ;</script>' ;
1518 // Display config form:
1519 list ( $timezone_form , $timezone_js ) = templateTZform ();
1520 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
1522 <html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" /> ${timezone_js} </head>
1523 <body onload="document.installform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
1524 It looks like it's the first time you run Shaarli. Please configure it:<br>
1525 <form method="POST" action="" name="installform" id="installform" style="border:1px solid black; padding:10 10 10 10;">
1526 <table border="0" cellpadding="20">
1527 <tr><td><b>Login:</b></td><td><input type="text" name="setlogin" size="30"></td></tr>
1528 <tr><td><b>Password:</b></td><td><input type="password" name="setpassword" size="30"></td></tr>
1530 <tr><td><b>Page title:</b></td><td><input type="text" name="title" size="30"></td></tr>
1531 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
1533 </form></body></html>
1538 // Generates the timezone selection form and javascript.
1539 // Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1540 // Output: array(html,js)
1541 // Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1542 // Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1543 function templateTZform ( $ptz = false )
1545 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1547 // Try to split the provided timezone.
1548 if ( $ptz == false ) { $l
= timezone_identifiers_list (); $ptz
= $l
[ 0 ]; }
1549 $spos = strpos ( $ptz , '/' ); $pcontinent = substr ( $ptz , 0 , $spos ); $pcity = substr ( $ptz , $spos +
1 );
1551 // Display config form:
1552 $timezone_form = '' ;
1554 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1555 // We split the list in continents/cities.
1556 $continents = array ();
1558 foreach ( timezone_identifiers_list () as $tz )
1560 if ( $tz == 'UTC' ) $tz = 'UTC/UTC' ;
1561 $spos = strpos ( $tz , '/' );
1564 $continent = substr ( $tz , 0 , $spos ); $city = substr ( $tz , $spos +
1 );
1565 $continents [ $continent ]= 1 ;
1566 if (! isset ( $cities [ $continent ])) $cities [ $continent ]= array ();
1567 $cities [ $continent ].= '<option value="' . $city . '"' .( $pcity == $city ? 'selected' : '' ). '>' . $city . '</option>' ;
1570 $continents_html = '' ;
1571 $continents = array_keys ( $continents );
1572 foreach ( $continents as $continent )
1573 $continents_html .= '<option value="' . $continent . '"' .( $pcontinent == $continent ? 'selected' : '' ). '>' . $continent . '</option>' ;
1574 $cities_html = $cities [ $pcontinent ];
1575 $timezone_form = "Continent: <select name= \" continent \" id= \" continent \" onChange= \" onChangecontinent(); \" > ${continents_html} </select><br /><br />" ;
1576 $timezone_form .= "City: <select name= \" city \" id= \" city \" > ${cities[$pcontinent]} </select><br /><br />" ;
1577 $timezone_js = "<script language= \" JavaScript \" >" ;
1578 $timezone_js .= "function onChangecontinent() {document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];} " ;
1579 $timezone_js .= "var citiescontinent = " . json_encode ( $cities ). ";" ;
1580 $timezone_js .= "</script>" ;
1581 return array ( $timezone_form , $timezone_js );
1583 return array ( '' , '' );
1586 // Tells if a timezone is valid or not.
1587 // If not valid, returns false.
1588 // If system does not support timezone list, returns false.
1589 function isTZvalid ( $continent , $city )
1591 $tz = $continent . '/' . $city ;
1592 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1594 if ( in_array ( $tz , timezone_identifiers_list ())) // it's a valid timezone ?
1601 // Webservices (for use with jQuery/jQueryUI)
1602 // eg. index.php?ws=tags&term=minecr
1603 function processWS ()
1605 if ( empty ( $_GET [ 'ws' ]) || empty ( $_GET [ 'term' ])) return ;
1606 $term = $_GET [ 'term' ];
1608 header ( 'Content-Type: application/json; charset=utf-8' );
1610 // Search in tags (case insentitive, cumulative search)
1611 if ( $_GET [ 'ws' ]== 'tags' )
1613 $tags = explode ( ' ' , str_replace ( ',' , ' ' , $term )); $last = array_pop ( $tags ); // Get the last term ("a b c d" ==> "a b c", "d")
1614 $addtags = '' ; if ( $tags ) $addtags = implode ( ' ' , $tags ). ' ' ; // We will pre-pend previous tags
1616 /* To speed up things, we store list of tags in session */
1617 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1618 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1620 if ( startsWith ( $key , $last , $case = false ) && ! in_array ( $key , $tags )) $suggested [ $addtags . $key . ' ' ]= 0 ; //FIXME
1622 echo json_encode ( array_keys ( $suggested ));
1626 // Search a single tag (case sentitive, single tag search)
1627 if ( $_GET [ 'ws' ]== 'singletag' )
1629 /* To speed up things, we store list of tags in session */
1630 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1631 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1633 if ( startsWith ( $key , $term , $case = true )) $suggested [ $key ]= 0 ;
1635 echo json_encode ( array_keys ( $suggested ));
1640 // Re-write configuration file according to globals.
1641 // Requires some $GLOBALS to be set (login,hash,salt,title).
1642 // If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1643 // (otherwise, the function simply returns.)
1644 function writeConfig ()
1646 if ( is_file ( CONFIG_FILE
) && ! isLoggedIn ()) die ( 'You are not authorized to alter config.' ); // Only logged in user can alter config.
1647 $config = '<?php $GLOBALS [ \' login \' ]=' . var_export ( $GLOBALS [ 'login' ], true ). '; $GLOBALS [ \' hash \' ]=' . var_export ( $GLOBALS [ 'hash' ], true ). '; $GLOBALS [ \' salt \' ]=' . var_export ( $GLOBALS [ 'salt' ], true ). '; ' ;
1648 $config .= ' $GLOBALS [ \' timezone \' ]=' . var_export ( $GLOBALS [ 'timezone' ], true ). '; date_default_timezone_set(' . var_export ( $GLOBALS [ 'timezone' ], true ). '); $GLOBALS [ \' title \' ]=' . var_export ( $GLOBALS [ 'title' ], true ). '; ?>' ;
1649 if (! file_put_contents ( CONFIG_FILE
, $config ) || strcmp ( file_get_contents ( CONFIG_FILE
), $config )!= 0 )
1651 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>' ;
1656 /* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
1657 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1658 The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
1659 This function is called by passing the url:
1660 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1661 [URL] is the URL of the link (eg. a flickr page)
1662 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1663 The function below will fetch the image from the webservice and store it in the cache.
1665 function genThumbnail ()
1667 // Make sure the parameters in the URL were generated by us.
1668 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
1669 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy !' );
1671 // Let's see if we don't already have the image for this URL in the cache.
1672 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
1673 if ( is_file ( CACHEDIR
. '/' . $thumbname ))
1674 { // We have the thumbnail, just serve it:
1675 header ( 'Content-Type: image/jpeg' );
1676 echo file_get_contents ( CACHEDIR
. '/' . $thumbname );
1679 // We may also serve a blank image (if service did not respond)
1680 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
1681 if ( is_file ( CACHEDIR
. '/' . $blankname ))
1683 header ( 'Content-Type: image/gif' );
1684 echo file_get_contents ( CACHEDIR
. '/' . $blankname );
1688 // Otherwise, generate the thumbnail.
1689 $url = $_GET [ 'url' ];
1690 $domain = parse_url ( $url , PHP_URL_HOST
);
1692 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
1694 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1695 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1696 // All images in Flickr are in the form:
1697 // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
1698 // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
1699 // We want the 240x120 format, which is _m.jpg.
1700 // We search for the first image in the page which does not have the _s size,
1701 // when use the _m to get the thumbnail.
1703 // Is this a link to an image, or to a flickr page ?
1705 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
1706 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1707 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
1708 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1710 else // this is a flickr page (html)
1712 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 20 ); // Get the flickr html page.
1713 if ( strpos ( $httpstatus , '200 OK' ))
1715 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!' , $data , $matches );
1716 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1720 { // Let's download the image.
1721 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 ); // Image is 240x120, so 10 seconds to download should be enough.
1722 if ( strpos ( $httpstatus , '200 OK' ))
1724 file_put_contents ( CACHEDIR
. '/' . $thumbname , $data ); // Save image to cache.
1725 header ( 'Content-Type: image/jpeg' );
1732 if ( $domain == 'vimeo.com' )
1734 // This is more complex: we have to perform a HTTP request, then parse the result.
1735 // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
1736 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
1737 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://vimeo.com/api/v2/video/' . htmlspecialchars ( $vid ). '.php' , 5 );
1738 if ( strpos ( $httpstatus , '200 OK' ))
1740 $t = unserialize ( $data );
1741 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
1742 // Then we download the image and serve it to our client.
1743 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 );
1744 if ( strpos ( $httpstatus , '200 OK' ))
1746 file_put_contents ( CACHEDIR
. '/' . $thumbname , $data ); // Save image to cache.
1747 header ( 'Content-Type: image/jpeg' );
1754 // For all other domains, we try to download the image and make a thumbnail.
1755 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 30 ); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1756 if ( strpos ( $httpstatus , '200 OK' ))
1758 $filepath = CACHEDIR
. '/' . $thumbname ;
1759 file_put_contents ( $filepath , $data ); // Save image to cache.
1760 if ( resizeImage ( $filepath ))
1762 header ( 'Content-Type: image/jpeg' );
1763 echo file_get_contents ( $filepath );
1768 // Otherwise, return an empty image (8x8 transparent gif)
1769 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
1770 file_put_contents ( CACHEDIR
. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
1771 header ( 'Content-Type: image/gif' );
1775 // Make a thumbnail of the image (to width: 120 pixels)
1776 // Returns true if success, false otherwise.
1777 function resizeImage ( $filepath )
1779 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
1781 // Trick: some stupid people rename GIF as JPEG... or else.
1782 // So we really try to open each image type whatever the extension is.
1783 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
1785 if ( strpos ( $header , 'GIF8' )== 0 ) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
1786 if ( strpos ( $header , 'PNG' )== 1 ) $im = imagecreatefrompng ( $filepath );
1787 if ( strpos ( $header , 'JFIF' )) $im = imagecreatefromjpeg ( $filepath );
1788 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
1791 $nw = 120 ; // Desired width
1792 $nh = floor (( $h * $nw )/ $w ); // Compute new width/height while keeping ratio
1794 $im2 = imagecreatetruecolor ( $nw , $nh );
1795 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , 0 , $nw , $nh , $w , $h );
1796 imageinterlace ( $im2 , true ); // For progressive JPEG.
1797 $tempname = $filepath . '_TEMP.jpg' ;
1798 imagejpeg ( $im2 , $tempname , 90 );
1801 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
1805 // Invalidate caches when the database is changed or the user logs out.
1806 // (eg. tags cache).
1807 function invalidateCaches ()
1809 unset ( $_SESSION [ 'tags' ]);
1812 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
1813 $LINKSDB = new linkdb ( isLoggedIn () || OPEN_SHAARLI
); // Read links from database (and filter private links if used it not logged in).
1814 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'ws=' )) { processWS (); exit ; } // Webservices (for jQuery/jQueryUI)
1815 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= LINKS_PER_PAGE
;
1816 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
1817 if ( startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }