]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
011aeed99c6f5ebb2f4e71647236ec2c2a5501da
2 // Shaarli 0.0.33 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.
23 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
24 // Note: You must have publisher.php in the same directory as Shaarli index.php
25 // -----------------------------------------------------------------------------------------------
26 // Program config (touch at your own risks !)
27 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ; // For updates check of Shaarli.
28 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
29 ini_set ( 'max_input_time' , '60' ); // High execution time in case of problematic imports/exports.
30 ini_set ( 'memory_limit' , '128M' ); // Try to set max upload file size and read (May not work on some hosts).
31 ini_set ( 'post_max_size' , '16M' );
32 ini_set ( 'upload_max_filesize' , '16M' );
33 define ( 'PHPPREFIX' , '<?php /* ' ); // Prefix to encapsulate data in php code.
34 define ( 'PHPSUFFIX' , ' */ ?>' ); // Suffix to encapsulate data in php code.
36 error_reporting ( E_ALL^E_WARNING
); // See all error except warnings.
37 //error_reporting(-1); // See all errors (for debugging only)
39 include "inc/rain.tpl.class.php" ; //include Rain TPL
40 raintpl
:: $tpl_dir = "tpl/" ; // template directory
41 raintpl
:: $cache_dir = "tmp/" ; // cache directory
45 // Optionnal config file.
46 if ( is_file ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/options.php' )) require ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/options.php' );
48 // In case stupid admin has left magic_quotes enabled in php.ini:
49 if ( get_magic_quotes_gpc ())
51 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
52 $_POST = array_map ( 'stripslashes_deep' , $_POST );
53 $_GET = array_map ( 'stripslashes_deep' , $_GET );
54 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
56 // Prevent caching: (yes, it's ugly)
57 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
58 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
59 header ( "Cache-Control: post-check=0, pre-check=0" , false );
60 header ( "Pragma: no-cache" );
61 define ( 'shaarli_version' , '0.0.33 beta' );
62 if (! is_dir ( $GLOBALS [ 'config' ][ 'DATADIR' ])) { mkdir ( $GLOBALS
[ 'config' ][ 'DATADIR' ], 0705 ); chmod ( $GLOBALS
[ 'config' ][ 'DATADIR' ], 0705 ); }
63 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.
64 if ( $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ])
66 if (! is_dir ( $GLOBALS [ 'config' ][ 'CACHEDIR' ])) { mkdir ( $GLOBALS
[ 'config' ][ 'CACHEDIR' ], 0705 ); chmod ( $GLOBALS
[ 'config' ][ 'CACHEDIR' ], 0705 ); }
67 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.
69 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) install ();
70 require $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]; // Read login/password hash into $GLOBALS.
71 // Small protection against dodgy config files:
72 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . htmlspecialchars ( indexUrl ());
73 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
74 autoLocale (); // Sniff browser language and set date format accordingly.
75 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
79 function checkphpversion ()
81 if ( version_compare ( PHP_VERSION
, '5.1.0' ) < 0 )
83 header ( 'Content-Type: text/plain; charset=utf-8' );
84 echo 'Your server supports php ' . PHP_VERSION
. '. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.' ;
89 // Checks if an update is available for Shaarli.
90 // (at most once a day, and only for registered user.)
91 // Output: '' = no new version.
92 // other= the available version.
93 function checkUpdate ()
95 if (! isLoggedIn ()) return '' ; // Do not check versions for visitors.
97 // Get latest version number at most once a day.
98 if (! is_file ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]) || ( filemtime ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ])< time ()-( $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ])))
100 $version = shaarli_version
;
101 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://sebsauvage.net/files/shaarli_version.txt' , 2 );
102 if ( strpos ( $httpstatus , '200 OK' )!== false ) $version = $data ;
103 // If failed, nevermind. We don't want to bother the user with that.
104 file_put_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ], $version ); // touch file date
107 $newestversion = file_get_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]);
108 if ( version_compare ( $newestversion , shaarli_version
)== 1 ) return $newestversion ;
112 // -----------------------------------------------------------------------------------------------
114 function logm ( $message )
116 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
117 file_put_contents ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' , $t , FILE_APPEND
);
120 // Same as nl2br(), but escapes < and >
121 function nl2br_escaped ( $html )
123 return str_replace ( '>' , '>' , str_replace ( '<' , '<' , nl2br ( $html )));
126 /* Returns the small hash of a string
127 eg. smallHash('20111006_131924') --> yZH23w
129 - are unique (well, as unique as crc32, at last)
130 - are always 6 characters long.
131 - only use the following characters: a-z A-Z 0-9 - _ @
132 - are NOT cryptographically secure (they CAN be forged)
133 In Shaarli, they are used as a tinyurl-like link to individual entries.
135 function smallHash ( $text )
137 $t = rtrim ( base64_encode ( hash ( 'crc32' , $text , true )), '=' );
138 $t = str_replace ( '+' , '-' , $t ); // Get rid of characters which need encoding in URLs.
139 $t = str_replace ( '/' , '_' , $t );
140 $t = str_replace ( '=' , '@' , $t );
144 // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
145 function text2clickable ( $url )
147 $redir = empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ];
148 return preg_replace ( '!((?:https?|ftp)://\S+[[:alnum:]]/?)!si' , '<a href="' . $redir . ' $1" rel="nofollow"> $1 </a>' , $url );
151 // This function inserts where relevant so that multiple spaces are properly displayed in HTML
152 // even in the absence of <pre> (This is used in description to keep text formatting)
153 function keepMultipleSpaces ( $text )
155 return str_replace ( ' ' , ' ' , $text );
158 // ------------------------------------------------------------------------------------------
159 // Sniff browser language to display dates in the right format automatically.
160 // (Note that is may not work on your server if the corresponding local is not installed.)
161 function autoLocale ()
163 $loc = 'en_US' ; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
164 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
165 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
166 if ( preg_match ( '/([a-z] {2} (-[a-z] {2} )?)/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) $loc = $matches [ 1 ];
168 setlocale ( LC_TIME
, $loc ); // LC_TIME = Set local for date/time format only.
171 // ------------------------------------------------------------------------------------------
172 // PubSubHubbub protocol support (if enabled) [UNTESTED]
173 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
174 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
177 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
179 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
181 indexUrl (). '?do=atom' ,
184 $p- > publish_update ( $topic_url );
188 // ------------------------------------------------------------------------------------------
189 // Session management
190 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
191 ini_set ( 'session.use_cookies' , 1 ); // Use cookies to store session.
192 ini_set ( 'session.use_only_cookies' , 1 ); // Force cookies for session (phpsessionID forbidden in URL)
193 ini_set ( 'session.use_trans_sid' , false ); // Prevent php to use sessionID in URL if cookies are disabled.
194 session_name ( 'shaarli' );
197 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
200 $ip = $_SERVER [ "REMOTE_ADDR" ];
201 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
202 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
203 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
207 // Check that user/password is correct.
208 function check_auth ( $login , $password )
210 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
211 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
212 { // Login/password is correct.
213 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // generate unique random number (different than phpsessionid)
214 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
215 $_SESSION [ 'username' ]= $login ;
216 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
217 logm ( 'Login successful' );
220 logm ( 'Login failed for user ' . $login );
224 // Returns true if the user is logged in.
225 function isLoggedIn ()
227 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) return true ;
229 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
230 if ( empty ( $_SESSION [ 'uid' ]) || $_SESSION [ 'ip' ]!= allIPs () || time ()>= $_SESSION [ 'expires_on' ])
235 if (! empty ( $_SESSION [ 'longlastingsession' ])) $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
236 else $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
242 function logout () { if ( isset ( $_SESSION
)) { unset ( $_SESSION
[ 'uid' ]); unset ( $_SESSION
[ 'ip' ]); unset ( $_SESSION
[ 'username' ]);} }
245 // ------------------------------------------------------------------------------------------
246 // Brute force protection system
247 // Several consecutive failed logins will ban the IP address for 30 minutes.
248 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 ?>" );
249 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
250 // Signal a failed login. Will ban the IP if too many failures:
251 function ban_loginFailed ()
253 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
254 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
255 $gb [ 'FAILURES' ][ $ip ] ++
;
256 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
258 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
259 logm ( 'IP address banned from login' );
261 $GLOBALS [ 'IPBANS' ] = $gb ;
262 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
265 // Signals a successful login. Resets failed login counter.
266 function ban_loginOk ()
268 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
269 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
270 $GLOBALS [ 'IPBANS' ] = $gb ;
271 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
274 // Checks if the user CAN login. If 'true', the user can try to login.
275 function ban_canLogin ()
277 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
278 if ( isset ( $gb [ 'BANS' ][ $ip ]))
280 // User is banned. Check if the ban has expired:
281 if ( $gb [ 'BANS' ][ $ip ]<= time ())
282 { // Ban expired, user can try to login again.
284 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
285 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
286 return true ; // Ban has expired, user can login.
288 return false ; // User is banned.
290 return true ; // User is not banned.
293 // ------------------------------------------------------------------------------------------
294 // Process login form: Check if login/password is correct.
295 if ( isset ( $_POST [ 'login' ]))
297 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
298 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
299 { // Login/password is ok.
301 // If user wants to keep the session cookie even after the browser closes:
302 if (! empty ( $_POST [ 'longlastingsession' ]))
304 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
305 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
306 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ]); // Set session cookie expiration on client side
307 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
309 else // Standard session expiration (=when browser closes)
311 session_set_cookie_params ( 0 ); // 0 means "When browser closes"
312 session_regenerate_id ( true );
314 // Optional redirect after login:
315 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 ; }
316 if ( isset ( $_POST [ 'returnurl' ]))
318 if ( endsWith ( $_POST [ 'returnurl' ], '?do=login' )) { header ( 'Location: ?' ); exit ; } // Prevent loops over login screen.
319 header ( 'Location: ' . $_POST [ 'returnurl' ]); exit ;
321 header ( 'Location: ?' ); exit ;
326 echo '<script language="JavaScript">alert("Wrong login/password.");document.location= \' ?do=login \' ;</script>' ; // Redirect to login screen.
331 // ------------------------------------------------------------------------------------------
332 // Misc utility functions:
334 // Returns the server URL (including port and http/https), without path.
335 // eg. "http://myserver.com:8080"
336 // You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
339 $serverport = ( $_SERVER [ "SERVER_PORT" ]== '80' || (! empty ( $_SERVER [ 'HTTPS' ]) && $_SERVER [ "SERVER_PORT" ]== '443' ) ? '' : ':' . $_SERVER [ "SERVER_PORT" ]);
340 return 'http' .(! empty ( $_SERVER [ 'HTTPS' ])? 's' : '' ). '://' . $_SERVER [ "SERVER_NAME" ]. $serverport ;
345 return serverUrl () . ( $_SERVER [ "SCRIPT_NAME" ] == '/index.php' ? '' : $_SERVER [ "SCRIPT_NAME" ]);
348 // Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
349 function return_bytes ( $val )
351 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
354 case 'g' : $val *= 1024 ;
355 case 'm' : $val *= 1024 ;
356 case 'k' : $val *= 1024 ;
361 // Try to determine max file size for uploads (POST).
362 // Returns an integer (in bytes)
363 function getMaxFileSize ()
365 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
366 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
367 // Return the smaller of two:
368 $maxsize = min ( $size1 , $size2 );
369 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
373 // Tells if a string start with a substring or not.
374 function startsWith ( $haystack , $needle , $case = true )
376 if ( $case ){ return ( strcmp ( substr ( $haystack
, 0 , strlen ( $needle
)), $needle
)=== 0 );}
377 return ( strcasecmp ( substr ( $haystack , 0 , strlen ( $needle )), $needle )=== 0 );
380 // Tells if a string ends with a substring or not.
381 function endsWith ( $haystack , $needle , $case = true )
383 if ( $case ){ return ( strcmp ( substr ( $haystack
, strlen ( $haystack
) - strlen ( $needle
)), $needle
)=== 0 );}
384 return ( strcasecmp ( substr ( $haystack , strlen ( $haystack ) - strlen ( $needle )), $needle )=== 0 );
387 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
388 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
389 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
390 function linkdate2timestamp ( $linkdate )
393 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
394 return mktime ( $h , $m , $s , $M , $D , $Y );
397 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
398 (used to build the pubDate attribute in RSS feed.) */
399 function linkdate2rfc822 ( $linkdate )
401 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
404 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
405 (used to build the updated tags in ATOM feed.) */
406 function linkdate2iso8601 ( $linkdate )
408 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
411 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
412 (used to display link date on screen)
413 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
414 function linkdate2locale ( $linkdate )
416 return utf8_encode ( strftime ( '%c' , linkdate2timestamp ( $linkdate ))); // %c is for automatic date format according to locale.
417 // Note that if you use a local which is not installed on your webserver,
418 // the date will not be displayed in the chosen locale, but probably in US notation.
421 // Parse HTTP response headers and return an associative array.
422 function http_parse_headers_shaarli ( $headers )
425 foreach ( $headers as $header )
427 $i = strpos ( $header , ': ' );
430 $key = substr ( $header , 0 , $i );
431 $value = substr ( $header , $i +
2 , strlen ( $header )- $i-2 );
439 Input: $url : url to get (http://...)
440 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
441 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
442 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
444 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
445 if (strpos($httpstatus,'200 OK')!==false)
446 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
448 echo 'There was an error: '.htmlspecialchars($httpstatus)
450 function getHTTP ( $url , $timeout = 30 )
454 $options = array ( 'http' => array ( 'method' => 'GET' , 'timeout' => $timeout )); // Force network timeout
455 $context = stream_context_create ( $options );
456 $data = file_get_contents ( $url , false , $context ,- 1 , 4000000 ); // We download at most 4 Mb from source.
457 if (! $data ) { $lasterror
= error_get_last (); return array ( $lasterror
[ 'message' ], array (), '' ); }
458 $httpStatus = $http_response_header [ 0 ]; // eg. "HTTP/1.1 200 OK"
459 $responseHeaders = http_parse_headers_shaarli ( $http_response_header );
460 return array ( $httpStatus , $responseHeaders , $data );
462 catch ( Exception
$e ) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
464 return array ( $e- > getMessage (), '' , '' );
468 // Extract title from an HTML document.
469 // (Returns an empty string if not found.)
470 function html_extract_title ( $html )
472 return preg_match ( '!<title>(.*?)</title>!is' , $html , $matches ) ? trim ( str_replace ( " \n " , ' ' , $matches [ 1 ])) : '' ;
475 // ------------------------------------------------------------------------------------------
476 // Token management for XSRF protection
477 // Token should be used in any form which acts on data (create,update,delete,import...).
478 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
483 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // We generate a random string.
484 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
488 // Tells if a token is ok. Using this function will destroy the token.
490 function tokenOk ( $token )
492 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
494 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
495 return true ; // Token is ok.
497 return false ; // Wrong token, or already used.
500 // ------------------------------------------------------------------------------------------
501 /* This class is in charge of building the final page.
502 (This is basically a wrapper around RainTPL which pre-fills some fields.)
504 p.assign('myfield','myvalue');
505 p.renderPage('mytemplate');
510 private $tpl ; // RainTPL template
511 function __construct ()
516 private function initialize ()
519 $this- > tpl
= new RainTPL
;
520 $this- > tpl
-> assign ( 'newversion' , checkUpdate ());
521 $this- > tpl
-> assign ( 'linkcount' , count ( $LINKSDB ));
522 $this- > tpl
-> assign ( 'feedurl' , htmlspecialchars ( indexUrl ()));
523 $searchcrits = '' ; // Search criteria
524 if (! empty ( $_GET [ 'searchtags' ])) $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
525 elseif (! empty ( $_GET [ 'searchterm' ])) $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
526 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
527 $this- > tpl
-> assign ( 'source' , indexUrl ());
528 $this- > tpl
-> assign ( 'version' , shaarli_version
);
529 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
530 if (! empty ( $GLOBALS [ 'title' ])) $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
531 if (! empty ( $GLOBALS [ 'pagetitle' ])) $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
532 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ] );
536 // The following assign() method is basically the same as RainTPL (except that it's lazy)
537 public function assign ( $what , $where )
539 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
540 $this- > tpl
-> assign ( $what , $where );
543 // Render a specific page (using a template).
544 // eg. pb.renderPage('picwall')
545 public function renderPage ( $page )
547 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
548 $this- > tpl
-> draw ( $page );
552 // ------------------------------------------------------------------------------------------
553 /* Data storage for links.
554 This object behaves like an associative array.
556 $mylinks = new linkdb();
557 echo $mylinks['20110826_161819']['title'];
558 foreach($mylinks as $link)
559 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
561 We implement 3 interfaces:
562 - ArrayAccess so that this object behaves like an associative array.
563 - Iterator so that this object can be used in foreach() loops.
564 - Countable interface so that we can do a count() on this object.
566 class linkdb
implements Iterator
, Countable
, ArrayAccess
568 private $links ; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
569 private $urls ; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
570 private $keys ; // List of linkdate keys (for the Iterator interface implementation)
571 private $position ; // Position in the $this->keys array. (for the Iterator interface implementation.)
572 private $loggedin ; // Is the used logged in ? (used to filter private links)
575 function __construct ( $isLoggedIn )
576 // Input : $isLoggedIn : is the used logged in ?
578 $this- > loggedin
= $isLoggedIn ;
579 $this- > checkdb (); // Make sure data file exists.
580 $this- > readdb (); // Then read it.
583 // ---- Countable interface implementation
584 public function count () { return count ( $this
-> links
); }
586 // ---- ArrayAccess interface implementation
587 public function offsetSet ( $offset , $value )
589 if (! $this- > loggedin
) die ( 'You are not authorized to add a link.' );
590 if ( empty ( $value [ 'linkdate' ]) || empty ( $value [ 'url' ])) die ( 'Internal Error: A link should always have a linkdate and url.' );
591 if ( empty ( $offset )) die ( 'You must specify a key.' );
592 $this- > links
[ $offset ] = $value ;
593 $this- > urls
[ $value [ 'url' ]]= $offset ;
595 public function offsetExists ( $offset ) { return array_key_exists ( $offset
, $this
-> links
); }
596 public function offsetUnset ( $offset )
598 if (! $this- > loggedin
) die ( 'You are not authorized to delete a link.' );
599 $url = $this- > links
[ $offset ][ 'url' ]; unset ( $this- > urls
[ $url ]);
600 unset ( $this- > links
[ $offset ]);
602 public function offsetGet ( $offset ) { return isset ( $this
-> links
[ $offset
]) ? $this
-> links
[ $offset
] : null ; }
604 // ---- Iterator interface implementation
605 function rewind () { $this
-> keys
= array_keys ( $this
-> links
); rsort ( $this
-> keys
); $this
-> position
= 0 ; } // Start over for iteration, ordered by date (latest first).
606 function key () { return $this
-> keys
[ $this
-> position
]; } // current key
607 function current () { return $this
-> links
[ $this
-> keys
[ $this
-> position
]]; } // current value
608 function next () { ++$this
-> position
; } // go to next item
609 function valid () { return isset ( $this
-> keys
[ $this
-> position
]); } // Check if current position is valid.
612 private function checkdb () // Check if db directory and file exists.
614 if (! file_exists ( $GLOBALS [ 'config' ][ 'DATASTORE' ])) // Create a dummy database for example.
616 $this- > links
= array ();
617 $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' );
618 $this- > links
[ $link [ 'linkdate' ]] = $link ;
619 $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' );
620 $this- > links
[ $link [ 'linkdate' ]] = $link ;
621 file_put_contents ( $GLOBALS [ 'config' ][ 'DATASTORE' ], PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
); // Write database to disk
625 // Read database from disk to memory
626 private function readdb ()
629 $this- > links
=( file_exists ( $GLOBALS [ 'config' ][ 'DATASTORE' ]) ? unserialize ( gzinflate ( base64_decode ( substr ( file_get_contents ( $GLOBALS [ 'config' ][ 'DATASTORE' ]), strlen ( PHPPREFIX
),- strlen ( PHPSUFFIX
))))) : array () );
630 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
632 // If user is not logged in, filter private links.
633 if (! $this- > loggedin
)
636 foreach ( $this- > links
as $link ) { if ( $link
[ 'private' ]!= 0 ) $toremove
[]= $link
[ 'linkdate' ]; }
637 foreach ( $toremove as $linkdate ) { unset ( $this
-> links
[ $linkdate
]); }
640 // Keep the list of the mapping URLs-->linkdate up-to-date.
642 foreach ( $this- > links
as $link ) { $this
-> urls
[ $link
[ 'url' ]]= $link
[ 'linkdate' ]; }
645 // Save database from memory to disk.
646 public function savedb ()
648 if (! $this- > loggedin
) die ( 'You are not authorized to change the database.' );
649 file_put_contents ( $GLOBALS [ 'config' ][ 'DATASTORE' ], PHPPREFIX
. base64_encode ( gzdeflate ( serialize ( $this- > links
))). PHPSUFFIX
);
652 // Returns the link for a given URL (if it exists). false it does not exist.
653 public function getLinkFromUrl ( $url )
655 if ( isset ( $this- > urls
[ $url ])) return $this- > links
[ $this- > urls
[ $url ]];
659 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
660 // eg. print_r($mydb->filterFulltext('hollandais'));
661 public function filterFulltext ( $searchterms )
663 // FIXME: explode(' ',$searchterms) and perform a AND search.
664 // FIXME: accept double-quotes to search for a string "as is" ?
666 $s = strtolower ( $searchterms );
667 foreach ( $this- > links
as $l )
669 $found = ( strpos ( strtolower ( $l [ 'title' ]), $s )!== false )
670 || ( strpos ( strtolower ( $l [ 'description' ]), $s )!== false )
671 || ( strpos ( strtolower ( $l [ 'url' ]), $s )!== false )
672 || ( strpos ( strtolower ( $l [ 'tags' ]), $s )!== false );
673 if ( $found ) $filtered [ $l [ 'linkdate' ]] = $l ;
680 // You can specify one or more tags (tags can be separated by space or comma).
681 // eg. print_r($mydb->filterTags('linux programming'));
682 public function filterTags ( $tags , $casesensitive = false )
684 $t = str_replace ( ',' , ' ' ,( $casesensitive ? $tags : strtolower ( $tags )));
685 $searchtags = explode ( ' ' , $t );
687 foreach ( $this- > links
as $l )
689 $linktags = explode ( ' ' ,( $casesensitive ? $l [ 'tags' ]: strtolower ( $l [ 'tags' ])));
690 if ( count ( array_intersect ( $linktags , $searchtags )) == count ( $searchtags ))
691 $filtered [ $l [ 'linkdate' ]] = $l ;
697 // Filter by smallHash.
698 // Only 1 article is returned.
699 public function filterSmallHash ( $smallHash )
702 foreach ( $this- > links
as $l )
704 if ( $smallHash == smallHash ( $l [ 'linkdate' ])) // Yes, this is ugly and slow
706 $filtered [ $l [ 'linkdate' ]] = $l ;
713 // Returns the list of all tags
714 // Output: associative array key=tags, value=0
715 public function allTags ()
718 foreach ( $this- > links
as $link )
719 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
720 if (! empty ( $tag )) $tags [ $tag ]=( empty ( $tags [ $tag ]) ? 1 : $tags [ $tag ] +
1 );
721 arsort ( $tags ); // Sort tags by usage (most used tag first)
726 // ------------------------------------------------------------------------------------------
727 // Ouput the last 50 links in RSS 2.0 format.
732 // Optionnaly filter the results:
733 $linksToDisplay = array ();
734 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
735 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
736 else $linksToDisplay = $LINKSDB ;
738 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
739 $pageaddr = htmlspecialchars ( indexUrl ());
740 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
741 echo '<channel><title>' . htmlspecialchars ( $GLOBALS [ 'title' ]). '</title><link>' . $pageaddr . '</link>' ;
742 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
743 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
745 echo '<!-- PubSubHubbub Discovery -->' ;
746 echo '<link rel="hub" href="' . htmlspecialchars ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
747 echo '<link rel="self" href="' . htmlspecialchars ( $pageaddr ). '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
748 echo '<!-- End Of PubSubHubbub Discovery -->' ;
751 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
752 while ( $i < 50 && $i < count ( $keys ))
754 $link = $linksToDisplay [ $keys [ $i ]];
755 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
756 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
757 $absurl = htmlspecialchars ( $link [ 'url' ]);
758 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
759 echo '<item><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><guid>' . $guid . '</guid><link>' . $absurl . '</link>' ;
760 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . htmlspecialchars ( $rfc822date ). "</pubDate> \n " ;
761 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
763 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . htmlspecialchars ( $pageaddr
). '">' . htmlspecialchars ( $tag
). '</category>' . " \n " ; }
765 echo '<description><![CDATA[' . nl2br ( keepMultipleSpaces ( text2clickable ( htmlspecialchars ( $link [ 'description' ])))). ']]></description>' . " \n </item> \n " ;
768 echo '</channel></rss>' ;
772 // ------------------------------------------------------------------------------------------
773 // Ouput the last 50 links in ATOM format.
778 // Optionnaly filter the results:
779 $linksToDisplay = array ();
780 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
781 elseif (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
782 else $linksToDisplay = $LINKSDB ;
784 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
785 $pageaddr = htmlspecialchars ( indexUrl ());
789 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
790 while ( $i < 50 && $i < count ( $keys ))
792 $link = $linksToDisplay [ $keys [ $i ]];
793 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
794 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
795 $latestDate = max ( $latestDate , $iso8601date );
796 $absurl = htmlspecialchars ( $link [ 'url' ]);
797 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
798 $entries .= '<entry><title>' . htmlspecialchars ( $link [ 'title' ]). '</title><link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
799 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . htmlspecialchars ( $iso8601date ). '</updated>' ;
800 $entries .= '<content type="html">' . htmlspecialchars ( nl2br ( keepMultipleSpaces ( text2clickable ( htmlspecialchars ( $link [ 'description' ]))))). "</content> \n " ;
801 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
803 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
804 { $entries
.= '<category scheme="' . htmlspecialchars ( $pageaddr
, ENT_QUOTES
). '" term="' . htmlspecialchars ( $tag
, ENT_QUOTES
). '" />' . " \n " ; }
806 $entries .= "</entry> \n " ;
809 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
810 $feed .= '<title>' . htmlspecialchars ( $GLOBALS [ 'title' ]). '</title>' ;
811 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . htmlspecialchars ( $latestDate ). '</updated>' ;
812 $feed .= '<link rel="self" href="' . htmlspecialchars ( serverUrl (). $_SERVER [ "REQUEST_URI" ]). '" />' ;
813 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
815 $feed .= '<!-- PubSubHubbub Discovery -->' ;
816 $feed .= '<link rel="hub" href="' . htmlspecialchars ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
817 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
819 $feed .= '<author><name>' . htmlspecialchars ( $pageaddr ). '</name><uri>' . htmlspecialchars ( $pageaddr ). '</uri></author>' ;
820 $feed .= '<id>' . htmlspecialchars ( $pageaddr ). '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
827 // ------------------------------------------------------------------------------------------
828 // Render HTML page (according to URL parameters and user rights)
829 function renderPage ()
833 // -------- Display login form.
834 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=login' ))
836 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
837 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
838 $PAGE = new pageBuilder
;
839 $PAGE- > assign ( 'token' , $token );
840 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? $_SERVER [ 'HTTP_REFERER' ]: '' ));
841 $PAGE- > renderPage ( 'loginform' );
844 // -------- User wants to logout.
845 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
849 header ( 'Location: ?' );
853 // -------- Picture wall
854 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=picwall' ))
856 // Optionnaly filter the results:
858 if (! empty ( $_GET [ 'searchterm' ])) $links = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
859 elseif (! empty ( $_GET [ 'searchtags' ])) $links = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
860 else $links = $LINKSDB ;
862 $linksToDisplay = array ();
864 // Get only links which have a thumbnail.
865 foreach ( $links as $link )
867 $permalink = '?' . htmlspecialchars ( smallhash ( $link [ 'linkdate' ]), ENT_QUOTES
);
868 $thumb = thumbnail ( $link [ 'url' ], $permalink );
869 if ( $thumb != '' ) // Only output links which have a thumbnail.
871 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
872 $link [ 'permalink' ]= $permalink ;
873 $linksToDisplay []= $link ; // Add to array.
876 $PAGE = new pageBuilder
;
877 $PAGE- > assign ( 'linksToDisplay' , $linksToDisplay );
878 $PAGE- > renderPage ( 'picwall' );
882 // -------- Tag cloud
883 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tagcloud' ))
885 $tags = $LINKSDB- > allTags ();
886 // We sort tags alphabetically, then choose a font size according to count.
887 // First, find max value.
888 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
891 foreach ( $tags as $key => $value )
893 $tagList [ $key ] = array ( 'count' => $value , 'size' => max ( 40 * $value / $maxcount , 8 ));
895 $PAGE = new pageBuilder
;
896 $PAGE- > assign ( 'tags' , $tagList );
897 $PAGE- > renderPage ( 'tagcloud' );
901 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
902 if ( isset ( $_GET [ 'addtag' ]))
904 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
905 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
906 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
907 $params [ 'searchtags' ] = ( empty ( $params [ 'searchtags' ]) ? trim ( $_GET [ 'addtag' ]) : trim ( $params [ 'searchtags' ]). ' ' . urlencode ( trim ( $_GET [ 'addtag' ])));
908 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
909 header ( 'Location: ?' . http_build_query ( $params ));
913 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
914 if ( isset ( $_GET [ 'removetag' ]))
916 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
917 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?' ); exit ; } // In case browser does not send HTTP_REFERER
918 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
919 if ( isset ( $params [ 'searchtags' ]))
921 $tags = explode ( ' ' , $params [ 'searchtags' ]);
922 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
923 if ( count ( $tags )== 0 ) unset ( $params [ 'searchtags' ]); else $params [ 'searchtags' ] = implode ( ' ' , $tags );
924 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
926 header ( 'Location: ?' . http_build_query ( $params ));
930 // -------- User wants to change the number of links per page (linksperpage=...)
931 if ( isset ( $_GET [ 'linksperpage' ]))
933 if ( is_numeric ( $_GET [ 'linksperpage' ])) { $_SESSION
[ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET
[ 'linksperpage' ])); }
934 header ( 'Location: ' .( empty ( $_SERVER [ 'HTTP_REFERER' ])? '?' : $_SERVER [ 'HTTP_REFERER' ]));
939 // -------- Handle other actions allowed for non-logged in users:
942 // User tries to post new link but is not loggedin:
943 // Show login screen, then redirect to ?post=...
944 if ( isset ( $_GET [ 'post' ]))
946 header ( 'Location: ?do=login&post=' . urlencode ( $_GET [ 'post' ]).(! empty ( $_GET [ 'title' ])? '&title=' . urlencode ( $_GET [ 'title' ]): '' ).(! empty ( $_GET [ 'source' ])? '&source=' . urlencode ( $_GET [ 'source' ]): '' )); // Redirect to login page, then back to post link.
949 $PAGE = new pageBuilder
;
950 buildLinkList ( $PAGE ); // Compute list of links to display
951 $PAGE- > renderPage ( 'linklist' );
952 exit ; // Never remove this one ! All operations below are reserved for logged in user.
955 // -------- All other functions are reserved for the registered user:
957 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
958 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=tools' ))
960 $PAGE = new pageBuilder
;
961 $PAGE- > assign ( 'pageabsaddr' , indexUrl ());
962 $PAGE- > renderPage ( 'tools' );
966 // -------- User wants to change his/her password.
967 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changepasswd' ))
969 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
970 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
972 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
974 // Make sure old password is correct.
975 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
976 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
978 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
979 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
981 echo '<script language="JavaScript">alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
984 else // show the change password form.
986 $PAGE = new pageBuilder
;
987 $PAGE- > assign ( 'token' , getToken ());
988 $PAGE- > renderPage ( 'changepassword' );
993 // -------- User wants to change configuration
994 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=configure' ))
996 if (! empty ( $_POST [ 'title' ]) )
998 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
1000 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1001 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1002 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1003 $GLOBALS [ 'timezone' ] = $tz ;
1004 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1005 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1007 echo '<script language="JavaScript">alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1010 else // Show the configuration form.
1012 $PAGE = new pageBuilder
;
1013 $PAGE- > assign ( 'token' , getToken ());
1014 $PAGE- > assign ( 'title' , htmlspecialchars ( empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] , ENT_QUOTES
));
1015 $PAGE- > assign ( 'redirector' , htmlspecialchars ( empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] , ENT_QUOTES
));
1016 list ( $timezone_form , $timezone_js ) = templateTZform ( $GLOBALS [ 'timezone' ]);
1017 $PAGE- > assign ( 'timezone_form' , $timezone_form ); // FIXME: put entire tz form generation in template ?
1018 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1019 $PAGE- > renderPage ( 'configure' );
1024 // -------- User wants to rename a tag or delete it
1025 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=changetag' ))
1027 if ( empty ( $_POST [ 'fromtag' ]))
1029 $PAGE = new pageBuilder
;
1030 $PAGE- > assign ( 'token' , getToken ());
1031 $PAGE- > renderPage ( 'changetag' );
1034 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1037 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
1039 $needle = trim ( $_POST [ 'fromtag' ]);
1040 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
1041 foreach ( $linksToAlter as $key => $value )
1043 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1044 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1045 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1046 $LINKSDB [ $key ]= $value ;
1048 $LINKSDB- > savedb (); // save to disk
1050 echo '<script language="JavaScript">alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1055 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
1057 $needle = trim ( $_POST [ 'fromtag' ]);
1058 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
1059 foreach ( $linksToAlter as $key => $value )
1061 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1062 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Remplace tags value.
1063 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1064 $LINKSDB [ $key ]= $value ;
1066 $LINKSDB- > savedb (); // save to disk
1068 echo '<script language="JavaScript">alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1073 // -------- User wants to add a link without using the bookmarklet: show form.
1074 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=addlink' ))
1076 $PAGE = new pageBuilder
;
1077 $PAGE- > renderPage ( 'addlink' );
1081 // -------- User clicked the "Save" button when editing a link: Save link to database.
1082 if ( isset ( $_POST [ 'save_edit' ]))
1084 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away !
1085 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
1086 $linkdate = $_POST [ 'lf_linkdate' ];
1087 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => trim ( $_POST [ 'lf_url' ]), 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1088 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
1089 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
1090 $LINKSDB [ $linkdate ] = $link ;
1091 $LINKSDB- > savedb (); // save to disk
1095 // If we are called from the bookmarklet, we must close the popup:
1096 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1097 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1098 header ( 'Location: ' . $returnurl ); // After saving the link, redirect to the page the user was on.
1102 // -------- User clicked the "Cancel" button when editing a link.
1103 if ( isset ( $_POST [ 'cancel_edit' ]))
1105 // If we are called from the bookmarklet, we must close the popup;
1106 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1107 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1108 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1112 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
1113 if ( isset ( $_POST [ 'delete_link' ]))
1115 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1116 // We do not need to ask for confirmation:
1117 // - confirmation is handled by javascript
1118 // - we are protected from XSRF by the token.
1119 $linkdate = $_POST [ 'lf_linkdate' ];
1120 unset ( $LINKSDB [ $linkdate ]);
1121 $LINKSDB- > savedb (); // save to disk
1123 // If we are called from the bookmarklet, we must close the popup:
1124 if ( isset ( $_GET [ 'source' ]) && $_GET [ 'source' ]== 'bookmarklet' ) { echo '<script language="JavaScript">self.close();</script>' ; exit ; }
1125 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1126 header ( 'Location: ' . $returnurl ); // After deleting the link, redirect to the page the user was on.
1130 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1131 if ( isset ( $_GET [ 'edit_link' ]))
1133 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1134 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1135 $PAGE = new pageBuilder
;
1136 $PAGE- > assign ( 'link' , $link );
1137 $PAGE- > assign ( 'link_is_new' , false );
1138 $PAGE- > assign ( 'token' , getToken ()); // XSRF protection.
1139 $PAGE- > assign ( 'http_referer' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? $_SERVER [ 'HTTP_REFERER' ] : '' ));
1140 $PAGE- > renderPage ( 'editlink' );
1144 // -------- User want to post a new link: Display link edit form.
1145 if ( isset ( $_GET [ 'post' ]))
1149 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
1150 $i = strpos ( $url , '&utm_source=' ); if ( $i !== false ) $url = substr ( $url , 0 , $i );
1151 $i = strpos ( $url , '?utm_source=' ); if ( $i !== false ) $url = substr ( $url , 0 , $i );
1152 $i = strpos ( $url , '#xtor=RSS-' ); if ( $i !== false ) $url = substr ( $url , 0 , $i );
1154 $link_is_new = false ;
1155 $link = $LINKSDB- > getLinkFromUrl ( $url ); // Check if URL is not already in database (in this case, we will edit the existing link)
1158 $link_is_new = true ; // This is a new link
1159 $linkdate = strval ( date ( 'Ymd_His' ));
1160 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] ); // Get title if it was provided in URL (by the bookmarklet).
1161 $description = '' ; $tags = '' ; $private = 0 ;
1162 if (( $url != '' ) && parse_url ( $url , PHP_URL_SCHEME
)== '' ) $url = 'http://' . $url ;
1163 // 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.)
1164 if ( empty ( $title ) && parse_url ( $url , PHP_URL_SCHEME
)== 'http' )
1166 list ( $status , $headers , $data ) = getHTTP ( $url , 4 ); // Short timeout to keep the application responsive.
1167 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1168 if ( strpos ( $status , '200 OK' )!== false ) $title = html_entity_decode ( html_extract_title ( $data ), ENT_QUOTES
, 'UTF-8' );
1170 if ( $url == '' ) $url = '?' . smallHash ( $linkdate ); // In case of empty URL, this is just a text (with a link that point to itself)
1171 $link = array ( 'linkdate' => $linkdate , 'title' => $title , 'url' => $url , 'description' => $description , 'tags' => $tags , 'private' => 0 );
1174 $PAGE = new pageBuilder
;
1175 $PAGE- > assign ( 'link' , $link );
1176 $PAGE- > assign ( 'link_is_new' , $link_is_new );
1177 $PAGE- > assign ( 'token' , getToken ()); // XSRF protection.
1178 $PAGE- > assign ( 'http_referer' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? $_SERVER [ 'HTTP_REFERER' ] : '' ));
1179 $PAGE- > renderPage ( 'editlink' );
1183 // -------- Export as Netscape Bookmarks HTML file.
1184 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=export' ))
1186 if ( empty ( $_GET [ 'what' ]))
1188 $PAGE = new pageBuilder
;
1189 $PAGE- > renderPage ( 'export' );
1192 $exportWhat = $_GET [ 'what' ];
1193 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export ???' );
1195 header ( 'Content-Type: text/html; charset=utf-8' );
1196 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1197 $currentdate = date ( 'Y/m/d H:i:s' );
1199 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1200 <!-- This is an automatically generated file.
1201 It will be read and overwritten.
1203 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1204 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1205 <TITLE>Bookmarks</TITLE>
1208 foreach ( $LINKSDB as $link )
1210 if ( $exportWhat == 'all' ||
1211 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1212 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1214 echo '<DT><A HREF="' . htmlspecialchars ( $link [ 'url' ]). '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1215 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . htmlspecialchars ( str_replace ( ' ' , ',' , $link [ 'tags' ])). '"' ;
1216 echo '>' . htmlspecialchars ( $link [ 'title' ]). "</A> \n " ;
1217 if ( $link [ 'description' ]!= '' ) echo '<DD>' . htmlspecialchars ( $link [ 'description' ]). " \n " ;
1223 // -------- User is uploading a file for import
1224 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1226 // If file is too big, some form field may be missing.
1227 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1229 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1230 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>' ;
1233 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1238 // -------- Show upload/import dialog:
1239 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=import' ))
1241 $PAGE = new pageBuilder
;
1242 $PAGE- > assign ( 'token' , getToken ());
1243 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1244 $PAGE- > renderPage ( 'import' );
1248 // -------- Otherwise, simply display search form and links:
1249 $PAGE = new pageBuilder
;
1250 buildLinkList ( $PAGE ); // Compute list of links to display
1251 $PAGE- > renderPage ( 'linklist' );
1255 // -----------------------------------------------------------------------------------------------
1256 // Process the import file form.
1257 function importFile ()
1260 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1261 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1262 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1263 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private ?
1264 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones ?
1269 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1271 // Then import the bookmarks.
1272 if ( $type == 'netscape' )
1274 // This is a standard Netscape-style bookmark file.
1275 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1276 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1278 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1279 $d = explode ( '<DD>' , $html );
1280 if ( startswith ( $d [ 0 ], '<A ' ))
1282 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1283 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1284 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1285 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1287 foreach ( $matches as $m )
1289 $attr = $m [ 1 ]; $value = $m [ 2 ];
1290 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1291 elseif ( $attr == 'ADD_DATE' ) $raw_add_date = intval ( $value );
1292 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1293 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1295 if ( $link [ 'url' ]!= '' )
1297 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1298 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1300 { // Link not in database, let's import it...
1301 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1303 // Make sure date/time is not already used by another link.
1304 // (Some bookmark files have several different links with the same ADD_DATE)
1305 // We increment date by 1 second until we find a date which is not used in db.
1306 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1307 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1308 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1309 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1312 else // link already present in database.
1315 { // If overwrite is required, we import link data, except date/time.
1316 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1317 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1327 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1331 echo '<script language="JavaScript">alert("File ' . $filename . ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1335 // -----------------------------------------------------------------------------------------------
1336 // Template for the list of links (<div id="linklist">)
1337 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1338 function buildLinkList ( $PAGE )
1340 global $LINKSDB ; // Get the links database.
1342 // ---- Filter link database according to parameters
1343 $linksToDisplay = array ();
1346 if (! empty ( $_GET [ 'searchterm' ])) // Fulltext search
1348 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1349 $search_crits = htmlspecialchars ( trim ( $_GET [ 'searchterm' ]));
1350 $search_type = 'fulltext' ;
1352 elseif (! empty ( $_GET [ 'searchtags' ])) // Search by tag
1354 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1355 $search_crits = explode ( ' ' , trim ( $_GET [ 'searchtags' ]));
1356 $search_type = 'tags' ;
1358 elseif ( isset ( $_SERVER [ "QUERY_STRING" ]) && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ "QUERY_STRING" ])) // Detect smallHashes in URL
1360 $linksToDisplay = $LINKSDB- > filterSmallHash ( substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 ));
1361 $search_type = 'permalink' ;
1364 $linksToDisplay = $LINKSDB ; // otherwise, display without filtering.
1367 // ---- Handle paging.
1368 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1369 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1370 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1372 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks php.
1374 // If there is only a single link, we change on-the-fly the title of the page.
1375 if ( count ( $linksToDisplay )== 1 ) $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1377 // Select articles according to paging.
1378 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1379 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1380 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1381 $page = ( $page < 1 ? 1 : $page );
1382 $page = ( $page > $pagecount ? $pagecount : $page );
1383 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1384 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1385 $linkDisp = array (); // Links to display
1386 while ( $i < $end && $i < count ( $keys ))
1388 $link = $linksToDisplay [ $keys [ $i ]];
1389 $link [ 'description' ]= nl2br ( keepMultipleSpaces ( text2clickable ( htmlspecialchars ( $link [ 'description' ]))));
1390 $title = $link [ 'title' ];
1391 $classLi = $i %
2 != 0 ? '' : 'publicLinkHightLight' ;
1392 $link [ 'class' ] = ( $link [ 'private' ]== 0 ? $classLi : 'private' );
1393 $link [ 'localdate' ]= linkdate2locale ( $link [ 'linkdate' ]);
1394 $link [ 'taglist' ]= explode ( ' ' , $link [ 'tags' ]);
1395 $linkDisp [ $keys [ $i ]] = $link ;
1399 // Compute paging navigation
1400 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1401 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1403 $previous_page_url = '' ; if ( $i != count ( $keys )) $previous_page_url = '?page=' .( $page +
1 ). $searchterm . $searchtags ;
1404 $next_page_url = '' ; if ( $page > 1 ) $next_page_url = '?page=' .( $page-1 ). $searchterm . $searchtags ;
1406 $token = '' ; if ( isLoggedIn ()) $token = getToken ();
1408 // Fill all template fields.
1409 $PAGE- > assign ( 'previous_page_url' , $previous_page_url );
1410 $PAGE- > assign ( 'next_page_url' , $next_page_url );
1411 $PAGE- > assign ( 'page_current' , $page );
1412 $PAGE- > assign ( 'page_max' , $pagecount );
1413 $PAGE- > assign ( 'result_count' , count ( $linksToDisplay ));
1414 $PAGE- > assign ( 'search_type' , $search_type );
1415 $PAGE- > assign ( 'search_crits' , $search_crits );
1416 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ]); // optional redirector URL
1417 $PAGE- > assign ( 'token' , $token );
1418 $PAGE- > assign ( 'links' , $linkDisp );
1422 // Returns the HTML code to display a thumbnail for a link
1423 // with a link to the original URL.
1424 // Understands various services (youtube.com...)
1425 // Input: $url = url for which the thumbnail must be found.
1426 // $href = if provided, this URL will be followed instead of $url
1427 function thumbnail ( $url , $href = false )
1429 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return '' ;
1431 if ( $href == false ) $href = $url ;
1433 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1434 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1435 // ^^^^^^^^^^^ ^^^^^^^^^^^
1436 $domain = parse_url ( $url , PHP_URL_HOST
);
1437 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1439 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1440 if (! empty ( $params [ 'v' ])) return '<a href="' . htmlspecialchars ( $href ). '"><img src="http://img.youtube.com/vi/' . htmlspecialchars ( $params [ 'v' ]). '/default.jpg" width="120" height="90"></a>' ;
1442 if ( $domain == 'youtu.be' ) // Youtube short links
1444 $path = parse_url ( $url , PHP_URL_PATH
);
1445 return '<a href="' . htmlspecialchars ( $href ). '"><img src="http://img.youtube.com/vi' . htmlspecialchars ( $path ). '/default.jpg" width="120" height="90"></a>' ;
1447 if ( $domain == 'imgur.com' )
1449 $path = parse_url ( $url , PHP_URL_PATH
);
1450 if ( startsWith ( $path , '/a/' )) return '' ; // Thumbnails for albums are not available.
1451 if ( startsWith ( $path , '/r/' )) return '<a href="' . htmlspecialchars ( $href ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( basename ( $path )). 's.jpg" width="90" height="90"></a>' ;
1452 if ( startsWith ( $path , '/gallery/' )) return '<a href="' . htmlspecialchars ( $href ). '"><img src="http://i.imgur.com' . htmlspecialchars ( substr ( $path , 8 )). 's.jpg" width="90" height="90"></a>' ;
1453 if ( substr_count ( $path , '/' )== 1 ) return '<a href="' . htmlspecialchars ( $href ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( substr ( $path , 1 )). 's.jpg" width="90" height="90"></a>' ;
1455 if ( $domain == 'i.imgur.com' )
1457 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1458 if (! empty ( $pi [ 'filename' ])) return '<a href="' . htmlspecialchars ( $href ). '"><img src="http://i.imgur.com/' . htmlspecialchars ( $pi [ 'filename' ]). 's.jpg" width="90" height="90"></a>' ;
1460 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1462 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1464 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1465 return '<a href="' . htmlspecialchars ( $href ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a>' ;
1468 if ( endsWith ( $domain , '.imageshack.us' ))
1470 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1471 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1473 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1474 return '<a href="' . htmlspecialchars ( $href ). '"><img src="' . htmlspecialchars ( $thumburl ). '" width="120" style="height:auto;"></a>' ;
1478 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1479 // So we deport the thumbnail generation in order not to slow down page generation
1480 // (and we also cache the thumbnail)
1482 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return '' ; // If local cache is disabled, no thumbnails for services which require the use a local cache.
1484 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1485 || $domain == 'vimeo.com'
1486 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1489 if ( $domain == 'vimeo.com' )
1490 { // Make sure this vimeo url points to a video (/xxx... where xxx is numeric)
1491 $path = parse_url ( $url , PHP_URL_PATH
);
1492 if (! preg_match ( '!/\d+.+?!' , $path )) return '' ; // This is not a single video URL.
1494 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1495 { // Make sure this TED url points to a video (/talks/...)
1496 $path = parse_url ( $url , PHP_URL_PATH
);
1497 if ( "/talks/" !== substr ( $path , 0 , 7 )) return '' ; // This is not a single video URL.
1499 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1500 return '<a href="' . htmlspecialchars ( $href ). '"><img src="?do=genthumbnail&hmac=' . htmlspecialchars ( $sign ). '&url=' . urlencode ( $url ). '" width="120" style="height:auto;"></a>' ;
1503 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1504 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1505 // But using the extension will do.
1506 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1507 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1509 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1510 return '<a href="' . htmlspecialchars ( $href ). '"><img src="?do=genthumbnail&hmac=' . htmlspecialchars ( $sign ). '&url=' . urlencode ( $url ). '" width="120" style="height:auto;"></a>' ;
1512 return '' ; // No thumbnail.
1516 // -----------------------------------------------------------------------------------------------
1518 // This function should NEVER be called if the file data/config.php exists.
1521 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1522 if ( endsWith ( $_SERVER [ 'SERVER_NAME' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1524 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1527 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1528 if ( isTZvalid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1529 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1530 $GLOBALS [ 'timezone' ] = $tz ;
1531 // Everything is ok, let's create config file.
1532 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
1533 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1534 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1535 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . htmlspecialchars ( indexUrl ()) : $_POST [ 'title' ] );
1537 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location= \' ?do=login \' ;</script>' ;
1541 // Display config form:
1542 list ( $timezone_form , $timezone_js ) = templateTZform ();
1543 $timezone_html = '' ; if ( $timezone_form != '' ) $timezone_html = '<tr><td valign="top"><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
1545 $PAGE = new pageBuilder
;
1546 $PAGE- > assign ( 'timezone_html' , $timezone_html );
1547 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1548 $PAGE- > renderPage ( 'install' );
1552 // Generates the timezone selection form and javascript.
1553 // Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1554 // Output: array(html,js)
1555 // Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1556 // Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1557 function templateTZform ( $ptz = false )
1559 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1561 // Try to split the provided timezone.
1562 if ( $ptz == false ) { $l
= timezone_identifiers_list (); $ptz
= $l
[ 0 ]; }
1563 $spos = strpos ( $ptz , '/' ); $pcontinent = substr ( $ptz , 0 , $spos ); $pcity = substr ( $ptz , $spos +
1 );
1565 // Display config form:
1566 $timezone_form = '' ;
1568 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1569 // We split the list in continents/cities.
1570 $continents = array ();
1572 foreach ( timezone_identifiers_list () as $tz )
1574 if ( $tz == 'UTC' ) $tz = 'UTC/UTC' ;
1575 $spos = strpos ( $tz , '/' );
1578 $continent = substr ( $tz , 0 , $spos ); $city = substr ( $tz , $spos +
1 );
1579 $continents [ $continent ]= 1 ;
1580 if (! isset ( $cities [ $continent ])) $cities [ $continent ]= array ();
1581 $cities [ $continent ].= '<option value="' . $city . '"' .( $pcity == $city ? 'selected' : '' ). '>' . $city . '</option>' ;
1584 $continents_html = '' ;
1585 $continents = array_keys ( $continents );
1586 foreach ( $continents as $continent )
1587 $continents_html .= '<option value="' . $continent . '"' .( $pcontinent == $continent ? 'selected' : '' ). '>' . $continent . '</option>' ;
1588 $cities_html = $cities [ $pcontinent ];
1589 $timezone_form = "Continent: <select name= \" continent \" id= \" continent \" onChange= \" onChangecontinent(); \" > ${continents_html} </select><br /><br />" ;
1590 $timezone_form .= "City: <select name= \" city \" id= \" city \" > ${cities[$pcontinent]} </select><br /><br />" ;
1591 $timezone_js = "<script language= \" JavaScript \" >" ;
1592 $timezone_js .= "function onChangecontinent() {document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];} " ;
1593 $timezone_js .= "var citiescontinent = " . json_encode ( $cities ). ";" ;
1594 $timezone_js .= "</script>" ;
1595 return array ( $timezone_form , $timezone_js );
1597 return array ( '' , '' );
1600 // Tells if a timezone is valid or not.
1601 // If not valid, returns false.
1602 // If system does not support timezone list, returns false.
1603 function isTZvalid ( $continent , $city )
1605 $tz = $continent . '/' . $city ;
1606 if ( function_exists ( 'timezone_identifiers_list' )) // because of old php version (5.1) which can be found on free.fr
1608 if ( in_array ( $tz , timezone_identifiers_list ())) // it's a valid timezone ?
1615 // Webservices (for use with jQuery/jQueryUI)
1616 // eg. index.php?ws=tags&term=minecr
1617 function processWS ()
1619 if ( empty ( $_GET [ 'ws' ]) || empty ( $_GET [ 'term' ])) return ;
1620 $term = $_GET [ 'term' ];
1622 header ( 'Content-Type: application/json; charset=utf-8' );
1624 // Search in tags (case insentitive, cumulative search)
1625 if ( $_GET [ 'ws' ]== 'tags' )
1627 $tags = explode ( ' ' , str_replace ( ',' , ' ' , $term )); $last = array_pop ( $tags ); // Get the last term ("a b c d" ==> "a b c", "d")
1628 $addtags = '' ; if ( $tags ) $addtags = implode ( ' ' , $tags ). ' ' ; // We will pre-pend previous tags
1630 /* To speed up things, we store list of tags in session */
1631 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1632 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1634 if ( startsWith ( $key , $last , $case = false ) && ! in_array ( $key , $tags )) $suggested [ $addtags . $key . ' ' ]= 0 ;
1636 echo json_encode ( array_keys ( $suggested ));
1640 // Search a single tag (case sentitive, single tag search)
1641 if ( $_GET [ 'ws' ]== 'singletag' )
1643 /* To speed up things, we store list of tags in session */
1644 if ( empty ( $_SESSION [ 'tags' ])) $_SESSION [ 'tags' ] = $LINKSDB- > allTags ();
1645 foreach ( $_SESSION [ 'tags' ] as $key => $value )
1647 if ( startsWith ( $key , $term , $case = true )) $suggested [ $key ]= 0 ;
1649 echo json_encode ( array_keys ( $suggested ));
1654 // Re-write configuration file according to globals.
1655 // Requires some $GLOBALS to be set (login,hash,salt,title).
1656 // If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1657 // (otherwise, the function simply returns.)
1658 function writeConfig ()
1660 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]) && ! isLoggedIn ()) die ( 'You are not authorized to alter config.' ); // Only logged in user can alter config.
1661 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
1662 $config = '<?php $GLOBALS [ \' login \' ]=' . var_export ( $GLOBALS [ 'login' ], true ). '; $GLOBALS [ \' hash \' ]=' . var_export ( $GLOBALS [ 'hash' ], true ). '; $GLOBALS [ \' salt \' ]=' . var_export ( $GLOBALS [ 'salt' ], true ). '; ' ;
1663 $config .= ' $GLOBALS [ \' timezone \' ]=' . var_export ( $GLOBALS [ 'timezone' ], true ). '; date_default_timezone_set(' . var_export ( $GLOBALS [ 'timezone' ], true ). '); $GLOBALS [ \' title \' ]=' . var_export ( $GLOBALS [ 'title' ], true ). ';' ;
1664 $config .= ' $GLOBALS [ \' redirector \' ]=' . var_export ( $GLOBALS [ 'redirector' ], true ). '; ' ;
1666 if (! file_put_contents ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ], $config ) || strcmp ( file_get_contents ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ]), $config )!= 0 )
1668 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>' ;
1673 /* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
1674 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1675 The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
1676 This function is called by passing the url:
1677 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1678 [URL] is the URL of the link (eg. a flickr page)
1679 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1680 The function below will fetch the image from the webservice and store it in the cache.
1682 function genThumbnail ()
1684 // Make sure the parameters in the URL were generated by us.
1685 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
1686 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy !' );
1688 // Let's see if we don't already have the image for this URL in the cache.
1689 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
1690 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
1691 { // We have the thumbnail, just serve it:
1692 header ( 'Content-Type: image/jpeg' );
1693 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
1696 // We may also serve a blank image (if service did not respond)
1697 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
1698 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
1700 header ( 'Content-Type: image/gif' );
1701 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
1705 // Otherwise, generate the thumbnail.
1706 $url = $_GET [ 'url' ];
1707 $domain = parse_url ( $url , PHP_URL_HOST
);
1709 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
1711 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1712 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1713 // All images in Flickr are in the form:
1714 // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
1715 // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
1716 // We want the 240x120 format, which is _m.jpg.
1717 // We search for the first image in the page which does not have the _s size,
1718 // when use the _m to get the thumbnail.
1720 // Is this a link to an image, or to a flickr page ?
1722 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
1723 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1724 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
1725 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1727 else // this is a flickr page (html)
1729 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 20 ); // Get the flickr html page.
1730 if ( strpos ( $httpstatus , '200 OK' )!== false )
1732 preg_match ( '!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!' , $data , $matches );
1733 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
1737 { // Let's download the image.
1738 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 ); // Image is 240x120, so 10 seconds to download should be enough.
1739 if ( strpos ( $httpstatus , '200 OK' )!== false )
1741 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
1742 header ( 'Content-Type: image/jpeg' );
1749 elseif ( $domain == 'vimeo.com' )
1751 // This is more complex: we have to perform a HTTP request, then parse the result.
1752 // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
1753 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
1754 list ( $httpstatus , $headers , $data ) = getHTTP ( 'http://vimeo.com/api/v2/video/' . htmlspecialchars ( $vid ). '.php' , 5 );
1755 if ( strpos ( $httpstatus , '200 OK' )!== false )
1757 $t = unserialize ( $data );
1758 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
1759 // Then we download the image and serve it to our client.
1760 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 10 );
1761 if ( strpos ( $httpstatus , '200 OK' )!== false )
1763 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
1764 header ( 'Content-Type: image/jpeg' );
1771 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1773 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
1774 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
1775 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
1776 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 5 );
1777 if ( strpos ( $httpstatus , '200 OK' )!== false )
1779 // Extract the link to the thumbnail
1780 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)[^s]!' , $data , $matches );
1781 if (! empty ( $matches [ 1 ]))
1782 { // Let's download the image.
1783 $imageurl = $matches [ 1 ];
1784 list ( $httpstatus , $headers , $data ) = getHTTP ( $imageurl , 20 ); // No control on image size, so wait long enough.
1785 if ( strpos ( $httpstatus , '200 OK' )!== false )
1787 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
1788 file_put_contents ( $filepath , $data ); // Save image to cache.
1789 if ( resizeImage ( $filepath ))
1791 header ( 'Content-Type: image/jpeg' );
1792 echo file_get_contents ( $filepath );
1802 // For all other domains, we try to download the image and make a thumbnail.
1803 list ( $httpstatus , $headers , $data ) = getHTTP ( $url , 30 ); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1804 if ( strpos ( $httpstatus , '200 OK' )!== false )
1806 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
1807 file_put_contents ( $filepath , $data ); // Save image to cache.
1808 if ( resizeImage ( $filepath ))
1810 header ( 'Content-Type: image/jpeg' );
1811 echo file_get_contents ( $filepath );
1818 // Otherwise, return an empty image (8x8 transparent gif)
1819 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
1820 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
1821 header ( 'Content-Type: image/gif' );
1825 // Make a thumbnail of the image (to width: 120 pixels)
1826 // Returns true if success, false otherwise.
1827 function resizeImage ( $filepath )
1829 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
1831 // Trick: some stupid people rename GIF as JPEG... or else.
1832 // So we really try to open each image type whatever the extension is.
1833 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
1835 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
1836 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
1837 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
1838 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
1841 $ystart = 0 ; $yheight = $h ;
1842 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
1843 $nw = 120 ; // Desired width
1844 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
1846 $im2 = imagecreatetruecolor ( $nw , $nh );
1847 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
1848 imageinterlace ( $im2 , true ); // For progressive JPEG.
1849 $tempname = $filepath . '_TEMP.jpg' ;
1850 imagejpeg ( $im2 , $tempname , 90 );
1853 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
1857 // Invalidate caches when the database is changed or the user logs out.
1858 // (eg. tags cache).
1859 function invalidateCaches ()
1861 unset ( $_SESSION [ 'tags' ]);
1864 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
1865 $LINKSDB = new linkdb ( isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]); // Read links from database (and filter private links if used it not logged in).
1866 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'ws=' )) { processWS (); exit ; } // Webservices (for jQuery/jQueryUI)
1867 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];
1868 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
1869 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }