]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
9100044e8c5afcdf24f49604f5d498ece2a46b62
3 * Shaarli v0.6.5 - 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.5' );
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 // Sniff browser language and set date format accordingly.
272 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
273 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
275 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
277 //==================================================================================================
278 // Checking session state (i.e. is the user still logged in)
279 //==================================================================================================
281 function setup_login_state () {
282 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
285 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
286 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
287 if (! isset ( $GLOBALS [ 'login' ])) {
288 $userIsLoggedIn = false ; // Shaarli is not configured yet.
289 $loginFailure = true ;
291 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
292 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
296 $userIsLoggedIn = true ;
298 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
299 if ( empty ( $_SESSION [ 'uid' ]) ||
300 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
301 time () >= $_SESSION [ 'expires_on' ])
304 $userIsLoggedIn = false ;
305 $loginFailure = true ;
307 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
308 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
311 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
313 if (! $loginFailure ) {
314 $userIsLoggedIn = true ;
317 return $userIsLoggedIn ;
319 $userIsLoggedIn = setup_login_state ();
321 // ------------------------------------------------------------------------------------------
322 // PubSubHubbub protocol support (if enabled) [UNTESTED]
323 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
324 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
327 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
329 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
331 index_url ( $_SERVER ). '?do=atom' ,
332 index_url ( $_SERVER ). '?do=rss'
334 $p- > publish_update ( $topic_url );
338 // ------------------------------------------------------------------------------------------
339 // Session management
341 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
344 $ip = $_SERVER [ "REMOTE_ADDR" ];
345 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
346 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
347 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
351 function fillSessionInfo () {
352 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
353 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
354 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
355 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
358 // Check that user/password is correct.
359 function check_auth ( $login , $password )
361 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
362 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
363 { // Login/password is correct.
365 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
368 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
372 // Returns true if the user is logged in.
373 function isLoggedIn ()
375 global $userIsLoggedIn ;
376 return $userIsLoggedIn ;
381 if ( isset ( $_SESSION )) {
382 unset ( $_SESSION [ 'uid' ]);
383 unset ( $_SESSION [ 'ip' ]);
384 unset ( $_SESSION [ 'username' ]);
385 unset ( $_SESSION [ 'privateonly' ]);
387 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
391 // ------------------------------------------------------------------------------------------
392 // Brute force protection system
393 // Several consecutive failed logins will ban the IP address for 30 minutes.
394 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 ?>" );
395 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
396 // Signal a failed login. Will ban the IP if too many failures:
397 function ban_loginFailed ()
399 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
400 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
401 $gb [ 'FAILURES' ][ $ip ] ++
;
402 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
404 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
405 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
407 $GLOBALS [ 'IPBANS' ] = $gb ;
408 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
411 // Signals a successful login. Resets failed login counter.
412 function ban_loginOk ()
414 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
415 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
416 $GLOBALS [ 'IPBANS' ] = $gb ;
417 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
420 // Checks if the user CAN login. If 'true', the user can try to login.
421 function ban_canLogin ()
423 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
424 if ( isset ( $gb [ 'BANS' ][ $ip ]))
426 // User is banned. Check if the ban has expired:
427 if ( $gb [ 'BANS' ][ $ip ]<= time ())
428 { // Ban expired, user can try to login again.
429 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
430 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
431 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
432 return true ; // Ban has expired, user can login.
434 return false ; // User is banned.
436 return true ; // User is not banned.
439 // ------------------------------------------------------------------------------------------
440 // Process login form: Check if login/password is correct.
441 if ( isset ( $_POST [ 'login' ]))
443 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
444 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
445 { // Login/password is OK.
447 // If user wants to keep the session cookie even after the browser closes:
448 if (! empty ( $_POST [ 'longlastingsession' ]))
450 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
451 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
452 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
454 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
455 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
456 // Note: Never forget the trailing slash on the cookie path!
457 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
459 else // Standard session expiration (=when browser closes)
461 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
462 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
463 session_regenerate_id ( true );
466 // Optional redirect after login:
467 if ( isset ( $_GET [ 'post' ])) {
468 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
469 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
470 if (! empty ( $_GET [ $param ])) {
471 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
474 header ( 'Location: ' . $uri );
478 if ( isset ( $_GET [ 'edit_link' ])) {
479 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
483 if ( isset ( $_POST [ 'returnurl' ])) {
484 // Prevent loops over login screen.
485 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
486 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
490 header ( 'Location: ?' ); exit ;
496 if ( isset ( $_GET [ 'post' ])) {
497 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
498 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
499 if (! empty ( $_GET [ $param ])) {
500 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
504 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
509 // ------------------------------------------------------------------------------------------
510 // Misc utility functions:
512 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
513 function return_bytes ( $val )
515 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
518 case 'g' : $val *= 1024 ;
519 case 'm' : $val *= 1024 ;
520 case 'k' : $val *= 1024 ;
525 // Try to determine max file size for uploads (POST).
526 // Returns an integer (in bytes)
527 function getMaxFileSize ()
529 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
530 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
531 // Return the smaller of two:
532 $maxsize = min ( $size1 , $size2 );
533 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
537 // ------------------------------------------------------------------------------------------
538 // Token management for XSRF protection
539 // Token should be used in any form which acts on data (create,update,delete,import...).
540 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
545 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
546 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
550 // Tells if a token is OK. Using this function will destroy the token.
552 function tokenOk ( $token )
554 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
556 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
557 return true ; // Token is OK.
559 return false ; // Wrong token, or already used.
562 // ------------------------------------------------------------------------------------------
563 /* This class is in charge of building the final page.
564 (This is basically a wrapper around RainTPL which pre-fills some fields.)
566 p.assign('myfield','myvalue');
567 p.renderPage('mytemplate');
572 private $tpl ; // RainTPL template
574 function __construct ()
580 * Initialize all default tpl tags.
582 private function initialize ()
584 $this- > tpl
= new RainTPL
;
587 $version = ApplicationUtils
:: checkUpdate (
589 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
590 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
591 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
593 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
595 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
596 $this- > tpl
-> assign ( 'versionError' , '' );
598 } catch ( Exception
$exc ) {
599 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
600 $this- > tpl
-> assign ( 'newVersion' , '' );
601 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
604 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
605 $searchcrits = '' ; // Search criteria
606 if (! empty ( $_GET [ 'searchtags' ])) {
607 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
609 if (! empty ( $_GET [ 'searchterm' ])) {
610 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
612 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
613 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
614 $this- > tpl
-> assign ( 'version' , shaarli_version
);
615 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
616 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
617 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
618 if (! empty ( $GLOBALS [ 'title' ])) {
619 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
621 if (! empty ( $GLOBALS [ 'titleLink' ])) {
622 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
624 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
625 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
627 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
628 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
629 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
633 // The following assign() method is basically the same as RainTPL (except that it's lazy)
634 public function assign ( $what , $where )
636 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
637 $this- > tpl
-> assign ( $what , $where );
641 * Assign an array of data to the template builder.
643 * @param array $data Data to assign.
645 * @return false if invalid data.
647 public function assignAll ( $data )
649 // Lazy initialization
650 if ( $this- > tpl
=== false ) {
654 if ( empty ( $data ) || ! is_array ( $data )){
658 foreach ( $data as $key => $value ) {
659 $this- > assign ( $key , $value );
663 // Render a specific page (using a template).
664 // e.g. pb.renderPage('picwall')
665 public function renderPage ( $page )
667 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
668 $this- > tpl
-> draw ( $page );
672 * Render a 404 page (uses the template : tpl/404.tpl)
674 * usage : $PAGE->render404('The link was deleted')
675 * @param string $message A messate to display what is not found
677 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
678 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
679 $this- > tpl
-> assign ( 'error_message' , $message );
680 $this- > renderPage ( '404' );
684 // ------------------------------------------------------------------------------------------
685 // Output the last N links in RSS 2.0 format.
688 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
690 // $usepermalink : If true, use permalink instead of final link.
691 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
692 // Also enabled through a config option
693 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
696 $query = $_SERVER [ "QUERY_STRING" ];
697 $cache = new CachedPage (
698 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
700 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
702 $cached = $cache- > cachedVersion ();
703 if (! empty ( $cached )) {
708 // If cached was not found (or not usable), then read the database and build the response:
709 $LINKSDB = new LinkDB (
710 $GLOBALS [ 'config' ][ 'DATASTORE' ],
712 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
713 $GLOBALS [ 'redirector' ]
715 // Read links from database (and filter private links if user it not logged in).
717 // Optionally filter the results:
718 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
719 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
720 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
721 $linksToDisplay = $LINKSDB- > filter (
722 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
723 array ( $searchtags , $searchterm )
726 elseif ( $searchtags ) {
727 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
729 elseif ( $searchterm ) {
730 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
733 $linksToDisplay = $LINKSDB ;
736 $nblinksToDisplay = 50 ; // Number of links to display.
737 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
738 if (! empty ( $_GET [ 'nb' ])) {
739 $nblinksToDisplay = $_GET [ 'nb' ] == 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
742 $pageaddr = escape ( index_url ( $_SERVER ));
743 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
744 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
745 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
746 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
748 echo '<!-- PubSubHubbub Discovery -->' ;
749 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
750 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
751 echo '<!-- End Of PubSubHubbub Discovery -->' ;
754 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
755 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
757 $link = $linksToDisplay [ $keys [ $i ]];
758 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
759 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
760 $absurl = $link [ 'url' ];
761 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
762 if ( $usepermalinks === true )
763 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
765 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
766 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) {
767 echo '<pubDate>' . escape ( $date- > format ( DateTime
:: RSS
)). "</pubDate> \n " ;
769 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
771 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
774 // Add permalink in description
775 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
776 // If user wants permalinks first, put the final link in description
777 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
778 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
779 echo '<description><![CDATA[' .
780 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
781 $descriptionlink . ']]></description>' . " \n </item> \n " ;
784 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
786 $cache- > cache ( ob_get_contents ());
791 // ------------------------------------------------------------------------------------------
792 // Output the last N links in ATOM format.
795 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
797 // $usepermalink : If true, use permalink instead of final link.
798 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
799 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
802 $query = $_SERVER [ "QUERY_STRING" ];
803 $cache = new CachedPage (
804 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
806 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
808 $cached = $cache- > cachedVersion ();
809 if (! empty ( $cached )) {
814 // If cached was not found (or not usable), then read the database and build the response:
815 // Read links from database (and filter private links if used it not logged in).
816 $LINKSDB = new LinkDB (
817 $GLOBALS [ 'config' ][ 'DATASTORE' ],
819 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
820 $GLOBALS [ 'redirector' ]
823 // Optionally filter the results:
824 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
825 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
826 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
827 $linksToDisplay = $LINKSDB- > filter (
828 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
829 array ( $searchtags , $searchterm )
832 elseif ( $searchtags ) {
833 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
835 elseif ( $searchterm ) {
836 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
839 $linksToDisplay = $LINKSDB ;
842 $nblinksToDisplay = 50 ; // Number of links to display.
843 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
844 if (! empty ( $_GET [ 'nb' ])) {
845 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
848 $pageaddr = escape ( index_url ( $_SERVER ));
852 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
853 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
855 $link = $linksToDisplay [ $keys [ $i ]];
856 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
857 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
858 $iso8601date = $date- > format ( DateTime
:: ISO8601
);
859 $latestDate = max ( $latestDate , $iso8601date );
860 $absurl = $link [ 'url' ];
861 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
862 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
863 if ( $usepermalinks === true )
864 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
866 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
868 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) {
869 $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
872 // Add permalink in description
873 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
874 // If user wants permalinks first, put the final link in description
875 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
876 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
878 $entries .= '<content type="html"><![CDATA[' .
879 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
880 $descriptionlink . "]]></content> \n " ;
881 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
883 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
884 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
886 $entries .= "</entry> \n " ;
889 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
890 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
891 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
892 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
893 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
895 $feed .= '<!-- PubSubHubbub Discovery -->' ;
896 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
897 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
899 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
900 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
902 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
905 $cache- > cache ( ob_get_contents ());
910 // ------------------------------------------------------------------------------------------
911 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
912 // Gives the last 7 days (which have links).
913 // This RSS feed cannot be filtered.
914 function showDailyRSS () {
916 $query = $_SERVER [ "QUERY_STRING" ];
917 $cache = new CachedPage (
918 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
920 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
922 $cached = $cache- > cachedVersion ();
923 if (! empty ( $cached )) {
928 // If cached was not found (or not usable), then read the database and build the response:
929 // Read links from database (and filter private links if used it not logged in).
930 $LINKSDB = new LinkDB (
931 $GLOBALS [ 'config' ][ 'DATASTORE' ],
933 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
934 $GLOBALS [ 'redirector' ]
937 /* Some Shaarlies may have very few links, so we need to look
938 back in time (rsort()) until we have enough days ($nb_of_days).
940 $linkdates = array ();
941 foreach ( $LINKSDB as $linkdate => $value ) {
942 $linkdates [] = $linkdate ;
945 $nb_of_days = 7 ; // We take 7 days.
946 $today = Date ( 'Ymd' );
949 foreach ( $linkdates as $linkdate ) {
950 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
951 if ( strcmp ( $day , $today ) < 0 ) {
952 if ( empty ( $days [ $day ])) {
953 $days [ $day ] = array ();
955 $days [ $day ][] = $linkdate ;
958 if ( count ( $days ) > $nb_of_days ) {
959 break ; // Have we collected enough days?
963 // Build the RSS feed.
964 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
965 $pageaddr = escape ( index_url ( $_SERVER ));
966 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
968 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
969 echo '<link>' . $pageaddr . '</link>' ;
970 echo '<description>Daily shared links</description>' ;
971 echo '<language>en-en</language>' ;
972 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
975 foreach ( $days as $day => $linkdates ) {
976 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
977 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
979 // Build the HTML body of this RSS entry.
984 // We pre-format some fields for proper output.
985 foreach ( $linkdates as $linkdate ) {
986 $l = $LINKSDB [ $linkdate ];
987 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
988 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
989 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
990 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
991 if ( startsWith ( $l [ 'url' ], '?' )) {
992 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
994 $links [ $linkdate ] = $l ;
997 // Then build the HTML for this day:
999 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
1000 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
1001 $tpl- > assign ( 'absurl' , $absurl );
1002 $tpl- > assign ( 'links' , $links );
1003 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
1004 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
1006 echo $html . PHP_EOL
;
1008 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
1010 $cache- > cache ( ob_get_contents ());
1016 * Show the 'Daily' page.
1018 * @param PageBuilder $pageBuilder Template engine wrapper.
1020 function showDaily ( $pageBuilder )
1022 $LINKSDB = new LinkDB (
1023 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1025 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1026 $GLOBALS [ 'redirector' ]
1029 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1030 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1032 $days = $LINKSDB- > days ();
1033 $i = array_search ( $day , $days );
1034 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1039 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1040 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1044 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_DAY , $day );
1045 } catch ( Exception
$exc ) {
1047 $linksToDisplay = array ();
1050 // We pre-format some fields for proper output.
1051 foreach ( $linksToDisplay as $key => $link )
1054 $taglist = explode ( ' ' , $link [ 'tags' ]);
1055 uasort ( $taglist , 'strcasecmp' );
1056 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1057 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1058 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1059 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1060 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
1063 /* We need to spread the articles on 3 columns.
1064 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1065 so I manually spread entries with a simple method: I roughly evaluate the
1066 height of a div according to title and description length.
1068 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1069 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1070 foreach ( $linksToDisplay as $key => $link )
1072 // Roughly estimate length of entry (by counting characters)
1073 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1074 // Description: 836 characters gives roughly 342 pixel height.
1075 // This is not perfect, but it's usually OK.
1076 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1077 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1078 // Then put in column which is the less filled:
1079 $smallest = min ( $fill ); // find smallest value in array.
1080 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1081 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1082 $fill [ $index ] +
= $length ;
1085 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
1087 'linksToDisplay' => $linksToDisplay ,
1088 'linkcount' => count ( $LINKSDB ),
1090 'day' => $dayDate- > getTimestamp (),
1091 'previousday' => $previousday ,
1092 'nextday' => $nextday ,
1094 $pluginManager = PluginManager
:: getInstance ();
1095 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1097 foreach ( $data as $key => $value ) {
1098 $pageBuilder- > assign ( $key , $value );
1101 $pageBuilder- > renderPage ( 'daily' );
1105 // Renders the linklist
1106 function showLinkList ( $PAGE , $LINKSDB ) {
1107 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1108 $PAGE- > renderPage ( 'linklist' );
1112 // ------------------------------------------------------------------------------------------
1113 // Render HTML page (according to URL parameters and user rights)
1114 function renderPage ()
1116 $LINKSDB = new LinkDB (
1117 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1119 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1120 $GLOBALS [ 'redirector' ]
1123 $updater = new Updater (
1124 read_updates_file ( $GLOBALS [ 'config' ][ 'UPDATES_FILE' ]),
1130 $newUpdates = $updater- > update ();
1131 if (! empty ( $newUpdates )) {
1133 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ],
1134 $updater- > getDoneUpdates ()
1138 catch ( Exception
$e ) {
1139 die ( $e- > getMessage ());
1142 $PAGE = new pageBuilder
;
1144 // Determine which page will be rendered.
1145 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1146 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1148 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1149 // Then assign generated data to RainTPL.
1150 $common_hooks = array (
1155 $pluginManager = PluginManager
:: getInstance ();
1156 foreach ( $common_hooks as $name ) {
1157 $plugin_data = array ();
1158 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1160 'target' => $targetPage ,
1161 'loggedin' => isLoggedIn ()
1164 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1167 // -------- Display login form.
1168 if ( $targetPage == Router
:: $PAGE_LOGIN )
1170 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1171 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1172 $PAGE- > assign ( 'token' , $token );
1173 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1174 $PAGE- > renderPage ( 'loginform' );
1177 // -------- User wants to logout.
1178 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1180 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1182 header ( 'Location: ?' );
1186 // -------- Picture wall
1187 if ( $targetPage == Router
:: $PAGE_PICWALL )
1189 // Optionally filter the results:
1190 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1191 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1192 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
1193 $links = $LINKSDB- > filter (
1194 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
1195 array ( $searchtags , $searchterm )
1198 elseif ( $searchtags ) {
1199 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
1201 elseif ( $searchterm ) {
1202 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
1208 $linksToDisplay = array ();
1210 // Get only links which have a thumbnail.
1211 foreach ( $links as $link )
1213 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1214 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1215 if ( $thumb != '' ) // Only output links which have a thumbnail.
1217 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1218 $linksToDisplay []= $link ; // Add to array.
1223 'linkcount' => count ( $LINKSDB ),
1224 'linksToDisplay' => $linksToDisplay ,
1226 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1228 foreach ( $data as $key => $value ) {
1229 $PAGE- > assign ( $key , $value );
1232 $PAGE- > renderPage ( 'picwall' );
1236 // -------- Tag cloud
1237 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1239 $tags = $LINKSDB- > allTags ();
1241 // We sort tags alphabetically, then choose a font size according to count.
1242 // First, find max value.
1244 foreach ( $tags as $value ) {
1245 $maxcount = max ( $maxcount , $value );
1248 // Sort tags alphabetically: case insensitive, support locale if avalaible.
1249 uksort ( $tags , function ( $a , $b ) {
1250 // Collator is part of PHP intl.
1251 if ( class_exists ( 'Collator' )) {
1252 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
1253 if (! intl_is_failure ( intl_get_error_code ())) {
1254 return $c- > compare ( $a , $b );
1257 return strcasecmp ( $a , $b );
1261 foreach ( $tags as $key => $value )
1262 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1264 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1268 'linkcount' => count ( $LINKSDB ),
1271 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1273 foreach ( $data as $key => $value ) {
1274 $PAGE- > assign ( $key , $value );
1277 $PAGE- > renderPage ( 'tagcloud' );
1282 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1286 // Display openseach plugin (XML)
1287 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1288 header ( 'Content-Type: application/xml; charset=utf-8' );
1289 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1290 $PAGE- > renderPage ( 'opensearch' );
1294 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1295 if ( isset ( $_GET [ 'addtag' ]))
1297 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1298 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1299 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1301 // Prevent redirection loop
1302 if ( isset ( $params [ 'addtag' ])) {
1303 unset ( $params [ 'addtag' ]);
1306 // Check if this tag is already in the search query and ignore it if it is.
1307 // Each tag is always separated by a space
1308 if ( isset ( $params [ 'searchtags' ])) {
1309 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1311 $current_tags = array ();
1314 foreach ( $current_tags as $value ) {
1315 if ( $value === $_GET [ 'addtag' ]) {
1320 // Append the tag if necessary
1321 if ( empty ( $params [ 'searchtags' ])) {
1322 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1325 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1328 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1329 header ( 'Location: ?' . http_build_query ( $params ));
1333 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1334 if ( isset ( $_GET [ 'removetag' ])) {
1335 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1336 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1337 header ( 'Location: ?' );
1341 // In case browser does not send HTTP_REFERER
1342 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1344 // Prevent redirection loop
1345 if ( isset ( $params [ 'removetag' ])) {
1346 unset ( $params [ 'removetag' ]);
1349 if ( isset ( $params [ 'searchtags' ])) {
1350 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1351 // Remove value from array $tags.
1352 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1353 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1355 if ( empty ( $params [ 'searchtags' ])) {
1356 unset ( $params [ 'searchtags' ]);
1359 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1361 header ( 'Location: ?' . http_build_query ( $params ));
1365 // -------- User wants to change the number of links per page (linksperpage=...)
1366 if ( isset ( $_GET [ 'linksperpage' ])) {
1367 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1368 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1371 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1375 // -------- User wants to see only private links (toggle)
1376 if ( isset ( $_GET [ 'privateonly' ])) {
1377 if ( empty ( $_SESSION [ 'privateonly' ])) {
1378 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1380 unset ( $_SESSION [ 'privateonly' ]); // See all links
1383 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1387 // -------- Handle other actions allowed for non-logged in users:
1390 // User tries to post new link but is not logged in:
1391 // Show login screen, then redirect to ?post=...
1392 if ( isset ( $_GET [ 'post' ]))
1394 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.
1398 // Same case as above except that user tried to access ?do=addlink without being logged in
1399 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1400 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1401 header ( 'Location: ?do=login&post=' );
1404 showLinkList ( $PAGE , $LINKSDB );
1405 if ( isset ( $_GET [ 'edit_link' ])) {
1406 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1410 exit ; // Never remove this one! All operations below are reserved for logged in user.
1413 // -------- All other functions are reserved for the registered user:
1415 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1416 if ( $targetPage == Router
:: $PAGE_TOOLS )
1419 'linkcount' => count ( $LINKSDB ),
1420 'pageabsaddr' => index_url ( $_SERVER ),
1422 $pluginManager- > executeHooks ( 'render_tools' , $data );
1424 foreach ( $data as $key => $value ) {
1425 $PAGE- > assign ( $key , $value );
1428 $PAGE- > renderPage ( 'tools' );
1432 // -------- User wants to change his/her password.
1433 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1435 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1436 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1438 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1440 // Make sure old password is correct.
1441 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1442 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1443 // Save new password
1444 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1445 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1447 writeConfig ( $GLOBALS , isLoggedIn ());
1449 catch ( Exception
$e ) {
1451 'ERROR while writing config file after changing password.' . PHP_EOL
.
1455 // TODO: do not handle exceptions/errors in JS.
1456 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1459 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1462 else // show the change password form.
1464 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1465 $PAGE- > assign ( 'token' , getToken ());
1466 $PAGE- > renderPage ( 'changepassword' );
1471 // -------- User wants to change configuration
1472 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1474 if (! empty ( $_POST [ 'title' ]) )
1476 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1478 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1479 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1480 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1481 $GLOBALS [ 'timezone' ] = $tz ;
1482 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1483 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1484 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1485 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1486 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1487 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1488 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1489 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1491 writeConfig ( $GLOBALS , isLoggedIn ());
1493 catch ( Exception
$e ) {
1495 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1499 // TODO: do not handle exceptions/errors in JS.
1500 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1503 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1506 else // Show the configuration form.
1508 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1509 $PAGE- > assign ( 'token' , getToken ());
1510 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1511 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1512 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1513 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1514 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1515 $PAGE- > renderPage ( 'configure' );
1520 // -------- User wants to rename a tag or delete it
1521 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1523 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1524 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1525 $PAGE- > assign ( 'token' , getToken ());
1526 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1527 $PAGE- > renderPage ( 'changetag' );
1531 if (! tokenOk ( $_POST [ 'token' ])) {
1532 die ( 'Wrong token.' );
1536 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1537 $needle = trim ( $_POST [ 'fromtag' ]);
1538 // True for case-sensitive tag search.
1539 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1540 foreach ( $linksToAlter as $key => $value )
1542 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1543 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1544 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1545 $LINKSDB [ $key ]= $value ;
1547 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1548 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1553 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1554 $needle = trim ( $_POST [ 'fromtag' ]);
1555 // True for case-sensitive tag search.
1556 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1557 foreach ( $linksToAlter as $key => $value )
1559 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1560 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1561 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1562 $LINKSDB [ $key ]= $value ;
1564 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1565 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1570 // -------- User wants to add a link without using the bookmarklet: Show form.
1571 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1573 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1574 $PAGE- > renderPage ( 'addlink' );
1578 // -------- User clicked the "Save" button when editing a link: Save link to database.
1579 if ( isset ( $_POST [ 'save_edit' ]))
1582 if (! tokenOk ( $_POST [ 'token' ])) {
1583 die ( 'Wrong token.' );
1585 // Remove multiple spaces.
1586 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1587 // Remove first '-' char in tags.
1588 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1589 // Remove duplicates.
1590 $tags = implode(' ', array_unique(explode(' ', $tags )));
1591 $linkdate = $_POST [' lf_linkdate
'];
1592 $url = trim( $_POST [' lf_url
']);
1593 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1594 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1595 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1597 $url = ' http
: //' . $url;
1601 'title' => trim ( $_POST [ 'lf_title' ]),
1603 'description' => $_POST [ 'lf_description' ],
1604 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1605 'linkdate' => $linkdate ,
1606 'tags' => str_replace ( ',' , ' ' , $tags )
1608 // If title is empty, use the URL as title.
1609 if ( $link [ 'title' ] == '' ) {
1610 $link [ 'title' ] = $link [ 'url' ];
1613 $pluginManager- > executeHooks ( 'save_link' , $link );
1615 $LINKSDB [ $linkdate ] = $link ;
1616 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1619 // If we are called from the bookmarklet, we must close the popup:
1620 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1621 echo '<script>self.close();</script>' ;
1625 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1626 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1627 // Scroll to the link which has been edited.
1628 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1629 // After saving the link, redirect to the page the user was on.
1630 header ( 'Location: ' . $location );
1634 // -------- User clicked the "Cancel" button when editing a link.
1635 if ( isset ( $_POST [ 'cancel_edit' ]))
1637 // If we are called from the bookmarklet, we must close the popup:
1638 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1639 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1640 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1641 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1642 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1646 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1647 if ( isset ( $_POST [ 'delete_link' ]))
1649 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1650 // We do not need to ask for confirmation:
1651 // - confirmation is handled by JavaScript
1652 // - we are protected from XSRF by the token.
1653 $linkdate = $_POST [ 'lf_linkdate' ];
1655 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1657 unset ( $LINKSDB [ $linkdate ]);
1658 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1660 // If we are called from the bookmarklet, we must close the popup:
1661 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1662 // Pick where we're going to redirect
1663 // =============================================================
1664 // Basically, we can't redirect to where we were previously if it was a permalink
1665 // or an edit_link, because it would 404.
1667 // - / : nothing in $_GET, redirect to self
1668 // - /?page : redirect to self
1669 // - /?searchterm : redirect to self (there might be other links)
1670 // - /?searchtags : redirect to self
1671 // - /permalink : redirect to / (the link does not exist anymore)
1672 // - /?edit_link : redirect to / (the link does not exist anymore)
1673 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1674 // redirect is not satisfied, and only then redirect to /
1677 if ( count ( $_GET ) == 0
1678 || isset ( $_GET [ 'page' ])
1679 || isset ( $_GET [ 'searchterm' ])
1680 || isset ( $_GET [ 'searchtags' ])
1682 if ( isset ( $_POST [ 'returnurl' ])) {
1683 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1685 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1689 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1693 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1694 if ( isset ( $_GET [ 'edit_link' ]))
1696 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1697 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1699 'linkcount' => count ( $LINKSDB ),
1701 'link_is_new' => false ,
1702 'token' => getToken (),
1703 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1704 'tags' => $LINKSDB- > allTags (),
1706 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1708 foreach ( $data as $key => $value ) {
1709 $PAGE- > assign ( $key , $value );
1712 $PAGE- > renderPage ( 'editlink' );
1716 // -------- User want to post a new link: Display link edit form.
1717 if ( isset ( $_GET [ 'post' ])) {
1718 $url = cleanup_url ( escape ( $_GET [ 'post' ]));
1720 $link_is_new = false ;
1721 // Check if URL is not already in database (in this case, we will edit the existing link)
1722 $link = $LINKSDB- > getLinkFromUrl ( $url );
1725 $link_is_new = true ;
1726 $linkdate = strval ( date ( 'Ymd_His' ));
1727 // Get title if it was provided in URL (by the bookmarklet).
1728 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1729 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1730 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1731 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1732 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1733 // 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.)
1734 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1735 // Short timeout to keep the application responsive
1736 list ( $headers , $content ) = get_http_response ( $url , 4 );
1737 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1738 // Retrieve charset.
1739 $charset = get_charset ( $headers , $content );
1741 $title = html_extract_title ( $content );
1742 // Re-encode title in utf-8 if necessary.
1743 if (! empty ( $title ) && $charset != 'utf-8' ) {
1744 $title = mb_convert_encoding ( $title , $charset , 'utf-8' );
1750 $url = '?' . smallHash ( $linkdate );
1755 'linkdate' => $linkdate ,
1758 'description' => $description ,
1760 'private' => $private
1765 'linkcount' => count ( $LINKSDB ),
1767 'link_is_new' => $link_is_new ,
1768 'token' => getToken (), // XSRF protection.
1769 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1770 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1771 'tags' => $LINKSDB- > allTags (),
1773 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1775 foreach ( $data as $key => $value ) {
1776 $PAGE- > assign ( $key , $value );
1779 $PAGE- > renderPage ( 'editlink' );
1783 // -------- Export as Netscape Bookmarks HTML file.
1784 if ( $targetPage == Router
:: $PAGE_EXPORT )
1786 if ( empty ( $_GET [ 'what' ]))
1788 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1789 $PAGE- > renderPage ( 'export' );
1792 $exportWhat = $_GET [ 'what' ];
1793 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1795 header ( 'Content-Type: text/html; charset=utf-8' );
1796 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1797 $currentdate = date ( 'Y/m/d H:i:s' );
1799 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1800 <!-- This is an automatically generated file.
1801 It will be read and overwritten.
1803 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1804 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1805 <TITLE>Bookmarks</TITLE>
1808 foreach ( $LINKSDB as $link )
1810 if ( $exportWhat == 'all' ||
1811 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1812 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1814 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1815 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . $date- > getTimestamp (). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1816 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1817 echo '>' . $link [ 'title' ]. "</A> \n " ;
1818 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1824 // -------- User is uploading a file for import
1825 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1827 // If file is too big, some form field may be missing.
1828 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1830 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1831 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>' ;
1834 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1839 // -------- Show upload/import dialog:
1840 if ( $targetPage == Router
:: $PAGE_IMPORT )
1842 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1843 $PAGE- > assign ( 'token' , getToken ());
1844 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1845 $PAGE- > renderPage ( 'import' );
1849 // Plugin administration page
1850 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1851 $pluginMeta = $pluginManager- > getPluginsMeta ();
1853 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1854 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1856 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1859 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1861 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1863 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1864 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1865 $PAGE- > renderPage ( 'pluginsadmin' );
1869 // Plugin administration form action
1870 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1872 if ( isset ( $_POST [ 'parameters_form' ])) {
1873 unset ( $_POST [ 'parameters_form' ]);
1874 foreach ( $_POST as $param => $value ) {
1875 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1879 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1881 writeConfig ( $GLOBALS , isLoggedIn ());
1883 catch ( Exception
$e ) {
1885 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1889 // TODO: do not handle exceptions/errors in JS.
1890 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1893 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1897 // -------- Otherwise, simply display search form and links:
1898 showLinkList ( $PAGE , $LINKSDB );
1902 // -----------------------------------------------------------------------------------------------
1903 // Process the import file form.
1904 function importFile ()
1906 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1907 $LINKSDB = new LinkDB (
1908 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1910 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1911 $GLOBALS [ 'redirector' ]
1913 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1914 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1915 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1916 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1917 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1922 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1924 // Then import the bookmarks.
1925 if ( $type == 'netscape' )
1927 // This is a standard Netscape-style bookmark file.
1928 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1929 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1931 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1932 $d = explode ( '<DD>' , $html );
1933 if ( startswith ( $d [ 0 ], '<A ' ))
1935 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1936 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1937 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1938 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1940 foreach ( $matches as $m )
1942 $attr = $m [ 1 ]; $value = $m [ 2 ];
1943 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1944 elseif ( $attr == 'ADD_DATE' )
1946 $raw_add_date = intval ( $value );
1947 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1949 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1950 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1952 if ( $link [ 'url' ]!= '' )
1954 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1955 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1957 { // Link not in database, let's import it...
1958 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1960 // Make sure date/time is not already used by another link.
1961 // (Some bookmark files have several different links with the same ADD_DATE)
1962 // We increment date by 1 second until we find a date which is not used in DB.
1963 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1964 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1965 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1966 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1969 else // Link already present in database.
1972 { // If overwrite is required, we import link data, except date/time.
1973 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1974 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1982 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1984 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1988 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1992 // -----------------------------------------------------------------------------------------------
1993 // Template for the list of links (<div id="linklist">)
1994 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1995 function buildLinkList ( $PAGE , $LINKSDB )
1997 // Filter link database according to parameters.
1998 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1999 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( trim ( $_GET [ 'searchterm' ])) : '' ;
2000 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]) ? true : false ;
2002 // Search tags + fullsearch.
2003 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
2004 $linksToDisplay = $LINKSDB- > filter (
2005 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
2006 array ( $searchtags , $searchterm ),
2012 elseif (! empty ( $searchtags )) {
2013 $linksToDisplay = $LINKSDB- > filter (
2014 LinkFilter
:: $FILTER_TAG ,
2021 elseif (! empty ( $searchterm )) {
2022 $linksToDisplay = $LINKSDB- > filter (
2023 LinkFilter
:: $FILTER_TEXT ,
2029 // Detect smallHashes in URL.
2030 elseif (! empty ( $_SERVER [ 'QUERY_STRING' ])
2031 && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])
2033 $linksToDisplay = $LINKSDB- > filter (
2034 LinkFilter
:: $FILTER_HASH ,
2035 substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 )
2038 if ( count ( $linksToDisplay ) == 0 ) {
2039 $PAGE- > render404 ( 'The link you are trying to reach does not exist or has been deleted.' );
2043 // Otherwise, display without filtering.
2045 $linksToDisplay = $LINKSDB- > filter ( '' , '' , false , $privateonly );
2048 // ---- Handle paging.
2050 foreach ( $linksToDisplay as $key => $value ) {
2054 // If there is only a single link, we change on-the-fly the title of the page.
2055 if ( count ( $linksToDisplay ) == 1 ) {
2056 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
2059 // Select articles according to paging.
2060 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
2061 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
2062 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
2063 $page = $page < 1 ? 1 : $page ;
2064 $page = $page > $pagecount ? $pagecount : $page ;
2066 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
2067 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
2068 $linkDisp = array ();
2069 while ( $i < $end && $i < count ( $keys ))
2071 $link = $linksToDisplay [ $keys [ $i ]];
2072 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
2073 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
2074 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
2075 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
2076 $link [ 'timestamp' ] = $date- > getTimestamp ();
2077 $taglist = explode ( ' ' , $link [ 'tags' ]);
2078 uasort ( $taglist , 'strcasecmp' );
2079 $link [ 'taglist' ] = $taglist ;
2080 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
2081 // Check for both signs of a note: starting with ? and 7 chars long.
2082 if ( $link [ 'url' ][ 0 ] === '?' &&
2083 strlen ( $link [ 'url' ]) === 7 ) {
2084 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
2087 $linkDisp [ $keys [ $i ]] = $link ;
2091 // Compute paging navigation
2092 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
2093 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
2094 $previous_page_url = '' ;
2095 if ( $i != count ( $keys )) {
2096 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
2100 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
2103 $token = isLoggedIn () ? getToken () : '' ;
2105 // Fill all template fields.
2107 'linkcount' => count ( $LINKSDB ),
2108 'previous_page_url' => $previous_page_url ,
2109 'next_page_url' => $next_page_url ,
2110 'page_current' => $page ,
2111 'page_max' => $pagecount ,
2112 'result_count' => count ( $linksToDisplay ),
2113 'search_term' => $searchterm ,
2114 'search_tags' => $searchtags ,
2115 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
2117 'links' => $linkDisp ,
2118 'tags' => $LINKSDB- > allTags (),
2120 // FIXME! temporary fix - see #399.
2121 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
2122 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
2125 $pluginManager = PluginManager
:: getInstance ();
2126 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
2128 foreach ( $data as $key => $value ) {
2129 $PAGE- > assign ( $key , $value );
2135 // Compute the thumbnail for a link.
2137 // With a link to the original URL.
2138 // Understands various services (youtube.com...)
2139 // Input: $url = URL for which the thumbnail must be found.
2140 // $href = if provided, this URL will be followed instead of $url
2141 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
2142 // Some of them may be missing.
2143 // Return an empty array if no thumbnail available.
2144 function computeThumbnail ( $url , $href = false )
2146 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
2147 if ( $href == false ) $href = $url ;
2149 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
2150 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
2151 // ^^^^^^^^^^^ ^^^^^^^^^^^
2152 $domain = parse_url ( $url , PHP_URL_HOST
);
2153 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
2155 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
2156 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
2157 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2159 if ( $domain == 'youtu.be' ) // Youtube short links
2161 $path = parse_url ( $url , PHP_URL_PATH
);
2162 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
2163 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2165 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
2167 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
2168 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
2169 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
2172 if ( $domain == 'imgur.com' )
2174 $path = parse_url ( $url , PHP_URL_PATH
);
2175 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2176 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2177 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2178 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2179 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2181 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2182 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2184 if ( $domain == 'i.imgur.com' )
2186 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2187 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2188 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2190 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2192 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2194 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2195 return array ( 'src' => $thumburl ,
2196 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2199 if ( endsWith ( $domain , '.imageshack.us' ))
2201 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2202 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2204 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2205 return array ( 'src' => $thumburl ,
2206 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2210 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2211 // So we deport the thumbnail generation in order not to slow down page generation
2212 // (and we also cache the thumbnail)
2214 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2216 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2217 || $domain == 'vimeo.com'
2218 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2219 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2222 if ( $domain == 'vimeo.com' )
2223 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2224 $path = parse_url ( $url , PHP_URL_PATH
);
2225 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2227 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2228 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2229 $path = parse_url ( $url , PHP_URL_PATH
);
2230 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2232 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2233 { // Make sure this TED URL points to a video (/talks/...)
2234 $path = parse_url ( $url , PHP_URL_PATH
);
2235 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2237 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2238 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2239 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2242 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2243 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2244 // But using the extension will do.
2245 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2246 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2248 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2249 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2250 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2252 return array (); // No thumbnail.
2257 // Returns the HTML code to display a thumbnail for a link
2258 // with a link to the original URL.
2259 // Understands various services (youtube.com...)
2260 // Input: $url = URL for which the thumbnail must be found.
2261 // $href = if provided, this URL will be followed instead of $url
2262 // Returns '' if no thumbnail available.
2263 function thumbnail ( $url , $href = false )
2265 $t = computeThumbnail ( $url , $href );
2266 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2268 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2269 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2270 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2271 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2272 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2277 // Returns the HTML code to display a thumbnail for a link
2278 // for the picture wall (using lazy image loading)
2279 // Understands various services (youtube.com...)
2280 // Input: $url = URL for which the thumbnail must be found.
2281 // $href = if provided, this URL will be followed instead of $url
2282 // Returns '' if no thumbnail available.
2283 function lazyThumbnail ( $url , $href = false )
2285 $t = computeThumbnail ( $url , $href );
2286 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2288 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2291 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2293 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2294 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2295 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2296 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2299 // No-JavaScript fallback.
2300 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2301 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2302 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2303 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2304 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2305 $html .= '></noscript></a>' ;
2311 // -----------------------------------------------------------------------------------------------
2313 // This function should NEVER be called if the file data/config.php exists.
2316 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2317 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2320 // This part makes sure sessions works correctly.
2321 // (Because on some hosts, session.save_path may not be set correctly,
2322 // or we may not have write access to it.)
2323 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2324 { // Step 2: Check if data in session is correct.
2325 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2326 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2327 echo 'It currently points to ' . session_save_path (). '<br>' ;
2328 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>' ;
2329 echo '<br><a href="?">Click to try again.</a></pre>' ;
2332 if (! isset ( $_SESSION [ 'session_tested' ]))
2333 { // Step 1 : Try to store data in session and reload page.
2334 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2335 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2337 if ( isset ( $_GET [ 'test_session' ]))
2338 { // Step 3: Sessions are OK. Remove test parameter from URL.
2339 header ( 'Location: ' . index_url ( $_SERVER ));
2343 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2346 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2347 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2348 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2351 $GLOBALS [ 'timezone' ] = $tz ;
2352 // Everything is ok, let's create config file.
2353 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2354 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2355 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2356 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2357 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2359 writeConfig ( $GLOBALS , isLoggedIn ());
2361 catch ( Exception
$e ) {
2363 'ERROR while writing config file after installation.' . PHP_EOL
.
2367 // TODO: do not handle exceptions/errors in JS.
2368 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2371 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2375 // Display config form:
2376 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2377 $timezone_html = '' ;
2378 if ( $timezone_form != '' ) {
2379 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2382 $PAGE = new pageBuilder
;
2383 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2384 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2385 $PAGE- > renderPage ( 'install' );
2389 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2390 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2391 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2392 This function is called by passing the URL:
2393 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2394 [URL] is the URL of the link (e.g. a flickr page)
2395 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2396 The function below will fetch the image from the webservice and store it in the cache.
2398 function genThumbnail ()
2400 // Make sure the parameters in the URL were generated by us.
2401 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2402 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2404 // Let's see if we don't already have the image for this URL in the cache.
2405 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2406 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2407 { // We have the thumbnail, just serve it:
2408 header ( 'Content-Type: image/jpeg' );
2409 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2412 // We may also serve a blank image (if service did not respond)
2413 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2414 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2416 header ( 'Content-Type: image/gif' );
2417 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2421 // Otherwise, generate the thumbnail.
2422 $url = $_GET [ 'url' ];
2423 $domain = parse_url ( $url , PHP_URL_HOST
);
2425 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2427 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2428 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2430 // Is this a link to an image, or to a flickr page ?
2432 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2433 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2434 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2435 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2437 else // This is a flickr page (html)
2439 // Get the flickr html page.
2440 list ( $headers , $content ) = get_http_response ( $url , 20 );
2441 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2443 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2444 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2445 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2447 // In albums (and some other pages), the link rel="image_src" is not provided,
2448 // but flickr provides:
2449 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2452 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2453 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2459 { // Let's download the image.
2460 // Image is 240x120, so 10 seconds to download should be enough.
2461 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2462 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2463 // Save image to cache.
2464 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2465 header ( 'Content-Type: image/jpeg' );
2472 elseif ( $domain == 'vimeo.com' )
2474 // This is more complex: we have to perform a HTTP request, then parse the result.
2475 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2476 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2477 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2478 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2479 $t = unserialize ( $content );
2480 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2481 // Then we download the image and serve it to our client.
2482 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2483 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2484 // Save image to cache.
2485 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2486 header ( 'Content-Type: image/jpeg' );
2493 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2495 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2496 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2497 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2498 list ( $headers , $content ) = get_http_response ( $url , 5 );
2499 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2500 // Extract the link to the thumbnail
2501 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2502 if (! empty ( $matches [ 1 ]))
2503 { // Let's download the image.
2504 $imageurl = $matches [ 1 ];
2505 // No control on image size, so wait long enough
2506 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2507 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2508 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2509 file_put_contents ( $filepath , $content ); // Save image to cache.
2510 if ( resizeImage ( $filepath ))
2512 header ( 'Content-Type: image/jpeg' );
2513 echo file_get_contents ( $filepath );
2521 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2523 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2524 // http://xkcd.com/327/
2525 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2526 list ( $headers , $content ) = get_http_response ( $url , 5 );
2527 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2528 // Extract the link to the thumbnail
2529 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2530 if (! empty ( $matches [ 1 ]))
2531 { // Let's download the image.
2532 $imageurl = $matches [ 1 ];
2533 // No control on image size, so wait long enough
2534 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2535 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2536 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2537 // Save image to cache.
2538 file_put_contents ( $filepath , $content );
2539 if ( resizeImage ( $filepath ))
2541 header ( 'Content-Type: image/jpeg' );
2542 echo file_get_contents ( $filepath );
2552 // For all other domains, we try to download the image and make a thumbnail.
2553 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2554 list ( $headers , $content ) = get_http_response ( $url , 30 );
2555 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2556 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2557 // Save image to cache.
2558 file_put_contents ( $filepath , $content );
2559 if ( resizeImage ( $filepath ))
2561 header ( 'Content-Type: image/jpeg' );
2562 echo file_get_contents ( $filepath );
2569 // Otherwise, return an empty image (8x8 transparent gif)
2570 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2571 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2572 header ( 'Content-Type: image/gif' );
2576 // Make a thumbnail of the image (to width: 120 pixels)
2577 // Returns true if success, false otherwise.
2578 function resizeImage ( $filepath )
2580 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2582 // Trick: some stupid people rename GIF as JPEG... or else.
2583 // So we really try to open each image type whatever the extension is.
2584 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2586 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2587 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2588 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2589 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2592 $ystart = 0 ; $yheight = $h ;
2593 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2594 $nw = 120 ; // Desired width
2595 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2597 $im2 = imagecreatetruecolor ( $nw , $nh );
2598 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2599 imageinterlace ( $im2 , true ); // For progressive JPEG.
2600 $tempname = $filepath . '_TEMP.jpg' ;
2601 imagejpeg ( $im2 , $tempname , 90 );
2605 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2609 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2610 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2611 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2612 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2613 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];