]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.3 - Shaare your links...
5 * The personal, minimalist, super-fast, no-database Delicious clone.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
25 /* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
33 * Shaarli directories & configuration files
36 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ;
38 // Main configuration file
39 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ;
42 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ;
45 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ;
47 // Processed updates file.
48 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/updates.txt' ;
51 $GLOBALS [ 'config' ][ 'LOG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' ;
53 // For updates check of Shaarli
54 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
56 // Set ENABLE_UPDATECHECK to disabled by default.
57 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = false ;
59 // RainTPL cache directory (keep the trailing slash!)
60 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
61 // Raintpl template directory (keep the trailing slash!)
62 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
64 // Thumbnail cache directory
65 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
67 // Atom & RSS feed cache directory
68 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
71 * Global configuration
73 // Ban IP after this many failures
74 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
75 // Ban duration for IP address after login failures (in seconds)
76 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
79 // Enable RSS permalinks by default.
80 // This corresponds to the default behavior of shaarli before this was added as an option.
81 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
82 // If true, an extra "ATOM feed" button will be displayed in the toolbar
83 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
85 // Link display options
86 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
87 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
88 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
90 // Open Shaarli (true): anyone can add/edit/delete links without having to login
91 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
94 // Display thumbnails in links
95 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
96 // Store thumbnails in a local cache
97 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
99 // Update check frequency for Shaarli. 86400 seconds=24 hours
100 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ] = 'stable' ;
101 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
105 * Plugin configuration
107 * Warning: order matters!
109 * These settings may be be overriden in:
111 * - each plugin's configuration file
113 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
114 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
115 // 'wallabag', 'markdown', 'addlink_toolbar',
117 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
119 // Initialize plugin parameters array.
120 $GLOBALS [ 'plugins' ] = array ();
122 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
123 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
128 define ( 'shaarli_version' , '0.6.3' );
130 // http://server.com/x/shaarli --> /shaarli/
131 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
133 // High execution time in case of problematic imports/exports.
134 ini_set ( 'max_input_time' , '60' );
136 // Try to set max upload file size and read
137 ini_set ( 'memory_limit' , '128M' );
138 ini_set ( 'post_max_size' , '16M' );
139 ini_set ( 'upload_max_filesize' , '16M' );
141 // See all error except warnings
142 error_reporting ( E_ALL^E_WARNING
);
143 // See all errors (for debugging only)
144 //error_reporting(-1);
149 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
150 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
154 require_once 'application/ApplicationUtils.php' ;
155 require_once 'application/Cache.php' ;
156 require_once 'application/CachedPage.php' ;
157 require_once 'application/FileUtils.php' ;
158 require_once 'application/HttpUtils.php' ;
159 require_once 'application/LinkDB.php' ;
160 require_once 'application/LinkFilter.php' ;
161 require_once 'application/LinkUtils.php' ;
162 require_once 'application/TimeZone.php' ;
163 require_once 'application/Url.php' ;
164 require_once 'application/Utils.php' ;
165 require_once 'application/Config.php' ;
166 require_once 'application/PluginManager.php' ;
167 require_once 'application/Router.php' ;
168 require_once 'application/Updater.php' ;
170 // Ensure the PHP version is supported
172 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
173 } catch ( Exception
$exc ) {
174 header ( 'Content-Type: text/plain; charset=utf-8' );
175 echo $exc- > getMessage ();
179 // Force cookie path (but do not change lifetime)
180 $cookie = session_get_cookie_params ();
182 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
183 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
185 // Set default cookie expiration and path.
186 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
187 // Set session parameters on server side.
188 // If the user does not access any page within this time, his/her session is considered expired.
189 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
190 // Use cookies to store session.
191 ini_set ( 'session.use_cookies' , 1 );
192 // Force cookies for session (phpsessionID forbidden in URL).
193 ini_set ( 'session.use_only_cookies' , 1 );
194 // Prevent PHP form using sessionID in URL if cookies are disabled.
195 ini_set ( 'session.use_trans_sid' , false );
197 session_name ( 'shaarli' );
198 // Start session if needed (Some server auto-start sessions).
199 if ( session_id () == '' ) {
203 // Regenerate session ID if invalid or not defined in cookie.
204 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
205 session_regenerate_id ( true );
206 $_COOKIE [ 'shaarli' ] = session_id ();
209 include "inc/rain.tpl.class.php" ; //include Rain TPL
210 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
211 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
213 $pluginManager = PluginManager
:: getInstance ();
214 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
216 ob_start (); // Output buffering for the page cache.
219 // In case stupid admin has left magic_quotes enabled in php.ini:
220 if ( get_magic_quotes_gpc ())
222 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
223 $_POST = array_map ( 'stripslashes_deep' , $_POST );
224 $_GET = array_map ( 'stripslashes_deep' , $_GET );
225 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
228 // Prevent caching on client side or proxy: (yes, it's ugly)
229 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
230 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
231 header ( "Cache-Control: post-check=0, pre-check=0" , false );
232 header ( "Pragma: no-cache" );
234 // Handling of old config file which do not have the new parameters.
235 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
236 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
237 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
238 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
239 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
240 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
241 // I really need to rewrite Shaarli with a proper configuation manager.
243 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
244 // Ensure Shaarli has proper access to its resources
245 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
247 if ( $errors != array ()) {
248 $message = '<p>Insufficient permissions:</p><ul>' ;
250 foreach ( $errors as $error ) {
251 $message .= '<li>' . $error . '</li>' ;
255 header ( 'Content-Type: text/html; charset=utf-8' );
260 // Display the installation form if no existing config is found
264 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
265 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
266 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
268 // a token depending of deployment salt, user password, and the current ip
269 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
271 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]); // Sniff browser language and set date format accordingly.
272 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
274 //==================================================================================================
275 // Checking session state (i.e. is the user still logged in)
276 //==================================================================================================
278 function setup_login_state () {
279 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
282 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
283 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
284 if (! isset ( $GLOBALS [ 'login' ])) {
285 $userIsLoggedIn = false ; // Shaarli is not configured yet.
286 $loginFailure = true ;
288 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
289 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
293 $userIsLoggedIn = true ;
295 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
296 if ( empty ( $_SESSION [ 'uid' ]) ||
297 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
298 time () >= $_SESSION [ 'expires_on' ])
301 $userIsLoggedIn = false ;
302 $loginFailure = true ;
304 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
305 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
308 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
310 if (! $loginFailure ) {
311 $userIsLoggedIn = true ;
314 return $userIsLoggedIn ;
316 $userIsLoggedIn = setup_login_state ();
318 // ------------------------------------------------------------------------------------------
319 // PubSubHubbub protocol support (if enabled) [UNTESTED]
320 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
321 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
324 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
326 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
328 index_url ( $_SERVER ). '?do=atom' ,
329 index_url ( $_SERVER ). '?do=rss'
331 $p- > publish_update ( $topic_url );
335 // ------------------------------------------------------------------------------------------
336 // Session management
338 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
341 $ip = $_SERVER [ "REMOTE_ADDR" ];
342 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
343 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
344 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
348 function fillSessionInfo () {
349 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
350 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
351 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
352 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
355 // Check that user/password is correct.
356 function check_auth ( $login , $password )
358 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
359 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
360 { // Login/password is correct.
362 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
365 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
369 // Returns true if the user is logged in.
370 function isLoggedIn ()
372 global $userIsLoggedIn ;
373 return $userIsLoggedIn ;
378 if ( isset ( $_SESSION )) {
379 unset ( $_SESSION [ 'uid' ]);
380 unset ( $_SESSION [ 'ip' ]);
381 unset ( $_SESSION [ 'username' ]);
382 unset ( $_SESSION [ 'privateonly' ]);
384 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
388 // ------------------------------------------------------------------------------------------
389 // Brute force protection system
390 // Several consecutive failed logins will ban the IP address for 30 minutes.
391 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 ?>" );
392 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
393 // Signal a failed login. Will ban the IP if too many failures:
394 function ban_loginFailed ()
396 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
397 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
398 $gb [ 'FAILURES' ][ $ip ] ++
;
399 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
401 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
402 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
404 $GLOBALS [ 'IPBANS' ] = $gb ;
405 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
408 // Signals a successful login. Resets failed login counter.
409 function ban_loginOk ()
411 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
412 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
413 $GLOBALS [ 'IPBANS' ] = $gb ;
414 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
417 // Checks if the user CAN login. If 'true', the user can try to login.
418 function ban_canLogin ()
420 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
421 if ( isset ( $gb [ 'BANS' ][ $ip ]))
423 // User is banned. Check if the ban has expired:
424 if ( $gb [ 'BANS' ][ $ip ]<= time ())
425 { // Ban expired, user can try to login again.
426 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
427 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
428 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
429 return true ; // Ban has expired, user can login.
431 return false ; // User is banned.
433 return true ; // User is not banned.
436 // ------------------------------------------------------------------------------------------
437 // Process login form: Check if login/password is correct.
438 if ( isset ( $_POST [ 'login' ]))
440 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
441 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
442 { // Login/password is OK.
444 // If user wants to keep the session cookie even after the browser closes:
445 if (! empty ( $_POST [ 'longlastingsession' ]))
447 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
448 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
449 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
451 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
452 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
453 // Note: Never forget the trailing slash on the cookie path!
454 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
456 else // Standard session expiration (=when browser closes)
458 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
459 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
460 session_regenerate_id ( true );
463 // Optional redirect after login:
464 if ( isset ( $_GET [ 'post' ])) {
465 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
466 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
467 if (! empty ( $_GET [ $param ])) {
468 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
471 header ( 'Location: ' . $uri );
475 if ( isset ( $_GET [ 'edit_link' ])) {
476 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
480 if ( isset ( $_POST [ 'returnurl' ])) {
481 // Prevent loops over login screen.
482 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
483 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
487 header ( 'Location: ?' ); exit ;
493 if ( isset ( $_GET [ 'post' ])) {
494 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
495 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
496 if (! empty ( $_GET [ $param ])) {
497 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
501 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
506 // ------------------------------------------------------------------------------------------
507 // Misc utility functions:
509 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
510 function return_bytes ( $val )
512 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
515 case 'g' : $val *= 1024 ;
516 case 'm' : $val *= 1024 ;
517 case 'k' : $val *= 1024 ;
522 // Try to determine max file size for uploads (POST).
523 // Returns an integer (in bytes)
524 function getMaxFileSize ()
526 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
527 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
528 // Return the smaller of two:
529 $maxsize = min ( $size1 , $size2 );
530 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
534 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
535 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
536 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
537 function linkdate2timestamp ( $linkdate )
539 if ( strcmp ( $linkdate , '_000000' ) !== 0 || ! $linkdate ){
541 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
542 return mktime ( $h , $m , $s , $M , $D , $Y );
547 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
548 (used to build the pubDate attribute in RSS feed.) */
549 function linkdate2rfc822 ( $linkdate )
551 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
554 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
555 (used to build the updated tags in ATOM feed.) */
556 function linkdate2iso8601 ( $linkdate )
558 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
561 // ------------------------------------------------------------------------------------------
562 // Token management for XSRF protection
563 // Token should be used in any form which acts on data (create,update,delete,import...).
564 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
569 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
570 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
574 // Tells if a token is OK. Using this function will destroy the token.
576 function tokenOk ( $token )
578 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
580 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
581 return true ; // Token is OK.
583 return false ; // Wrong token, or already used.
586 // ------------------------------------------------------------------------------------------
587 /* This class is in charge of building the final page.
588 (This is basically a wrapper around RainTPL which pre-fills some fields.)
590 p.assign('myfield','myvalue');
591 p.renderPage('mytemplate');
596 private $tpl ; // RainTPL template
598 function __construct ()
604 * Initialize all default tpl tags.
606 private function initialize ()
608 $this- > tpl
= new RainTPL
;
611 $version = ApplicationUtils
:: checkUpdate (
613 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
614 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
615 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
617 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
619 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
620 $this- > tpl
-> assign ( 'versionError' , '' );
622 } catch ( Exception
$exc ) {
623 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
624 $this- > tpl
-> assign ( 'newVersion' , '' );
625 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
628 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
629 $searchcrits = '' ; // Search criteria
630 if (! empty ( $_GET [ 'searchtags' ])) {
631 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
633 elseif (! empty ( $_GET [ 'searchterm' ])) {
634 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
636 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
637 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
638 $this- > tpl
-> assign ( 'version' , shaarli_version
);
639 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
640 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
641 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
642 if (! empty ( $GLOBALS [ 'title' ])) {
643 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
645 if (! empty ( $GLOBALS [ 'titleLink' ])) {
646 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
648 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
649 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
651 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
652 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
653 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
657 // The following assign() method is basically the same as RainTPL (except that it's lazy)
658 public function assign ( $what , $where )
660 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
661 $this- > tpl
-> assign ( $what , $where );
664 // Render a specific page (using a template).
665 // e.g. pb.renderPage('picwall')
666 public function renderPage ( $page )
668 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
669 $this- > tpl
-> draw ( $page );
673 * Render a 404 page (uses the template : tpl/404.tpl)
675 * usage : $PAGE->render404('The link was deleted')
676 * @param string $message A messate to display what is not found
678 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
679 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
680 $this- > tpl
-> assign ( 'error_message' , $message );
681 $this- > renderPage ( '404' );
685 // ------------------------------------------------------------------------------------------
686 // Output the last N links in RSS 2.0 format.
689 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
691 // $usepermalink : If true, use permalink instead of final link.
692 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
693 // Also enabled through a config option
694 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
697 $query = $_SERVER [ "QUERY_STRING" ];
698 $cache = new CachedPage (
699 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
701 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
703 $cached = $cache- > cachedVersion ();
704 if (! empty ( $cached )) {
709 // If cached was not found (or not usable), then read the database and build the response:
710 $LINKSDB = new LinkDB (
711 $GLOBALS [ 'config' ][ 'DATASTORE' ],
713 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
714 $GLOBALS [ 'redirector' ]
716 // Read links from database (and filter private links if user it not logged in).
718 // Optionally filter the results:
719 if (! empty ( $_GET [ 'searchterm' ])) {
720 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
722 elseif (! empty ( $_GET [ 'searchtags' ])) {
723 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
726 $linksToDisplay = $LINKSDB ;
729 $nblinksToDisplay = 50 ; // Number of links to display.
730 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
731 if (! empty ( $_GET [ 'nb' ])) {
732 $nblinksToDisplay = $_GET [ 'nb' ] == 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
735 $pageaddr = escape ( index_url ( $_SERVER ));
736 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
737 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
738 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
739 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
741 echo '<!-- PubSubHubbub Discovery -->' ;
742 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
743 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
744 echo '<!-- End Of PubSubHubbub Discovery -->' ;
747 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
748 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
750 $link = $linksToDisplay [ $keys [ $i ]];
751 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
752 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
753 $absurl = $link [ 'url' ];
754 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
755 if ( $usepermalinks === true )
756 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
758 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
759 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . escape ( $rfc822date ). "</pubDate> \n " ;
760 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
762 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
765 // Add permalink in description
766 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
767 // If user wants permalinks first, put the final link in description
768 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
769 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
770 echo '<description><![CDATA[' .
771 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
772 $descriptionlink . ']]></description>' . " \n </item> \n " ;
775 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
777 $cache- > cache ( ob_get_contents ());
782 // ------------------------------------------------------------------------------------------
783 // Output the last N links in ATOM format.
786 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
788 // $usepermalink : If true, use permalink instead of final link.
789 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
790 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
793 $query = $_SERVER [ "QUERY_STRING" ];
794 $cache = new CachedPage (
795 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
797 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
799 $cached = $cache- > cachedVersion ();
800 if (! empty ( $cached )) {
805 // If cached was not found (or not usable), then read the database and build the response:
806 // Read links from database (and filter private links if used it not logged in).
807 $LINKSDB = new LinkDB (
808 $GLOBALS [ 'config' ][ 'DATASTORE' ],
810 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
811 $GLOBALS [ 'redirector' ]
814 // Optionally filter the results:
815 if (! empty ( $_GET [ 'searchterm' ])) {
816 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
818 else if (! empty ( $_GET [ 'searchtags' ])) {
819 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
822 $linksToDisplay = $LINKSDB ;
825 $nblinksToDisplay = 50 ; // Number of links to display.
826 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
827 if (! empty ( $_GET [ 'nb' ])) {
828 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
831 $pageaddr = escape ( index_url ( $_SERVER ));
835 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
836 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
838 $link = $linksToDisplay [ $keys [ $i ]];
839 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
840 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
841 $latestDate = max ( $latestDate , $iso8601date );
842 $absurl = $link [ 'url' ];
843 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
844 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
845 if ( $usepermalinks === true )
846 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
848 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
849 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
851 // Add permalink in description
852 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
853 // If user wants permalinks first, put the final link in description
854 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
855 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
857 $entries .= '<content type="html"><![CDATA[' .
858 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
859 $descriptionlink . "]]></content> \n " ;
860 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
862 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
863 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
865 $entries .= "</entry> \n " ;
868 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
869 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
870 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
871 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
872 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
874 $feed .= '<!-- PubSubHubbub Discovery -->' ;
875 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
876 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
878 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
879 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
881 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
884 $cache- > cache ( ob_get_contents ());
889 // ------------------------------------------------------------------------------------------
890 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
891 // Gives the last 7 days (which have links).
892 // This RSS feed cannot be filtered.
893 function showDailyRSS () {
895 $query = $_SERVER [ "QUERY_STRING" ];
896 $cache = new CachedPage (
897 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
899 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
901 $cached = $cache- > cachedVersion ();
902 if (! empty ( $cached )) {
907 // If cached was not found (or not usable), then read the database and build the response:
908 // Read links from database (and filter private links if used it not logged in).
909 $LINKSDB = new LinkDB (
910 $GLOBALS [ 'config' ][ 'DATASTORE' ],
912 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
913 $GLOBALS [ 'redirector' ]
916 /* Some Shaarlies may have very few links, so we need to look
917 back in time (rsort()) until we have enough days ($nb_of_days).
919 $linkdates = array ();
920 foreach ( $LINKSDB as $linkdate => $value ) {
921 $linkdates [] = $linkdate ;
924 $nb_of_days = 7 ; // We take 7 days.
925 $today = Date ( 'Ymd' );
928 foreach ( $linkdates as $linkdate ) {
929 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
930 if ( strcmp ( $day , $today ) < 0 ) {
931 if ( empty ( $days [ $day ])) {
932 $days [ $day ] = array ();
934 $days [ $day ][] = $linkdate ;
937 if ( count ( $days ) > $nb_of_days ) {
938 break ; // Have we collected enough days?
942 // Build the RSS feed.
943 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
944 $pageaddr = escape ( index_url ( $_SERVER ));
945 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
947 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
948 echo '<link>' . $pageaddr . '</link>' ;
949 echo '<description>Daily shared links</description>' ;
950 echo '<language>en-en</language>' ;
951 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
954 foreach ( $days as $day => $linkdates ) {
955 $daydate = linkdate2timestamp ( $day . '_000000' ); // Full text date
956 $rfc822date = linkdate2rfc822 ( $day . '_000000' );
957 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
959 // Build the HTML body of this RSS entry.
964 // We pre-format some fields for proper output.
965 foreach ( $linkdates as $linkdate ) {
966 $l = $LINKSDB [ $linkdate ];
967 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
968 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
969 $l [ 'timestamp' ] = linkdate2timestamp ( $l [ 'linkdate' ]);
970 if ( startsWith ( $l [ 'url' ], '?' )) {
971 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
973 $links [ $linkdate ] = $l ;
976 // Then build the HTML for this day:
978 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
979 $tpl- > assign ( 'daydate' , $daydate );
980 $tpl- > assign ( 'absurl' , $absurl );
981 $tpl- > assign ( 'links' , $links );
982 $tpl- > assign ( 'rfc822date' , escape ( $rfc822date ));
983 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
985 echo $html . PHP_EOL
;
987 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
989 $cache- > cache ( ob_get_contents ());
995 * Show the 'Daily' page.
997 * @param PageBuilder $pageBuilder Template engine wrapper.
999 function showDaily ( $pageBuilder )
1001 $LINKSDB = new LinkDB (
1002 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1004 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1005 $GLOBALS [ 'redirector' ]
1008 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1009 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1011 $days = $LINKSDB- > days ();
1012 $i = array_search ( $day , $days );
1013 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1018 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1019 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1023 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_DAY , $day );
1024 } catch ( Exception
$exc ) {
1026 $linksToDisplay = array ();
1029 // We pre-format some fields for proper output.
1030 foreach ( $linksToDisplay as $key => $link )
1033 $taglist = explode ( ' ' , $link [ 'tags' ]);
1034 uasort ( $taglist , 'strcasecmp' );
1035 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1036 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1037 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1038 $linksToDisplay [ $key ][ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
1041 /* We need to spread the articles on 3 columns.
1042 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1043 so I manually spread entries with a simple method: I roughly evaluate the
1044 height of a div according to title and description length.
1046 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1047 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1048 foreach ( $linksToDisplay as $key => $link )
1050 // Roughly estimate length of entry (by counting characters)
1051 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1052 // Description: 836 characters gives roughly 342 pixel height.
1053 // This is not perfect, but it's usually OK.
1054 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1055 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1056 // Then put in column which is the less filled:
1057 $smallest = min ( $fill ); // find smallest value in array.
1058 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1059 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1060 $fill [ $index ] +
= $length ;
1064 'linksToDisplay' => $linksToDisplay ,
1065 'linkcount' => count ( $LINKSDB ),
1067 'day' => linkdate2timestamp ( $day . '_000000' ),
1068 'previousday' => $previousday ,
1069 'nextday' => $nextday ,
1071 $pluginManager = PluginManager
:: getInstance ();
1072 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1074 foreach ( $data as $key => $value ) {
1075 $pageBuilder- > assign ( $key , $value );
1078 $pageBuilder- > renderPage ( 'daily' );
1082 // Renders the linklist
1083 function showLinkList ( $PAGE , $LINKSDB ) {
1084 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1085 $PAGE- > renderPage ( 'linklist' );
1089 // ------------------------------------------------------------------------------------------
1090 // Render HTML page (according to URL parameters and user rights)
1091 function renderPage ()
1093 $LINKSDB = new LinkDB (
1094 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1096 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1097 $GLOBALS [ 'redirector' ]
1100 $updater = new Updater (
1101 read_updates_file ( $GLOBALS [ 'config' ][ 'UPDATES_FILE' ]),
1107 $newUpdates = $updater- > update ();
1108 if (! empty ( $newUpdates )) {
1110 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ],
1111 $updater- > getDoneUpdates ()
1115 catch ( Exception
$e ) {
1116 die ( $e- > getMessage ());
1119 $PAGE = new pageBuilder
;
1121 // Determine which page will be rendered.
1122 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1123 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1125 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1126 // Then assign generated data to RainTPL.
1127 $common_hooks = array (
1132 $pluginManager = PluginManager
:: getInstance ();
1133 foreach ( $common_hooks as $name ) {
1134 $plugin_data = array ();
1135 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1137 'target' => $targetPage ,
1138 'loggedin' => isLoggedIn ()
1141 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1144 // -------- Display login form.
1145 if ( $targetPage == Router
:: $PAGE_LOGIN )
1147 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1148 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1149 $PAGE- > assign ( 'token' , $token );
1150 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1151 $PAGE- > renderPage ( 'loginform' );
1154 // -------- User wants to logout.
1155 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1157 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1159 header ( 'Location: ?' );
1163 // -------- Picture wall
1164 if ( $targetPage == Router
:: $PAGE_PICWALL )
1166 // Optionally filter the results:
1167 if (! empty ( $_GET [ 'searchterm' ])) {
1168 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
1170 elseif (! empty ( $_GET [ 'searchtags' ])) {
1171 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
1177 $linksToDisplay = array ();
1179 // Get only links which have a thumbnail.
1180 foreach ( $links as $link )
1182 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1183 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1184 if ( $thumb != '' ) // Only output links which have a thumbnail.
1186 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1187 $linksToDisplay []= $link ; // Add to array.
1192 'linkcount' => count ( $LINKSDB ),
1193 'linksToDisplay' => $linksToDisplay ,
1195 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1197 foreach ( $data as $key => $value ) {
1198 $PAGE- > assign ( $key , $value );
1201 $PAGE- > renderPage ( 'picwall' );
1205 // -------- Tag cloud
1206 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1208 $tags = $LINKSDB- > allTags ();
1210 // We sort tags alphabetically, then choose a font size according to count.
1211 // First, find max value.
1213 foreach ( $tags as $value ) {
1214 $maxcount = max ( $maxcount , $value );
1217 // Sort tags alphabetically: case insensitive, support locale if avalaible.
1218 uksort ( $tags , function ( $a , $b ) {
1219 // Collator is part of PHP intl.
1220 if ( class_exists ( 'Collator' )) {
1221 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
1222 if (! intl_is_failure ( intl_get_error_code ())) {
1223 return $c- > compare ( $a , $b );
1226 return strcasecmp ( $a , $b );
1230 foreach ( $tags as $key => $value )
1231 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1233 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1237 'linkcount' => count ( $LINKSDB ),
1240 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1242 foreach ( $data as $key => $value ) {
1243 $PAGE- > assign ( $key , $value );
1246 $PAGE- > renderPage ( 'tagcloud' );
1251 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1255 // Display openseach plugin (XML)
1256 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1257 header ( 'Content-Type: application/xml; charset=utf-8' );
1258 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1259 $PAGE- > renderPage ( 'opensearch' );
1263 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1264 if ( isset ( $_GET [ 'addtag' ]))
1266 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1267 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1268 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1270 // Prevent redirection loop
1271 if ( isset ( $params [ 'addtag' ])) {
1272 unset ( $params [ 'addtag' ]);
1275 // Check if this tag is already in the search query and ignore it if it is.
1276 // Each tag is always separated by a space
1277 if ( isset ( $params [ 'searchtags' ])) {
1278 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1280 $current_tags = array ();
1283 foreach ( $current_tags as $value ) {
1284 if ( $value === $_GET [ 'addtag' ]) {
1289 // Append the tag if necessary
1290 if ( empty ( $params [ 'searchtags' ])) {
1291 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1294 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1297 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1298 header ( 'Location: ?' . http_build_query ( $params ));
1302 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1303 if ( isset ( $_GET [ 'removetag' ])) {
1304 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1305 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1306 header ( 'Location: ?' );
1310 // In case browser does not send HTTP_REFERER
1311 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1313 // Prevent redirection loop
1314 if ( isset ( $params [ 'removetag' ])) {
1315 unset ( $params [ 'removetag' ]);
1318 if ( isset ( $params [ 'searchtags' ])) {
1319 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1320 // Remove value from array $tags.
1321 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1322 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1324 if ( empty ( $params [ 'searchtags' ])) {
1325 unset ( $params [ 'searchtags' ]);
1328 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1330 header ( 'Location: ?' . http_build_query ( $params ));
1334 // -------- User wants to change the number of links per page (linksperpage=...)
1335 if ( isset ( $_GET [ 'linksperpage' ])) {
1336 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1337 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1340 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1344 // -------- User wants to see only private links (toggle)
1345 if ( isset ( $_GET [ 'privateonly' ])) {
1346 if ( empty ( $_SESSION [ 'privateonly' ])) {
1347 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1349 unset ( $_SESSION [ 'privateonly' ]); // See all links
1352 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1356 // -------- Handle other actions allowed for non-logged in users:
1359 // User tries to post new link but is not logged in:
1360 // Show login screen, then redirect to ?post=...
1361 if ( isset ( $_GET [ 'post' ]))
1363 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.
1367 // Same case as above except that user tried to access ?do=addlink without being logged in
1368 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1369 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1370 header ( 'Location: ?do=login&post=' );
1373 showLinkList ( $PAGE , $LINKSDB );
1374 if ( isset ( $_GET [ 'edit_link' ])) {
1375 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1379 exit ; // Never remove this one! All operations below are reserved for logged in user.
1382 // -------- All other functions are reserved for the registered user:
1384 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1385 if ( $targetPage == Router
:: $PAGE_TOOLS )
1388 'linkcount' => count ( $LINKSDB ),
1389 'pageabsaddr' => index_url ( $_SERVER ),
1391 $pluginManager- > executeHooks ( 'render_tools' , $data );
1393 foreach ( $data as $key => $value ) {
1394 $PAGE- > assign ( $key , $value );
1397 $PAGE- > renderPage ( 'tools' );
1401 // -------- User wants to change his/her password.
1402 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1404 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1405 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1407 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1409 // Make sure old password is correct.
1410 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1411 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1412 // Save new password
1413 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1414 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1416 writeConfig ( $GLOBALS , isLoggedIn ());
1418 catch ( Exception
$e ) {
1420 'ERROR while writing config file after changing password.' . PHP_EOL
.
1424 // TODO: do not handle exceptions/errors in JS.
1425 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1428 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1431 else // show the change password form.
1433 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1434 $PAGE- > assign ( 'token' , getToken ());
1435 $PAGE- > renderPage ( 'changepassword' );
1440 // -------- User wants to change configuration
1441 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1443 if (! empty ( $_POST [ 'title' ]) )
1445 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1447 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1448 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1449 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1450 $GLOBALS [ 'timezone' ] = $tz ;
1451 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1452 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1453 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1454 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1455 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1456 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1457 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1458 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1460 writeConfig ( $GLOBALS , isLoggedIn ());
1462 catch ( Exception
$e ) {
1464 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1468 // TODO: do not handle exceptions/errors in JS.
1469 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1472 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1475 else // Show the configuration form.
1477 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1478 $PAGE- > assign ( 'token' , getToken ());
1479 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1480 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1481 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1482 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1483 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1484 $PAGE- > renderPage ( 'configure' );
1489 // -------- User wants to rename a tag or delete it
1490 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1492 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1493 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1494 $PAGE- > assign ( 'token' , getToken ());
1495 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1496 $PAGE- > renderPage ( 'changetag' );
1500 if (! tokenOk ( $_POST [ 'token' ])) {
1501 die ( 'Wrong token.' );
1505 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1506 $needle = trim ( $_POST [ 'fromtag' ]);
1507 // True for case-sensitive tag search.
1508 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1509 foreach ( $linksToAlter as $key => $value )
1511 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1512 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1513 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1514 $LINKSDB [ $key ]= $value ;
1516 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1517 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1522 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1523 $needle = trim ( $_POST [ 'fromtag' ]);
1524 // True for case-sensitive tag search.
1525 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1526 foreach ( $linksToAlter as $key => $value )
1528 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1529 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1530 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1531 $LINKSDB [ $key ]= $value ;
1533 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1534 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1539 // -------- User wants to add a link without using the bookmarklet: Show form.
1540 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1542 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1543 $PAGE- > renderPage ( 'addlink' );
1547 // -------- User clicked the "Save" button when editing a link: Save link to database.
1548 if ( isset ( $_POST [ 'save_edit' ]))
1551 if (! tokenOk ( $_POST [ 'token' ])) {
1552 die ( 'Wrong token.' );
1554 // Remove multiple spaces.
1555 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1556 // Remove first '-' char in tags.
1557 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1558 // Remove duplicates.
1559 $tags = implode(' ', array_unique(explode(' ', $tags )));
1560 $linkdate = $_POST [' lf_linkdate
'];
1561 $url = trim( $_POST [' lf_url
']);
1562 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1563 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1564 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1566 $url = ' http
: //' . $url;
1570 'title' => trim ( $_POST [ 'lf_title' ]),
1572 'description' => trim ( $_POST [ 'lf_description' ]),
1573 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1574 'linkdate' => $linkdate ,
1575 'tags' => str_replace ( ',' , ' ' , $tags )
1577 // If title is empty, use the URL as title.
1578 if ( $link [ 'title' ] == '' ) {
1579 $link [ 'title' ] = $link [ 'url' ];
1582 $pluginManager- > executeHooks ( 'save_link' , $link );
1584 $LINKSDB [ $linkdate ] = $link ;
1585 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1588 // If we are called from the bookmarklet, we must close the popup:
1589 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1590 echo '<script>self.close();</script>' ;
1594 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1595 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1596 // Scroll to the link which has been edited.
1597 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1598 // After saving the link, redirect to the page the user was on.
1599 header ( 'Location: ' . $location );
1603 // -------- User clicked the "Cancel" button when editing a link.
1604 if ( isset ( $_POST [ 'cancel_edit' ]))
1606 // If we are called from the bookmarklet, we must close the popup:
1607 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1608 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1609 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1610 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1611 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1615 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1616 if ( isset ( $_POST [ 'delete_link' ]))
1618 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1619 // We do not need to ask for confirmation:
1620 // - confirmation is handled by JavaScript
1621 // - we are protected from XSRF by the token.
1622 $linkdate = $_POST [ 'lf_linkdate' ];
1624 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1626 unset ( $LINKSDB [ $linkdate ]);
1627 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1629 // If we are called from the bookmarklet, we must close the popup:
1630 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1631 // Pick where we're going to redirect
1632 // =============================================================
1633 // Basically, we can't redirect to where we were previously if it was a permalink
1634 // or an edit_link, because it would 404.
1636 // - / : nothing in $_GET, redirect to self
1637 // - /?page : redirect to self
1638 // - /?searchterm : redirect to self (there might be other links)
1639 // - /?searchtags : redirect to self
1640 // - /permalink : redirect to / (the link does not exist anymore)
1641 // - /?edit_link : redirect to / (the link does not exist anymore)
1642 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1643 // redirect is not satisfied, and only then redirect to /
1646 if ( count ( $_GET ) == 0
1647 || isset ( $_GET [ 'page' ])
1648 || isset ( $_GET [ 'searchterm' ])
1649 || isset ( $_GET [ 'searchtags' ])
1651 if ( isset ( $_POST [ 'returnurl' ])) {
1652 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1654 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1658 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1662 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1663 if ( isset ( $_GET [ 'edit_link' ]))
1665 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1666 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1668 'linkcount' => count ( $LINKSDB ),
1670 'link_is_new' => false ,
1671 'token' => getToken (),
1672 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1673 'tags' => $LINKSDB- > allTags (),
1675 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1677 foreach ( $data as $key => $value ) {
1678 $PAGE- > assign ( $key , $value );
1681 $PAGE- > renderPage ( 'editlink' );
1685 // -------- User want to post a new link: Display link edit form.
1686 if ( isset ( $_GET [ 'post' ])) {
1687 $url = cleanup_url ( escape ( $_GET [ 'post' ]));
1689 $link_is_new = false ;
1690 // Check if URL is not already in database (in this case, we will edit the existing link)
1691 $link = $LINKSDB- > getLinkFromUrl ( $url );
1694 $link_is_new = true ;
1695 $linkdate = strval ( date ( 'Ymd_His' ));
1696 // Get title if it was provided in URL (by the bookmarklet).
1697 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1698 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1699 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1700 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1701 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1702 // 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.)
1703 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1704 // Short timeout to keep the application responsive
1705 list ( $headers , $content ) = get_http_response ( $url , 4 );
1706 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1707 // Retrieve charset.
1708 $charset = get_charset ( $headers , $content );
1710 $title = html_extract_title ( $content );
1711 // Re-encode title in utf-8 if necessary.
1712 if (! empty ( $title ) && $charset != 'utf-8' ) {
1713 $title = mb_convert_encoding ( $title , $charset , 'utf-8' );
1719 $url = '?' . smallHash ( $linkdate );
1724 'linkdate' => $linkdate ,
1727 'description' => $description ,
1729 'private' => $private
1734 'linkcount' => count ( $LINKSDB ),
1736 'link_is_new' => $link_is_new ,
1737 'token' => getToken (), // XSRF protection.
1738 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1739 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1740 'tags' => $LINKSDB- > allTags (),
1742 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1744 foreach ( $data as $key => $value ) {
1745 $PAGE- > assign ( $key , $value );
1748 $PAGE- > renderPage ( 'editlink' );
1752 // -------- Export as Netscape Bookmarks HTML file.
1753 if ( $targetPage == Router
:: $PAGE_EXPORT )
1755 if ( empty ( $_GET [ 'what' ]))
1757 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1758 $PAGE- > renderPage ( 'export' );
1761 $exportWhat = $_GET [ 'what' ];
1762 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1764 header ( 'Content-Type: text/html; charset=utf-8' );
1765 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1766 $currentdate = date ( 'Y/m/d H:i:s' );
1768 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1769 <!-- This is an automatically generated file.
1770 It will be read and overwritten.
1772 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1773 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1774 <TITLE>Bookmarks</TITLE>
1777 foreach ( $LINKSDB as $link )
1779 if ( $exportWhat == 'all' ||
1780 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1781 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1783 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1784 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1785 echo '>' . $link [ 'title' ]. "</A> \n " ;
1786 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1792 // -------- User is uploading a file for import
1793 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1795 // If file is too big, some form field may be missing.
1796 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1798 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1799 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>' ;
1802 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1807 // -------- Show upload/import dialog:
1808 if ( $targetPage == Router
:: $PAGE_IMPORT )
1810 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1811 $PAGE- > assign ( 'token' , getToken ());
1812 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1813 $PAGE- > renderPage ( 'import' );
1817 // Plugin administration page
1818 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1819 $pluginMeta = $pluginManager- > getPluginsMeta ();
1821 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1822 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1824 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1827 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1829 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1831 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1832 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1833 $PAGE- > renderPage ( 'pluginsadmin' );
1837 // Plugin administration form action
1838 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1840 if ( isset ( $_POST [ 'parameters_form' ])) {
1841 unset ( $_POST [ 'parameters_form' ]);
1842 foreach ( $_POST as $param => $value ) {
1843 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1847 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1849 writeConfig ( $GLOBALS , isLoggedIn ());
1851 catch ( Exception
$e ) {
1853 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1857 // TODO: do not handle exceptions/errors in JS.
1858 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1861 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1865 // -------- Otherwise, simply display search form and links:
1866 showLinkList ( $PAGE , $LINKSDB );
1870 // -----------------------------------------------------------------------------------------------
1871 // Process the import file form.
1872 function importFile ()
1874 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1875 $LINKSDB = new LinkDB (
1876 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1878 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1879 $GLOBALS [ 'redirector' ]
1881 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1882 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1883 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1884 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1885 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1890 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1892 // Then import the bookmarks.
1893 if ( $type == 'netscape' )
1895 // This is a standard Netscape-style bookmark file.
1896 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1897 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1899 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1900 $d = explode ( '<DD>' , $html );
1901 if ( startswith ( $d [ 0 ], '<A ' ))
1903 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1904 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1905 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1906 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1908 foreach ( $matches as $m )
1910 $attr = $m [ 1 ]; $value = $m [ 2 ];
1911 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1912 elseif ( $attr == 'ADD_DATE' )
1914 $raw_add_date = intval ( $value );
1915 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1917 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1918 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1920 if ( $link [ 'url' ]!= '' )
1922 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1923 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1925 { // Link not in database, let's import it...
1926 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1928 // Make sure date/time is not already used by another link.
1929 // (Some bookmark files have several different links with the same ADD_DATE)
1930 // We increment date by 1 second until we find a date which is not used in DB.
1931 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1932 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1933 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1934 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1937 else // Link already present in database.
1940 { // If overwrite is required, we import link data, except date/time.
1941 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1942 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1950 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1952 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1956 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1960 // -----------------------------------------------------------------------------------------------
1961 // Template for the list of links (<div id="linklist">)
1962 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1963 function buildLinkList ( $PAGE , $LINKSDB )
1965 // ---- Filter link database according to parameters
1968 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]) ? true : false ;
1971 if ( isset ( $_GET [ 'searchterm' ])) {
1972 $search_crits = escape ( trim ( $_GET [ 'searchterm' ]));
1973 $search_type = LinkFilter
:: $FILTER_TEXT ;
1974 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits , false , $privateonly );
1977 elseif ( isset ( $_GET [ 'searchtags' ])) {
1978 $search_crits = explode ( ' ' , escape ( trim ( $_GET [ 'searchtags' ])));
1979 $search_type = LinkFilter
:: $FILTER_TAG ;
1980 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits , false , $privateonly );
1982 // Detect smallHashes in URL.
1983 elseif ( isset ( $_SERVER [ 'QUERY_STRING' ])
1984 && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])) {
1985 $search_type = LinkFilter
:: $FILTER_HASH ;
1986 $search_crits = substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 );
1987 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits );
1989 if ( count ( $linksToDisplay ) == 0 ) {
1990 $PAGE- > render404 ( 'The link you are trying to reach does not exist or has been deleted.' );
1994 // Otherwise, display without filtering.
1996 $linksToDisplay = $LINKSDB- > filter ( '' , '' , false , $privateonly );
1999 // ---- Handle paging.
2001 foreach ( $linksToDisplay as $key => $value ) {
2005 // If there is only a single link, we change on-the-fly the title of the page.
2006 if ( count ( $linksToDisplay ) == 1 ) {
2007 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
2010 // Select articles according to paging.
2011 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
2012 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
2013 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
2014 $page = $page < 1 ? 1 : $page ;
2015 $page = $page > $pagecount ? $pagecount : $page ;
2017 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
2018 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
2019 $linkDisp = array ();
2020 while ( $i < $end && $i < count ( $keys ))
2022 $link = $linksToDisplay [ $keys [ $i ]];
2023 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
2024 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
2025 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
2026 $link [ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
2027 $taglist = explode ( ' ' , $link [ 'tags' ]);
2028 uasort ( $taglist , 'strcasecmp' );
2029 $link [ 'taglist' ] = $taglist ;
2030 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
2031 // Check for both signs of a note: starting with ? and 7 chars long.
2032 if ( $link [ 'url' ][ 0 ] === '?' &&
2033 strlen ( $link [ 'url' ]) === 7 ) {
2034 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
2037 $linkDisp [ $keys [ $i ]] = $link ;
2041 // Compute paging navigation
2042 $searchterm = empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ];
2043 $searchtags = empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ];
2044 $previous_page_url = '' ;
2045 if ( $i != count ( $keys )) {
2046 $previous_page_url = '?page=' . ( $page +
1 ) . $searchterm . $searchtags ;
2050 $next_page_url = '?page=' . ( $page-1 ) . $searchterm . $searchtags ;
2055 $token = getToken ();
2058 // Fill all template fields.
2060 'linkcount' => count ( $LINKSDB ),
2061 'previous_page_url' => $previous_page_url ,
2062 'next_page_url' => $next_page_url ,
2063 'page_current' => $page ,
2064 'page_max' => $pagecount ,
2065 'result_count' => count ( $linksToDisplay ),
2066 'search_type' => $search_type ,
2067 'search_crits' => $search_crits ,
2068 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
2070 'links' => $linkDisp ,
2071 'tags' => $LINKSDB- > allTags (),
2073 // FIXME! temporary fix - see #399.
2074 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
2075 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
2078 $pluginManager = PluginManager
:: getInstance ();
2079 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
2081 foreach ( $data as $key => $value ) {
2082 $PAGE- > assign ( $key , $value );
2088 // Compute the thumbnail for a link.
2090 // With a link to the original URL.
2091 // Understands various services (youtube.com...)
2092 // Input: $url = URL for which the thumbnail must be found.
2093 // $href = if provided, this URL will be followed instead of $url
2094 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
2095 // Some of them may be missing.
2096 // Return an empty array if no thumbnail available.
2097 function computeThumbnail ( $url , $href = false )
2099 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
2100 if ( $href == false ) $href = $url ;
2102 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
2103 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
2104 // ^^^^^^^^^^^ ^^^^^^^^^^^
2105 $domain = parse_url ( $url , PHP_URL_HOST
);
2106 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
2108 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
2109 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
2110 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2112 if ( $domain == 'youtu.be' ) // Youtube short links
2114 $path = parse_url ( $url , PHP_URL_PATH
);
2115 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
2116 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2118 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
2120 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
2121 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
2122 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
2125 if ( $domain == 'imgur.com' )
2127 $path = parse_url ( $url , PHP_URL_PATH
);
2128 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2129 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2130 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2131 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2132 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2134 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2135 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2137 if ( $domain == 'i.imgur.com' )
2139 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2140 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2141 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2143 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2145 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2147 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2148 return array ( 'src' => $thumburl ,
2149 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2152 if ( endsWith ( $domain , '.imageshack.us' ))
2154 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2155 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2157 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2158 return array ( 'src' => $thumburl ,
2159 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2163 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2164 // So we deport the thumbnail generation in order not to slow down page generation
2165 // (and we also cache the thumbnail)
2167 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2169 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2170 || $domain == 'vimeo.com'
2171 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2172 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2175 if ( $domain == 'vimeo.com' )
2176 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2177 $path = parse_url ( $url , PHP_URL_PATH
);
2178 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2180 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2181 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2182 $path = parse_url ( $url , PHP_URL_PATH
);
2183 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2185 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2186 { // Make sure this TED URL points to a video (/talks/...)
2187 $path = parse_url ( $url , PHP_URL_PATH
);
2188 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2190 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2191 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2192 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2195 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2196 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2197 // But using the extension will do.
2198 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2199 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2201 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2202 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2203 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2205 return array (); // No thumbnail.
2210 // Returns the HTML code to display a thumbnail for a link
2211 // with a link to the original URL.
2212 // Understands various services (youtube.com...)
2213 // Input: $url = URL for which the thumbnail must be found.
2214 // $href = if provided, this URL will be followed instead of $url
2215 // Returns '' if no thumbnail available.
2216 function thumbnail ( $url , $href = false )
2218 $t = computeThumbnail ( $url , $href );
2219 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2221 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2222 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2223 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2224 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2225 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2230 // Returns the HTML code to display a thumbnail for a link
2231 // for the picture wall (using lazy image loading)
2232 // Understands various services (youtube.com...)
2233 // Input: $url = URL for which the thumbnail must be found.
2234 // $href = if provided, this URL will be followed instead of $url
2235 // Returns '' if no thumbnail available.
2236 function lazyThumbnail ( $url , $href = false )
2238 $t = computeThumbnail ( $url , $href );
2239 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2241 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2244 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2246 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2247 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2248 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2249 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2252 // No-JavaScript fallback.
2253 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2254 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2255 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2256 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2257 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2258 $html .= '></noscript></a>' ;
2264 // -----------------------------------------------------------------------------------------------
2266 // This function should NEVER be called if the file data/config.php exists.
2269 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2270 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2273 // This part makes sure sessions works correctly.
2274 // (Because on some hosts, session.save_path may not be set correctly,
2275 // or we may not have write access to it.)
2276 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2277 { // Step 2: Check if data in session is correct.
2278 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2279 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2280 echo 'It currently points to ' . session_save_path (). '<br>' ;
2281 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>' ;
2282 echo '<br><a href="?">Click to try again.</a></pre>' ;
2285 if (! isset ( $_SESSION [ 'session_tested' ]))
2286 { // Step 1 : Try to store data in session and reload page.
2287 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2288 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2290 if ( isset ( $_GET [ 'test_session' ]))
2291 { // Step 3: Sessions are OK. Remove test parameter from URL.
2292 header ( 'Location: ' . index_url ( $_SERVER ));
2296 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2299 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2300 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2301 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2304 $GLOBALS [ 'timezone' ] = $tz ;
2305 // Everything is ok, let's create config file.
2306 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2307 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2308 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2309 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2310 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2312 writeConfig ( $GLOBALS , isLoggedIn ());
2314 catch ( Exception
$e ) {
2316 'ERROR while writing config file after installation.' . PHP_EOL
.
2320 // TODO: do not handle exceptions/errors in JS.
2321 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2324 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2328 // Display config form:
2329 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2330 $timezone_html = '' ;
2331 if ( $timezone_form != '' ) {
2332 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2335 $PAGE = new pageBuilder
;
2336 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2337 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2338 $PAGE- > renderPage ( 'install' );
2342 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2343 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2344 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2345 This function is called by passing the URL:
2346 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2347 [URL] is the URL of the link (e.g. a flickr page)
2348 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2349 The function below will fetch the image from the webservice and store it in the cache.
2351 function genThumbnail ()
2353 // Make sure the parameters in the URL were generated by us.
2354 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2355 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2357 // Let's see if we don't already have the image for this URL in the cache.
2358 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2359 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2360 { // We have the thumbnail, just serve it:
2361 header ( 'Content-Type: image/jpeg' );
2362 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2365 // We may also serve a blank image (if service did not respond)
2366 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2367 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2369 header ( 'Content-Type: image/gif' );
2370 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2374 // Otherwise, generate the thumbnail.
2375 $url = $_GET [ 'url' ];
2376 $domain = parse_url ( $url , PHP_URL_HOST
);
2378 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2380 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2381 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2383 // Is this a link to an image, or to a flickr page ?
2385 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2386 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2387 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2388 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2390 else // This is a flickr page (html)
2392 // Get the flickr html page.
2393 list ( $headers , $content ) = get_http_response ( $url , 20 );
2394 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2396 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2397 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2398 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2400 // In albums (and some other pages), the link rel="image_src" is not provided,
2401 // but flickr provides:
2402 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2405 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2406 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2412 { // Let's download the image.
2413 // Image is 240x120, so 10 seconds to download should be enough.
2414 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2415 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2416 // Save image to cache.
2417 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2418 header ( 'Content-Type: image/jpeg' );
2425 elseif ( $domain == 'vimeo.com' )
2427 // This is more complex: we have to perform a HTTP request, then parse the result.
2428 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2429 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2430 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2431 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2432 $t = unserialize ( $content );
2433 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2434 // Then we download the image and serve it to our client.
2435 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2436 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2437 // Save image to cache.
2438 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2439 header ( 'Content-Type: image/jpeg' );
2446 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2448 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2449 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2450 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2451 list ( $headers , $content ) = get_http_response ( $url , 5 );
2452 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2453 // Extract the link to the thumbnail
2454 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2455 if (! empty ( $matches [ 1 ]))
2456 { // Let's download the image.
2457 $imageurl = $matches [ 1 ];
2458 // No control on image size, so wait long enough
2459 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2460 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2461 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2462 file_put_contents ( $filepath , $content ); // Save image to cache.
2463 if ( resizeImage ( $filepath ))
2465 header ( 'Content-Type: image/jpeg' );
2466 echo file_get_contents ( $filepath );
2474 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2476 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2477 // http://xkcd.com/327/
2478 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2479 list ( $headers , $content ) = get_http_response ( $url , 5 );
2480 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2481 // Extract the link to the thumbnail
2482 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2483 if (! empty ( $matches [ 1 ]))
2484 { // Let's download the image.
2485 $imageurl = $matches [ 1 ];
2486 // No control on image size, so wait long enough
2487 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2488 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2489 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2490 // Save image to cache.
2491 file_put_contents ( $filepath , $content );
2492 if ( resizeImage ( $filepath ))
2494 header ( 'Content-Type: image/jpeg' );
2495 echo file_get_contents ( $filepath );
2505 // For all other domains, we try to download the image and make a thumbnail.
2506 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2507 list ( $headers , $content ) = get_http_response ( $url , 30 );
2508 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2509 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2510 // Save image to cache.
2511 file_put_contents ( $filepath , $content );
2512 if ( resizeImage ( $filepath ))
2514 header ( 'Content-Type: image/jpeg' );
2515 echo file_get_contents ( $filepath );
2522 // Otherwise, return an empty image (8x8 transparent gif)
2523 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2524 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2525 header ( 'Content-Type: image/gif' );
2529 // Make a thumbnail of the image (to width: 120 pixels)
2530 // Returns true if success, false otherwise.
2531 function resizeImage ( $filepath )
2533 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2535 // Trick: some stupid people rename GIF as JPEG... or else.
2536 // So we really try to open each image type whatever the extension is.
2537 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2539 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2540 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2541 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2542 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2545 $ystart = 0 ; $yheight = $h ;
2546 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2547 $nw = 120 ; // Desired width
2548 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2550 $im2 = imagecreatetruecolor ( $nw , $nh );
2551 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2552 imageinterlace ( $im2 , true ); // For progressive JPEG.
2553 $tempname = $filepath . '_TEMP.jpg' ;
2554 imagejpeg ( $im2 , $tempname , 90 );
2558 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2562 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2563 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2564 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2565 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2566 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];