]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.3 - 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 // Processed updates file.
48 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/updates.txt' ;
51 $GLOBALS [ 'config' ][ 'LOG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' ;
53 // For updates check of Shaarli
54 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
56 // Set ENABLE_UPDATECHECK to disabled by default.
57 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = false ;
59 // RainTPL cache directory (keep the trailing slash!)
60 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
61 // Raintpl template directory (keep the trailing slash!)
62 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
64 // Thumbnail cache directory
65 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
67 // Atom & RSS feed cache directory
68 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
71 * Global configuration
73 // Ban IP after this many failures
74 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
75 // Ban duration for IP address after login failures (in seconds)
76 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
79 // Enable RSS permalinks by default.
80 // This corresponds to the default behavior of shaarli before this was added as an option.
81 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
82 // If true, an extra "ATOM feed" button will be displayed in the toolbar
83 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
85 // Link display options
86 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
87 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
88 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
90 // Open Shaarli (true): anyone can add/edit/delete links without having to login
91 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
94 // Display thumbnails in links
95 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
96 // Store thumbnails in a local cache
97 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
99 // Update check frequency for Shaarli. 86400 seconds=24 hours
100 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ] = 'stable' ;
101 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
105 * Plugin configuration
107 * Warning: order matters!
109 * These settings may be be overriden in:
111 * - each plugin's configuration file
113 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
114 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
115 // 'wallabag', 'markdown', 'addlink_toolbar',
117 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
119 // Initialize plugin parameters array.
120 $GLOBALS [ 'plugins' ] = array ();
122 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
123 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
128 define ( 'shaarli_version' , '0.6.3' );
130 // http://server.com/x/shaarli --> /shaarli/
131 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
133 // High execution time in case of problematic imports/exports.
134 ini_set ( 'max_input_time' , '60' );
136 // Try to set max upload file size and read
137 ini_set ( 'memory_limit' , '128M' );
138 ini_set ( 'post_max_size' , '16M' );
139 ini_set ( 'upload_max_filesize' , '16M' );
141 // See all error except warnings
142 error_reporting ( E_ALL^E_WARNING
);
143 // See all errors (for debugging only)
144 //error_reporting(-1);
149 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
150 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
154 require_once 'application/ApplicationUtils.php' ;
155 require_once 'application/Cache.php' ;
156 require_once 'application/CachedPage.php' ;
157 require_once 'application/FileUtils.php' ;
158 require_once 'application/HttpUtils.php' ;
159 require_once 'application/LinkDB.php' ;
160 require_once 'application/LinkFilter.php' ;
161 require_once 'application/LinkUtils.php' ;
162 require_once 'application/TimeZone.php' ;
163 require_once 'application/Url.php' ;
164 require_once 'application/Utils.php' ;
165 require_once 'application/Config.php' ;
166 require_once 'application/PluginManager.php' ;
167 require_once 'application/Router.php' ;
168 require_once 'application/Updater.php' ;
170 // Ensure the PHP version is supported
172 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
173 } catch ( Exception
$exc ) {
174 header ( 'Content-Type: text/plain; charset=utf-8' );
175 echo $exc- > getMessage ();
179 // Force cookie path (but do not change lifetime)
180 $cookie = session_get_cookie_params ();
182 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
183 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
185 // Set default cookie expiration and path.
186 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
187 // Set session parameters on server side.
188 // If the user does not access any page within this time, his/her session is considered expired.
189 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
190 // Use cookies to store session.
191 ini_set ( 'session.use_cookies' , 1 );
192 // Force cookies for session (phpsessionID forbidden in URL).
193 ini_set ( 'session.use_only_cookies' , 1 );
194 // Prevent PHP form using sessionID in URL if cookies are disabled.
195 ini_set ( 'session.use_trans_sid' , false );
197 session_name ( 'shaarli' );
198 // Start session if needed (Some server auto-start sessions).
199 if ( session_id () == '' ) {
203 // Regenerate session ID if invalid or not defined in cookie.
204 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
205 session_regenerate_id ( true );
206 $_COOKIE [ 'shaarli' ] = session_id ();
209 include "inc/rain.tpl.class.php" ; //include Rain TPL
210 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
211 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
213 $pluginManager = PluginManager
:: getInstance ();
214 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
216 ob_start (); // Output buffering for the page cache.
219 // In case stupid admin has left magic_quotes enabled in php.ini:
220 if ( get_magic_quotes_gpc ())
222 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
223 $_POST = array_map ( 'stripslashes_deep' , $_POST );
224 $_GET = array_map ( 'stripslashes_deep' , $_GET );
225 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
228 // Prevent caching on client side or proxy: (yes, it's ugly)
229 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
230 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
231 header ( "Cache-Control: post-check=0, pre-check=0" , false );
232 header ( "Pragma: no-cache" );
234 // Handling of old config file which do not have the new parameters.
235 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
236 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
237 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
238 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
239 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
240 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
241 // I really need to rewrite Shaarli with a proper configuation manager.
243 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
244 // Ensure Shaarli has proper access to its resources
245 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
247 if ( $errors != array ()) {
248 $message = '<p>Insufficient permissions:</p><ul>' ;
250 foreach ( $errors as $error ) {
251 $message .= '<li>' . $error . '</li>' ;
255 header ( 'Content-Type: text/html; charset=utf-8' );
260 // Display the installation form if no existing config is found
264 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
265 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
266 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
268 // a token depending of deployment salt, user password, and the current ip
269 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
271 autoLocale (); // Sniff browser language and set date format accordingly.
272 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
274 //==================================================================================================
275 // Checking session state (i.e. is the user still logged in)
276 //==================================================================================================
278 function setup_login_state () {
279 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
282 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
283 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
284 if (! isset ( $GLOBALS [ 'login' ])) {
285 $userIsLoggedIn = false ; // Shaarli is not configured yet.
286 $loginFailure = true ;
288 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
289 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
293 $userIsLoggedIn = true ;
295 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
296 if ( empty ( $_SESSION [ 'uid' ]) ||
297 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
298 time () >= $_SESSION [ 'expires_on' ])
301 $userIsLoggedIn = false ;
302 $loginFailure = true ;
304 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
305 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
308 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
310 if (! $loginFailure ) {
311 $userIsLoggedIn = true ;
314 return $userIsLoggedIn ;
316 $userIsLoggedIn = setup_login_state ();
319 // ------------------------------------------------------------------------------------------
320 // Sniff browser language to display dates in the right format automatically.
321 // (Note that is may not work on your server if the corresponding local is not installed.)
322 function autoLocale ()
324 $attempts = array ( 'en_US' ); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
325 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
326 { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
327 if ( preg_match ( '/([a-z] {2} )-?([a-z] {2} )?/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) {
328 $loc = $matches [ 1 ] . (! empty ( $matches [ 2 ]) ? '_' . strtoupper ( $matches [ 2 ]) : '' );
329 $attempts = array ( $loc . '.UTF-8' , $loc , str_replace ( '_' , '-' , $loc ). '.UTF-8' , str_replace ( '_' , '-' , $loc ),
330 $loc . '_' . strtoupper ( $loc ). '.UTF-8' , $loc . '_' . strtoupper ( $loc ),
331 $loc . '_' . $loc . '.UTF-8' , $loc . '_' . $loc , $loc . '-' . strtoupper ( $loc ). '.UTF-8' ,
332 $loc . '-' . strtoupper ( $loc ), $loc . '-' . $loc . '.UTF-8' , $loc . '-' . $loc );
335 setlocale ( LC_TIME
, $attempts ); // LC_TIME = Set local for date/time format only.
338 // ------------------------------------------------------------------------------------------
339 // PubSubHubbub protocol support (if enabled) [UNTESTED]
340 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
341 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
344 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
346 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
348 index_url ( $_SERVER ). '?do=atom' ,
349 index_url ( $_SERVER ). '?do=rss'
351 $p- > publish_update ( $topic_url );
355 // ------------------------------------------------------------------------------------------
356 // Session management
358 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
361 $ip = $_SERVER [ "REMOTE_ADDR" ];
362 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
363 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
364 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
368 function fillSessionInfo () {
369 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
370 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
371 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
372 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
375 // Check that user/password is correct.
376 function check_auth ( $login , $password )
378 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
379 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
380 { // Login/password is correct.
382 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
385 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
389 // Returns true if the user is logged in.
390 function isLoggedIn ()
392 global $userIsLoggedIn ;
393 return $userIsLoggedIn ;
398 if ( isset ( $_SESSION )) {
399 unset ( $_SESSION [ 'uid' ]);
400 unset ( $_SESSION [ 'ip' ]);
401 unset ( $_SESSION [ 'username' ]);
402 unset ( $_SESSION [ 'privateonly' ]);
404 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
408 // ------------------------------------------------------------------------------------------
409 // Brute force protection system
410 // Several consecutive failed logins will ban the IP address for 30 minutes.
411 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 ?>" );
412 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
413 // Signal a failed login. Will ban the IP if too many failures:
414 function ban_loginFailed ()
416 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
417 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
418 $gb [ 'FAILURES' ][ $ip ] ++
;
419 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
421 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
422 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
424 $GLOBALS [ 'IPBANS' ] = $gb ;
425 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
428 // Signals a successful login. Resets failed login counter.
429 function ban_loginOk ()
431 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
432 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
433 $GLOBALS [ 'IPBANS' ] = $gb ;
434 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
437 // Checks if the user CAN login. If 'true', the user can try to login.
438 function ban_canLogin ()
440 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
441 if ( isset ( $gb [ 'BANS' ][ $ip ]))
443 // User is banned. Check if the ban has expired:
444 if ( $gb [ 'BANS' ][ $ip ]<= time ())
445 { // Ban expired, user can try to login again.
446 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
447 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
448 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
449 return true ; // Ban has expired, user can login.
451 return false ; // User is banned.
453 return true ; // User is not banned.
456 // ------------------------------------------------------------------------------------------
457 // Process login form: Check if login/password is correct.
458 if ( isset ( $_POST [ 'login' ]))
460 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
461 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
462 { // Login/password is OK.
464 // If user wants to keep the session cookie even after the browser closes:
465 if (! empty ( $_POST [ 'longlastingsession' ]))
467 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
468 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
469 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
471 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
472 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
473 // Note: Never forget the trailing slash on the cookie path!
474 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
476 else // Standard session expiration (=when browser closes)
478 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
479 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
480 session_regenerate_id ( true );
483 // Optional redirect after login:
484 if ( isset ( $_GET [ 'post' ])) {
485 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
486 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
487 if (! empty ( $_GET [ $param ])) {
488 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
491 header ( 'Location: ' . $uri );
495 if ( isset ( $_GET [ 'edit_link' ])) {
496 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
500 if ( isset ( $_POST [ 'returnurl' ])) {
501 // Prevent loops over login screen.
502 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
503 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
507 header ( 'Location: ?' ); exit ;
513 if ( isset ( $_GET [ 'post' ])) {
514 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
515 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
516 if (! empty ( $_GET [ $param ])) {
517 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
521 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
526 // ------------------------------------------------------------------------------------------
527 // Misc utility functions:
529 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
530 function return_bytes ( $val )
532 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
535 case 'g' : $val *= 1024 ;
536 case 'm' : $val *= 1024 ;
537 case 'k' : $val *= 1024 ;
542 // Try to determine max file size for uploads (POST).
543 // Returns an integer (in bytes)
544 function getMaxFileSize ()
546 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
547 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
548 // Return the smaller of two:
549 $maxsize = min ( $size1 , $size2 );
550 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
554 // ------------------------------------------------------------------------------------------
555 // Token management for XSRF protection
556 // Token should be used in any form which acts on data (create,update,delete,import...).
557 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
562 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
563 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
567 // Tells if a token is OK. Using this function will destroy the token.
569 function tokenOk ( $token )
571 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
573 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
574 return true ; // Token is OK.
576 return false ; // Wrong token, or already used.
579 // ------------------------------------------------------------------------------------------
580 /* This class is in charge of building the final page.
581 (This is basically a wrapper around RainTPL which pre-fills some fields.)
583 p.assign('myfield','myvalue');
584 p.renderPage('mytemplate');
589 private $tpl ; // RainTPL template
591 function __construct ()
597 * Initialize all default tpl tags.
599 private function initialize ()
601 $this- > tpl
= new RainTPL
;
604 $version = ApplicationUtils
:: checkUpdate (
606 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
607 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
608 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
610 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
612 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
613 $this- > tpl
-> assign ( 'versionError' , '' );
615 } catch ( Exception
$exc ) {
616 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
617 $this- > tpl
-> assign ( 'newVersion' , '' );
618 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
621 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
622 $searchcrits = '' ; // Search criteria
623 if (! empty ( $_GET [ 'searchtags' ])) {
624 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
626 if (! empty ( $_GET [ 'searchterm' ])) {
627 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
629 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
630 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
631 $this- > tpl
-> assign ( 'version' , shaarli_version
);
632 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
633 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
634 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
635 if (! empty ( $GLOBALS [ 'title' ])) {
636 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
638 if (! empty ( $GLOBALS [ 'titleLink' ])) {
639 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
641 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
642 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
644 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
645 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
646 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
650 // The following assign() method is basically the same as RainTPL (except that it's lazy)
651 public function assign ( $what , $where )
653 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
654 $this- > tpl
-> assign ( $what , $where );
657 // Render a specific page (using a template).
658 // e.g. pb.renderPage('picwall')
659 public function renderPage ( $page )
661 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
662 $this- > tpl
-> draw ( $page );
666 * Render a 404 page (uses the template : tpl/404.tpl)
668 * usage : $PAGE->render404('The link was deleted')
669 * @param string $message A messate to display what is not found
671 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
672 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
673 $this- > tpl
-> assign ( 'error_message' , $message );
674 $this- > renderPage ( '404' );
678 // ------------------------------------------------------------------------------------------
679 // Output the last N links in RSS 2.0 format.
682 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
684 // $usepermalink : If true, use permalink instead of final link.
685 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
686 // Also enabled through a config option
687 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
690 $query = $_SERVER [ "QUERY_STRING" ];
691 $cache = new CachedPage (
692 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
694 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
696 $cached = $cache- > cachedVersion ();
697 if (! empty ( $cached )) {
702 // If cached was not found (or not usable), then read the database and build the response:
703 $LINKSDB = new LinkDB (
704 $GLOBALS [ 'config' ][ 'DATASTORE' ],
706 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
707 $GLOBALS [ 'redirector' ]
709 // Read links from database (and filter private links if user it not logged in).
711 // Optionally filter the results:
712 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
713 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
714 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
715 $linksToDisplay = $LINKSDB- > filter (
716 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
717 array ( $searchtags , $searchterm )
720 elseif ( $searchtags ) {
721 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
723 elseif ( $searchterm ) {
724 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
727 $linksToDisplay = $LINKSDB ;
730 $nblinksToDisplay = 50 ; // Number of links to display.
731 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
732 if (! empty ( $_GET [ 'nb' ])) {
733 $nblinksToDisplay = $_GET [ 'nb' ] == 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
736 $pageaddr = escape ( index_url ( $_SERVER ));
737 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
738 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
739 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
740 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
742 echo '<!-- PubSubHubbub Discovery -->' ;
743 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
744 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
745 echo '<!-- End Of PubSubHubbub Discovery -->' ;
748 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
749 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
751 $link = $linksToDisplay [ $keys [ $i ]];
752 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
753 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
754 $absurl = $link [ 'url' ];
755 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
756 if ( $usepermalinks === true )
757 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
759 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
760 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) {
761 echo '<pubDate>' . escape ( $date- > format ( DateTime
:: RSS
)). "</pubDate> \n " ;
763 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
765 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
768 // Add permalink in description
769 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
770 // If user wants permalinks first, put the final link in description
771 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
772 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
773 echo '<description><![CDATA[' .
774 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
775 $descriptionlink . ']]></description>' . " \n </item> \n " ;
778 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
780 $cache- > cache ( ob_get_contents ());
785 // ------------------------------------------------------------------------------------------
786 // Output the last N links in ATOM format.
789 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
791 // $usepermalink : If true, use permalink instead of final link.
792 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
793 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
796 $query = $_SERVER [ "QUERY_STRING" ];
797 $cache = new CachedPage (
798 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
800 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
802 $cached = $cache- > cachedVersion ();
803 if (! empty ( $cached )) {
808 // If cached was not found (or not usable), then read the database and build the response:
809 // Read links from database (and filter private links if used it not logged in).
810 $LINKSDB = new LinkDB (
811 $GLOBALS [ 'config' ][ 'DATASTORE' ],
813 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
814 $GLOBALS [ 'redirector' ]
817 // Optionally filter the results:
818 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
819 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
820 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
821 $linksToDisplay = $LINKSDB- > filter (
822 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
823 array ( $searchtags , $searchterm )
826 elseif ( $searchtags ) {
827 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
829 elseif ( $searchterm ) {
830 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
833 $linksToDisplay = $LINKSDB ;
836 $nblinksToDisplay = 50 ; // Number of links to display.
837 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
838 if (! empty ( $_GET [ 'nb' ])) {
839 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
842 $pageaddr = escape ( index_url ( $_SERVER ));
846 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
847 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
849 $link = $linksToDisplay [ $keys [ $i ]];
850 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
851 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
852 $iso8601date = $date- > format ( DateTime
:: ISO8601
);
853 $latestDate = max ( $latestDate , $iso8601date );
854 $absurl = $link [ 'url' ];
855 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
856 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
857 if ( $usepermalinks === true )
858 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
860 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
862 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) {
863 $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
866 // Add permalink in description
867 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
868 // If user wants permalinks first, put the final link in description
869 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
870 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
872 $entries .= '<content type="html"><![CDATA[' .
873 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
874 $descriptionlink . "]]></content> \n " ;
875 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
877 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
878 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
880 $entries .= "</entry> \n " ;
883 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
884 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
885 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
886 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
887 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
889 $feed .= '<!-- PubSubHubbub Discovery -->' ;
890 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
891 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
893 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
894 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
896 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
899 $cache- > cache ( ob_get_contents ());
904 // ------------------------------------------------------------------------------------------
905 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
906 // Gives the last 7 days (which have links).
907 // This RSS feed cannot be filtered.
908 function showDailyRSS () {
910 $query = $_SERVER [ "QUERY_STRING" ];
911 $cache = new CachedPage (
912 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
914 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
916 $cached = $cache- > cachedVersion ();
917 if (! empty ( $cached )) {
922 // If cached was not found (or not usable), then read the database and build the response:
923 // Read links from database (and filter private links if used it not logged in).
924 $LINKSDB = new LinkDB (
925 $GLOBALS [ 'config' ][ 'DATASTORE' ],
927 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
928 $GLOBALS [ 'redirector' ]
931 /* Some Shaarlies may have very few links, so we need to look
932 back in time (rsort()) until we have enough days ($nb_of_days).
934 $linkdates = array ();
935 foreach ( $LINKSDB as $linkdate => $value ) {
936 $linkdates [] = $linkdate ;
939 $nb_of_days = 7 ; // We take 7 days.
940 $today = Date ( 'Ymd' );
943 foreach ( $linkdates as $linkdate ) {
944 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
945 if ( strcmp ( $day , $today ) < 0 ) {
946 if ( empty ( $days [ $day ])) {
947 $days [ $day ] = array ();
949 $days [ $day ][] = $linkdate ;
952 if ( count ( $days ) > $nb_of_days ) {
953 break ; // Have we collected enough days?
957 // Build the RSS feed.
958 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
959 $pageaddr = escape ( index_url ( $_SERVER ));
960 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
962 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
963 echo '<link>' . $pageaddr . '</link>' ;
964 echo '<description>Daily shared links</description>' ;
965 echo '<language>en-en</language>' ;
966 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
969 foreach ( $days as $day => $linkdates ) {
970 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
971 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
973 // Build the HTML body of this RSS entry.
978 // We pre-format some fields for proper output.
979 foreach ( $linkdates as $linkdate ) {
980 $l = $LINKSDB [ $linkdate ];
981 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
982 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
983 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
984 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
985 if ( startsWith ( $l [ 'url' ], '?' )) {
986 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
988 $links [ $linkdate ] = $l ;
991 // Then build the HTML for this day:
993 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
994 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
995 $tpl- > assign ( 'absurl' , $absurl );
996 $tpl- > assign ( 'links' , $links );
997 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
998 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
1000 echo $html . PHP_EOL
;
1002 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
1004 $cache- > cache ( ob_get_contents ());
1010 * Show the 'Daily' page.
1012 * @param PageBuilder $pageBuilder Template engine wrapper.
1014 function showDaily ( $pageBuilder )
1016 $LINKSDB = new LinkDB (
1017 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1019 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1020 $GLOBALS [ 'redirector' ]
1023 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1024 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1026 $days = $LINKSDB- > days ();
1027 $i = array_search ( $day , $days );
1028 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1033 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1034 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1038 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_DAY , $day );
1039 } catch ( Exception
$exc ) {
1041 $linksToDisplay = array ();
1044 // We pre-format some fields for proper output.
1045 foreach ( $linksToDisplay as $key => $link )
1048 $taglist = explode ( ' ' , $link [ 'tags' ]);
1049 uasort ( $taglist , 'strcasecmp' );
1050 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1051 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1052 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1053 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1054 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
1057 /* We need to spread the articles on 3 columns.
1058 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1059 so I manually spread entries with a simple method: I roughly evaluate the
1060 height of a div according to title and description length.
1062 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1063 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1064 foreach ( $linksToDisplay as $key => $link )
1066 // Roughly estimate length of entry (by counting characters)
1067 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1068 // Description: 836 characters gives roughly 342 pixel height.
1069 // This is not perfect, but it's usually OK.
1070 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1071 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1072 // Then put in column which is the less filled:
1073 $smallest = min ( $fill ); // find smallest value in array.
1074 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1075 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1076 $fill [ $index ] +
= $length ;
1079 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
1081 'linksToDisplay' => $linksToDisplay ,
1082 'linkcount' => count ( $LINKSDB ),
1084 'day' => $dayDate- > getTimestamp (),
1085 'previousday' => $previousday ,
1086 'nextday' => $nextday ,
1088 $pluginManager = PluginManager
:: getInstance ();
1089 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1091 foreach ( $data as $key => $value ) {
1092 $pageBuilder- > assign ( $key , $value );
1095 $pageBuilder- > renderPage ( 'daily' );
1099 // Renders the linklist
1100 function showLinkList ( $PAGE , $LINKSDB ) {
1101 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1102 $PAGE- > renderPage ( 'linklist' );
1106 // ------------------------------------------------------------------------------------------
1107 // Render HTML page (according to URL parameters and user rights)
1108 function renderPage ()
1110 $LINKSDB = new LinkDB (
1111 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1113 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1114 $GLOBALS [ 'redirector' ]
1117 $updater = new Updater (
1118 read_updates_file ( $GLOBALS [ 'config' ][ 'UPDATES_FILE' ]),
1124 $newUpdates = $updater- > update ();
1125 if (! empty ( $newUpdates )) {
1127 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ],
1128 $updater- > getDoneUpdates ()
1132 catch ( Exception
$e ) {
1133 die ( $e- > getMessage ());
1136 $PAGE = new pageBuilder
;
1138 // Determine which page will be rendered.
1139 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1140 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1142 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1143 // Then assign generated data to RainTPL.
1144 $common_hooks = array (
1149 $pluginManager = PluginManager
:: getInstance ();
1150 foreach ( $common_hooks as $name ) {
1151 $plugin_data = array ();
1152 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1154 'target' => $targetPage ,
1155 'loggedin' => isLoggedIn ()
1158 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1161 // -------- Display login form.
1162 if ( $targetPage == Router
:: $PAGE_LOGIN )
1164 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1165 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1166 $PAGE- > assign ( 'token' , $token );
1167 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1168 $PAGE- > renderPage ( 'loginform' );
1171 // -------- User wants to logout.
1172 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1174 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1176 header ( 'Location: ?' );
1180 // -------- Picture wall
1181 if ( $targetPage == Router
:: $PAGE_PICWALL )
1183 // Optionally filter the results:
1184 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1185 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1186 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
1187 $links = $LINKSDB- > filter (
1188 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
1189 array ( $searchtags , $searchterm )
1192 elseif ( $searchtags ) {
1193 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
1195 elseif ( $searchterm ) {
1196 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
1202 $linksToDisplay = array ();
1204 // Get only links which have a thumbnail.
1205 foreach ( $links as $link )
1207 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1208 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1209 if ( $thumb != '' ) // Only output links which have a thumbnail.
1211 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1212 $linksToDisplay []= $link ; // Add to array.
1217 'linkcount' => count ( $LINKSDB ),
1218 'linksToDisplay' => $linksToDisplay ,
1220 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1222 foreach ( $data as $key => $value ) {
1223 $PAGE- > assign ( $key , $value );
1226 $PAGE- > renderPage ( 'picwall' );
1230 // -------- Tag cloud
1231 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1233 $tags = $LINKSDB- > allTags ();
1235 // We sort tags alphabetically, then choose a font size according to count.
1236 // First, find max value.
1238 foreach ( $tags as $value ) {
1239 $maxcount = max ( $maxcount , $value );
1242 // Sort tags alphabetically: case insensitive, support locale if avalaible.
1243 uksort ( $tags , function ( $a , $b ) {
1244 // Collator is part of PHP intl.
1245 if ( class_exists ( 'Collator' )) {
1246 $c = new Collator ( setlocale ( LC_ALL
, 0 ));
1247 return $c- > compare ( $a , $b );
1249 return strcasecmp ( $a , $b );
1254 foreach ( $tags as $key => $value )
1255 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1257 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1261 'linkcount' => count ( $LINKSDB ),
1264 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1266 foreach ( $data as $key => $value ) {
1267 $PAGE- > assign ( $key , $value );
1270 $PAGE- > renderPage ( 'tagcloud' );
1275 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1279 // Display openseach plugin (XML)
1280 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1281 header ( 'Content-Type: application/xml; charset=utf-8' );
1282 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1283 $PAGE- > renderPage ( 'opensearch' );
1287 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1288 if ( isset ( $_GET [ 'addtag' ]))
1290 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1291 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1292 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1294 // Prevent redirection loop
1295 if ( isset ( $params [ 'addtag' ])) {
1296 unset ( $params [ 'addtag' ]);
1299 // Check if this tag is already in the search query and ignore it if it is.
1300 // Each tag is always separated by a space
1301 if ( isset ( $params [ 'searchtags' ])) {
1302 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1304 $current_tags = array ();
1307 foreach ( $current_tags as $value ) {
1308 if ( $value === $_GET [ 'addtag' ]) {
1313 // Append the tag if necessary
1314 if ( empty ( $params [ 'searchtags' ])) {
1315 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1318 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1321 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1322 header ( 'Location: ?' . http_build_query ( $params ));
1326 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1327 if ( isset ( $_GET [ 'removetag' ])) {
1328 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1329 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1330 header ( 'Location: ?' );
1334 // In case browser does not send HTTP_REFERER
1335 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1337 // Prevent redirection loop
1338 if ( isset ( $params [ 'removetag' ])) {
1339 unset ( $params [ 'removetag' ]);
1342 if ( isset ( $params [ 'searchtags' ])) {
1343 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1344 // Remove value from array $tags.
1345 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1346 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1348 if ( empty ( $params [ 'searchtags' ])) {
1349 unset ( $params [ 'searchtags' ]);
1352 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1354 header ( 'Location: ?' . http_build_query ( $params ));
1358 // -------- User wants to change the number of links per page (linksperpage=...)
1359 if ( isset ( $_GET [ 'linksperpage' ])) {
1360 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1361 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1364 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1368 // -------- User wants to see only private links (toggle)
1369 if ( isset ( $_GET [ 'privateonly' ])) {
1370 if ( empty ( $_SESSION [ 'privateonly' ])) {
1371 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1373 unset ( $_SESSION [ 'privateonly' ]); // See all links
1376 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1380 // -------- Handle other actions allowed for non-logged in users:
1383 // User tries to post new link but is not logged in:
1384 // Show login screen, then redirect to ?post=...
1385 if ( isset ( $_GET [ 'post' ]))
1387 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.
1391 // Same case as above except that user tried to access ?do=addlink without being logged in
1392 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1393 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1394 header ( 'Location: ?do=login&post=' );
1397 showLinkList ( $PAGE , $LINKSDB );
1398 if ( isset ( $_GET [ 'edit_link' ])) {
1399 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1403 exit ; // Never remove this one! All operations below are reserved for logged in user.
1406 // -------- All other functions are reserved for the registered user:
1408 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1409 if ( $targetPage == Router
:: $PAGE_TOOLS )
1412 'linkcount' => count ( $LINKSDB ),
1413 'pageabsaddr' => index_url ( $_SERVER ),
1415 $pluginManager- > executeHooks ( 'render_tools' , $data );
1417 foreach ( $data as $key => $value ) {
1418 $PAGE- > assign ( $key , $value );
1421 $PAGE- > renderPage ( 'tools' );
1425 // -------- User wants to change his/her password.
1426 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1428 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1429 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1431 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1433 // Make sure old password is correct.
1434 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1435 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1436 // Save new password
1437 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1438 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1440 writeConfig ( $GLOBALS , isLoggedIn ());
1442 catch ( Exception
$e ) {
1444 'ERROR while writing config file after changing password.' . PHP_EOL
.
1448 // TODO: do not handle exceptions/errors in JS.
1449 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1452 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1455 else // show the change password form.
1457 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1458 $PAGE- > assign ( 'token' , getToken ());
1459 $PAGE- > renderPage ( 'changepassword' );
1464 // -------- User wants to change configuration
1465 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1467 if (! empty ( $_POST [ 'title' ]) )
1469 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1471 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1472 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1473 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1474 $GLOBALS [ 'timezone' ] = $tz ;
1475 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1476 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1477 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1478 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1479 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1480 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1481 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1482 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1484 writeConfig ( $GLOBALS , isLoggedIn ());
1486 catch ( Exception
$e ) {
1488 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1492 // TODO: do not handle exceptions/errors in JS.
1493 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1496 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1499 else // Show the configuration form.
1501 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1502 $PAGE- > assign ( 'token' , getToken ());
1503 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1504 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1505 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1506 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1507 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1508 $PAGE- > renderPage ( 'configure' );
1513 // -------- User wants to rename a tag or delete it
1514 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1516 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1517 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1518 $PAGE- > assign ( 'token' , getToken ());
1519 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1520 $PAGE- > renderPage ( 'changetag' );
1524 if (! tokenOk ( $_POST [ 'token' ])) {
1525 die ( 'Wrong token.' );
1529 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1530 $needle = trim ( $_POST [ 'fromtag' ]);
1531 // True for case-sensitive tag search.
1532 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1533 foreach ( $linksToAlter as $key => $value )
1535 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1536 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1537 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1538 $LINKSDB [ $key ]= $value ;
1540 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1541 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1546 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1547 $needle = trim ( $_POST [ 'fromtag' ]);
1548 // True for case-sensitive tag search.
1549 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1550 foreach ( $linksToAlter as $key => $value )
1552 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1553 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1554 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1555 $LINKSDB [ $key ]= $value ;
1557 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1558 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1563 // -------- User wants to add a link without using the bookmarklet: Show form.
1564 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1566 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1567 $PAGE- > renderPage ( 'addlink' );
1571 // -------- User clicked the "Save" button when editing a link: Save link to database.
1572 if ( isset ( $_POST [ 'save_edit' ]))
1575 if (! tokenOk ( $_POST [ 'token' ])) {
1576 die ( 'Wrong token.' );
1578 // Remove multiple spaces.
1579 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1580 // Remove first '-' char in tags.
1581 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1582 // Remove duplicates.
1583 $tags = implode(' ', array_unique(explode(' ', $tags )));
1584 $linkdate = $_POST [' lf_linkdate
'];
1585 $url = trim( $_POST [' lf_url
']);
1586 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1587 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1588 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1590 $url = ' http
: //' . $url;
1594 'title' => trim ( $_POST [ 'lf_title' ]),
1596 'description' => $_POST [ 'lf_description' ],
1597 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1598 'linkdate' => $linkdate ,
1599 'tags' => str_replace ( ',' , ' ' , $tags )
1601 // If title is empty, use the URL as title.
1602 if ( $link [ 'title' ] == '' ) {
1603 $link [ 'title' ] = $link [ 'url' ];
1606 $pluginManager- > executeHooks ( 'save_link' , $link );
1608 $LINKSDB [ $linkdate ] = $link ;
1609 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1612 // If we are called from the bookmarklet, we must close the popup:
1613 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1614 echo '<script>self.close();</script>' ;
1618 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1619 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1620 // Scroll to the link which has been edited.
1621 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1622 // After saving the link, redirect to the page the user was on.
1623 header ( 'Location: ' . $location );
1627 // -------- User clicked the "Cancel" button when editing a link.
1628 if ( isset ( $_POST [ 'cancel_edit' ]))
1630 // If we are called from the bookmarklet, we must close the popup:
1631 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1632 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1633 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1634 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1635 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1639 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1640 if ( isset ( $_POST [ 'delete_link' ]))
1642 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1643 // We do not need to ask for confirmation:
1644 // - confirmation is handled by JavaScript
1645 // - we are protected from XSRF by the token.
1646 $linkdate = $_POST [ 'lf_linkdate' ];
1648 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1650 unset ( $LINKSDB [ $linkdate ]);
1651 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1653 // If we are called from the bookmarklet, we must close the popup:
1654 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1655 // Pick where we're going to redirect
1656 // =============================================================
1657 // Basically, we can't redirect to where we were previously if it was a permalink
1658 // or an edit_link, because it would 404.
1660 // - / : nothing in $_GET, redirect to self
1661 // - /?page : redirect to self
1662 // - /?searchterm : redirect to self (there might be other links)
1663 // - /?searchtags : redirect to self
1664 // - /permalink : redirect to / (the link does not exist anymore)
1665 // - /?edit_link : redirect to / (the link does not exist anymore)
1666 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1667 // redirect is not satisfied, and only then redirect to /
1670 if ( count ( $_GET ) == 0
1671 || isset ( $_GET [ 'page' ])
1672 || isset ( $_GET [ 'searchterm' ])
1673 || isset ( $_GET [ 'searchtags' ])
1675 if ( isset ( $_POST [ 'returnurl' ])) {
1676 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1678 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1682 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1686 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1687 if ( isset ( $_GET [ 'edit_link' ]))
1689 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1690 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1692 'linkcount' => count ( $LINKSDB ),
1694 'link_is_new' => false ,
1695 'token' => getToken (),
1696 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1697 'tags' => $LINKSDB- > allTags (),
1699 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1701 foreach ( $data as $key => $value ) {
1702 $PAGE- > assign ( $key , $value );
1705 $PAGE- > renderPage ( 'editlink' );
1709 // -------- User want to post a new link: Display link edit form.
1710 if ( isset ( $_GET [ 'post' ])) {
1711 $url = cleanup_url ( escape ( $_GET [ 'post' ]));
1713 $link_is_new = false ;
1714 // Check if URL is not already in database (in this case, we will edit the existing link)
1715 $link = $LINKSDB- > getLinkFromUrl ( $url );
1718 $link_is_new = true ;
1719 $linkdate = strval ( date ( 'Ymd_His' ));
1720 // Get title if it was provided in URL (by the bookmarklet).
1721 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1722 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1723 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1724 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1725 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1726 // 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.)
1727 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1728 // Short timeout to keep the application responsive
1729 list ( $headers , $content ) = get_http_response ( $url , 4 );
1730 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1731 // Retrieve charset.
1732 $charset = get_charset ( $headers , $content );
1734 $title = html_extract_title ( $content );
1735 // Re-encode title in utf-8 if necessary.
1736 if (! empty ( $title ) && $charset != 'utf-8' ) {
1737 $title = mb_convert_encoding ( $title , $charset , 'utf-8' );
1743 $url = '?' . smallHash ( $linkdate );
1748 'linkdate' => $linkdate ,
1751 'description' => $description ,
1753 'private' => $private
1758 'linkcount' => count ( $LINKSDB ),
1760 'link_is_new' => $link_is_new ,
1761 'token' => getToken (), // XSRF protection.
1762 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1763 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1764 'tags' => $LINKSDB- > allTags (),
1766 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1768 foreach ( $data as $key => $value ) {
1769 $PAGE- > assign ( $key , $value );
1772 $PAGE- > renderPage ( 'editlink' );
1776 // -------- Export as Netscape Bookmarks HTML file.
1777 if ( $targetPage == Router
:: $PAGE_EXPORT )
1779 if ( empty ( $_GET [ 'what' ]))
1781 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1782 $PAGE- > renderPage ( 'export' );
1785 $exportWhat = $_GET [ 'what' ];
1786 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1788 header ( 'Content-Type: text/html; charset=utf-8' );
1789 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1790 $currentdate = date ( 'Y/m/d H:i:s' );
1792 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1793 <!-- This is an automatically generated file.
1794 It will be read and overwritten.
1796 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1797 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1798 <TITLE>Bookmarks</TITLE>
1801 foreach ( $LINKSDB as $link )
1803 if ( $exportWhat == 'all' ||
1804 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1805 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1807 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1808 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . $date- > getTimestamp (). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1809 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1810 echo '>' . $link [ 'title' ]. "</A> \n " ;
1811 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1817 // -------- User is uploading a file for import
1818 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1820 // If file is too big, some form field may be missing.
1821 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1823 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1824 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>' ;
1827 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1832 // -------- Show upload/import dialog:
1833 if ( $targetPage == Router
:: $PAGE_IMPORT )
1835 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1836 $PAGE- > assign ( 'token' , getToken ());
1837 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1838 $PAGE- > renderPage ( 'import' );
1842 // Plugin administration page
1843 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1844 $pluginMeta = $pluginManager- > getPluginsMeta ();
1846 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1847 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1849 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1852 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1854 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1856 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1857 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1858 $PAGE- > renderPage ( 'pluginsadmin' );
1862 // Plugin administration form action
1863 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1865 if ( isset ( $_POST [ 'parameters_form' ])) {
1866 unset ( $_POST [ 'parameters_form' ]);
1867 foreach ( $_POST as $param => $value ) {
1868 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1872 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1874 writeConfig ( $GLOBALS , isLoggedIn ());
1876 catch ( Exception
$e ) {
1878 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1882 // TODO: do not handle exceptions/errors in JS.
1883 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1886 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1890 // -------- Otherwise, simply display search form and links:
1891 showLinkList ( $PAGE , $LINKSDB );
1895 // -----------------------------------------------------------------------------------------------
1896 // Process the import file form.
1897 function importFile ()
1899 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1900 $LINKSDB = new LinkDB (
1901 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1903 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1904 $GLOBALS [ 'redirector' ]
1906 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1907 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1908 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1909 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1910 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1915 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1917 // Then import the bookmarks.
1918 if ( $type == 'netscape' )
1920 // This is a standard Netscape-style bookmark file.
1921 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1922 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1924 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1925 $d = explode ( '<DD>' , $html );
1926 if ( startswith ( $d [ 0 ], '<A ' ))
1928 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1929 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1930 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1931 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1933 foreach ( $matches as $m )
1935 $attr = $m [ 1 ]; $value = $m [ 2 ];
1936 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1937 elseif ( $attr == 'ADD_DATE' )
1939 $raw_add_date = intval ( $value );
1940 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1942 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1943 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1945 if ( $link [ 'url' ]!= '' )
1947 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1948 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1950 { // Link not in database, let's import it...
1951 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1953 // Make sure date/time is not already used by another link.
1954 // (Some bookmark files have several different links with the same ADD_DATE)
1955 // We increment date by 1 second until we find a date which is not used in DB.
1956 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1957 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1958 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1959 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1962 else // Link already present in database.
1965 { // If overwrite is required, we import link data, except date/time.
1966 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1967 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1975 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1977 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1981 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1985 // -----------------------------------------------------------------------------------------------
1986 // Template for the list of links (<div id="linklist">)
1987 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1988 function buildLinkList ( $PAGE , $LINKSDB )
1990 // Filter link database according to parameters.
1991 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1992 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( trim ( $_GET [ 'searchterm' ])) : '' ;
1993 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]) ? true : false ;
1995 // Search tags + fullsearch.
1996 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
1997 $linksToDisplay = $LINKSDB- > filter (
1998 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
1999 array ( $searchtags , $searchterm ),
2005 elseif (! empty ( $searchtags )) {
2006 $linksToDisplay = $LINKSDB- > filter (
2007 LinkFilter
:: $FILTER_TAG ,
2014 elseif (! empty ( $searchterm )) {
2015 $linksToDisplay = $LINKSDB- > filter (
2016 LinkFilter
:: $FILTER_TEXT ,
2022 // Detect smallHashes in URL.
2023 elseif (! empty ( $_SERVER [ 'QUERY_STRING' ])
2024 && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])
2026 $linksToDisplay = $LINKSDB- > filter (
2027 LinkFilter
:: $FILTER_HASH ,
2028 substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 )
2031 if ( count ( $linksToDisplay ) == 0 ) {
2032 $PAGE- > render404 ( 'The link you are trying to reach does not exist or has been deleted.' );
2036 // Otherwise, display without filtering.
2038 $linksToDisplay = $LINKSDB- > filter ( '' , '' , false , $privateonly );
2041 // ---- Handle paging.
2043 foreach ( $linksToDisplay as $key => $value ) {
2047 // If there is only a single link, we change on-the-fly the title of the page.
2048 if ( count ( $linksToDisplay ) == 1 ) {
2049 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
2052 // Select articles according to paging.
2053 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
2054 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
2055 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
2056 $page = $page < 1 ? 1 : $page ;
2057 $page = $page > $pagecount ? $pagecount : $page ;
2059 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
2060 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
2061 $linkDisp = array ();
2062 while ( $i < $end && $i < count ( $keys ))
2064 $link = $linksToDisplay [ $keys [ $i ]];
2065 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
2066 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
2067 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
2068 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
2069 $link [ 'timestamp' ] = $date- > getTimestamp ();
2070 $taglist = explode ( ' ' , $link [ 'tags' ]);
2071 uasort ( $taglist , 'strcasecmp' );
2072 $link [ 'taglist' ] = $taglist ;
2073 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
2074 // Check for both signs of a note: starting with ? and 7 chars long.
2075 if ( $link [ 'url' ][ 0 ] === '?' &&
2076 strlen ( $link [ 'url' ]) === 7 ) {
2077 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
2080 $linkDisp [ $keys [ $i ]] = $link ;
2084 // Compute paging navigation
2085 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
2086 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
2087 $previous_page_url = '' ;
2088 if ( $i != count ( $keys )) {
2089 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
2093 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
2096 $token = isLoggedIn () ? getToken () : '' ;
2098 // Fill all template fields.
2100 'linkcount' => count ( $LINKSDB ),
2101 'previous_page_url' => $previous_page_url ,
2102 'next_page_url' => $next_page_url ,
2103 'page_current' => $page ,
2104 'page_max' => $pagecount ,
2105 'result_count' => count ( $linksToDisplay ),
2106 'search_term' => $searchterm ,
2107 'search_tags' => $searchtags ,
2108 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
2110 'links' => $linkDisp ,
2111 'tags' => $LINKSDB- > allTags (),
2113 // FIXME! temporary fix - see #399.
2114 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
2115 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
2118 $pluginManager = PluginManager
:: getInstance ();
2119 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
2121 foreach ( $data as $key => $value ) {
2122 $PAGE- > assign ( $key , $value );
2128 // Compute the thumbnail for a link.
2130 // With a link to the original URL.
2131 // Understands various services (youtube.com...)
2132 // Input: $url = URL for which the thumbnail must be found.
2133 // $href = if provided, this URL will be followed instead of $url
2134 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
2135 // Some of them may be missing.
2136 // Return an empty array if no thumbnail available.
2137 function computeThumbnail ( $url , $href = false )
2139 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
2140 if ( $href == false ) $href = $url ;
2142 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
2143 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
2144 // ^^^^^^^^^^^ ^^^^^^^^^^^
2145 $domain = parse_url ( $url , PHP_URL_HOST
);
2146 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
2148 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
2149 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
2150 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2152 if ( $domain == 'youtu.be' ) // Youtube short links
2154 $path = parse_url ( $url , PHP_URL_PATH
);
2155 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
2156 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2158 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
2160 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
2161 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
2162 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
2165 if ( $domain == 'imgur.com' )
2167 $path = parse_url ( $url , PHP_URL_PATH
);
2168 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2169 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2170 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2171 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2172 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2174 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2175 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2177 if ( $domain == 'i.imgur.com' )
2179 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2180 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2181 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2183 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2185 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2187 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2188 return array ( 'src' => $thumburl ,
2189 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2192 if ( endsWith ( $domain , '.imageshack.us' ))
2194 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2195 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2197 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2198 return array ( 'src' => $thumburl ,
2199 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2203 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2204 // So we deport the thumbnail generation in order not to slow down page generation
2205 // (and we also cache the thumbnail)
2207 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2209 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2210 || $domain == 'vimeo.com'
2211 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2212 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2215 if ( $domain == 'vimeo.com' )
2216 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2217 $path = parse_url ( $url , PHP_URL_PATH
);
2218 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2220 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2221 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2222 $path = parse_url ( $url , PHP_URL_PATH
);
2223 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2225 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2226 { // Make sure this TED URL points to a video (/talks/...)
2227 $path = parse_url ( $url , PHP_URL_PATH
);
2228 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2230 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2231 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2232 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2235 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2236 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2237 // But using the extension will do.
2238 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2239 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2241 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2242 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2243 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2245 return array (); // No thumbnail.
2250 // Returns the HTML code to display a thumbnail for a link
2251 // with a link to the original URL.
2252 // Understands various services (youtube.com...)
2253 // Input: $url = URL for which the thumbnail must be found.
2254 // $href = if provided, this URL will be followed instead of $url
2255 // Returns '' if no thumbnail available.
2256 function thumbnail ( $url , $href = false )
2258 $t = computeThumbnail ( $url , $href );
2259 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2261 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2262 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2263 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2264 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2265 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2270 // Returns the HTML code to display a thumbnail for a link
2271 // for the picture wall (using lazy image loading)
2272 // Understands various services (youtube.com...)
2273 // Input: $url = URL for which the thumbnail must be found.
2274 // $href = if provided, this URL will be followed instead of $url
2275 // Returns '' if no thumbnail available.
2276 function lazyThumbnail ( $url , $href = false )
2278 $t = computeThumbnail ( $url , $href );
2279 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2281 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2284 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2286 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2287 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2288 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2289 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2292 // No-JavaScript fallback.
2293 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2294 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2295 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2296 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2297 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2298 $html .= '></noscript></a>' ;
2304 // -----------------------------------------------------------------------------------------------
2306 // This function should NEVER be called if the file data/config.php exists.
2309 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2310 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2313 // This part makes sure sessions works correctly.
2314 // (Because on some hosts, session.save_path may not be set correctly,
2315 // or we may not have write access to it.)
2316 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2317 { // Step 2: Check if data in session is correct.
2318 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2319 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2320 echo 'It currently points to ' . session_save_path (). '<br>' ;
2321 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>' ;
2322 echo '<br><a href="?">Click to try again.</a></pre>' ;
2325 if (! isset ( $_SESSION [ 'session_tested' ]))
2326 { // Step 1 : Try to store data in session and reload page.
2327 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2328 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2330 if ( isset ( $_GET [ 'test_session' ]))
2331 { // Step 3: Sessions are OK. Remove test parameter from URL.
2332 header ( 'Location: ' . index_url ( $_SERVER ));
2336 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2339 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2340 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2341 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2344 $GLOBALS [ 'timezone' ] = $tz ;
2345 // Everything is ok, let's create config file.
2346 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2347 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2348 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2349 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2350 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2352 writeConfig ( $GLOBALS , isLoggedIn ());
2354 catch ( Exception
$e ) {
2356 'ERROR while writing config file after installation.' . PHP_EOL
.
2360 // TODO: do not handle exceptions/errors in JS.
2361 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2364 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2368 // Display config form:
2369 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2370 $timezone_html = '' ;
2371 if ( $timezone_form != '' ) {
2372 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2375 $PAGE = new pageBuilder
;
2376 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2377 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2378 $PAGE- > renderPage ( 'install' );
2382 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2383 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2384 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2385 This function is called by passing the URL:
2386 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2387 [URL] is the URL of the link (e.g. a flickr page)
2388 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2389 The function below will fetch the image from the webservice and store it in the cache.
2391 function genThumbnail ()
2393 // Make sure the parameters in the URL were generated by us.
2394 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2395 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2397 // Let's see if we don't already have the image for this URL in the cache.
2398 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2399 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2400 { // We have the thumbnail, just serve it:
2401 header ( 'Content-Type: image/jpeg' );
2402 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2405 // We may also serve a blank image (if service did not respond)
2406 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2407 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2409 header ( 'Content-Type: image/gif' );
2410 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2414 // Otherwise, generate the thumbnail.
2415 $url = $_GET [ 'url' ];
2416 $domain = parse_url ( $url , PHP_URL_HOST
);
2418 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2420 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2421 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2423 // Is this a link to an image, or to a flickr page ?
2425 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2426 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2427 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2428 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2430 else // This is a flickr page (html)
2432 // Get the flickr html page.
2433 list ( $headers , $content ) = get_http_response ( $url , 20 );
2434 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2436 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2437 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2438 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2440 // In albums (and some other pages), the link rel="image_src" is not provided,
2441 // but flickr provides:
2442 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2445 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2446 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2452 { // Let's download the image.
2453 // Image is 240x120, so 10 seconds to download should be enough.
2454 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2455 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2456 // Save image to cache.
2457 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2458 header ( 'Content-Type: image/jpeg' );
2465 elseif ( $domain == 'vimeo.com' )
2467 // This is more complex: we have to perform a HTTP request, then parse the result.
2468 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2469 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2470 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2471 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2472 $t = unserialize ( $content );
2473 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2474 // Then we download the image and serve it to our client.
2475 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2476 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2477 // Save image to cache.
2478 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2479 header ( 'Content-Type: image/jpeg' );
2486 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2488 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2489 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2490 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2491 list ( $headers , $content ) = get_http_response ( $url , 5 );
2492 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2493 // Extract the link to the thumbnail
2494 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2495 if (! empty ( $matches [ 1 ]))
2496 { // Let's download the image.
2497 $imageurl = $matches [ 1 ];
2498 // No control on image size, so wait long enough
2499 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2500 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2501 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2502 file_put_contents ( $filepath , $content ); // Save image to cache.
2503 if ( resizeImage ( $filepath ))
2505 header ( 'Content-Type: image/jpeg' );
2506 echo file_get_contents ( $filepath );
2514 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2516 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2517 // http://xkcd.com/327/
2518 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2519 list ( $headers , $content ) = get_http_response ( $url , 5 );
2520 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2521 // Extract the link to the thumbnail
2522 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2523 if (! empty ( $matches [ 1 ]))
2524 { // Let's download the image.
2525 $imageurl = $matches [ 1 ];
2526 // No control on image size, so wait long enough
2527 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2528 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2529 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2530 // Save image to cache.
2531 file_put_contents ( $filepath , $content );
2532 if ( resizeImage ( $filepath ))
2534 header ( 'Content-Type: image/jpeg' );
2535 echo file_get_contents ( $filepath );
2545 // For all other domains, we try to download the image and make a thumbnail.
2546 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2547 list ( $headers , $content ) = get_http_response ( $url , 30 );
2548 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2549 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2550 // Save image to cache.
2551 file_put_contents ( $filepath , $content );
2552 if ( resizeImage ( $filepath ))
2554 header ( 'Content-Type: image/jpeg' );
2555 echo file_get_contents ( $filepath );
2562 // Otherwise, return an empty image (8x8 transparent gif)
2563 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2564 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2565 header ( 'Content-Type: image/gif' );
2569 // Make a thumbnail of the image (to width: 120 pixels)
2570 // Returns true if success, false otherwise.
2571 function resizeImage ( $filepath )
2573 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2575 // Trick: some stupid people rename GIF as JPEG... or else.
2576 // So we really try to open each image type whatever the extension is.
2577 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2579 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2580 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2581 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2582 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2585 $ystart = 0 ; $yheight = $h ;
2586 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2587 $nw = 120 ; // Desired width
2588 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2590 $im2 = imagecreatetruecolor ( $nw , $nh );
2591 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2592 imageinterlace ( $im2 , true ); // For progressive JPEG.
2593 $tempname = $filepath . '_TEMP.jpg' ;
2594 imagejpeg ( $im2 , $tempname , 90 );
2598 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2602 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2603 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2604 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2605 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2606 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];