]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
82a6abb343bee4a65ca6b0a8e015365fa66cc170
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' ;
48 $GLOBALS [ 'config' ][ 'LOG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' ;
50 // For updates check of Shaarli
51 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
53 // RainTPL cache directory (keep the trailing slash!)
54 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
55 // Raintpl template directory (keep the trailing slash!)
56 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
58 // Thumbnail cache directory
59 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
61 // Atom & RSS feed cache directory
62 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
66 * Global configuration
68 // Ban IP after this many failures
69 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
70 // Ban duration for IP address after login failures (in seconds)
71 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
74 // Enable RSS permalinks by default.
75 // This corresponds to the default behavior of shaarli before this was added as an option.
76 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
77 // If true, an extra "ATOM feed" button will be displayed in the toolbar
78 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
80 // Link display options
81 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
82 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
83 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
85 // Open Shaarli (true): anyone can add/edit/delete links without having to login
86 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
89 // Display thumbnails in links
90 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
91 // Store thumbnails in a local cache
92 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
94 // Update check frequency for Shaarli. 86400 seconds=24 hours
95 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ] = 'stable' ;
96 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
100 * Plugin configuration
102 * Warning: order matters!
104 * These settings may be be overriden in:
106 * - each plugin's configuration file
108 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
109 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
110 // 'wallabag', 'markdown', 'addlink_toolbar',
112 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
114 //$GLOBALS['plugins']['WALLABAG_URL'] = 'https://demo.wallabag.org/';
116 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
117 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
122 define ( 'shaarli_version' , '0.6.3' );
124 // http://server.com/x/shaarli --> /shaarli/
125 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
127 // High execution time in case of problematic imports/exports.
128 ini_set ( 'max_input_time' , '60' );
130 // Try to set max upload file size and read
131 ini_set ( 'memory_limit' , '128M' );
132 ini_set ( 'post_max_size' , '16M' );
133 ini_set ( 'upload_max_filesize' , '16M' );
135 // See all error except warnings
136 error_reporting ( E_ALL^E_WARNING
);
137 // See all errors (for debugging only)
138 //error_reporting(-1);
143 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
144 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
148 require_once 'application/ApplicationUtils.php' ;
149 require_once 'application/Cache.php' ;
150 require_once 'application/CachedPage.php' ;
151 require_once 'application/FileUtils.php' ;
152 require_once 'application/HttpUtils.php' ;
153 require_once 'application/LinkDB.php' ;
154 require_once 'application/LinkFilter.php' ;
155 require_once 'application/LinkUtils.php' ;
156 require_once 'application/TimeZone.php' ;
157 require_once 'application/Url.php' ;
158 require_once 'application/Utils.php' ;
159 require_once 'application/Config.php' ;
160 require_once 'application/PluginManager.php' ;
161 require_once 'application/Router.php' ;
163 // Ensure the PHP version is supported
165 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
166 } catch ( Exception
$exc ) {
167 header ( 'Content-Type: text/plain; charset=utf-8' );
168 echo $exc- > getMessage ();
172 // Force cookie path (but do not change lifetime)
173 $cookie = session_get_cookie_params ();
175 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
176 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
178 // Set default cookie expiration and path.
179 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
180 // Set session parameters on server side.
181 // If the user does not access any page within this time, his/her session is considered expired.
182 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
183 // Use cookies to store session.
184 ini_set ( 'session.use_cookies' , 1 );
185 // Force cookies for session (phpsessionID forbidden in URL).
186 ini_set ( 'session.use_only_cookies' , 1 );
187 // Prevent PHP form using sessionID in URL if cookies are disabled.
188 ini_set ( 'session.use_trans_sid' , false );
190 session_name ( 'shaarli' );
191 // Start session if needed (Some server auto-start sessions).
192 if ( session_id () == '' ) {
196 // Regenerate session ID if invalid or not defined in cookie.
197 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
198 session_regenerate_id ( true );
199 $_COOKIE [ 'shaarli' ] = session_id ();
202 include "inc/rain.tpl.class.php" ; //include Rain TPL
203 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
204 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
206 $pluginManager = PluginManager
:: getInstance ();
207 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
209 ob_start (); // Output buffering for the page cache.
212 // In case stupid admin has left magic_quotes enabled in php.ini:
213 if ( get_magic_quotes_gpc ())
215 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
216 $_POST = array_map ( 'stripslashes_deep' , $_POST );
217 $_GET = array_map ( 'stripslashes_deep' , $_GET );
218 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
221 // Prevent caching on client side or proxy: (yes, it's ugly)
222 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
223 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
224 header ( "Cache-Control: post-check=0, pre-check=0" , false );
225 header ( "Pragma: no-cache" );
227 // Handling of old config file which do not have the new parameters.
228 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
229 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
230 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
231 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
232 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
233 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
234 // I really need to rewrite Shaarli with a proper configuation manager.
236 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
237 // Ensure Shaarli has proper access to its resources
238 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
240 if ( $errors != array ()) {
241 $message = '<p>Insufficient permissions:</p><ul>' ;
243 foreach ( $errors as $error ) {
244 $message .= '<li>' . $error . '</li>' ;
248 header ( 'Content-Type: text/html; charset=utf-8' );
253 // Display the installation form if no existing config is found
257 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
258 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
259 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
261 // a token depending of deployment salt, user password, and the current ip
262 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
264 autoLocale (); // Sniff browser language and set date format accordingly.
265 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
267 //==================================================================================================
268 // Checking session state (i.e. is the user still logged in)
269 //==================================================================================================
271 function setup_login_state () {
272 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
275 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
276 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
277 if (! isset ( $GLOBALS [ 'login' ])) {
278 $userIsLoggedIn = false ; // Shaarli is not configured yet.
279 $loginFailure = true ;
281 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
282 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
286 $userIsLoggedIn = true ;
288 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
289 if ( empty ( $_SESSION [ 'uid' ]) ||
290 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
291 time () >= $_SESSION [ 'expires_on' ])
294 $userIsLoggedIn = false ;
295 $loginFailure = true ;
297 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
298 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
301 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
303 if (! $loginFailure ) {
304 $userIsLoggedIn = true ;
307 return $userIsLoggedIn ;
309 $userIsLoggedIn = setup_login_state ();
312 // ------------------------------------------------------------------------------------------
313 // Sniff browser language to display dates in the right format automatically.
314 // (Note that is may not work on your server if the corresponding local is not installed.)
315 function autoLocale ()
317 $attempts = array ( 'en_US' ); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
318 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
319 { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
320 if ( preg_match ( '/([a-z] {2} )-?([a-z] {2} )?/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) {
321 $loc = $matches [ 1 ] . (! empty ( $matches [ 2 ]) ? '_' . strtoupper ( $matches [ 2 ]) : '' );
322 $attempts = array ( $loc . '.UTF-8' , $loc , str_replace ( '_' , '-' , $loc ). '.UTF-8' , str_replace ( '_' , '-' , $loc ),
323 $loc . '_' . strtoupper ( $loc ). '.UTF-8' , $loc . '_' . strtoupper ( $loc ),
324 $loc . '_' . $loc . '.UTF-8' , $loc . '_' . $loc , $loc . '-' . strtoupper ( $loc ). '.UTF-8' ,
325 $loc . '-' . strtoupper ( $loc ), $loc . '-' . $loc . '.UTF-8' , $loc . '-' . $loc );
328 setlocale ( LC_TIME
, $attempts ); // LC_TIME = Set local for date/time format only.
331 // ------------------------------------------------------------------------------------------
332 // PubSubHubbub protocol support (if enabled) [UNTESTED]
333 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
334 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
337 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
339 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
341 index_url ( $_SERVER ). '?do=atom' ,
342 index_url ( $_SERVER ). '?do=rss'
344 $p- > publish_update ( $topic_url );
348 // ------------------------------------------------------------------------------------------
349 // Session management
351 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
354 $ip = $_SERVER [ "REMOTE_ADDR" ];
355 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
356 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
357 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
361 function fillSessionInfo () {
362 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
363 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
364 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
365 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
368 // Check that user/password is correct.
369 function check_auth ( $login , $password )
371 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
372 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
373 { // Login/password is correct.
375 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
378 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
382 // Returns true if the user is logged in.
383 function isLoggedIn ()
385 global $userIsLoggedIn ;
386 return $userIsLoggedIn ;
391 if ( isset ( $_SESSION )) {
392 unset ( $_SESSION [ 'uid' ]);
393 unset ( $_SESSION [ 'ip' ]);
394 unset ( $_SESSION [ 'username' ]);
395 unset ( $_SESSION [ 'privateonly' ]);
397 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
401 // ------------------------------------------------------------------------------------------
402 // Brute force protection system
403 // Several consecutive failed logins will ban the IP address for 30 minutes.
404 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 ?>" );
405 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
406 // Signal a failed login. Will ban the IP if too many failures:
407 function ban_loginFailed ()
409 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
410 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
411 $gb [ 'FAILURES' ][ $ip ] ++
;
412 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
414 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
415 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
417 $GLOBALS [ 'IPBANS' ] = $gb ;
418 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
421 // Signals a successful login. Resets failed login counter.
422 function ban_loginOk ()
424 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
425 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
426 $GLOBALS [ 'IPBANS' ] = $gb ;
427 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
430 // Checks if the user CAN login. If 'true', the user can try to login.
431 function ban_canLogin ()
433 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
434 if ( isset ( $gb [ 'BANS' ][ $ip ]))
436 // User is banned. Check if the ban has expired:
437 if ( $gb [ 'BANS' ][ $ip ]<= time ())
438 { // Ban expired, user can try to login again.
439 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
440 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
441 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
442 return true ; // Ban has expired, user can login.
444 return false ; // User is banned.
446 return true ; // User is not banned.
449 // ------------------------------------------------------------------------------------------
450 // Process login form: Check if login/password is correct.
451 if ( isset ( $_POST [ 'login' ]))
453 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
454 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
455 { // Login/password is OK.
457 // If user wants to keep the session cookie even after the browser closes:
458 if (! empty ( $_POST [ 'longlastingsession' ]))
460 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
461 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
462 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
464 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
465 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
466 // Note: Never forget the trailing slash on the cookie path!
467 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
469 else // Standard session expiration (=when browser closes)
471 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
472 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
473 session_regenerate_id ( true );
476 // Optional redirect after login:
477 if ( isset ( $_GET [ 'post' ])) {
478 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
479 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
480 if (! empty ( $_GET [ $param ])) {
481 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
484 header ( 'Location: ' . $uri );
488 if ( isset ( $_GET [ 'edit_link' ])) {
489 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
493 if ( isset ( $_POST [ 'returnurl' ])) {
494 // Prevent loops over login screen.
495 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
496 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
500 header ( 'Location: ?' ); exit ;
506 if ( isset ( $_GET [ 'post' ])) {
507 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
508 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
509 if (! empty ( $_GET [ $param ])) {
510 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
514 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
519 // ------------------------------------------------------------------------------------------
520 // Misc utility functions:
522 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
523 function return_bytes ( $val )
525 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
528 case 'g' : $val *= 1024 ;
529 case 'm' : $val *= 1024 ;
530 case 'k' : $val *= 1024 ;
535 // Try to determine max file size for uploads (POST).
536 // Returns an integer (in bytes)
537 function getMaxFileSize ()
539 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
540 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
541 // Return the smaller of two:
542 $maxsize = min ( $size1 , $size2 );
543 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
547 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
548 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
549 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
550 function linkdate2timestamp ( $linkdate )
552 if ( strcmp ( $linkdate , '_000000' ) !== 0 || ! $linkdate ){
554 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
555 return mktime ( $h , $m , $s , $M , $D , $Y );
560 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
561 (used to build the pubDate attribute in RSS feed.) */
562 function linkdate2rfc822 ( $linkdate )
564 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
567 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
568 (used to build the updated tags in ATOM feed.) */
569 function linkdate2iso8601 ( $linkdate )
571 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
574 // ------------------------------------------------------------------------------------------
575 // Token management for XSRF protection
576 // Token should be used in any form which acts on data (create,update,delete,import...).
577 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
582 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
583 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
587 // Tells if a token is OK. Using this function will destroy the token.
589 function tokenOk ( $token )
591 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
593 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
594 return true ; // Token is OK.
596 return false ; // Wrong token, or already used.
599 // ------------------------------------------------------------------------------------------
600 /* This class is in charge of building the final page.
601 (This is basically a wrapper around RainTPL which pre-fills some fields.)
603 p.assign('myfield','myvalue');
604 p.renderPage('mytemplate');
609 private $tpl ; // RainTPL template
611 function __construct ()
617 * Initialize all default tpl tags.
619 private function initialize ()
621 $this- > tpl
= new RainTPL
;
624 $version = ApplicationUtils
:: checkUpdate (
626 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
627 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
628 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
630 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
632 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
633 $this- > tpl
-> assign ( 'versionError' , '' );
635 } catch ( Exception
$exc ) {
636 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
637 $this- > tpl
-> assign ( 'newVersion' , '' );
638 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
641 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
642 $searchcrits = '' ; // Search criteria
643 if (! empty ( $_GET [ 'searchtags' ])) {
644 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
646 elseif (! empty ( $_GET [ 'searchterm' ])) {
647 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
649 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
650 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
651 $this- > tpl
-> assign ( 'version' , shaarli_version
);
652 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
653 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
654 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
655 if (! empty ( $GLOBALS [ 'title' ])) {
656 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
658 if (! empty ( $GLOBALS [ 'titleLink' ])) {
659 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
661 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
662 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
664 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
665 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
666 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
670 // The following assign() method is basically the same as RainTPL (except that it's lazy)
671 public function assign ( $what , $where )
673 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
674 $this- > tpl
-> assign ( $what , $where );
677 // Render a specific page (using a template).
678 // e.g. pb.renderPage('picwall')
679 public function renderPage ( $page )
681 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
682 $this- > tpl
-> draw ( $page );
686 * Render a 404 page (uses the template : tpl/404.tpl)
688 * usage : $PAGE->render404('The link was deleted')
689 * @param string $message A messate to display what is not found
691 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
692 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
693 $this- > tpl
-> assign ( 'error_message' , $message );
694 $this- > renderPage ( '404' );
698 // ------------------------------------------------------------------------------------------
699 // Output the last N links in RSS 2.0 format.
702 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
704 // $usepermalink : If true, use permalink instead of final link.
705 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
706 // Also enabled through a config option
707 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
710 $query = $_SERVER [ "QUERY_STRING" ];
711 $cache = new CachedPage (
712 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
714 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
716 $cached = $cache- > cachedVersion ();
717 if (! empty ( $cached )) {
722 // If cached was not found (or not usable), then read the database and build the response:
723 $LINKSDB = new LinkDB (
724 $GLOBALS [ 'config' ][ 'DATASTORE' ],
726 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
727 $GLOBALS [ 'redirector' ]
729 // Read links from database (and filter private links if user it not logged in).
731 // Optionally filter the results:
732 if (! empty ( $_GET [ 'searchterm' ])) {
733 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
735 elseif (! empty ( $_GET [ 'searchtags' ])) {
736 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
739 $linksToDisplay = $LINKSDB ;
742 $nblinksToDisplay = 50 ; // Number of links to display.
743 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
744 if (! empty ( $_GET [ 'nb' ])) {
745 $nblinksToDisplay = $_GET [ 'nb' ] == 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
748 $pageaddr = escape ( index_url ( $_SERVER ));
749 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
750 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
751 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
752 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
754 echo '<!-- PubSubHubbub Discovery -->' ;
755 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
756 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
757 echo '<!-- End Of PubSubHubbub Discovery -->' ;
760 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
761 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
763 $link = $linksToDisplay [ $keys [ $i ]];
764 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
765 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
766 $absurl = $link [ 'url' ];
767 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
768 if ( $usepermalinks === true )
769 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
771 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
772 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . escape ( $rfc822date ). "</pubDate> \n " ;
773 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
775 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
778 // Add permalink in description
779 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
780 // If user wants permalinks first, put the final link in description
781 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
782 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
783 echo '<description><![CDATA[' .
784 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
785 $descriptionlink . ']]></description>' . " \n </item> \n " ;
788 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
790 $cache- > cache ( ob_get_contents ());
795 // ------------------------------------------------------------------------------------------
796 // Output the last N links in ATOM format.
799 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
801 // $usepermalink : If true, use permalink instead of final link.
802 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
803 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
806 $query = $_SERVER [ "QUERY_STRING" ];
807 $cache = new CachedPage (
808 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
810 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
812 $cached = $cache- > cachedVersion ();
813 if (! empty ( $cached )) {
818 // If cached was not found (or not usable), then read the database and build the response:
819 // Read links from database (and filter private links if used it not logged in).
820 $LINKSDB = new LinkDB (
821 $GLOBALS [ 'config' ][ 'DATASTORE' ],
823 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
824 $GLOBALS [ 'redirector' ]
827 // Optionally filter the results:
828 if (! empty ( $_GET [ 'searchterm' ])) {
829 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
831 else if (! empty ( $_GET [ 'searchtags' ])) {
832 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
835 $linksToDisplay = $LINKSDB ;
838 $nblinksToDisplay = 50 ; // Number of links to display.
839 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
840 if (! empty ( $_GET [ 'nb' ])) {
841 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
844 $pageaddr = escape ( index_url ( $_SERVER ));
848 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
849 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
851 $link = $linksToDisplay [ $keys [ $i ]];
852 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
853 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
854 $latestDate = max ( $latestDate , $iso8601date );
855 $absurl = $link [ 'url' ];
856 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
857 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
858 if ( $usepermalinks === true )
859 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
861 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
862 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
864 // Add permalink in description
865 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
866 // If user wants permalinks first, put the final link in description
867 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
868 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
870 $entries .= '<content type="html"><![CDATA[' .
871 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
872 $descriptionlink . "]]></content> \n " ;
873 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
875 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
876 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
878 $entries .= "</entry> \n " ;
881 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
882 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
883 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
884 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
885 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
887 $feed .= '<!-- PubSubHubbub Discovery -->' ;
888 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
889 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
891 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
892 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
894 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
897 $cache- > cache ( ob_get_contents ());
902 // ------------------------------------------------------------------------------------------
903 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
904 // Gives the last 7 days (which have links).
905 // This RSS feed cannot be filtered.
906 function showDailyRSS () {
908 $query = $_SERVER [ "QUERY_STRING" ];
909 $cache = new CachedPage (
910 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
912 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
914 $cached = $cache- > cachedVersion ();
915 if (! empty ( $cached )) {
920 // If cached was not found (or not usable), then read the database and build the response:
921 // Read links from database (and filter private links if used it not logged in).
922 $LINKSDB = new LinkDB (
923 $GLOBALS [ 'config' ][ 'DATASTORE' ],
925 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
926 $GLOBALS [ 'redirector' ]
929 /* Some Shaarlies may have very few links, so we need to look
930 back in time (rsort()) until we have enough days ($nb_of_days).
932 $linkdates = array ();
933 foreach ( $LINKSDB as $linkdate => $value ) {
934 $linkdates [] = $linkdate ;
937 $nb_of_days = 7 ; // We take 7 days.
938 $today = Date ( 'Ymd' );
941 foreach ( $linkdates as $linkdate ) {
942 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
943 if ( strcmp ( $day , $today ) < 0 ) {
944 if ( empty ( $days [ $day ])) {
945 $days [ $day ] = array ();
947 $days [ $day ][] = $linkdate ;
950 if ( count ( $days ) > $nb_of_days ) {
951 break ; // Have we collected enough days?
955 // Build the RSS feed.
956 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
957 $pageaddr = escape ( index_url ( $_SERVER ));
958 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
960 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
961 echo '<link>' . $pageaddr . '</link>' ;
962 echo '<description>Daily shared links</description>' ;
963 echo '<language>en-en</language>' ;
964 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
967 foreach ( $days as $day => $linkdates ) {
968 $daydate = linkdate2timestamp ( $day . '_000000' ); // Full text date
969 $rfc822date = linkdate2rfc822 ( $day . '_000000' );
970 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
972 // Build the HTML body of this RSS entry.
977 // We pre-format some fields for proper output.
978 foreach ( $linkdates as $linkdate ) {
979 $l = $LINKSDB [ $linkdate ];
980 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
981 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
982 $l [ 'timestamp' ] = linkdate2timestamp ( $l [ 'linkdate' ]);
983 if ( startsWith ( $l [ 'url' ], '?' )) {
984 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
986 $links [ $linkdate ] = $l ;
989 // Then build the HTML for this day:
991 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
992 $tpl- > assign ( 'daydate' , $daydate );
993 $tpl- > assign ( 'absurl' , $absurl );
994 $tpl- > assign ( 'links' , $links );
995 $tpl- > assign ( 'rfc822date' , escape ( $rfc822date ));
996 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
998 echo $html . PHP_EOL
;
1000 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
1002 $cache- > cache ( ob_get_contents ());
1008 * Show the 'Daily' page.
1010 * @param PageBuilder $pageBuilder Template engine wrapper.
1012 function showDaily ( $pageBuilder )
1014 $LINKSDB = new LinkDB (
1015 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1017 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1018 $GLOBALS [ 'redirector' ]
1021 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1022 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1024 $days = $LINKSDB- > days ();
1025 $i = array_search ( $day , $days );
1026 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1031 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1032 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1036 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_DAY , $day );
1037 } catch ( Exception
$exc ) {
1039 $linksToDisplay = array ();
1042 // We pre-format some fields for proper output.
1043 foreach ( $linksToDisplay as $key => $link )
1046 $taglist = explode ( ' ' , $link [ 'tags' ]);
1047 uasort ( $taglist , 'strcasecmp' );
1048 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1049 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1050 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1051 $linksToDisplay [ $key ][ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
1054 /* We need to spread the articles on 3 columns.
1055 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1056 so I manually spread entries with a simple method: I roughly evaluate the
1057 height of a div according to title and description length.
1059 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1060 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1061 foreach ( $linksToDisplay as $key => $link )
1063 // Roughly estimate length of entry (by counting characters)
1064 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1065 // Description: 836 characters gives roughly 342 pixel height.
1066 // This is not perfect, but it's usually OK.
1067 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1068 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1069 // Then put in column which is the less filled:
1070 $smallest = min ( $fill ); // find smallest value in array.
1071 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1072 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1073 $fill [ $index ] +
= $length ;
1077 'linksToDisplay' => $linksToDisplay ,
1078 'linkcount' => count ( $LINKSDB ),
1080 'day' => linkdate2timestamp ( $day . '_000000' ),
1081 'previousday' => $previousday ,
1082 'nextday' => $nextday ,
1084 $pluginManager = PluginManager
:: getInstance ();
1085 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1087 foreach ( $data as $key => $value ) {
1088 $pageBuilder- > assign ( $key , $value );
1091 $pageBuilder- > renderPage ( 'daily' );
1095 // Renders the linklist
1096 function showLinkList ( $PAGE , $LINKSDB ) {
1097 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1098 $PAGE- > renderPage ( 'linklist' );
1102 // ------------------------------------------------------------------------------------------
1103 // Render HTML page (according to URL parameters and user rights)
1104 function renderPage ()
1106 $LINKSDB = new LinkDB (
1107 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1109 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1110 $GLOBALS [ 'redirector' ]
1113 $PAGE = new pageBuilder
;
1115 // Determine which page will be rendered.
1116 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1117 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1119 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1120 // Then assign generated data to RainTPL.
1121 $common_hooks = array (
1126 $pluginManager = PluginManager
:: getInstance ();
1127 foreach ( $common_hooks as $name ) {
1128 $plugin_data = array ();
1129 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1131 'target' => $targetPage ,
1132 'loggedin' => isLoggedIn ()
1135 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1138 // -------- Display login form.
1139 if ( $targetPage == Router
:: $PAGE_LOGIN )
1141 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1142 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1143 $PAGE- > assign ( 'token' , $token );
1144 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1145 $PAGE- > renderPage ( 'loginform' );
1148 // -------- User wants to logout.
1149 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1151 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1153 header ( 'Location: ?' );
1157 // -------- Picture wall
1158 if ( $targetPage == Router
:: $PAGE_PICWALL )
1160 // Optionally filter the results:
1161 if (! empty ( $_GET [ 'searchterm' ])) {
1162 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
1164 elseif (! empty ( $_GET [ 'searchtags' ])) {
1165 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
1171 $linksToDisplay = array ();
1173 // Get only links which have a thumbnail.
1174 foreach ( $links as $link )
1176 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1177 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1178 if ( $thumb != '' ) // Only output links which have a thumbnail.
1180 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1181 $linksToDisplay []= $link ; // Add to array.
1186 'linkcount' => count ( $LINKSDB ),
1187 'linksToDisplay' => $linksToDisplay ,
1189 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1191 foreach ( $data as $key => $value ) {
1192 $PAGE- > assign ( $key , $value );
1195 $PAGE- > renderPage ( 'picwall' );
1199 // -------- Tag cloud
1200 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1202 $tags = $LINKSDB- > allTags ();
1204 // We sort tags alphabetically, then choose a font size according to count.
1205 // First, find max value.
1206 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
1209 foreach ( $tags as $key => $value )
1210 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1212 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1216 'linkcount' => count ( $LINKSDB ),
1219 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1221 foreach ( $data as $key => $value ) {
1222 $PAGE- > assign ( $key , $value );
1225 $PAGE- > renderPage ( 'tagcloud' );
1230 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1234 // Display openseach plugin (XML)
1235 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1236 header ( 'Content-Type: application/xml; charset=utf-8' );
1237 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1238 $PAGE- > renderPage ( 'opensearch' );
1242 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1243 if ( isset ( $_GET [ 'addtag' ]))
1245 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1246 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1247 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1249 // Prevent redirection loop
1250 if ( isset ( $params [ 'addtag' ])) {
1251 unset ( $params [ 'addtag' ]);
1254 // Check if this tag is already in the search query and ignore it if it is.
1255 // Each tag is always separated by a space
1256 if ( isset ( $params [ 'searchtags' ])) {
1257 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1259 $current_tags = array ();
1262 foreach ( $current_tags as $value ) {
1263 if ( $value === $_GET [ 'addtag' ]) {
1268 // Append the tag if necessary
1269 if ( empty ( $params [ 'searchtags' ])) {
1270 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1273 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1276 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1277 header ( 'Location: ?' . http_build_query ( $params ));
1281 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1282 if ( isset ( $_GET [ 'removetag' ])) {
1283 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1284 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1285 header ( 'Location: ?' );
1289 // In case browser does not send HTTP_REFERER
1290 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1292 // Prevent redirection loop
1293 if ( isset ( $params [ 'removetag' ])) {
1294 unset ( $params [ 'removetag' ]);
1297 if ( isset ( $params [ 'searchtags' ])) {
1298 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1299 // Remove value from array $tags.
1300 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1301 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1303 if ( empty ( $params [ 'searchtags' ])) {
1304 unset ( $params [ 'searchtags' ]);
1307 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1309 header ( 'Location: ?' . http_build_query ( $params ));
1313 // -------- User wants to change the number of links per page (linksperpage=...)
1314 if ( isset ( $_GET [ 'linksperpage' ])) {
1315 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1316 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1319 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1323 // -------- User wants to see only private links (toggle)
1324 if ( isset ( $_GET [ 'privateonly' ])) {
1325 if ( empty ( $_SESSION [ 'privateonly' ])) {
1326 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1328 unset ( $_SESSION [ 'privateonly' ]); // See all links
1331 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1335 // -------- Handle other actions allowed for non-logged in users:
1338 // User tries to post new link but is not logged in:
1339 // Show login screen, then redirect to ?post=...
1340 if ( isset ( $_GET [ 'post' ]))
1342 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.
1346 // Same case as above except that user tried to access ?do=addlink without being logged in
1347 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1348 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1349 header ( 'Location: ?do=login&post=' );
1352 showLinkList ( $PAGE , $LINKSDB );
1353 if ( isset ( $_GET [ 'edit_link' ])) {
1354 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1358 exit ; // Never remove this one! All operations below are reserved for logged in user.
1361 // -------- All other functions are reserved for the registered user:
1363 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1364 if ( $targetPage == Router
:: $PAGE_TOOLS )
1367 'linkcount' => count ( $LINKSDB ),
1368 'pageabsaddr' => index_url ( $_SERVER ),
1370 $pluginManager- > executeHooks ( 'render_tools' , $data );
1372 foreach ( $data as $key => $value ) {
1373 $PAGE- > assign ( $key , $value );
1376 $PAGE- > renderPage ( 'tools' );
1380 // -------- User wants to change his/her password.
1381 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1383 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1384 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1386 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1388 // Make sure old password is correct.
1389 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1390 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1391 // Save new password
1392 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1393 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1395 writeConfig ( $GLOBALS , isLoggedIn ());
1397 catch ( Exception
$e ) {
1399 'ERROR while writing config file after changing password.' . PHP_EOL
.
1403 // TODO: do not handle exceptions/errors in JS.
1404 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1407 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1410 else // show the change password form.
1412 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1413 $PAGE- > assign ( 'token' , getToken ());
1414 $PAGE- > renderPage ( 'changepassword' );
1419 // -------- User wants to change configuration
1420 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1422 if (! empty ( $_POST [ 'title' ]) )
1424 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1426 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1427 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1428 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1429 $GLOBALS [ 'timezone' ] = $tz ;
1430 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1431 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1432 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1433 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1434 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1435 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1436 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1437 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1439 writeConfig ( $GLOBALS , isLoggedIn ());
1441 catch ( Exception
$e ) {
1443 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1447 // TODO: do not handle exceptions/errors in JS.
1448 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1451 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1454 else // Show the configuration form.
1456 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1457 $PAGE- > assign ( 'token' , getToken ());
1458 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1459 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1460 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1461 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1462 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1463 $PAGE- > renderPage ( 'configure' );
1468 // -------- User wants to rename a tag or delete it
1469 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1471 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1472 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1473 $PAGE- > assign ( 'token' , getToken ());
1474 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1475 $PAGE- > renderPage ( 'changetag' );
1479 if (! tokenOk ( $_POST [ 'token' ])) {
1480 die ( 'Wrong token.' );
1484 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1485 $needle = trim ( $_POST [ 'fromtag' ]);
1486 // True for case-sensitive tag search.
1487 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1488 foreach ( $linksToAlter as $key => $value )
1490 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1491 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1492 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1493 $LINKSDB [ $key ]= $value ;
1495 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1496 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1501 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1502 $needle = trim ( $_POST [ 'fromtag' ]);
1503 // True for case-sensitive tag search.
1504 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1505 foreach ( $linksToAlter as $key => $value )
1507 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1508 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1509 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1510 $LINKSDB [ $key ]= $value ;
1512 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1513 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1518 // -------- User wants to add a link without using the bookmarklet: Show form.
1519 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1521 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1522 $PAGE- > renderPage ( 'addlink' );
1526 // -------- User clicked the "Save" button when editing a link: Save link to database.
1527 if ( isset ( $_POST [ 'save_edit' ]))
1530 if (! tokenOk ( $_POST [ 'token' ])) {
1531 die ( 'Wrong token.' );
1533 // Remove multiple spaces.
1534 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1535 // Remove duplicates.
1536 $tags = implode ( ' ' , array_unique ( explode ( ' ' , $tags )));
1537 $linkdate = $_POST [ 'lf_linkdate' ];
1538 $url = trim ( $_POST [ 'lf_url' ]);
1539 if (! startsWith ( $url , 'http:' ) && ! startsWith ( $url , 'https:' )
1540 && ! startsWith ( $url , 'ftp:' ) && ! startsWith ( $url , 'magnet:' )
1541 && ! startsWith ( $url , '?' ) && ! startsWith ( $url , 'javascript:' )
1543 $url = 'http://' . $url ;
1547 'title' => trim ( $_POST [ 'lf_title' ]),
1549 'description' => trim ( $_POST [ 'lf_description' ]),
1550 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1551 'linkdate' => $linkdate ,
1552 'tags' => str_replace ( ',' , ' ' , $tags )
1554 // If title is empty, use the URL as title.
1555 if ( $link [ 'title' ] == '' ) {
1556 $link [ 'title' ] = $link [ 'url' ];
1559 $pluginManager- > executeHooks ( 'save_link' , $link );
1561 $LINKSDB [ $linkdate ] = $link ;
1562 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1565 // If we are called from the bookmarklet, we must close the popup:
1566 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1567 echo '<script>self.close();</script>' ;
1571 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? escape ( $_POST [ 'returnurl' ]): '?' ;
1572 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1573 // Scroll to the link which has been edited.
1574 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1575 // After saving the link, redirect to the page the user was on.
1576 header ( 'Location: ' . $location );
1580 // -------- User clicked the "Cancel" button when editing a link.
1581 if ( isset ( $_POST [ 'cancel_edit' ]))
1583 // If we are called from the bookmarklet, we must close the popup:
1584 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1585 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1586 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1587 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1588 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1592 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1593 if ( isset ( $_POST [ 'delete_link' ]))
1595 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1596 // We do not need to ask for confirmation:
1597 // - confirmation is handled by JavaScript
1598 // - we are protected from XSRF by the token.
1599 $linkdate = $_POST [ 'lf_linkdate' ];
1601 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1603 unset ( $LINKSDB [ $linkdate ]);
1604 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
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 // Pick where we're going to redirect
1609 // =============================================================
1610 // Basically, we can't redirect to where we were previously if it was a permalink
1611 // or an edit_link, because it would 404.
1613 // - / : nothing in $_GET, redirect to self
1614 // - /?page : redirect to self
1615 // - /?searchterm : redirect to self (there might be other links)
1616 // - /?searchtags : redirect to self
1617 // - /permalink : redirect to / (the link does not exist anymore)
1618 // - /?edit_link : redirect to / (the link does not exist anymore)
1619 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1620 // redirect is not satisfied, and only then redirect to /
1623 if ( count ( $_GET ) == 0
1624 || isset ( $_GET [ 'page' ])
1625 || isset ( $_GET [ 'searchterm' ])
1626 || isset ( $_GET [ 'searchtags' ])
1628 if ( isset ( $_POST [ 'returnurl' ])) {
1629 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1631 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1635 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1639 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1640 if ( isset ( $_GET [ 'edit_link' ]))
1642 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1643 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1645 'linkcount' => count ( $LINKSDB ),
1647 'link_is_new' => false ,
1648 'token' => getToken (),
1649 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1650 'tags' => $LINKSDB- > allTags (),
1652 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1654 foreach ( $data as $key => $value ) {
1655 $PAGE- > assign ( $key , $value );
1658 $PAGE- > renderPage ( 'editlink' );
1662 // -------- User want to post a new link: Display link edit form.
1663 if ( isset ( $_GET [ 'post' ])) {
1664 $url = cleanup_url ( escape ( $_GET [ 'post' ]));
1666 $link_is_new = false ;
1667 // Check if URL is not already in database (in this case, we will edit the existing link)
1668 $link = $LINKSDB- > getLinkFromUrl ( $url );
1671 $link_is_new = true ;
1672 $linkdate = strval ( date ( 'Ymd_His' ));
1673 // Get title if it was provided in URL (by the bookmarklet).
1674 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1675 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1676 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1677 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1678 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1679 // 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.)
1680 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1681 // Short timeout to keep the application responsive
1682 list ( $headers , $content ) = get_http_response ( $url , 4 );
1683 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1684 // Retrieve charset.
1685 $charset = get_charset ( $headers , $content );
1687 $title = html_extract_title ( $content );
1688 // Re-encode title in utf-8 if necessary.
1689 if (! empty ( $title ) && $charset != 'utf-8' ) {
1690 $title = mb_convert_encoding ( $title , $charset , 'utf-8' );
1696 $url = '?' . smallHash ( $linkdate );
1701 'linkdate' => $linkdate ,
1704 'description' => $description ,
1706 'private' => $private
1711 'linkcount' => count ( $LINKSDB ),
1713 'link_is_new' => $link_is_new ,
1714 'token' => getToken (), // XSRF protection.
1715 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1716 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1717 'tags' => $LINKSDB- > allTags (),
1719 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1721 foreach ( $data as $key => $value ) {
1722 $PAGE- > assign ( $key , $value );
1725 $PAGE- > renderPage ( 'editlink' );
1729 // -------- Export as Netscape Bookmarks HTML file.
1730 if ( $targetPage == Router
:: $PAGE_EXPORT )
1732 if ( empty ( $_GET [ 'what' ]))
1734 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1735 $PAGE- > renderPage ( 'export' );
1738 $exportWhat = $_GET [ 'what' ];
1739 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1741 header ( 'Content-Type: text/html; charset=utf-8' );
1742 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1743 $currentdate = date ( 'Y/m/d H:i:s' );
1745 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1746 <!-- This is an automatically generated file.
1747 It will be read and overwritten.
1749 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1750 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1751 <TITLE>Bookmarks</TITLE>
1754 foreach ( $LINKSDB as $link )
1756 if ( $exportWhat == 'all' ||
1757 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1758 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1760 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1761 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1762 echo '>' . $link [ 'title' ]. "</A> \n " ;
1763 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1769 // -------- User is uploading a file for import
1770 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1772 // If file is too big, some form field may be missing.
1773 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1775 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1776 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>' ;
1779 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1784 // -------- Show upload/import dialog:
1785 if ( $targetPage == Router
:: $PAGE_IMPORT )
1787 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1788 $PAGE- > assign ( 'token' , getToken ());
1789 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1790 $PAGE- > renderPage ( 'import' );
1794 // Plugin administration page
1795 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1796 $pluginMeta = $pluginManager- > getPluginsMeta ();
1798 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1799 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1801 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1804 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1806 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1808 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1809 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1810 $PAGE- > renderPage ( 'pluginsadmin' );
1814 // Plugin administration form action
1815 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1817 if ( isset ( $_POST [ 'parameters_form' ])) {
1818 unset ( $_POST [ 'parameters_form' ]);
1819 foreach ( $_POST as $param => $value ) {
1820 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1824 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1826 writeConfig ( $GLOBALS , isLoggedIn ());
1828 catch ( Exception
$e ) {
1830 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1834 // TODO: do not handle exceptions/errors in JS.
1835 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=pluginsadmin \' ;</script>' ;
1838 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1842 // -------- Otherwise, simply display search form and links:
1843 showLinkList ( $PAGE , $LINKSDB );
1847 // -----------------------------------------------------------------------------------------------
1848 // Process the import file form.
1849 function importFile ()
1851 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1852 $LINKSDB = new LinkDB (
1853 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1855 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1856 $GLOBALS [ 'redirector' ]
1858 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1859 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1860 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1861 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1862 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1867 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1869 // Then import the bookmarks.
1870 if ( $type == 'netscape' )
1872 // This is a standard Netscape-style bookmark file.
1873 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1874 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1876 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1877 $d = explode ( '<DD>' , $html );
1878 if ( startswith ( $d [ 0 ], '<A ' ))
1880 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1881 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1882 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1883 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1885 foreach ( $matches as $m )
1887 $attr = $m [ 1 ]; $value = $m [ 2 ];
1888 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1889 elseif ( $attr == 'ADD_DATE' )
1891 $raw_add_date = intval ( $value );
1892 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1894 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1895 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1897 if ( $link [ 'url' ]!= '' )
1899 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1900 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1902 { // Link not in database, let's import it...
1903 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1905 // Make sure date/time is not already used by another link.
1906 // (Some bookmark files have several different links with the same ADD_DATE)
1907 // We increment date by 1 second until we find a date which is not used in DB.
1908 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1909 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1910 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1911 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1914 else // Link already present in database.
1917 { // If overwrite is required, we import link data, except date/time.
1918 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1919 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1927 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1929 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1933 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1937 // -----------------------------------------------------------------------------------------------
1938 // Template for the list of links (<div id="linklist">)
1939 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1940 function buildLinkList ( $PAGE , $LINKSDB )
1942 // ---- Filter link database according to parameters
1945 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]) ? true : false ;
1948 if ( isset ( $_GET [ 'searchterm' ])) {
1949 $search_crits = escape ( trim ( $_GET [ 'searchterm' ]));
1950 $search_type = LinkFilter
:: $FILTER_TEXT ;
1951 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits , false , $privateonly );
1954 elseif ( isset ( $_GET [ 'searchtags' ])) {
1955 $search_crits = explode ( ' ' , escape ( trim ( $_GET [ 'searchtags' ])));
1956 $search_type = LinkFilter
:: $FILTER_TAG ;
1957 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits , false , $privateonly );
1959 // Detect smallHashes in URL.
1960 elseif ( isset ( $_SERVER [ 'QUERY_STRING' ])
1961 && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])) {
1962 $search_type = LinkFilter
:: $FILTER_HASH ;
1963 $search_crits = substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 );
1964 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits );
1966 if ( count ( $linksToDisplay ) == 0 ) {
1967 $PAGE- > render404 ( 'The link you are trying to reach does not exist or has been deleted.' );
1971 // Otherwise, display without filtering.
1973 $linksToDisplay = $LINKSDB- > filter ( '' , '' , false , $privateonly );
1976 // ---- Handle paging.
1978 foreach ( $linksToDisplay as $key => $value ) {
1982 // If there is only a single link, we change on-the-fly the title of the page.
1983 if ( count ( $linksToDisplay ) == 1 ) {
1984 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1987 // Select articles according to paging.
1988 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1989 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1990 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1991 $page = $page < 1 ? 1 : $page ;
1992 $page = $page > $pagecount ? $pagecount : $page ;
1994 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1995 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1996 $linkDisp = array ();
1997 while ( $i < $end && $i < count ( $keys ))
1999 $link = $linksToDisplay [ $keys [ $i ]];
2000 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
2001 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
2002 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
2003 $link [ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
2004 $taglist = explode ( ' ' , $link [ 'tags' ]);
2005 uasort ( $taglist , 'strcasecmp' );
2006 $link [ 'taglist' ] = $taglist ;
2007 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
2008 // Check for both signs of a note: starting with ? and 7 chars long.
2009 if ( $link [ 'url' ][ 0 ] === '?' &&
2010 strlen ( $link [ 'url' ]) === 7 ) {
2011 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
2014 $linkDisp [ $keys [ $i ]] = $link ;
2018 // Compute paging navigation
2019 $searchterm = empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ];
2020 $searchtags = empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ];
2021 $previous_page_url = '' ;
2022 if ( $i != count ( $keys )) {
2023 $previous_page_url = '?page=' . ( $page +
1 ) . $searchterm . $searchtags ;
2027 $next_page_url = '?page=' . ( $page-1 ) . $searchterm . $searchtags ;
2032 $token = getToken ();
2035 // Fill all template fields.
2037 'linkcount' => count ( $LINKSDB ),
2038 'previous_page_url' => $previous_page_url ,
2039 'next_page_url' => $next_page_url ,
2040 'page_current' => $page ,
2041 'page_max' => $pagecount ,
2042 'result_count' => count ( $linksToDisplay ),
2043 'search_type' => $search_type ,
2044 'search_crits' => $search_crits ,
2045 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
2047 'links' => $linkDisp ,
2048 'tags' => $LINKSDB- > allTags (),
2050 // FIXME! temporary fix - see #399.
2051 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
2052 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
2055 $pluginManager = PluginManager
:: getInstance ();
2056 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
2058 foreach ( $data as $key => $value ) {
2059 $PAGE- > assign ( $key , $value );
2065 // Compute the thumbnail for a link.
2067 // With a link to the original URL.
2068 // Understands various services (youtube.com...)
2069 // Input: $url = URL for which the thumbnail must be found.
2070 // $href = if provided, this URL will be followed instead of $url
2071 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
2072 // Some of them may be missing.
2073 // Return an empty array if no thumbnail available.
2074 function computeThumbnail ( $url , $href = false )
2076 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
2077 if ( $href == false ) $href = $url ;
2079 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
2080 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
2081 // ^^^^^^^^^^^ ^^^^^^^^^^^
2082 $domain = parse_url ( $url , PHP_URL_HOST
);
2083 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
2085 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
2086 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
2087 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2089 if ( $domain == 'youtu.be' ) // Youtube short links
2091 $path = parse_url ( $url , PHP_URL_PATH
);
2092 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
2093 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2095 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
2097 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
2098 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
2099 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
2102 if ( $domain == 'imgur.com' )
2104 $path = parse_url ( $url , PHP_URL_PATH
);
2105 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2106 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2107 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2108 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2109 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2111 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2112 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2114 if ( $domain == 'i.imgur.com' )
2116 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2117 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2118 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2120 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2122 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2124 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2125 return array ( 'src' => $thumburl ,
2126 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2129 if ( endsWith ( $domain , '.imageshack.us' ))
2131 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2132 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2134 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2135 return array ( 'src' => $thumburl ,
2136 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2140 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2141 // So we deport the thumbnail generation in order not to slow down page generation
2142 // (and we also cache the thumbnail)
2144 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2146 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2147 || $domain == 'vimeo.com'
2148 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2149 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2152 if ( $domain == 'vimeo.com' )
2153 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2154 $path = parse_url ( $url , PHP_URL_PATH
);
2155 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2157 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2158 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2159 $path = parse_url ( $url , PHP_URL_PATH
);
2160 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2162 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2163 { // Make sure this TED URL points to a video (/talks/...)
2164 $path = parse_url ( $url , PHP_URL_PATH
);
2165 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2167 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2168 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2169 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2172 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2173 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2174 // But using the extension will do.
2175 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2176 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2178 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2179 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2180 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2182 return array (); // No thumbnail.
2187 // Returns the HTML code to display a thumbnail for a link
2188 // with a link to the original URL.
2189 // Understands various services (youtube.com...)
2190 // Input: $url = URL for which the thumbnail must be found.
2191 // $href = if provided, this URL will be followed instead of $url
2192 // Returns '' if no thumbnail available.
2193 function thumbnail ( $url , $href = false )
2195 $t = computeThumbnail ( $url , $href );
2196 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2198 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2199 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2200 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2201 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2202 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2207 // Returns the HTML code to display a thumbnail for a link
2208 // for the picture wall (using lazy image loading)
2209 // Understands various services (youtube.com...)
2210 // Input: $url = URL for which the thumbnail must be found.
2211 // $href = if provided, this URL will be followed instead of $url
2212 // Returns '' if no thumbnail available.
2213 function lazyThumbnail ( $url , $href = false )
2215 $t = computeThumbnail ( $url , $href );
2216 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2218 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2221 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2223 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2224 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2225 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2226 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2229 // No-JavaScript fallback.
2230 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2231 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2232 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2233 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2234 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2235 $html .= '></noscript></a>' ;
2241 // -----------------------------------------------------------------------------------------------
2243 // This function should NEVER be called if the file data/config.php exists.
2246 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2247 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2250 // This part makes sure sessions works correctly.
2251 // (Because on some hosts, session.save_path may not be set correctly,
2252 // or we may not have write access to it.)
2253 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2254 { // Step 2: Check if data in session is correct.
2255 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2256 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2257 echo 'It currently points to ' . session_save_path (). '<br>' ;
2258 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>' ;
2259 echo '<br><a href="?">Click to try again.</a></pre>' ;
2262 if (! isset ( $_SESSION [ 'session_tested' ]))
2263 { // Step 1 : Try to store data in session and reload page.
2264 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2265 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2267 if ( isset ( $_GET [ 'test_session' ]))
2268 { // Step 3: Sessions are OK. Remove test parameter from URL.
2269 header ( 'Location: ' . index_url ( $_SERVER ));
2273 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2276 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2277 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2278 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2281 $GLOBALS [ 'timezone' ] = $tz ;
2282 // Everything is ok, let's create config file.
2283 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2284 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2285 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2286 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2287 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2289 writeConfig ( $GLOBALS , isLoggedIn ());
2291 catch ( Exception
$e ) {
2293 'ERROR while writing config file after installation.' . PHP_EOL
.
2297 // TODO: do not handle exceptions/errors in JS.
2298 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2301 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2305 // Display config form:
2306 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2307 $timezone_html = '' ;
2308 if ( $timezone_form != '' ) {
2309 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2312 $PAGE = new pageBuilder
;
2313 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2314 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2315 $PAGE- > renderPage ( 'install' );
2319 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2320 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2321 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2322 This function is called by passing the URL:
2323 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2324 [URL] is the URL of the link (e.g. a flickr page)
2325 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2326 The function below will fetch the image from the webservice and store it in the cache.
2328 function genThumbnail ()
2330 // Make sure the parameters in the URL were generated by us.
2331 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2332 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2334 // Let's see if we don't already have the image for this URL in the cache.
2335 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2336 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2337 { // We have the thumbnail, just serve it:
2338 header ( 'Content-Type: image/jpeg' );
2339 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2342 // We may also serve a blank image (if service did not respond)
2343 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2344 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2346 header ( 'Content-Type: image/gif' );
2347 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2351 // Otherwise, generate the thumbnail.
2352 $url = $_GET [ 'url' ];
2353 $domain = parse_url ( $url , PHP_URL_HOST
);
2355 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2357 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2358 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2360 // Is this a link to an image, or to a flickr page ?
2362 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2363 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2364 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2365 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2367 else // This is a flickr page (html)
2369 // Get the flickr html page.
2370 list ( $headers , $content ) = get_http_response ( $url , 20 );
2371 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2373 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2374 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2375 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2377 // In albums (and some other pages), the link rel="image_src" is not provided,
2378 // but flickr provides:
2379 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2382 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2383 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2389 { // Let's download the image.
2390 // Image is 240x120, so 10 seconds to download should be enough.
2391 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2392 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2393 // Save image to cache.
2394 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2395 header ( 'Content-Type: image/jpeg' );
2402 elseif ( $domain == 'vimeo.com' )
2404 // This is more complex: we have to perform a HTTP request, then parse the result.
2405 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2406 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2407 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2408 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2409 $t = unserialize ( $content );
2410 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2411 // Then we download the image and serve it to our client.
2412 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2413 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2414 // Save image to cache.
2415 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2416 header ( 'Content-Type: image/jpeg' );
2423 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2425 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2426 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2427 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2428 list ( $headers , $content ) = get_http_response ( $url , 5 );
2429 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2430 // Extract the link to the thumbnail
2431 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2432 if (! empty ( $matches [ 1 ]))
2433 { // Let's download the image.
2434 $imageurl = $matches [ 1 ];
2435 // No control on image size, so wait long enough
2436 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2437 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2438 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2439 file_put_contents ( $filepath , $content ); // Save image to cache.
2440 if ( resizeImage ( $filepath ))
2442 header ( 'Content-Type: image/jpeg' );
2443 echo file_get_contents ( $filepath );
2451 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2453 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2454 // http://xkcd.com/327/
2455 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2456 list ( $headers , $content ) = get_http_response ( $url , 5 );
2457 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2458 // Extract the link to the thumbnail
2459 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2460 if (! empty ( $matches [ 1 ]))
2461 { // Let's download the image.
2462 $imageurl = $matches [ 1 ];
2463 // No control on image size, so wait long enough
2464 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2465 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2466 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2467 // Save image to cache.
2468 file_put_contents ( $filepath , $content );
2469 if ( resizeImage ( $filepath ))
2471 header ( 'Content-Type: image/jpeg' );
2472 echo file_get_contents ( $filepath );
2482 // For all other domains, we try to download the image and make a thumbnail.
2483 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2484 list ( $headers , $content ) = get_http_response ( $url , 30 );
2485 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2486 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2487 // Save image to cache.
2488 file_put_contents ( $filepath , $content );
2489 if ( resizeImage ( $filepath ))
2491 header ( 'Content-Type: image/jpeg' );
2492 echo file_get_contents ( $filepath );
2499 // Otherwise, return an empty image (8x8 transparent gif)
2500 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2501 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2502 header ( 'Content-Type: image/gif' );
2506 // Make a thumbnail of the image (to width: 120 pixels)
2507 // Returns true if success, false otherwise.
2508 function resizeImage ( $filepath )
2510 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2512 // Trick: some stupid people rename GIF as JPEG... or else.
2513 // So we really try to open each image type whatever the extension is.
2514 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2516 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2517 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2518 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2519 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2522 $ystart = 0 ; $yheight = $h ;
2523 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2524 $nw = 120 ; // Desired width
2525 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2527 $im2 = imagecreatetruecolor ( $nw , $nh );
2528 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2529 imageinterlace ( $im2 , true ); // For progressive JPEG.
2530 $tempname = $filepath . '_TEMP.jpg' ;
2531 imagejpeg ( $im2 , $tempname , 90 );
2535 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2540 mergeDeprecatedConfig ( $GLOBALS , isLoggedIn ());
2541 } catch ( Exception
$e ) {
2543 'ERROR while merging deprecated options.php file.' . PHP_EOL
.
2548 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2549 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2550 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2551 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2552 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];