]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.0 - Shaare your links...
5 * The personal, minimalist, super-fast, no-database Delicious clone.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
25 /* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
33 * Shaarli directories & configuration files
36 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ;
38 // Main configuration file
39 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ;
42 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ;
45 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ;
47 // For updates check of Shaarli
48 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
50 // RainTPL cache directory (keep the trailing slash!)
51 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
52 // Raintpl template directory (keep the trailing slash!)
53 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
55 // Thuumbnail cache directory
56 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
58 // Atom & RSS feed cache directory
59 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
63 * Global configuration
65 // Ban IP after this many failures
66 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
67 // Ban duration for IP address after login failures (in seconds)
68 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
71 // Enable RSS permalinks by default.
72 // This corresponds to the default behavior of shaarli before this was added as an option.
73 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
74 // If true, an extra "ATOM feed" button will be displayed in the toolbar
75 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
77 // Link display options
78 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
79 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
80 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
82 // Open Shaarli (true): anyone can add/edit/delete links without having to login
83 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
86 // Display thumbnails in links
87 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
88 // Store thumbnails in a local cache
89 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
91 // Update check frequency for Shaarli. 86400 seconds=24 hours
92 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
96 * Plugin configuration
98 * Warning: order matters!
100 * These settings may be be overriden in:
102 * - each plugin's configuration file
104 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
105 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
106 // 'wallabag', 'markdown', 'addlink_toolbar',
108 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
110 //$GLOBALS['plugins']['WALLABAG_URL'] = 'https://demo.wallabag.org/';
112 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
113 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
118 define ( 'shaarli_version' , '0.6.0' );
120 // http://server.com/x/shaarli --> /shaarli/
121 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
123 // High execution time in case of problematic imports/exports.
124 ini_set ( 'max_input_time' , '60' );
126 // Try to set max upload file size and read
127 ini_set ( 'memory_limit' , '128M' );
128 ini_set ( 'post_max_size' , '16M' );
129 ini_set ( 'upload_max_filesize' , '16M' );
131 // See all error except warnings
132 error_reporting ( E_ALL^E_WARNING
);
133 // See all errors (for debugging only)
134 //error_reporting(-1);
139 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
140 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
144 require_once 'application/Cache.php' ;
145 require_once 'application/CachedPage.php' ;
146 require_once 'application/HttpUtils.php' ;
147 require_once 'application/LinkDB.php' ;
148 require_once 'application/TimeZone.php' ;
149 require_once 'application/Url.php' ;
150 require_once 'application/Utils.php' ;
151 require_once 'application/Config.php' ;
152 require_once 'application/PluginManager.php' ;
153 require_once 'application/Router.php' ;
155 // Ensure the PHP version is supported
157 checkPHPVersion ( '5.3' , PHP_VERSION
);
158 } catch ( Exception
$e ) {
159 header ( 'Content-Type: text/plain; charset=utf-8' );
160 echo $e- > getMessage ();
164 // Force cookie path (but do not change lifetime)
165 $cookie = session_get_cookie_params ();
167 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
168 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
170 // Set default cookie expiration and path.
171 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
172 // Set session parameters on server side.
173 // If the user does not access any page within this time, his/her session is considered expired.
174 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
175 // Use cookies to store session.
176 ini_set ( 'session.use_cookies' , 1 );
177 // Force cookies for session (phpsessionID forbidden in URL).
178 ini_set ( 'session.use_only_cookies' , 1 );
179 // Prevent PHP form using sessionID in URL if cookies are disabled.
180 ini_set ( 'session.use_trans_sid' , false );
182 session_name ( 'shaarli' );
183 // Start session if needed (Some server auto-start sessions).
184 if ( session_id () == '' ) {
188 // Regenerate session ID if invalid or not defined in cookie.
189 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
190 session_regenerate_id ( true );
191 $_COOKIE [ 'shaarli' ] = session_id ();
194 include "inc/rain.tpl.class.php" ; //include Rain TPL
195 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
196 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
198 $pluginManager = PluginManager
:: getInstance ();
199 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
201 ob_start (); // Output buffering for the page cache.
204 // In case stupid admin has left magic_quotes enabled in php.ini:
205 if ( get_magic_quotes_gpc ())
207 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
208 $_POST = array_map ( 'stripslashes_deep' , $_POST );
209 $_GET = array_map ( 'stripslashes_deep' , $_GET );
210 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
213 // Prevent caching on client side or proxy: (yes, it's ugly)
214 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
215 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
216 header ( "Cache-Control: post-check=0, pre-check=0" , false );
217 header ( "Pragma: no-cache" );
219 // Directories creations (Note that your web host may require different rights than 705.)
220 if (! is_writable ( realpath ( dirname ( __FILE__
)))) die ( '<pre>ERROR: Shaarli does not have the right to write in its own directory.</pre>' );
222 // Handling of old config file which do not have the new parameters.
223 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
224 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
225 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
226 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
227 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
228 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
229 // I really need to rewrite Shaarli with a proper configuation manager.
231 // Run config screen if first run:
232 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
236 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
237 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
238 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
240 // a token depending of deployment salt, user password, and the current ip
241 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
243 autoLocale (); // Sniff browser language and set date format accordingly.
244 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
246 //==================================================================================================
247 // Checking session state (i.e. is the user still logged in)
248 //==================================================================================================
250 function setup_login_state () {
251 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
252 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
253 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
254 $userIsLoggedIn = true ;
256 if (! isset ( $GLOBALS [ 'login' ])) {
257 $userIsLoggedIn = false ; // Shaarli is not configured yet.
258 $loginFailure = true ;
260 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
261 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
265 $userIsLoggedIn = true ;
267 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
268 if ( empty ( $_SESSION [ 'uid' ]) ||
269 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
270 time () >= $_SESSION [ 'expires_on' ])
273 $userIsLoggedIn = false ;
274 $loginFailure = true ;
276 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
277 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
280 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
282 if (! $loginFailure ) {
283 $userIsLoggedIn = true ;
286 return $userIsLoggedIn ;
288 $userIsLoggedIn = setup_login_state ();
290 // Checks if an update is available for Shaarli.
291 // (at most once a day, and only for registered user.)
292 // Output: '' = no new version.
293 // other= the available version.
294 function checkUpdate ()
296 if (! isLoggedIn ()) return '' ; // Do not check versions for visitors.
297 if ( empty ( $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ])) return '' ; // Do not check if the user doesn't want to.
299 // Get latest version number at most once a day.
300 if (! is_file ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]) || ( filemtime ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ])< time ()-( $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ])))
302 $version = shaarli_version
;
303 list ( $headers , $data ) = get_http_url ( 'https://raw.githubusercontent.com/shaarli/Shaarli/master/shaarli_version.php' , 2 );
304 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
305 $version = str_replace ( ' */ ?>' , '' , str_replace ( '<?php /* ' , '' , $data ));
307 // If failed, never mind. We don't want to bother the user with that.
308 file_put_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ], $version ); // touch file date
311 $newestversion = file_get_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]);
312 if ( version_compare ( $newestversion , shaarli_version
)== 1 ) return $newestversion ;
317 // -----------------------------------------------------------------------------------------------
319 function logm ( $message )
321 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
322 file_put_contents ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' , $t , FILE_APPEND
);
325 // In a string, converts URLs to clickable links.
326 // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
327 function text2clickable ( $url )
329 $redir = empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ];
330 return preg_replace ( '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si' , '<a href="' . $redir . ' $1" rel="nofollow"> $1 </a>' , $url );
333 // This function inserts where relevant so that multiple spaces are properly displayed in HTML
334 // even in the absence of <pre> (This is used in description to keep text formatting)
335 function keepMultipleSpaces ( $text )
337 return str_replace ( ' ' , ' ' , $text );
340 // ------------------------------------------------------------------------------------------
341 // Sniff browser language to display dates in the right format automatically.
342 // (Note that is may not work on your server if the corresponding local is not installed.)
343 function autoLocale ()
345 $attempts = array ( 'en_US' ); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
346 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
347 { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
348 if ( preg_match ( '/([a-z] {2} )-?([a-z] {2} )?/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) {
349 $loc = $matches [ 1 ] . (! empty ( $matches [ 2 ]) ? '_' . strtoupper ( $matches [ 2 ]) : '' );
350 $attempts = array ( $loc . '.UTF-8' , $loc , str_replace ( '_' , '-' , $loc ). '.UTF-8' , str_replace ( '_' , '-' , $loc ),
351 $loc . '_' . strtoupper ( $loc ). '.UTF-8' , $loc . '_' . strtoupper ( $loc ),
352 $loc . '_' . $loc . '.UTF-8' , $loc . '_' . $loc , $loc . '-' . strtoupper ( $loc ). '.UTF-8' ,
353 $loc . '-' . strtoupper ( $loc ), $loc . '-' . $loc . '.UTF-8' , $loc . '-' . $loc );
356 setlocale ( LC_TIME
, $attempts ); // LC_TIME = Set local for date/time format only.
359 // ------------------------------------------------------------------------------------------
360 // PubSubHubbub protocol support (if enabled) [UNTESTED]
361 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
362 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
365 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
367 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
369 index_url ( $_SERVER ). '?do=atom' ,
370 index_url ( $_SERVER ). '?do=rss'
372 $p- > publish_update ( $topic_url );
376 // ------------------------------------------------------------------------------------------
377 // Session management
379 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
382 $ip = $_SERVER [ "REMOTE_ADDR" ];
383 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
384 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
385 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
389 function fillSessionInfo () {
390 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
391 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
392 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
393 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
396 // Check that user/password is correct.
397 function check_auth ( $login , $password )
399 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
400 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
401 { // Login/password is correct.
403 logm ( 'Login successful' );
406 logm ( 'Login failed for user ' . $login );
410 // Returns true if the user is logged in.
411 function isLoggedIn ()
413 global $userIsLoggedIn ;
414 return $userIsLoggedIn ;
419 if ( isset ( $_SESSION )) {
420 unset ( $_SESSION [ 'uid' ]);
421 unset ( $_SESSION [ 'ip' ]);
422 unset ( $_SESSION [ 'username' ]);
423 unset ( $_SESSION [ 'privateonly' ]);
425 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
429 // ------------------------------------------------------------------------------------------
430 // Brute force protection system
431 // Several consecutive failed logins will ban the IP address for 30 minutes.
432 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 ?>" );
433 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
434 // Signal a failed login. Will ban the IP if too many failures:
435 function ban_loginFailed ()
437 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
438 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
439 $gb [ 'FAILURES' ][ $ip ] ++
;
440 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
442 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
443 logm ( 'IP address banned from login' );
445 $GLOBALS [ 'IPBANS' ] = $gb ;
446 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
449 // Signals a successful login. Resets failed login counter.
450 function ban_loginOk ()
452 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
453 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
454 $GLOBALS [ 'IPBANS' ] = $gb ;
455 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
458 // Checks if the user CAN login. If 'true', the user can try to login.
459 function ban_canLogin ()
461 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
462 if ( isset ( $gb [ 'BANS' ][ $ip ]))
464 // User is banned. Check if the ban has expired:
465 if ( $gb [ 'BANS' ][ $ip ]<= time ())
466 { // Ban expired, user can try to login again.
468 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
469 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
470 return true ; // Ban has expired, user can login.
472 return false ; // User is banned.
474 return true ; // User is not banned.
477 // ------------------------------------------------------------------------------------------
478 // Process login form: Check if login/password is correct.
479 if ( isset ( $_POST [ 'login' ]))
481 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
482 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
483 { // Login/password is OK.
485 // If user wants to keep the session cookie even after the browser closes:
486 if (! empty ( $_POST [ 'longlastingsession' ]))
488 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
489 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
490 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
492 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
493 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
494 // Note: Never forget the trailing slash on the cookie path!
495 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
497 else // Standard session expiration (=when browser closes)
499 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
500 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
501 session_regenerate_id ( true );
504 // Optional redirect after login:
505 if ( isset ( $_GET [ 'post' ])) {
506 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
507 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
508 if (! empty ( $_GET [ $param ])) {
509 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
512 header ( 'Location: ' . $uri );
516 if ( isset ( $_GET [ 'edit_link' ])) {
517 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
521 if ( isset ( $_POST [ 'returnurl' ])) {
522 // Prevent loops over login screen.
523 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
524 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
528 header ( 'Location: ?' ); exit ;
534 if ( isset ( $_GET [ 'post' ])) {
535 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
536 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
537 if (! empty ( $_GET [ $param ])) {
538 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
542 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
547 // ------------------------------------------------------------------------------------------
548 // Misc utility functions:
550 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
551 function return_bytes ( $val )
553 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
556 case 'g' : $val *= 1024 ;
557 case 'm' : $val *= 1024 ;
558 case 'k' : $val *= 1024 ;
563 // Try to determine max file size for uploads (POST).
564 // Returns an integer (in bytes)
565 function getMaxFileSize ()
567 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
568 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
569 // Return the smaller of two:
570 $maxsize = min ( $size1 , $size2 );
571 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
575 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
576 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
577 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
578 function linkdate2timestamp ( $linkdate )
580 if ( strcmp ( $linkdate , '_000000' ) !== 0 || ! $linkdate ){
582 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
583 return mktime ( $h , $m , $s , $M , $D , $Y );
588 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
589 (used to build the pubDate attribute in RSS feed.) */
590 function linkdate2rfc822 ( $linkdate )
592 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
595 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
596 (used to build the updated tags in ATOM feed.) */
597 function linkdate2iso8601 ( $linkdate )
599 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
602 // Extract title from an HTML document.
603 // (Returns an empty string if not found.)
604 function html_extract_title ( $html )
606 return preg_match ( '!<title>(.*?)</title>!is' , $html , $matches ) ? trim ( str_replace ( " \n " , ' ' , $matches [ 1 ])) : '' ;
609 // ------------------------------------------------------------------------------------------
610 // Token management for XSRF protection
611 // Token should be used in any form which acts on data (create,update,delete,import...).
612 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
617 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
618 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
622 // Tells if a token is OK. Using this function will destroy the token.
624 function tokenOk ( $token )
626 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
628 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
629 return true ; // Token is OK.
631 return false ; // Wrong token, or already used.
634 // ------------------------------------------------------------------------------------------
635 /* This class is in charge of building the final page.
636 (This is basically a wrapper around RainTPL which pre-fills some fields.)
638 p.assign('myfield','myvalue');
639 p.renderPage('mytemplate');
644 private $tpl ; // RainTPL template
646 function __construct ()
652 * Initialize all default tpl tags.
654 private function initialize ()
656 $this- > tpl
= new RainTPL
;
657 $this- > tpl
-> assign ( 'newversion' , escape ( checkUpdate ()));
658 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
659 $searchcrits = '' ; // Search criteria
660 if (! empty ( $_GET [ 'searchtags' ])) {
661 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
663 elseif (! empty ( $_GET [ 'searchterm' ])) {
664 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
666 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
667 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
668 $this- > tpl
-> assign ( 'version' , shaarli_version
);
669 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
670 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
671 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
672 if (! empty ( $GLOBALS [ 'title' ])) {
673 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
675 if (! empty ( $GLOBALS [ 'titleLink' ])) {
676 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
678 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
679 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
681 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
682 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
683 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
687 // The following assign() method is basically the same as RainTPL (except that it's lazy)
688 public function assign ( $what , $where )
690 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
691 $this- > tpl
-> assign ( $what , $where );
694 // Render a specific page (using a template).
695 // e.g. pb.renderPage('picwall')
696 public function renderPage ( $page )
698 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
699 $this- > tpl
-> draw ( $page );
703 // ------------------------------------------------------------------------------------------
704 // Output the last N links in RSS 2.0 format.
707 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
709 // $usepermalink : If true, use permalink instead of final link.
710 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
711 // Also enabled through a config option
712 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
715 $query = $_SERVER [ "QUERY_STRING" ];
716 $cache = new CachedPage (
717 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
719 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
721 $cached = $cache- > cachedVersion ();
722 if (! empty ( $cached )) {
727 // If cached was not found (or not usable), then read the database and build the response:
728 $LINKSDB = new LinkDB (
729 $GLOBALS [ 'config' ][ 'DATASTORE' ],
730 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
731 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
733 // Read links from database (and filter private links if user it not logged in).
735 // Optionally filter the results:
736 $linksToDisplay = array ();
737 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
738 else if (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
739 else $linksToDisplay = $LINKSDB ;
741 $nblinksToDisplay = 50 ; // Number of links to display.
742 if (! empty ( $_GET [ 'nb' ])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
744 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( $_GET [ 'nb' ] +
0 , 1 ) ;
747 $pageaddr = escape ( index_url ( $_SERVER ));
748 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
749 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
750 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
751 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
753 echo '<!-- PubSubHubbub Discovery -->' ;
754 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
755 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
756 echo '<!-- End Of PubSubHubbub Discovery -->' ;
759 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
760 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
762 $link = $linksToDisplay [ $keys [ $i ]];
763 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
764 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
765 $absurl = $link [ 'url' ];
766 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
767 if ( $usepermalinks === true )
768 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
770 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
771 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . escape ( $rfc822date ). "</pubDate> \n " ;
772 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
774 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
777 // Add permalink in description
778 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
779 // If user wants permalinks first, put the final link in description
780 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
781 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
782 echo '<description><![CDATA[' . nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ]))). $descriptionlink . ']]></description>' . " \n </item> \n " ;
785 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
787 $cache- > cache ( ob_get_contents ());
792 // ------------------------------------------------------------------------------------------
793 // Output the last N links in ATOM format.
796 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
798 // $usepermalink : If true, use permalink instead of final link.
799 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
800 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
803 $query = $_SERVER [ "QUERY_STRING" ];
804 $cache = new CachedPage (
805 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
807 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
809 $cached = $cache- > cachedVersion ();
810 if (! empty ( $cached )) {
815 // If cached was not found (or not usable), then read the database and build the response:
816 // Read links from database (and filter private links if used it not logged in).
817 $LINKSDB = new LinkDB (
818 $GLOBALS [ 'config' ][ 'DATASTORE' ],
819 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
820 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
823 // Optionally filter the results:
824 $linksToDisplay = array ();
825 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
826 else if (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
827 else $linksToDisplay = $LINKSDB ;
829 $nblinksToDisplay = 50 ; // Number of links to display.
830 if (! empty ( $_GET [ 'nb' ])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
832 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( $_GET [ 'nb' ] +
0 , 1 ) ;
835 $pageaddr = escape ( index_url ( $_SERVER ));
839 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
840 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
842 $link = $linksToDisplay [ $keys [ $i ]];
843 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
844 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
845 $latestDate = max ( $latestDate , $iso8601date );
846 $absurl = $link [ 'url' ];
847 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
848 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
849 if ( $usepermalinks === true )
850 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
852 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
853 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
855 // Add permalink in description
856 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
857 // If user wants permalinks first, put the final link in description
858 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
859 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
861 $entries .= '<content type="html"><![CDATA[' . nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ]))). $descriptionlink . "]]></content> \n " ;
862 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
864 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
865 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
867 $entries .= "</entry> \n " ;
870 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
871 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
872 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
873 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
874 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
876 $feed .= '<!-- PubSubHubbub Discovery -->' ;
877 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
878 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
880 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
881 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
883 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
886 $cache- > cache ( ob_get_contents ());
891 // ------------------------------------------------------------------------------------------
892 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
893 // Gives the last 7 days (which have links).
894 // This RSS feed cannot be filtered.
895 function showDailyRSS () {
897 $query = $_SERVER [ "QUERY_STRING" ];
898 $cache = new CachedPage (
899 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
901 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
903 $cached = $cache- > cachedVersion ();
904 if (! empty ( $cached )) {
909 // If cached was not found (or not usable), then read the database and build the response:
910 // Read links from database (and filter private links if used it not logged in).
911 $LINKSDB = new LinkDB (
912 $GLOBALS [ 'config' ][ 'DATASTORE' ],
913 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
914 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
917 /* Some Shaarlies may have very few links, so we need to look
918 back in time (rsort()) until we have enough days ($nb_of_days).
920 $linkdates = array ();
921 foreach ( $LINKSDB as $linkdate => $value ) {
922 $linkdates [] = $linkdate ;
925 $nb_of_days = 7 ; // We take 7 days.
926 $today = Date ( 'Ymd' );
929 foreach ( $linkdates as $linkdate ) {
930 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
931 if ( strcmp ( $day , $today ) < 0 ) {
932 if ( empty ( $days [ $day ])) {
933 $days [ $day ] = array ();
935 $days [ $day ][] = $linkdate ;
938 if ( count ( $days ) > $nb_of_days ) {
939 break ; // Have we collected enough days?
943 // Build the RSS feed.
944 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
945 $pageaddr = escape ( index_url ( $_SERVER ));
946 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
948 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
949 echo '<link>' . $pageaddr . '</link>' ;
950 echo '<description>Daily shared links</description>' ;
951 echo '<language>en-en</language>' ;
952 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
955 foreach ( $days as $day => $linkdates ) {
956 $daydate = linkdate2timestamp ( $day . '_000000' ); // Full text date
957 $rfc822date = linkdate2rfc822 ( $day . '_000000' );
958 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
960 // Build the HTML body of this RSS entry.
965 // We pre-format some fields for proper output.
966 foreach ( $linkdates as $linkdate ) {
967 $l = $LINKSDB [ $linkdate ];
968 $l [ 'formatedDescription' ] = nl2br ( keepMultipleSpaces ( text2clickable ( $l [ 'description' ])));
969 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
970 $l [ 'timestamp' ] = linkdate2timestamp ( $l [ 'linkdate' ]);
971 if ( startsWith ( $l [ 'url' ], '?' )) {
972 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
974 $links [ $linkdate ] = $l ;
977 // Then build the HTML for this day:
979 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
980 $tpl- > assign ( 'daydate' , $daydate );
981 $tpl- > assign ( 'absurl' , $absurl );
982 $tpl- > assign ( 'links' , $links );
983 $tpl- > assign ( 'rfc822date' , escape ( $rfc822date ));
984 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
986 echo $html . PHP_EOL
;
988 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
990 $cache- > cache ( ob_get_contents ());
998 $LINKSDB = new LinkDB (
999 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1000 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
1001 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
1004 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1005 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1007 $days = $LINKSDB- > days ();
1008 $i = array_search ( $day , $days );
1009 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1014 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1015 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1019 $linksToDisplay = $LINKSDB- > filterDay ( $day );
1020 } catch ( Exception
$exc ) {
1022 $linksToDisplay = array ();
1025 // We pre-format some fields for proper output.
1026 foreach ( $linksToDisplay as $key => $link )
1029 $taglist = explode ( ' ' , $link [ 'tags' ]);
1030 uasort ( $taglist , 'strcasecmp' );
1031 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1032 $linksToDisplay [ $key ][ 'formatedDescription' ]= nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ])));
1033 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1034 $linksToDisplay [ $key ][ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
1037 /* We need to spread the articles on 3 columns.
1038 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1039 so I manually spread entries with a simple method: I roughly evaluate the
1040 height of a div according to title and description length.
1042 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1043 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1044 foreach ( $linksToDisplay as $key => $link )
1046 // Roughly estimate length of entry (by counting characters)
1047 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1048 // Description: 836 characters gives roughly 342 pixel height.
1049 // This is not perfect, but it's usually OK.
1050 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1051 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1052 // Then put in column which is the less filled:
1053 $smallest = min ( $fill ); // find smallest value in array.
1054 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1055 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1056 $fill [ $index ] +
= $length ;
1058 $PAGE = new pageBuilder
;
1060 'linksToDisplay' => $linksToDisplay ,
1061 'linkcount' => count ( $LINKSDB ),
1063 'day' => linkdate2timestamp ( $day . '_000000' ),
1064 'previousday' => $previousday ,
1065 'nextday' => $nextday ,
1067 $pluginManager = PluginManager
:: getInstance ();
1068 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1070 foreach ( $data as $key => $value ) {
1071 $PAGE- > assign ( $key , $value );
1074 $PAGE- > renderPage ( 'daily' );
1078 // Renders the linklist
1079 function showLinkList ( $PAGE , $LINKSDB ) {
1080 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1081 $PAGE- > renderPage ( 'linklist' );
1085 // ------------------------------------------------------------------------------------------
1086 // Render HTML page (according to URL parameters and user rights)
1087 function renderPage ()
1089 $LINKSDB = new LinkDB (
1090 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1091 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
1092 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
1095 $PAGE = new pageBuilder
;
1097 // Determine which page will be rendered.
1098 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1099 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1101 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1102 // Then assign generated data to RainTPL.
1103 $common_hooks = array (
1108 $pluginManager = PluginManager
:: getInstance ();
1109 foreach ( $common_hooks as $name ) {
1110 $plugin_data = array ();
1111 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1113 'target' => $targetPage ,
1114 'loggedin' => isLoggedIn ()
1117 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1120 // -------- Display login form.
1121 if ( $targetPage == Router
:: $PAGE_LOGIN )
1123 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1124 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1125 $PAGE- > assign ( 'token' , $token );
1126 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1127 $PAGE- > renderPage ( 'loginform' );
1130 // -------- User wants to logout.
1131 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1133 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1135 header ( 'Location: ?' );
1139 // -------- Picture wall
1140 if ( $targetPage == Router
:: $PAGE_PICWALL )
1142 // Optionally filter the results:
1144 if (! empty ( $_GET [ 'searchterm' ])) $links = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
1145 elseif (! empty ( $_GET [ 'searchtags' ])) $links = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1146 else $links = $LINKSDB ;
1149 $linksToDisplay = array ();
1151 // Get only links which have a thumbnail.
1152 foreach ( $links as $link )
1154 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1155 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1156 if ( $thumb != '' ) // Only output links which have a thumbnail.
1158 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1159 $linksToDisplay []= $link ; // Add to array.
1164 'linkcount' => count ( $LINKSDB ),
1165 'linksToDisplay' => $linksToDisplay ,
1167 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1169 foreach ( $data as $key => $value ) {
1170 $PAGE- > assign ( $key , $value );
1173 $PAGE- > renderPage ( 'picwall' );
1177 // -------- Tag cloud
1178 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1180 $tags = $LINKSDB- > allTags ();
1182 // We sort tags alphabetically, then choose a font size according to count.
1183 // First, find max value.
1184 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
1187 foreach ( $tags as $key => $value )
1188 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1190 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1194 'linkcount' => count ( $LINKSDB ),
1197 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1199 foreach ( $data as $key => $value ) {
1200 $PAGE- > assign ( $key , $value );
1203 $PAGE- > renderPage ( 'tagcloud' );
1207 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1208 if ( isset ( $_GET [ 'addtag' ]))
1210 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1211 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1212 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1214 // Prevent redirection loop
1215 if ( isset ( $params [ 'addtag' ])) {
1216 unset ( $params [ 'addtag' ]);
1219 // Check if this tag is already in the search query and ignore it if it is.
1220 // Each tag is always separated by a space
1221 if ( isset ( $params [ 'searchtags' ])) {
1222 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1224 $current_tags = array ();
1227 foreach ( $current_tags as $value ) {
1228 if ( $value === $_GET [ 'addtag' ]) {
1233 // Append the tag if necessary
1234 if ( empty ( $params [ 'searchtags' ])) {
1235 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1238 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1241 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1242 header ( 'Location: ?' . http_build_query ( $params ));
1246 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1247 if ( isset ( $_GET [ 'removetag' ])) {
1248 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1249 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1250 header ( 'Location: ?' );
1254 // In case browser does not send HTTP_REFERER
1255 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1257 // Prevent redirection loop
1258 if ( isset ( $params [ 'removetag' ])) {
1259 unset ( $params [ 'removetag' ]);
1262 if ( isset ( $params [ 'searchtags' ])) {
1263 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1264 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
1265 if ( count ( $tags )== 0 ) {
1266 unset ( $params [ 'searchtags' ]);
1268 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1270 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1272 header ( 'Location: ?' . http_build_query ( $params ));
1276 // -------- User wants to change the number of links per page (linksperpage=...)
1277 if ( isset ( $_GET [ 'linksperpage' ])) {
1278 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1279 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1282 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1286 // -------- User wants to see only private links (toggle)
1287 if ( isset ( $_GET [ 'privateonly' ])) {
1288 if ( empty ( $_SESSION [ 'privateonly' ])) {
1289 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1291 unset ( $_SESSION [ 'privateonly' ]); // See all links
1294 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1298 // -------- Handle other actions allowed for non-logged in users:
1301 // User tries to post new link but is not logged in:
1302 // Show login screen, then redirect to ?post=...
1303 if ( isset ( $_GET [ 'post' ]))
1305 header ( 'Location: ?do=login&post=' . urlencode ( $_GET [ 'post' ]).(! empty ( $_GET [ 'title' ])? '&title=' . urlencode ( $_GET [ 'title' ]): '' ).(! empty ( $_GET [ 'description' ])? '&description=' . urlencode ( $_GET [ 'description' ]): '' ).(! empty ( $_GET [ 'source' ])? '&source=' . urlencode ( $_GET [ 'source' ]): '' )); // Redirect to login page, then back to post link.
1309 // Same case as above except that user tried to access ?do=addlink without being logged in
1310 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1311 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1312 header ( 'Location: ?do=login&post=' );
1315 showLinkList ( $PAGE , $LINKSDB );
1316 if ( isset ( $_GET [ 'edit_link' ])) {
1317 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1321 exit ; // Never remove this one! All operations below are reserved for logged in user.
1324 // -------- All other functions are reserved for the registered user:
1326 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1327 if ( $targetPage == Router
:: $PAGE_TOOLS )
1330 'linkcount' => count ( $LINKSDB ),
1331 'pageabsaddr' => index_url ( $_SERVER ),
1333 $pluginManager- > executeHooks ( 'render_tools' , $data );
1335 foreach ( $data as $key => $value ) {
1336 $PAGE- > assign ( $key , $value );
1339 $PAGE- > renderPage ( 'tools' );
1343 // -------- User wants to change his/her password.
1344 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1346 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1347 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1349 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1351 // Make sure old password is correct.
1352 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1353 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1354 // Save new password
1355 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1356 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1358 writeConfig ( $GLOBALS , isLoggedIn ());
1360 catch ( Exception
$e ) {
1362 'ERROR while writing config file after changing password.' . PHP_EOL
.
1366 // TODO: do not handle exceptions/errors in JS.
1367 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1370 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1373 else // show the change password form.
1375 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1376 $PAGE- > assign ( 'token' , getToken ());
1377 $PAGE- > renderPage ( 'changepassword' );
1382 // -------- User wants to change configuration
1383 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1385 if (! empty ( $_POST [ 'title' ]) )
1387 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1389 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1390 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1391 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1392 $GLOBALS [ 'timezone' ] = $tz ;
1393 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1394 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1395 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1396 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1397 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1398 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1399 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1400 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1402 writeConfig ( $GLOBALS , isLoggedIn ());
1404 catch ( Exception
$e ) {
1406 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1410 // TODO: do not handle exceptions/errors in JS.
1411 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1414 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1417 else // Show the configuration form.
1419 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1420 $PAGE- > assign ( 'token' , getToken ());
1421 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1422 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1423 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1424 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1425 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1426 $PAGE- > renderPage ( 'configure' );
1431 // -------- User wants to rename a tag or delete it
1432 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1434 if ( empty ( $_POST [ 'fromtag' ]))
1436 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1437 $PAGE- > assign ( 'token' , getToken ());
1438 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1439 $PAGE- > renderPage ( 'changetag' );
1442 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1445 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
1447 $needle = trim ( $_POST [ 'fromtag' ]);
1448 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // True for case-sensitive tag search.
1449 foreach ( $linksToAlter as $key => $value )
1451 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1452 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1453 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1454 $LINKSDB [ $key ]= $value ;
1456 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1457 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1462 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
1464 $needle = trim ( $_POST [ 'fromtag' ]);
1465 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
1466 foreach ( $linksToAlter as $key => $value )
1468 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1469 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1470 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1471 $LINKSDB [ $key ]= $value ;
1473 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1474 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1479 // -------- User wants to add a link without using the bookmarklet: Show form.
1480 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1482 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1483 $PAGE- > renderPage ( 'addlink' );
1487 // -------- User clicked the "Save" button when editing a link: Save link to database.
1488 if ( isset ( $_POST [ 'save_edit' ]))
1490 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1491 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
1492 $tags = implode ( ' ' , array_unique ( explode ( ' ' , $tags ))); // Remove duplicates.
1493 $linkdate = $_POST [ 'lf_linkdate' ];
1494 $url = trim ( $_POST [ 'lf_url' ]);
1495 if (! startsWith ( $url , 'http:' ) && ! startsWith ( $url , 'https:' ) && ! startsWith ( $url , 'ftp:' ) && ! startsWith ( $url , 'magnet:' ) && ! startsWith ( $url , '?' ) && ! startsWith ( $url , 'javascript:' ))
1496 $url = 'http://' . $url ;
1497 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => $url , 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1498 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
1499 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
1501 $pluginManager- > executeHooks ( 'save_link' , $link );
1503 $LINKSDB [ $linkdate ] = $link ;
1504 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1507 // If we are called from the bookmarklet, we must close the popup:
1508 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1509 echo '<script>self.close();</script>' ;
1513 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? escape ( $_POST [ 'returnurl' ]): '?' ;
1514 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1515 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1516 header ( 'Location: ' . $location ); // After saving the link, redirect to the page the user was on.
1520 // -------- User clicked the "Cancel" button when editing a link.
1521 if ( isset ( $_POST [ 'cancel_edit' ]))
1523 // If we are called from the bookmarklet, we must close the popup:
1524 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1525 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1526 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1527 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1528 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1532 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1533 if ( isset ( $_POST [ 'delete_link' ]))
1535 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1536 // We do not need to ask for confirmation:
1537 // - confirmation is handled by JavaScript
1538 // - we are protected from XSRF by the token.
1539 $linkdate = $_POST [ 'lf_linkdate' ];
1541 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1543 unset ( $LINKSDB [ $linkdate ]);
1544 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1546 // If we are called from the bookmarklet, we must close the popup:
1547 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1548 // Pick where we're going to redirect
1549 // =============================================================
1550 // Basically, we can't redirect to where we were previously if it was a permalink
1551 // or an edit_link, because it would 404.
1553 // - / : nothing in $_GET, redirect to self
1554 // - /?page : redirect to self
1555 // - /?searchterm : redirect to self (there might be other links)
1556 // - /?searchtags : redirect to self
1557 // - /permalink : redirect to / (the link does not exist anymore)
1558 // - /?edit_link : redirect to / (the link does not exist anymore)
1559 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1560 // redirect is not satisfied, and only then redirect to /
1563 if ( count ( $_GET ) == 0
1564 || isset ( $_GET [ 'page' ])
1565 || isset ( $_GET [ 'searchterm' ])
1566 || isset ( $_GET [ 'searchtags' ])
1568 if ( isset ( $_POST [ 'returnurl' ])) {
1569 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1571 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1575 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1579 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1580 if ( isset ( $_GET [ 'edit_link' ]))
1582 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1583 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1585 'linkcount' => count ( $LINKSDB ),
1587 'link_is_new' => false ,
1588 'token' => getToken (),
1589 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1590 'tags' => $LINKSDB- > allTags (),
1592 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1594 foreach ( $data as $key => $value ) {
1595 $PAGE- > assign ( $key , $value );
1598 $PAGE- > renderPage ( 'editlink' );
1602 // -------- User want to post a new link: Display link edit form.
1603 if ( isset ( $_GET [ 'post' ])) {
1604 $url = cleanup_url ( $_GET [ 'post' ]);
1606 $link_is_new = false ;
1607 // Check if URL is not already in database (in this case, we will edit the existing link)
1608 $link = $LINKSDB- > getLinkFromUrl ( $url );
1611 $link_is_new = true ;
1612 $linkdate = strval ( date ( 'Ymd_His' ));
1613 // Get title if it was provided in URL (by the bookmarklet).
1614 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] );
1615 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1616 $description = ( empty ( $_GET [ 'description' ]) ? '' : $_GET [ 'description' ]);
1617 $tags = ( empty ( $_GET [ 'tags' ]) ? '' : $_GET [ 'tags' ] );
1618 $private = (! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 );
1619 // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
1620 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1621 // Short timeout to keep the application responsive
1622 list ( $headers , $data ) = get_http_url ( $url , 4 );
1623 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1624 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1625 // Look for charset in html header.
1626 preg_match ( '#<meta .*charset=.*>#Usi' , $data , $meta );
1628 // If found, extract encoding.
1629 if (! empty ( $meta [ 0 ])) {
1630 // Get encoding specified in header.
1631 preg_match ( '#charset="?(.*)"#si' , $meta [ 0 ], $enc );
1632 // If charset not found, use utf-8.
1633 $html_charset = (! empty ( $enc [ 1 ])) ? strtolower ( $enc [ 1 ]) : 'utf-8' ;
1636 $html_charset = 'utf-8' ;
1640 $title = html_extract_title ( $data );
1641 if (! empty ( $title )) {
1642 // Re-encode title in utf-8 if necessary.
1643 $title = ( $html_charset == 'iso-8859-1' ) ? utf8_encode ( $title ) : $title ;
1648 $url = '?' . smallHash ( $linkdate );
1652 'linkdate' => $linkdate ,
1655 'description' => $description ,
1657 'private' => $private
1662 'linkcount' => count ( $LINKSDB ),
1664 'link_is_new' => $link_is_new ,
1665 'token' => getToken (), // XSRF protection.
1666 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1667 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1668 'tags' => $LINKSDB- > allTags (),
1670 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1672 foreach ( $data as $key => $value ) {
1673 $PAGE- > assign ( $key , $value );
1676 $PAGE- > renderPage ( 'editlink' );
1680 // -------- Export as Netscape Bookmarks HTML file.
1681 if ( $targetPage == Router
:: $PAGE_EXPORT )
1683 if ( empty ( $_GET [ 'what' ]))
1685 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1686 $PAGE- > renderPage ( 'export' );
1689 $exportWhat = $_GET [ 'what' ];
1690 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1692 header ( 'Content-Type: text/html; charset=utf-8' );
1693 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1694 $currentdate = date ( 'Y/m/d H:i:s' );
1696 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1697 <!-- This is an automatically generated file.
1698 It will be read and overwritten.
1700 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1701 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1702 <TITLE>Bookmarks</TITLE>
1705 foreach ( $LINKSDB as $link )
1707 if ( $exportWhat == 'all' ||
1708 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1709 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1711 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1712 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1713 echo '>' . $link [ 'title' ]. "</A> \n " ;
1714 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1720 // -------- User is uploading a file for import
1721 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1723 // If file is too big, some form field may be missing.
1724 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1726 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1727 echo '<script>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= \' ' . escape ( $returnurl ). ' \' ;</script>' ;
1730 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1735 // -------- Show upload/import dialog:
1736 if ( $targetPage == Router
:: $PAGE_IMPORT )
1738 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1739 $PAGE- > assign ( 'token' , getToken ());
1740 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1741 $PAGE- > renderPage ( 'import' );
1745 // -------- Otherwise, simply display search form and links:
1746 showLinkList ( $PAGE , $LINKSDB );
1750 // -----------------------------------------------------------------------------------------------
1751 // Process the import file form.
1752 function importFile ()
1754 if (!( isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ])) { die ( 'Not allowed.' ); }
1755 $LINKSDB = new LinkDB (
1756 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1757 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
1758 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
1760 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1761 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1762 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1763 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1764 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1769 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1771 // Then import the bookmarks.
1772 if ( $type == 'netscape' )
1774 // This is a standard Netscape-style bookmark file.
1775 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1776 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1778 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1779 $d = explode ( '<DD>' , $html );
1780 if ( startswith ( $d [ 0 ], '<A ' ))
1782 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1783 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1784 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1785 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1787 foreach ( $matches as $m )
1789 $attr = $m [ 1 ]; $value = $m [ 2 ];
1790 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1791 elseif ( $attr == 'ADD_DATE' )
1793 $raw_add_date = intval ( $value );
1794 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1796 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1797 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1799 if ( $link [ 'url' ]!= '' )
1801 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1802 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1804 { // Link not in database, let's import it...
1805 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1807 // Make sure date/time is not already used by another link.
1808 // (Some bookmark files have several different links with the same ADD_DATE)
1809 // We increment date by 1 second until we find a date which is not used in DB.
1810 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1811 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1812 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1813 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1816 else // Link already present in database.
1819 { // If overwrite is required, we import link data, except date/time.
1820 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1821 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1829 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1831 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1835 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1839 // -----------------------------------------------------------------------------------------------
1840 // Template for the list of links (<div id="linklist">)
1841 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1842 function buildLinkList ( $PAGE , $LINKSDB )
1844 // ---- Filter link database according to parameters
1845 $linksToDisplay = array ();
1848 if ( isset ( $_GET [ 'searchterm' ])) // Fulltext search
1850 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1851 $search_crits = escape ( trim ( $_GET [ 'searchterm' ]));
1852 $search_type = 'fulltext' ;
1854 elseif ( isset ( $_GET [ 'searchtags' ])) // Search by tag
1856 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1857 $search_crits = explode ( ' ' , escape ( trim ( $_GET [ 'searchtags' ])));
1858 $search_type = 'tags' ;
1860 elseif ( isset ( $_SERVER [ 'QUERY_STRING' ]) && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])) // Detect smallHashes in URL
1862 $linksToDisplay = $LINKSDB- > filterSmallHash ( substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 ));
1863 if ( count ( $linksToDisplay )== 0 )
1865 header ( $_SERVER [ "SERVER_PROTOCOL" ]. " 404 Not Found" );
1866 echo '<h1>404 Not found.</h1>Oh crap. The link you are trying to reach does not exist or has been deleted.' ;
1867 echo '<br>Would you mind <a href="?">clicking here</a>?' ;
1870 $search_type = 'permalink' ;
1873 $linksToDisplay = $LINKSDB ; // Otherwise, display without filtering.
1876 // Option: Show only private links
1877 if (! empty ( $_SESSION [ 'privateonly' ]))
1880 foreach ( $linksToDisplay as $linkdate => $link )
1882 if ( $link [ 'private' ]!= 0 ) $tmp [ $linkdate ]= $link ;
1884 $linksToDisplay = $tmp ;
1887 // ---- Handle paging.
1888 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess???
1889 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1890 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1892 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks PHP.
1894 // If there is only a single link, we change on-the-fly the title of the page.
1895 if ( count ( $linksToDisplay )== 1 ) $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1897 // Select articles according to paging.
1898 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1899 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1900 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1901 $page = ( $page < 1 ? 1 : $page );
1902 $page = ( $page > $pagecount ? $pagecount : $page );
1903 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1904 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1905 $linkDisp = array (); // Links to display
1906 while ( $i < $end && $i < count ( $keys ))
1908 $link = $linksToDisplay [ $keys [ $i ]];
1909 $link [ 'description' ]= nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ])));
1910 $title = $link [ 'title' ];
1911 $classLi = $i %
2 != 0 ? '' : 'publicLinkHightLight' ;
1912 $link [ 'class' ] = ( $link [ 'private' ]== 0 ? $classLi : 'private' );
1913 $link [ 'timestamp' ]= linkdate2timestamp ( $link [ 'linkdate' ]);
1914 $taglist = explode ( ' ' , $link [ 'tags' ]);
1915 uasort ( $taglist , 'strcasecmp' );
1916 $link [ 'taglist' ]= $taglist ;
1917 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1918 if ( $link [ "url" ][ 0 ] === '?' && // Check for both signs of a note: starting with ? and 7 chars long. I doubt that you'll post any links that look like this.
1919 strlen ( $link [ "url" ]) === 7 ) {
1920 $link [ "url" ] = index_url ( $_SERVER ) . $link [ "url" ];
1923 $linkDisp [ $keys [ $i ]] = $link ;
1927 // Compute paging navigation
1928 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1929 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1931 $previous_page_url = '' ; if ( $i != count ( $keys )) $previous_page_url = '?page=' .( $page +
1 ). $searchterm . $searchtags ;
1932 $next_page_url = '' ; if ( $page > 1 ) $next_page_url = '?page=' .( $page-1 ). $searchterm . $searchtags ;
1934 $token = '' ; if ( isLoggedIn ()) $token = getToken ();
1936 // Fill all template fields.
1938 'linkcount' => count ( $LINKSDB ),
1939 'previous_page_url' => $previous_page_url ,
1940 'next_page_url' => $next_page_url ,
1941 'page_current' => $page ,
1942 'page_max' => $pagecount ,
1943 'result_count' => count ( $linksToDisplay ),
1944 'search_type' => $search_type ,
1945 'search_crits' => $search_crits ,
1946 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
1948 'links' => $linkDisp ,
1949 'tags' => $LINKSDB- > allTags (),
1952 $pluginManager = PluginManager
:: getInstance ();
1953 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1955 foreach ( $data as $key => $value ) {
1956 $PAGE- > assign ( $key , $value );
1962 // Compute the thumbnail for a link.
1964 // With a link to the original URL.
1965 // Understands various services (youtube.com...)
1966 // Input: $url = URL for which the thumbnail must be found.
1967 // $href = if provided, this URL will be followed instead of $url
1968 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1969 // Some of them may be missing.
1970 // Return an empty array if no thumbnail available.
1971 function computeThumbnail ( $url , $href = false )
1973 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
1974 if ( $href == false ) $href = $url ;
1976 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1977 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1978 // ^^^^^^^^^^^ ^^^^^^^^^^^
1979 $domain = parse_url ( $url , PHP_URL_HOST
);
1980 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1982 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1983 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1984 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1986 if ( $domain == 'youtu.be' ) // Youtube short links
1988 $path = parse_url ( $url , PHP_URL_PATH
);
1989 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1990 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1992 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1994 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1995 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1996 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1999 if ( $domain == 'imgur.com' )
2001 $path = parse_url ( $url , PHP_URL_PATH
);
2002 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2003 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2004 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2005 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2006 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2008 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2009 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2011 if ( $domain == 'i.imgur.com' )
2013 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2014 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2015 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2017 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2019 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2021 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2022 return array ( 'src' => $thumburl ,
2023 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2026 if ( endsWith ( $domain , '.imageshack.us' ))
2028 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2029 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2031 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2032 return array ( 'src' => $thumburl ,
2033 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2037 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2038 // So we deport the thumbnail generation in order not to slow down page generation
2039 // (and we also cache the thumbnail)
2041 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2043 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2044 || $domain == 'vimeo.com'
2045 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2046 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2049 if ( $domain == 'vimeo.com' )
2050 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2051 $path = parse_url ( $url , PHP_URL_PATH
);
2052 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2054 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2055 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2056 $path = parse_url ( $url , PHP_URL_PATH
);
2057 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2059 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2060 { // Make sure this TED URL points to a video (/talks/...)
2061 $path = parse_url ( $url , PHP_URL_PATH
);
2062 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2064 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2065 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2066 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2069 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2070 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2071 // But using the extension will do.
2072 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2073 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2075 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2076 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2077 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2079 return array (); // No thumbnail.
2084 // Returns the HTML code to display a thumbnail for a link
2085 // with a link to the original URL.
2086 // Understands various services (youtube.com...)
2087 // Input: $url = URL for which the thumbnail must be found.
2088 // $href = if provided, this URL will be followed instead of $url
2089 // Returns '' if no thumbnail available.
2090 function thumbnail ( $url , $href = false )
2092 $t = computeThumbnail ( $url , $href );
2093 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2095 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2096 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2097 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2098 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2099 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2104 // Returns the HTML code to display a thumbnail for a link
2105 // for the picture wall (using lazy image loading)
2106 // Understands various services (youtube.com...)
2107 // Input: $url = URL for which the thumbnail must be found.
2108 // $href = if provided, this URL will be followed instead of $url
2109 // Returns '' if no thumbnail available.
2110 function lazyThumbnail ( $url , $href = false )
2112 $t = computeThumbnail ( $url , $href );
2113 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2115 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2118 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2120 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2121 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2122 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2123 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2126 // No-JavaScript fallback.
2127 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2128 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2129 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2130 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2131 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2132 $html .= '></noscript></a>' ;
2138 // -----------------------------------------------------------------------------------------------
2140 // This function should NEVER be called if the file data/config.php exists.
2143 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2144 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2147 // This part makes sure sessions works correctly.
2148 // (Because on some hosts, session.save_path may not be set correctly,
2149 // or we may not have write access to it.)
2150 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2151 { // Step 2: Check if data in session is correct.
2152 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2153 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2154 echo 'It currently points to ' . session_save_path (). '<br>' ;
2155 echo 'Check that the hostname used to access Shaarli contains a dot. On some browsers, accessing your server via a hostname like \' localhost \' or any custom hostname without a dot causes cookie storage to fail. We recommend accessing your server via it \' s IP address or Fully Qualified Domain Name.<br>' ;
2156 echo '<br><a href="?">Click to try again.</a></pre>' ;
2159 if (! isset ( $_SESSION [ 'session_tested' ]))
2160 { // Step 1 : Try to store data in session and reload page.
2161 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2162 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2164 if ( isset ( $_GET [ 'test_session' ]))
2165 { // Step 3: Sessions are OK. Remove test parameter from URL.
2166 header ( 'Location: ' . index_url ( $_SERVER ));
2170 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2173 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2174 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2175 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2178 $GLOBALS [ 'timezone' ] = $tz ;
2179 // Everything is ok, let's create config file.
2180 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2181 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2182 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2183 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2184 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2186 writeConfig ( $GLOBALS , isLoggedIn ());
2188 catch ( Exception
$e ) {
2190 'ERROR while writing config file after installation.' . PHP_EOL
.
2194 // TODO: do not handle exceptions/errors in JS.
2195 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2198 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2202 // Display config form:
2203 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2204 $timezone_html = '' ;
2205 if ( $timezone_form != '' ) {
2206 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2209 $PAGE = new pageBuilder
;
2210 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2211 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2212 $PAGE- > renderPage ( 'install' );
2216 if (! function_exists ( 'json_encode' )) {
2217 function json_encode ( $data ) {
2218 switch ( $type = gettype ( $data )) {
2222 return ( $data ? 'true' : 'false' );
2228 return '"' . addslashes ( $data ) . '"' ;
2230 $data = get_object_vars ( $data );
2232 $output_index_count = 0 ;
2233 $output_indexed = array ();
2234 $output_associative = array ();
2235 foreach ( $data as $key => $value ) {
2236 $output_indexed [] = json_encode ( $value );
2237 $output_associative [] = json_encode ( $key ) . ':' . json_encode ( $value );
2238 if ( $output_index_count !== NULL && $output_index_count ++
!== $key ) {
2239 $output_index_count = NULL ;
2242 if ( $output_index_count !== NULL ) {
2243 return '[' . implode ( ',' , $output_indexed ) . ']' ;
2245 return ' {' . implode(',', $output_associative) . '} ' ;
2248 return '' ; // Not supported
2255 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2256 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2257 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2258 This function is called by passing the URL:
2259 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2260 [URL] is the URL of the link (e.g. a flickr page)
2261 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2262 The function below will fetch the image from the webservice and store it in the cache.
2264 function genThumbnail ()
2266 // Make sure the parameters in the URL were generated by us.
2267 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2268 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2270 // Let's see if we don't already have the image for this URL in the cache.
2271 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2272 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2273 { // We have the thumbnail, just serve it:
2274 header ( 'Content-Type: image/jpeg' );
2275 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2278 // We may also serve a blank image (if service did not respond)
2279 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2280 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2282 header ( 'Content-Type: image/gif' );
2283 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2287 // Otherwise, generate the thumbnail.
2288 $url = $_GET [ 'url' ];
2289 $domain = parse_url ( $url , PHP_URL_HOST
);
2291 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2293 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2294 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2296 // Is this a link to an image, or to a flickr page ?
2298 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2299 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2300 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2301 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2303 else // This is a flickr page (html)
2305 // Get the flickr html page.
2306 list ( $headers , $data ) = get_http_url ( $url , 20 );
2307 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2309 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2310 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $data , $matches );
2311 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2313 // In albums (and some other pages), the link rel="image_src" is not provided,
2314 // but flickr provides:
2315 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2318 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $data , $matches );
2319 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2325 { // Let's download the image.
2326 // Image is 240x120, so 10 seconds to download should be enough.
2327 list ( $headers , $data ) = get_http_url ( $imageurl , 10 );
2328 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2329 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
2330 header ( 'Content-Type: image/jpeg' );
2337 elseif ( $domain == 'vimeo.com' )
2339 // This is more complex: we have to perform a HTTP request, then parse the result.
2340 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2341 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2342 list ( $headers , $data ) = get_http_url ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2343 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2344 $t = unserialize ( $data );
2345 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2346 // Then we download the image and serve it to our client.
2347 list ( $headers , $data ) = get_http_url ( $imageurl , 10 );
2348 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2349 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
2350 header ( 'Content-Type: image/jpeg' );
2357 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2359 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2360 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2361 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2362 list ( $headers , $data ) = get_http_url ( $url , 5 );
2363 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2364 // Extract the link to the thumbnail
2365 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $data , $matches );
2366 if (! empty ( $matches [ 1 ]))
2367 { // Let's download the image.
2368 $imageurl = $matches [ 1 ];
2369 // No control on image size, so wait long enough
2370 list ( $headers , $data ) = get_http_url ( $imageurl , 20 );
2371 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2372 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2373 file_put_contents ( $filepath , $data ); // Save image to cache.
2374 if ( resizeImage ( $filepath ))
2376 header ( 'Content-Type: image/jpeg' );
2377 echo file_get_contents ( $filepath );
2385 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2387 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2388 // http://xkcd.com/327/
2389 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2390 list ( $headers , $data ) = get_http_url ( $url , 5 );
2391 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2392 // Extract the link to the thumbnail
2393 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $data , $matches );
2394 if (! empty ( $matches [ 1 ]))
2395 { // Let's download the image.
2396 $imageurl = $matches [ 1 ];
2397 // No control on image size, so wait long enough
2398 list ( $headers , $data ) = get_http_url ( $imageurl , 20 );
2399 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2400 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2401 file_put_contents ( $filepath , $data ); // Save image to cache.
2402 if ( resizeImage ( $filepath ))
2404 header ( 'Content-Type: image/jpeg' );
2405 echo file_get_contents ( $filepath );
2415 // For all other domains, we try to download the image and make a thumbnail.
2416 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2417 list ( $headers , $data ) = get_http_url ( $url , 30 );
2418 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2419 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2420 file_put_contents ( $filepath , $data ); // Save image to cache.
2421 if ( resizeImage ( $filepath ))
2423 header ( 'Content-Type: image/jpeg' );
2424 echo file_get_contents ( $filepath );
2431 // Otherwise, return an empty image (8x8 transparent gif)
2432 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2433 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2434 header ( 'Content-Type: image/gif' );
2438 // Make a thumbnail of the image (to width: 120 pixels)
2439 // Returns true if success, false otherwise.
2440 function resizeImage ( $filepath )
2442 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2444 // Trick: some stupid people rename GIF as JPEG... or else.
2445 // So we really try to open each image type whatever the extension is.
2446 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2448 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2449 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2450 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2451 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2454 $ystart = 0 ; $yheight = $h ;
2455 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2456 $nw = 120 ; // Desired width
2457 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2459 $im2 = imagecreatetruecolor ( $nw , $nh );
2460 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2461 imageinterlace ( $im2 , true ); // For progressive JPEG.
2462 $tempname = $filepath . '_TEMP.jpg' ;
2463 imagejpeg ( $im2 , $tempname , 90 );
2467 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2472 mergeDeprecatedConfig ( $GLOBALS , isLoggedIn ());
2473 } catch ( Exception
$e ) {
2475 'ERROR while merging deprecated options.php file.' . PHP_EOL
.
2480 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2481 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2482 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2483 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2484 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=daily' )) { showDaily (); exit ; }
2485 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];