]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.3 - Shaare your links...
5 * The personal, minimalist, super-fast, no-database Delicious clone.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
25 /* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
33 * Shaarli directories & configuration files
36 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ;
38 // Main configuration file
39 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ;
42 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ;
45 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ;
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 // Set ENABLE_UPDATECHECK to disabled by default.
54 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = false ;
56 // RainTPL cache directory (keep the trailing slash!)
57 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
58 // Raintpl template directory (keep the trailing slash!)
59 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
61 // Thumbnail cache directory
62 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
64 // Atom & RSS feed cache directory
65 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
69 * Global configuration
71 // Ban IP after this many failures
72 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
73 // Ban duration for IP address after login failures (in seconds)
74 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
77 // Enable RSS permalinks by default.
78 // This corresponds to the default behavior of shaarli before this was added as an option.
79 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
80 // If true, an extra "ATOM feed" button will be displayed in the toolbar
81 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
83 // Link display options
84 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
85 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
86 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
88 // Open Shaarli (true): anyone can add/edit/delete links without having to login
89 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
92 // Display thumbnails in links
93 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
94 // Store thumbnails in a local cache
95 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
97 // Update check frequency for Shaarli. 86400 seconds=24 hours
98 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ] = 'stable' ;
99 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
103 * Plugin configuration
105 * Warning: order matters!
107 * These settings may be be overriden in:
109 * - each plugin's configuration file
111 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
112 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
113 // 'wallabag', 'markdown', 'addlink_toolbar',
115 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
117 // Initialize plugin parameters array.
118 $GLOBALS [ 'plugins' ] = array ();
120 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
121 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
126 define ( 'shaarli_version' , '0.6.3' );
128 // http://server.com/x/shaarli --> /shaarli/
129 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
131 // High execution time in case of problematic imports/exports.
132 ini_set ( 'max_input_time' , '60' );
134 // Try to set max upload file size and read
135 ini_set ( 'memory_limit' , '128M' );
136 ini_set ( 'post_max_size' , '16M' );
137 ini_set ( 'upload_max_filesize' , '16M' );
139 // See all error except warnings
140 error_reporting ( E_ALL^E_WARNING
);
141 // See all errors (for debugging only)
142 //error_reporting(-1);
147 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
148 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
152 require_once 'application/ApplicationUtils.php' ;
153 require_once 'application/Cache.php' ;
154 require_once 'application/CachedPage.php' ;
155 require_once 'application/FileUtils.php' ;
156 require_once 'application/HttpUtils.php' ;
157 require_once 'application/LinkDB.php' ;
158 require_once 'application/LinkFilter.php' ;
159 require_once 'application/LinkUtils.php' ;
160 require_once 'application/TimeZone.php' ;
161 require_once 'application/Url.php' ;
162 require_once 'application/Utils.php' ;
163 require_once 'application/Config.php' ;
164 require_once 'application/PluginManager.php' ;
165 require_once 'application/Router.php' ;
167 // Ensure the PHP version is supported
169 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
170 } catch ( Exception
$exc ) {
171 header ( 'Content-Type: text/plain; charset=utf-8' );
172 echo $exc- > getMessage ();
176 // Force cookie path (but do not change lifetime)
177 $cookie = session_get_cookie_params ();
179 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
180 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
182 // Set default cookie expiration and path.
183 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
184 // Set session parameters on server side.
185 // If the user does not access any page within this time, his/her session is considered expired.
186 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
187 // Use cookies to store session.
188 ini_set ( 'session.use_cookies' , 1 );
189 // Force cookies for session (phpsessionID forbidden in URL).
190 ini_set ( 'session.use_only_cookies' , 1 );
191 // Prevent PHP form using sessionID in URL if cookies are disabled.
192 ini_set ( 'session.use_trans_sid' , false );
194 session_name ( 'shaarli' );
195 // Start session if needed (Some server auto-start sessions).
196 if ( session_id () == '' ) {
200 // Regenerate session ID if invalid or not defined in cookie.
201 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
202 session_regenerate_id ( true );
203 $_COOKIE [ 'shaarli' ] = session_id ();
206 include "inc/rain.tpl.class.php" ; //include Rain TPL
207 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
208 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
210 $pluginManager = PluginManager
:: getInstance ();
211 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
213 ob_start (); // Output buffering for the page cache.
216 // In case stupid admin has left magic_quotes enabled in php.ini:
217 if ( get_magic_quotes_gpc ())
219 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
220 $_POST = array_map ( 'stripslashes_deep' , $_POST );
221 $_GET = array_map ( 'stripslashes_deep' , $_GET );
222 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
225 // Prevent caching on client side or proxy: (yes, it's ugly)
226 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
227 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
228 header ( "Cache-Control: post-check=0, pre-check=0" , false );
229 header ( "Pragma: no-cache" );
231 // Handling of old config file which do not have the new parameters.
232 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
233 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
234 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
235 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
236 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
237 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
238 // I really need to rewrite Shaarli with a proper configuation manager.
240 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
241 // Ensure Shaarli has proper access to its resources
242 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
244 if ( $errors != array ()) {
245 $message = '<p>Insufficient permissions:</p><ul>' ;
247 foreach ( $errors as $error ) {
248 $message .= '<li>' . $error . '</li>' ;
252 header ( 'Content-Type: text/html; charset=utf-8' );
257 // Display the installation form if no existing config is found
261 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
262 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
263 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
265 // a token depending of deployment salt, user password, and the current ip
266 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
268 autoLocale (); // Sniff browser language and set date format accordingly.
269 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
271 //==================================================================================================
272 // Checking session state (i.e. is the user still logged in)
273 //==================================================================================================
275 function setup_login_state () {
276 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
279 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
280 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
281 if (! isset ( $GLOBALS [ 'login' ])) {
282 $userIsLoggedIn = false ; // Shaarli is not configured yet.
283 $loginFailure = true ;
285 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
286 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
290 $userIsLoggedIn = true ;
292 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
293 if ( empty ( $_SESSION [ 'uid' ]) ||
294 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
295 time () >= $_SESSION [ 'expires_on' ])
298 $userIsLoggedIn = false ;
299 $loginFailure = true ;
301 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
302 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
305 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
307 if (! $loginFailure ) {
308 $userIsLoggedIn = true ;
311 return $userIsLoggedIn ;
313 $userIsLoggedIn = setup_login_state ();
316 // ------------------------------------------------------------------------------------------
317 // Sniff browser language to display dates in the right format automatically.
318 // (Note that is may not work on your server if the corresponding local is not installed.)
319 function autoLocale ()
321 $attempts = array ( 'en_US' ); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
322 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
323 { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
324 if ( preg_match ( '/([a-z] {2} )-?([a-z] {2} )?/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) {
325 $loc = $matches [ 1 ] . (! empty ( $matches [ 2 ]) ? '_' . strtoupper ( $matches [ 2 ]) : '' );
326 $attempts = array ( $loc . '.UTF-8' , $loc , str_replace ( '_' , '-' , $loc ). '.UTF-8' , str_replace ( '_' , '-' , $loc ),
327 $loc . '_' . strtoupper ( $loc ). '.UTF-8' , $loc . '_' . strtoupper ( $loc ),
328 $loc . '_' . $loc . '.UTF-8' , $loc . '_' . $loc , $loc . '-' . strtoupper ( $loc ). '.UTF-8' ,
329 $loc . '-' . strtoupper ( $loc ), $loc . '-' . $loc . '.UTF-8' , $loc . '-' . $loc );
332 setlocale ( LC_TIME
, $attempts ); // LC_TIME = Set local for date/time format only.
335 // ------------------------------------------------------------------------------------------
336 // PubSubHubbub protocol support (if enabled) [UNTESTED]
337 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
338 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
341 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
343 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
345 index_url ( $_SERVER ). '?do=atom' ,
346 index_url ( $_SERVER ). '?do=rss'
348 $p- > publish_update ( $topic_url );
352 // ------------------------------------------------------------------------------------------
353 // Session management
355 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
358 $ip = $_SERVER [ "REMOTE_ADDR" ];
359 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
360 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
361 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
365 function fillSessionInfo () {
366 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
367 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
368 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
369 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
372 // Check that user/password is correct.
373 function check_auth ( $login , $password )
375 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
376 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
377 { // Login/password is correct.
379 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
382 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
386 // Returns true if the user is logged in.
387 function isLoggedIn ()
389 global $userIsLoggedIn ;
390 return $userIsLoggedIn ;
395 if ( isset ( $_SESSION )) {
396 unset ( $_SESSION [ 'uid' ]);
397 unset ( $_SESSION [ 'ip' ]);
398 unset ( $_SESSION [ 'username' ]);
399 unset ( $_SESSION [ 'privateonly' ]);
401 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
405 // ------------------------------------------------------------------------------------------
406 // Brute force protection system
407 // Several consecutive failed logins will ban the IP address for 30 minutes.
408 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 ?>" );
409 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
410 // Signal a failed login. Will ban the IP if too many failures:
411 function ban_loginFailed ()
413 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
414 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
415 $gb [ 'FAILURES' ][ $ip ] ++
;
416 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
418 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
419 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
421 $GLOBALS [ 'IPBANS' ] = $gb ;
422 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
425 // Signals a successful login. Resets failed login counter.
426 function ban_loginOk ()
428 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
429 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
430 $GLOBALS [ 'IPBANS' ] = $gb ;
431 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
434 // Checks if the user CAN login. If 'true', the user can try to login.
435 function ban_canLogin ()
437 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
438 if ( isset ( $gb [ 'BANS' ][ $ip ]))
440 // User is banned. Check if the ban has expired:
441 if ( $gb [ 'BANS' ][ $ip ]<= time ())
442 { // Ban expired, user can try to login again.
443 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
444 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
445 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
446 return true ; // Ban has expired, user can login.
448 return false ; // User is banned.
450 return true ; // User is not banned.
453 // ------------------------------------------------------------------------------------------
454 // Process login form: Check if login/password is correct.
455 if ( isset ( $_POST [ 'login' ]))
457 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
458 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
459 { // Login/password is OK.
461 // If user wants to keep the session cookie even after the browser closes:
462 if (! empty ( $_POST [ 'longlastingsession' ]))
464 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
465 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
466 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
468 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
469 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
470 // Note: Never forget the trailing slash on the cookie path!
471 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
473 else // Standard session expiration (=when browser closes)
475 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
476 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
477 session_regenerate_id ( true );
480 // Optional redirect after login:
481 if ( isset ( $_GET [ 'post' ])) {
482 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
483 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
484 if (! empty ( $_GET [ $param ])) {
485 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
488 header ( 'Location: ' . $uri );
492 if ( isset ( $_GET [ 'edit_link' ])) {
493 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
497 if ( isset ( $_POST [ 'returnurl' ])) {
498 // Prevent loops over login screen.
499 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
500 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
504 header ( 'Location: ?' ); exit ;
510 if ( isset ( $_GET [ 'post' ])) {
511 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
512 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
513 if (! empty ( $_GET [ $param ])) {
514 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
518 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
523 // ------------------------------------------------------------------------------------------
524 // Misc utility functions:
526 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
527 function return_bytes ( $val )
529 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
532 case 'g' : $val *= 1024 ;
533 case 'm' : $val *= 1024 ;
534 case 'k' : $val *= 1024 ;
539 // Try to determine max file size for uploads (POST).
540 // Returns an integer (in bytes)
541 function getMaxFileSize ()
543 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
544 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
545 // Return the smaller of two:
546 $maxsize = min ( $size1 , $size2 );
547 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
551 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
552 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
553 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
554 function linkdate2timestamp ( $linkdate )
556 if ( strcmp ( $linkdate , '_000000' ) !== 0 || ! $linkdate ){
558 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
559 return mktime ( $h , $m , $s , $M , $D , $Y );
564 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
565 (used to build the pubDate attribute in RSS feed.) */
566 function linkdate2rfc822 ( $linkdate )
568 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
571 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
572 (used to build the updated tags in ATOM feed.) */
573 function linkdate2iso8601 ( $linkdate )
575 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
578 // ------------------------------------------------------------------------------------------
579 // Token management for XSRF protection
580 // Token should be used in any form which acts on data (create,update,delete,import...).
581 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
586 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
587 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
591 // Tells if a token is OK. Using this function will destroy the token.
593 function tokenOk ( $token )
595 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
597 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
598 return true ; // Token is OK.
600 return false ; // Wrong token, or already used.
603 // ------------------------------------------------------------------------------------------
604 /* This class is in charge of building the final page.
605 (This is basically a wrapper around RainTPL which pre-fills some fields.)
607 p.assign('myfield','myvalue');
608 p.renderPage('mytemplate');
613 private $tpl ; // RainTPL template
615 function __construct ()
621 * Initialize all default tpl tags.
623 private function initialize ()
625 $this- > tpl
= new RainTPL
;
628 $version = ApplicationUtils
:: checkUpdate (
630 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
631 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
632 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
634 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
636 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
637 $this- > tpl
-> assign ( 'versionError' , '' );
639 } catch ( Exception
$exc ) {
640 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
641 $this- > tpl
-> assign ( 'newVersion' , '' );
642 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
645 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
646 $searchcrits = '' ; // Search criteria
647 if (! empty ( $_GET [ 'searchtags' ])) {
648 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
650 elseif (! empty ( $_GET [ 'searchterm' ])) {
651 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
653 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
654 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
655 $this- > tpl
-> assign ( 'version' , shaarli_version
);
656 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
657 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
658 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
659 if (! empty ( $GLOBALS [ 'title' ])) {
660 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
662 if (! empty ( $GLOBALS [ 'titleLink' ])) {
663 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
665 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
666 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
668 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
669 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
670 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
674 // The following assign() method is basically the same as RainTPL (except that it's lazy)
675 public function assign ( $what , $where )
677 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
678 $this- > tpl
-> assign ( $what , $where );
681 // Render a specific page (using a template).
682 // e.g. pb.renderPage('picwall')
683 public function renderPage ( $page )
685 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
686 $this- > tpl
-> draw ( $page );
690 * Render a 404 page (uses the template : tpl/404.tpl)
692 * usage : $PAGE->render404('The link was deleted')
693 * @param string $message A messate to display what is not found
695 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
696 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
697 $this- > tpl
-> assign ( 'error_message' , $message );
698 $this- > renderPage ( '404' );
702 // ------------------------------------------------------------------------------------------
703 // Output the last N links in RSS 2.0 format.
706 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
708 // $usepermalink : If true, use permalink instead of final link.
709 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
710 // Also enabled through a config option
711 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
714 $query = $_SERVER [ "QUERY_STRING" ];
715 $cache = new CachedPage (
716 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
718 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
720 $cached = $cache- > cachedVersion ();
721 if (! empty ( $cached )) {
726 // If cached was not found (or not usable), then read the database and build the response:
727 $LINKSDB = new LinkDB (
728 $GLOBALS [ 'config' ][ 'DATASTORE' ],
730 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
731 $GLOBALS [ 'redirector' ]
733 // Read links from database (and filter private links if user it not logged in).
735 // Optionally filter the results:
736 if (! empty ( $_GET [ 'searchterm' ])) {
737 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
739 elseif (! empty ( $_GET [ 'searchtags' ])) {
740 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
743 $linksToDisplay = $LINKSDB ;
746 $nblinksToDisplay = 50 ; // Number of links to display.
747 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
748 if (! empty ( $_GET [ 'nb' ])) {
749 $nblinksToDisplay = $_GET [ 'nb' ] == 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
752 $pageaddr = escape ( index_url ( $_SERVER ));
753 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
754 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
755 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
756 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
758 echo '<!-- PubSubHubbub Discovery -->' ;
759 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
760 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
761 echo '<!-- End Of PubSubHubbub Discovery -->' ;
764 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
765 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
767 $link = $linksToDisplay [ $keys [ $i ]];
768 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
769 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
770 $absurl = $link [ 'url' ];
771 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
772 if ( $usepermalinks === true )
773 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
775 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
776 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . escape ( $rfc822date ). "</pubDate> \n " ;
777 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
779 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
782 // Add permalink in description
783 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
784 // If user wants permalinks first, put the final link in description
785 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
786 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
787 echo '<description><![CDATA[' .
788 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
789 $descriptionlink . ']]></description>' . " \n </item> \n " ;
792 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
794 $cache- > cache ( ob_get_contents ());
799 // ------------------------------------------------------------------------------------------
800 // Output the last N links in ATOM format.
803 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
805 // $usepermalink : If true, use permalink instead of final link.
806 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
807 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
810 $query = $_SERVER [ "QUERY_STRING" ];
811 $cache = new CachedPage (
812 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
814 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
816 $cached = $cache- > cachedVersion ();
817 if (! empty ( $cached )) {
822 // If cached was not found (or not usable), then read the database and build the response:
823 // Read links from database (and filter private links if used it not logged in).
824 $LINKSDB = new LinkDB (
825 $GLOBALS [ 'config' ][ 'DATASTORE' ],
827 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
828 $GLOBALS [ 'redirector' ]
831 // Optionally filter the results:
832 if (! empty ( $_GET [ 'searchterm' ])) {
833 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
835 else if (! empty ( $_GET [ 'searchtags' ])) {
836 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
839 $linksToDisplay = $LINKSDB ;
842 $nblinksToDisplay = 50 ; // Number of links to display.
843 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
844 if (! empty ( $_GET [ 'nb' ])) {
845 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( intval ( $_GET [ 'nb' ]), 1 );
848 $pageaddr = escape ( index_url ( $_SERVER ));
852 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
853 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
855 $link = $linksToDisplay [ $keys [ $i ]];
856 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
857 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
858 $latestDate = max ( $latestDate , $iso8601date );
859 $absurl = $link [ 'url' ];
860 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
861 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
862 if ( $usepermalinks === true )
863 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
865 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
866 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
868 // Add permalink in description
869 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
870 // If user wants permalinks first, put the final link in description
871 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
872 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
874 $entries .= '<content type="html"><![CDATA[' .
875 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
876 $descriptionlink . "]]></content> \n " ;
877 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
879 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
880 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
882 $entries .= "</entry> \n " ;
885 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
886 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
887 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
888 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
889 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
891 $feed .= '<!-- PubSubHubbub Discovery -->' ;
892 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
893 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
895 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
896 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
898 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
901 $cache- > cache ( ob_get_contents ());
906 // ------------------------------------------------------------------------------------------
907 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
908 // Gives the last 7 days (which have links).
909 // This RSS feed cannot be filtered.
910 function showDailyRSS () {
912 $query = $_SERVER [ "QUERY_STRING" ];
913 $cache = new CachedPage (
914 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
916 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
918 $cached = $cache- > cachedVersion ();
919 if (! empty ( $cached )) {
924 // If cached was not found (or not usable), then read the database and build the response:
925 // Read links from database (and filter private links if used it not logged in).
926 $LINKSDB = new LinkDB (
927 $GLOBALS [ 'config' ][ 'DATASTORE' ],
929 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
930 $GLOBALS [ 'redirector' ]
933 /* Some Shaarlies may have very few links, so we need to look
934 back in time (rsort()) until we have enough days ($nb_of_days).
936 $linkdates = array ();
937 foreach ( $LINKSDB as $linkdate => $value ) {
938 $linkdates [] = $linkdate ;
941 $nb_of_days = 7 ; // We take 7 days.
942 $today = Date ( 'Ymd' );
945 foreach ( $linkdates as $linkdate ) {
946 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
947 if ( strcmp ( $day , $today ) < 0 ) {
948 if ( empty ( $days [ $day ])) {
949 $days [ $day ] = array ();
951 $days [ $day ][] = $linkdate ;
954 if ( count ( $days ) > $nb_of_days ) {
955 break ; // Have we collected enough days?
959 // Build the RSS feed.
960 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
961 $pageaddr = escape ( index_url ( $_SERVER ));
962 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
964 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
965 echo '<link>' . $pageaddr . '</link>' ;
966 echo '<description>Daily shared links</description>' ;
967 echo '<language>en-en</language>' ;
968 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
971 foreach ( $days as $day => $linkdates ) {
972 $daydate = linkdate2timestamp ( $day . '_000000' ); // Full text date
973 $rfc822date = linkdate2rfc822 ( $day . '_000000' );
974 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
976 // Build the HTML body of this RSS entry.
981 // We pre-format some fields for proper output.
982 foreach ( $linkdates as $linkdate ) {
983 $l = $LINKSDB [ $linkdate ];
984 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
985 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
986 $l [ 'timestamp' ] = linkdate2timestamp ( $l [ 'linkdate' ]);
987 if ( startsWith ( $l [ 'url' ], '?' )) {
988 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
990 $links [ $linkdate ] = $l ;
993 // Then build the HTML for this day:
995 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
996 $tpl- > assign ( 'daydate' , $daydate );
997 $tpl- > assign ( 'absurl' , $absurl );
998 $tpl- > assign ( 'links' , $links );
999 $tpl- > assign ( 'rfc822date' , escape ( $rfc822date ));
1000 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
1002 echo $html . PHP_EOL
;
1004 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
1006 $cache- > cache ( ob_get_contents ());
1012 * Show the 'Daily' page.
1014 * @param PageBuilder $pageBuilder Template engine wrapper.
1016 function showDaily ( $pageBuilder )
1018 $LINKSDB = new LinkDB (
1019 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1021 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1022 $GLOBALS [ 'redirector' ]
1025 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1026 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1028 $days = $LINKSDB- > days ();
1029 $i = array_search ( $day , $days );
1030 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1035 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1036 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1040 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_DAY , $day );
1041 } catch ( Exception
$exc ) {
1043 $linksToDisplay = array ();
1046 // We pre-format some fields for proper output.
1047 foreach ( $linksToDisplay as $key => $link )
1050 $taglist = explode ( ' ' , $link [ 'tags' ]);
1051 uasort ( $taglist , 'strcasecmp' );
1052 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1053 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1054 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1055 $linksToDisplay [ $key ][ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
1058 /* We need to spread the articles on 3 columns.
1059 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1060 so I manually spread entries with a simple method: I roughly evaluate the
1061 height of a div according to title and description length.
1063 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1064 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1065 foreach ( $linksToDisplay as $key => $link )
1067 // Roughly estimate length of entry (by counting characters)
1068 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1069 // Description: 836 characters gives roughly 342 pixel height.
1070 // This is not perfect, but it's usually OK.
1071 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1072 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1073 // Then put in column which is the less filled:
1074 $smallest = min ( $fill ); // find smallest value in array.
1075 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1076 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1077 $fill [ $index ] +
= $length ;
1081 'linksToDisplay' => $linksToDisplay ,
1082 'linkcount' => count ( $LINKSDB ),
1084 'day' => linkdate2timestamp ( $day . '_000000' ),
1085 'previousday' => $previousday ,
1086 'nextday' => $nextday ,
1088 $pluginManager = PluginManager
:: getInstance ();
1089 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1091 foreach ( $data as $key => $value ) {
1092 $pageBuilder- > assign ( $key , $value );
1095 $pageBuilder- > renderPage ( 'daily' );
1099 // Renders the linklist
1100 function showLinkList ( $PAGE , $LINKSDB ) {
1101 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1102 $PAGE- > renderPage ( 'linklist' );
1106 // ------------------------------------------------------------------------------------------
1107 // Render HTML page (according to URL parameters and user rights)
1108 function renderPage ()
1110 $LINKSDB = new LinkDB (
1111 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1113 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1114 $GLOBALS [ 'redirector' ]
1117 $PAGE = new pageBuilder
;
1119 // Determine which page will be rendered.
1120 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1121 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1123 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1124 // Then assign generated data to RainTPL.
1125 $common_hooks = array (
1130 $pluginManager = PluginManager
:: getInstance ();
1131 foreach ( $common_hooks as $name ) {
1132 $plugin_data = array ();
1133 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1135 'target' => $targetPage ,
1136 'loggedin' => isLoggedIn ()
1139 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1142 // -------- Display login form.
1143 if ( $targetPage == Router
:: $PAGE_LOGIN )
1145 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1146 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1147 $PAGE- > assign ( 'token' , $token );
1148 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1149 $PAGE- > renderPage ( 'loginform' );
1152 // -------- User wants to logout.
1153 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1155 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1157 header ( 'Location: ?' );
1161 // -------- Picture wall
1162 if ( $targetPage == Router
:: $PAGE_PICWALL )
1164 // Optionally filter the results:
1165 if (! empty ( $_GET [ 'searchterm' ])) {
1166 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $_GET [ 'searchterm' ]);
1168 elseif (! empty ( $_GET [ 'searchtags' ])) {
1169 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , trim ( $_GET [ 'searchtags' ]));
1175 $linksToDisplay = array ();
1177 // Get only links which have a thumbnail.
1178 foreach ( $links as $link )
1180 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1181 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1182 if ( $thumb != '' ) // Only output links which have a thumbnail.
1184 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1185 $linksToDisplay []= $link ; // Add to array.
1190 'linkcount' => count ( $LINKSDB ),
1191 'linksToDisplay' => $linksToDisplay ,
1193 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1195 foreach ( $data as $key => $value ) {
1196 $PAGE- > assign ( $key , $value );
1199 $PAGE- > renderPage ( 'picwall' );
1203 // -------- Tag cloud
1204 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1206 $tags = $LINKSDB- > allTags ();
1208 // We sort tags alphabetically, then choose a font size according to count.
1209 // First, find max value.
1210 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
1213 foreach ( $tags as $key => $value )
1214 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1216 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1220 'linkcount' => count ( $LINKSDB ),
1223 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1225 foreach ( $data as $key => $value ) {
1226 $PAGE- > assign ( $key , $value );
1229 $PAGE- > renderPage ( 'tagcloud' );
1234 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1238 // Display openseach plugin (XML)
1239 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1240 header ( 'Content-Type: application/xml; charset=utf-8' );
1241 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1242 $PAGE- > renderPage ( 'opensearch' );
1246 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1247 if ( isset ( $_GET [ 'addtag' ]))
1249 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1250 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1251 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1253 // Prevent redirection loop
1254 if ( isset ( $params [ 'addtag' ])) {
1255 unset ( $params [ 'addtag' ]);
1258 // Check if this tag is already in the search query and ignore it if it is.
1259 // Each tag is always separated by a space
1260 if ( isset ( $params [ 'searchtags' ])) {
1261 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1263 $current_tags = array ();
1266 foreach ( $current_tags as $value ) {
1267 if ( $value === $_GET [ 'addtag' ]) {
1272 // Append the tag if necessary
1273 if ( empty ( $params [ 'searchtags' ])) {
1274 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1277 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1280 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1281 header ( 'Location: ?' . http_build_query ( $params ));
1285 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1286 if ( isset ( $_GET [ 'removetag' ])) {
1287 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1288 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1289 header ( 'Location: ?' );
1293 // In case browser does not send HTTP_REFERER
1294 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1296 // Prevent redirection loop
1297 if ( isset ( $params [ 'removetag' ])) {
1298 unset ( $params [ 'removetag' ]);
1301 if ( isset ( $params [ 'searchtags' ])) {
1302 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1303 // Remove value from array $tags.
1304 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1305 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1307 if ( empty ( $params [ 'searchtags' ])) {
1308 unset ( $params [ 'searchtags' ]);
1311 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1313 header ( 'Location: ?' . http_build_query ( $params ));
1317 // -------- User wants to change the number of links per page (linksperpage=...)
1318 if ( isset ( $_GET [ 'linksperpage' ])) {
1319 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1320 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1323 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1327 // -------- User wants to see only private links (toggle)
1328 if ( isset ( $_GET [ 'privateonly' ])) {
1329 if ( empty ( $_SESSION [ 'privateonly' ])) {
1330 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1332 unset ( $_SESSION [ 'privateonly' ]); // See all links
1335 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1339 // -------- Handle other actions allowed for non-logged in users:
1342 // User tries to post new link but is not logged in:
1343 // Show login screen, then redirect to ?post=...
1344 if ( isset ( $_GET [ 'post' ]))
1346 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.
1350 // Same case as above except that user tried to access ?do=addlink without being logged in
1351 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1352 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1353 header ( 'Location: ?do=login&post=' );
1356 showLinkList ( $PAGE , $LINKSDB );
1357 if ( isset ( $_GET [ 'edit_link' ])) {
1358 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1362 exit ; // Never remove this one! All operations below are reserved for logged in user.
1365 // -------- All other functions are reserved for the registered user:
1367 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1368 if ( $targetPage == Router
:: $PAGE_TOOLS )
1371 'linkcount' => count ( $LINKSDB ),
1372 'pageabsaddr' => index_url ( $_SERVER ),
1374 $pluginManager- > executeHooks ( 'render_tools' , $data );
1376 foreach ( $data as $key => $value ) {
1377 $PAGE- > assign ( $key , $value );
1380 $PAGE- > renderPage ( 'tools' );
1384 // -------- User wants to change his/her password.
1385 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1387 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1388 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1390 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1392 // Make sure old password is correct.
1393 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1394 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1395 // Save new password
1396 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1397 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1399 writeConfig ( $GLOBALS , isLoggedIn ());
1401 catch ( Exception
$e ) {
1403 'ERROR while writing config file after changing password.' . PHP_EOL
.
1407 // TODO: do not handle exceptions/errors in JS.
1408 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1411 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1414 else // show the change password form.
1416 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1417 $PAGE- > assign ( 'token' , getToken ());
1418 $PAGE- > renderPage ( 'changepassword' );
1423 // -------- User wants to change configuration
1424 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1426 if (! empty ( $_POST [ 'title' ]) )
1428 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1430 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1431 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1432 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1433 $GLOBALS [ 'timezone' ] = $tz ;
1434 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1435 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1436 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1437 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1438 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1439 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1440 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1441 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1443 writeConfig ( $GLOBALS , isLoggedIn ());
1445 catch ( Exception
$e ) {
1447 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1451 // TODO: do not handle exceptions/errors in JS.
1452 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1455 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1458 else // Show the configuration form.
1460 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1461 $PAGE- > assign ( 'token' , getToken ());
1462 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1463 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1464 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1465 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1466 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1467 $PAGE- > renderPage ( 'configure' );
1472 // -------- User wants to rename a tag or delete it
1473 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1475 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1476 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1477 $PAGE- > assign ( 'token' , getToken ());
1478 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1479 $PAGE- > renderPage ( 'changetag' );
1483 if (! tokenOk ( $_POST [ 'token' ])) {
1484 die ( 'Wrong token.' );
1488 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1489 $needle = trim ( $_POST [ 'fromtag' ]);
1490 // True for case-sensitive tag search.
1491 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1492 foreach ( $linksToAlter as $key => $value )
1494 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1495 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1496 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1497 $LINKSDB [ $key ]= $value ;
1499 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1500 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1505 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1506 $needle = trim ( $_POST [ 'fromtag' ]);
1507 // True for case-sensitive tag search.
1508 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1509 foreach ( $linksToAlter as $key => $value )
1511 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1512 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1513 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1514 $LINKSDB [ $key ]= $value ;
1516 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1517 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1522 // -------- User wants to add a link without using the bookmarklet: Show form.
1523 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1525 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1526 $PAGE- > renderPage ( 'addlink' );
1530 // -------- User clicked the "Save" button when editing a link: Save link to database.
1531 if ( isset ( $_POST [ 'save_edit' ]))
1533 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1534 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
1535 $tags = implode ( ' ' , array_unique ( explode ( ' ' , $tags ))); // Remove duplicates.
1536 $linkdate = $_POST [ 'lf_linkdate' ];
1537 $url = trim ( $_POST [ 'lf_url' ]);
1538 if (! startsWith ( $url , 'http:' ) && ! startsWith ( $url , 'https:' ) && ! startsWith ( $url , 'ftp:' ) && ! startsWith ( $url , 'magnet:' ) && ! startsWith ( $url , '?' ) && ! startsWith ( $url , 'javascript:' ))
1539 $url = 'http://' . $url ;
1540 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => $url , 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1541 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
1542 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
1544 $pluginManager- > executeHooks ( 'save_link' , $link );
1546 $LINKSDB [ $linkdate ] = $link ;
1547 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1550 // If we are called from the bookmarklet, we must close the popup:
1551 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1552 echo '<script>self.close();</script>' ;
1556 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? escape ( $_POST [ 'returnurl' ]): '?' ;
1557 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1558 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1559 header ( 'Location: ' . $location ); // After saving the link, redirect to the page the user was on.
1563 // -------- User clicked the "Cancel" button when editing a link.
1564 if ( isset ( $_POST [ 'cancel_edit' ]))
1566 // If we are called from the bookmarklet, we must close the popup:
1567 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1568 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1569 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1570 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1571 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1575 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1576 if ( isset ( $_POST [ 'delete_link' ]))
1578 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1579 // We do not need to ask for confirmation:
1580 // - confirmation is handled by JavaScript
1581 // - we are protected from XSRF by the token.
1582 $linkdate = $_POST [ 'lf_linkdate' ];
1584 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1586 unset ( $LINKSDB [ $linkdate ]);
1587 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1589 // If we are called from the bookmarklet, we must close the popup:
1590 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1591 // Pick where we're going to redirect
1592 // =============================================================
1593 // Basically, we can't redirect to where we were previously if it was a permalink
1594 // or an edit_link, because it would 404.
1596 // - / : nothing in $_GET, redirect to self
1597 // - /?page : redirect to self
1598 // - /?searchterm : redirect to self (there might be other links)
1599 // - /?searchtags : redirect to self
1600 // - /permalink : redirect to / (the link does not exist anymore)
1601 // - /?edit_link : redirect to / (the link does not exist anymore)
1602 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1603 // redirect is not satisfied, and only then redirect to /
1606 if ( count ( $_GET ) == 0
1607 || isset ( $_GET [ 'page' ])
1608 || isset ( $_GET [ 'searchterm' ])
1609 || isset ( $_GET [ 'searchtags' ])
1611 if ( isset ( $_POST [ 'returnurl' ])) {
1612 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1614 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1618 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1622 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1623 if ( isset ( $_GET [ 'edit_link' ]))
1625 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1626 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1628 'linkcount' => count ( $LINKSDB ),
1630 'link_is_new' => false ,
1631 'token' => getToken (),
1632 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1633 'tags' => $LINKSDB- > allTags (),
1635 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1637 foreach ( $data as $key => $value ) {
1638 $PAGE- > assign ( $key , $value );
1641 $PAGE- > renderPage ( 'editlink' );
1645 // -------- User want to post a new link: Display link edit form.
1646 if ( isset ( $_GET [ 'post' ])) {
1647 $url = cleanup_url ( escape ( $_GET [ 'post' ]));
1649 $link_is_new = false ;
1650 // Check if URL is not already in database (in this case, we will edit the existing link)
1651 $link = $LINKSDB- > getLinkFromUrl ( $url );
1654 $link_is_new = true ;
1655 $linkdate = strval ( date ( 'Ymd_His' ));
1656 // Get title if it was provided in URL (by the bookmarklet).
1657 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1658 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1659 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1660 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1661 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1662 // 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.)
1663 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1664 // Short timeout to keep the application responsive
1665 list ( $headers , $content ) = get_http_response ( $url , 4 );
1666 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1667 // Retrieve charset.
1668 $charset = get_charset ( $headers , $content );
1670 $title = html_extract_title ( $content );
1671 // Re-encode title in utf-8 if necessary.
1672 if (! empty ( $title ) && $charset != 'utf-8' ) {
1673 $title = mb_convert_encoding ( $title , $charset , 'utf-8' );
1679 $url = '?' . smallHash ( $linkdate );
1684 'linkdate' => $linkdate ,
1687 'description' => $description ,
1689 'private' => $private
1694 'linkcount' => count ( $LINKSDB ),
1696 'link_is_new' => $link_is_new ,
1697 'token' => getToken (), // XSRF protection.
1698 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1699 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1700 'tags' => $LINKSDB- > allTags (),
1702 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1704 foreach ( $data as $key => $value ) {
1705 $PAGE- > assign ( $key , $value );
1708 $PAGE- > renderPage ( 'editlink' );
1712 // -------- Export as Netscape Bookmarks HTML file.
1713 if ( $targetPage == Router
:: $PAGE_EXPORT )
1715 if ( empty ( $_GET [ 'what' ]))
1717 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1718 $PAGE- > renderPage ( 'export' );
1721 $exportWhat = $_GET [ 'what' ];
1722 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1724 header ( 'Content-Type: text/html; charset=utf-8' );
1725 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1726 $currentdate = date ( 'Y/m/d H:i:s' );
1728 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1729 <!-- This is an automatically generated file.
1730 It will be read and overwritten.
1732 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1733 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1734 <TITLE>Bookmarks</TITLE>
1737 foreach ( $LINKSDB as $link )
1739 if ( $exportWhat == 'all' ||
1740 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1741 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1743 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1744 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1745 echo '>' . $link [ 'title' ]. "</A> \n " ;
1746 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1752 // -------- User is uploading a file for import
1753 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1755 // If file is too big, some form field may be missing.
1756 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1758 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1759 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>' ;
1762 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1767 // -------- Show upload/import dialog:
1768 if ( $targetPage == Router
:: $PAGE_IMPORT )
1770 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1771 $PAGE- > assign ( 'token' , getToken ());
1772 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1773 $PAGE- > renderPage ( 'import' );
1777 // Plugin administration page
1778 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1779 $pluginMeta = $pluginManager- > getPluginsMeta ();
1781 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1782 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1784 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1787 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1789 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1791 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1792 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1793 $PAGE- > renderPage ( 'pluginsadmin' );
1797 // Plugin administration form action
1798 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1800 if ( isset ( $_POST [ 'parameters_form' ])) {
1801 unset ( $_POST [ 'parameters_form' ]);
1802 foreach ( $_POST as $param => $value ) {
1803 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1807 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1809 writeConfig ( $GLOBALS , isLoggedIn ());
1811 catch ( Exception
$e ) {
1813 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1817 // TODO: do not handle exceptions/errors in JS.
1818 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1821 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1825 // -------- Otherwise, simply display search form and links:
1826 showLinkList ( $PAGE , $LINKSDB );
1830 // -----------------------------------------------------------------------------------------------
1831 // Process the import file form.
1832 function importFile ()
1834 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1835 $LINKSDB = new LinkDB (
1836 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1838 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1839 $GLOBALS [ 'redirector' ]
1841 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1842 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1843 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1844 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1845 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1850 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1852 // Then import the bookmarks.
1853 if ( $type == 'netscape' )
1855 // This is a standard Netscape-style bookmark file.
1856 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1857 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1859 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1860 $d = explode ( '<DD>' , $html );
1861 if ( startswith ( $d [ 0 ], '<A ' ))
1863 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1864 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1865 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1866 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1868 foreach ( $matches as $m )
1870 $attr = $m [ 1 ]; $value = $m [ 2 ];
1871 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1872 elseif ( $attr == 'ADD_DATE' )
1874 $raw_add_date = intval ( $value );
1875 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1877 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1878 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1880 if ( $link [ 'url' ]!= '' )
1882 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1883 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1885 { // Link not in database, let's import it...
1886 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1888 // Make sure date/time is not already used by another link.
1889 // (Some bookmark files have several different links with the same ADD_DATE)
1890 // We increment date by 1 second until we find a date which is not used in DB.
1891 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1892 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1893 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1894 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1897 else // Link already present in database.
1900 { // If overwrite is required, we import link data, except date/time.
1901 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1902 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1910 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1912 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1916 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1920 // -----------------------------------------------------------------------------------------------
1921 // Template for the list of links (<div id="linklist">)
1922 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1923 function buildLinkList ( $PAGE , $LINKSDB )
1925 // ---- Filter link database according to parameters
1928 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]) ? true : false ;
1931 if ( isset ( $_GET [ 'searchterm' ])) {
1932 $search_crits = escape ( trim ( $_GET [ 'searchterm' ]));
1933 $search_type = LinkFilter
:: $FILTER_TEXT ;
1934 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits , false , $privateonly );
1937 elseif ( isset ( $_GET [ 'searchtags' ])) {
1938 $search_crits = explode ( ' ' , escape ( trim ( $_GET [ 'searchtags' ])));
1939 $search_type = LinkFilter
:: $FILTER_TAG ;
1940 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits , false , $privateonly );
1942 // Detect smallHashes in URL.
1943 elseif ( isset ( $_SERVER [ 'QUERY_STRING' ])
1944 && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])) {
1945 $search_type = LinkFilter
:: $FILTER_HASH ;
1946 $search_crits = substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 );
1947 $linksToDisplay = $LINKSDB- > filter ( $search_type , $search_crits );
1949 if ( count ( $linksToDisplay ) == 0 ) {
1950 $PAGE- > render404 ( 'The link you are trying to reach does not exist or has been deleted.' );
1954 // Otherwise, display without filtering.
1956 $linksToDisplay = $LINKSDB- > filter ( '' , '' , false , $privateonly );
1959 // ---- Handle paging.
1961 foreach ( $linksToDisplay as $key => $value ) {
1965 // If there is only a single link, we change on-the-fly the title of the page.
1966 if ( count ( $linksToDisplay ) == 1 ) {
1967 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1970 // Select articles according to paging.
1971 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1972 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1973 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1974 $page = $page < 1 ? 1 : $page ;
1975 $page = $page > $pagecount ? $pagecount : $page ;
1977 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1978 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1979 $linkDisp = array ();
1980 while ( $i < $end && $i < count ( $keys ))
1982 $link = $linksToDisplay [ $keys [ $i ]];
1983 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1984 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1985 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1986 $link [ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
1987 $taglist = explode ( ' ' , $link [ 'tags' ]);
1988 uasort ( $taglist , 'strcasecmp' );
1989 $link [ 'taglist' ] = $taglist ;
1990 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1991 // Check for both signs of a note: starting with ? and 7 chars long.
1992 if ( $link [ 'url' ][ 0 ] === '?' &&
1993 strlen ( $link [ 'url' ]) === 7 ) {
1994 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1997 $linkDisp [ $keys [ $i ]] = $link ;
2001 // Compute paging navigation
2002 $searchterm = empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ];
2003 $searchtags = empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ];
2004 $previous_page_url = '' ;
2005 if ( $i != count ( $keys )) {
2006 $previous_page_url = '?page=' . ( $page +
1 ) . $searchterm . $searchtags ;
2010 $next_page_url = '?page=' . ( $page-1 ) . $searchterm . $searchtags ;
2015 $token = getToken ();
2018 // Fill all template fields.
2020 'linkcount' => count ( $LINKSDB ),
2021 'previous_page_url' => $previous_page_url ,
2022 'next_page_url' => $next_page_url ,
2023 'page_current' => $page ,
2024 'page_max' => $pagecount ,
2025 'result_count' => count ( $linksToDisplay ),
2026 'search_type' => $search_type ,
2027 'search_crits' => $search_crits ,
2028 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
2030 'links' => $linkDisp ,
2031 'tags' => $LINKSDB- > allTags (),
2033 // FIXME! temporary fix - see #399.
2034 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
2035 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
2038 $pluginManager = PluginManager
:: getInstance ();
2039 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
2041 foreach ( $data as $key => $value ) {
2042 $PAGE- > assign ( $key , $value );
2048 // Compute the thumbnail for a link.
2050 // With a link to the original URL.
2051 // Understands various services (youtube.com...)
2052 // Input: $url = URL for which the thumbnail must be found.
2053 // $href = if provided, this URL will be followed instead of $url
2054 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
2055 // Some of them may be missing.
2056 // Return an empty array if no thumbnail available.
2057 function computeThumbnail ( $url , $href = false )
2059 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
2060 if ( $href == false ) $href = $url ;
2062 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
2063 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
2064 // ^^^^^^^^^^^ ^^^^^^^^^^^
2065 $domain = parse_url ( $url , PHP_URL_HOST
);
2066 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
2068 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
2069 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
2070 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2072 if ( $domain == 'youtu.be' ) // Youtube short links
2074 $path = parse_url ( $url , PHP_URL_PATH
);
2075 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
2076 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
2078 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
2080 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
2081 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
2082 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
2085 if ( $domain == 'imgur.com' )
2087 $path = parse_url ( $url , PHP_URL_PATH
);
2088 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2089 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2090 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2091 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2092 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2094 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2095 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2097 if ( $domain == 'i.imgur.com' )
2099 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2100 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2101 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2103 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2105 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2107 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2108 return array ( 'src' => $thumburl ,
2109 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2112 if ( endsWith ( $domain , '.imageshack.us' ))
2114 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2115 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2117 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2118 return array ( 'src' => $thumburl ,
2119 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2123 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2124 // So we deport the thumbnail generation in order not to slow down page generation
2125 // (and we also cache the thumbnail)
2127 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2129 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2130 || $domain == 'vimeo.com'
2131 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2132 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2135 if ( $domain == 'vimeo.com' )
2136 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2137 $path = parse_url ( $url , PHP_URL_PATH
);
2138 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2140 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2141 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2142 $path = parse_url ( $url , PHP_URL_PATH
);
2143 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2145 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2146 { // Make sure this TED URL points to a video (/talks/...)
2147 $path = parse_url ( $url , PHP_URL_PATH
);
2148 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2150 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2151 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2152 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2155 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2156 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2157 // But using the extension will do.
2158 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2159 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2161 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2162 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2163 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2165 return array (); // No thumbnail.
2170 // Returns the HTML code to display a thumbnail for a link
2171 // with a link to the original URL.
2172 // Understands various services (youtube.com...)
2173 // Input: $url = URL for which the thumbnail must be found.
2174 // $href = if provided, this URL will be followed instead of $url
2175 // Returns '' if no thumbnail available.
2176 function thumbnail ( $url , $href = false )
2178 $t = computeThumbnail ( $url , $href );
2179 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2181 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2182 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2183 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2184 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2185 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2190 // Returns the HTML code to display a thumbnail for a link
2191 // for the picture wall (using lazy image loading)
2192 // Understands various services (youtube.com...)
2193 // Input: $url = URL for which the thumbnail must be found.
2194 // $href = if provided, this URL will be followed instead of $url
2195 // Returns '' if no thumbnail available.
2196 function lazyThumbnail ( $url , $href = false )
2198 $t = computeThumbnail ( $url , $href );
2199 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2201 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2204 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2206 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2207 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2208 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2209 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2212 // No-JavaScript fallback.
2213 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2214 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2215 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2216 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2217 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2218 $html .= '></noscript></a>' ;
2224 // -----------------------------------------------------------------------------------------------
2226 // This function should NEVER be called if the file data/config.php exists.
2229 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2230 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2233 // This part makes sure sessions works correctly.
2234 // (Because on some hosts, session.save_path may not be set correctly,
2235 // or we may not have write access to it.)
2236 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2237 { // Step 2: Check if data in session is correct.
2238 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2239 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2240 echo 'It currently points to ' . session_save_path (). '<br>' ;
2241 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>' ;
2242 echo '<br><a href="?">Click to try again.</a></pre>' ;
2245 if (! isset ( $_SESSION [ 'session_tested' ]))
2246 { // Step 1 : Try to store data in session and reload page.
2247 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2248 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2250 if ( isset ( $_GET [ 'test_session' ]))
2251 { // Step 3: Sessions are OK. Remove test parameter from URL.
2252 header ( 'Location: ' . index_url ( $_SERVER ));
2256 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2259 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2260 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2261 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2264 $GLOBALS [ 'timezone' ] = $tz ;
2265 // Everything is ok, let's create config file.
2266 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2267 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2268 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2269 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2270 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2272 writeConfig ( $GLOBALS , isLoggedIn ());
2274 catch ( Exception
$e ) {
2276 'ERROR while writing config file after installation.' . PHP_EOL
.
2280 // TODO: do not handle exceptions/errors in JS.
2281 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2284 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2288 // Display config form:
2289 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2290 $timezone_html = '' ;
2291 if ( $timezone_form != '' ) {
2292 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2295 $PAGE = new pageBuilder
;
2296 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2297 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2298 $PAGE- > renderPage ( 'install' );
2302 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2303 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2304 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2305 This function is called by passing the URL:
2306 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2307 [URL] is the URL of the link (e.g. a flickr page)
2308 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2309 The function below will fetch the image from the webservice and store it in the cache.
2311 function genThumbnail ()
2313 // Make sure the parameters in the URL were generated by us.
2314 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2315 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2317 // Let's see if we don't already have the image for this URL in the cache.
2318 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2319 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2320 { // We have the thumbnail, just serve it:
2321 header ( 'Content-Type: image/jpeg' );
2322 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2325 // We may also serve a blank image (if service did not respond)
2326 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2327 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2329 header ( 'Content-Type: image/gif' );
2330 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2334 // Otherwise, generate the thumbnail.
2335 $url = $_GET [ 'url' ];
2336 $domain = parse_url ( $url , PHP_URL_HOST
);
2338 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2340 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2341 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2343 // Is this a link to an image, or to a flickr page ?
2345 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2346 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2347 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2348 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2350 else // This is a flickr page (html)
2352 // Get the flickr html page.
2353 list ( $headers , $content ) = get_http_response ( $url , 20 );
2354 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2356 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2357 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2358 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2360 // In albums (and some other pages), the link rel="image_src" is not provided,
2361 // but flickr provides:
2362 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2365 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2366 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2372 { // Let's download the image.
2373 // Image is 240x120, so 10 seconds to download should be enough.
2374 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2375 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2376 // Save image to cache.
2377 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2378 header ( 'Content-Type: image/jpeg' );
2385 elseif ( $domain == 'vimeo.com' )
2387 // This is more complex: we have to perform a HTTP request, then parse the result.
2388 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2389 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2390 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2391 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2392 $t = unserialize ( $content );
2393 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2394 // Then we download the image and serve it to our client.
2395 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2396 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2397 // Save image to cache.
2398 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2399 header ( 'Content-Type: image/jpeg' );
2406 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2408 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2409 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2410 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2411 list ( $headers , $content ) = get_http_response ( $url , 5 );
2412 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2413 // Extract the link to the thumbnail
2414 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2415 if (! empty ( $matches [ 1 ]))
2416 { // Let's download the image.
2417 $imageurl = $matches [ 1 ];
2418 // No control on image size, so wait long enough
2419 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2420 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2421 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2422 file_put_contents ( $filepath , $content ); // Save image to cache.
2423 if ( resizeImage ( $filepath ))
2425 header ( 'Content-Type: image/jpeg' );
2426 echo file_get_contents ( $filepath );
2434 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2436 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2437 // http://xkcd.com/327/
2438 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2439 list ( $headers , $content ) = get_http_response ( $url , 5 );
2440 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2441 // Extract the link to the thumbnail
2442 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2443 if (! empty ( $matches [ 1 ]))
2444 { // Let's download the image.
2445 $imageurl = $matches [ 1 ];
2446 // No control on image size, so wait long enough
2447 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2448 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2449 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2450 // Save image to cache.
2451 file_put_contents ( $filepath , $content );
2452 if ( resizeImage ( $filepath ))
2454 header ( 'Content-Type: image/jpeg' );
2455 echo file_get_contents ( $filepath );
2465 // For all other domains, we try to download the image and make a thumbnail.
2466 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2467 list ( $headers , $content ) = get_http_response ( $url , 30 );
2468 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2469 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2470 // Save image to cache.
2471 file_put_contents ( $filepath , $content );
2472 if ( resizeImage ( $filepath ))
2474 header ( 'Content-Type: image/jpeg' );
2475 echo file_get_contents ( $filepath );
2482 // Otherwise, return an empty image (8x8 transparent gif)
2483 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2484 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2485 header ( 'Content-Type: image/gif' );
2489 // Make a thumbnail of the image (to width: 120 pixels)
2490 // Returns true if success, false otherwise.
2491 function resizeImage ( $filepath )
2493 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2495 // Trick: some stupid people rename GIF as JPEG... or else.
2496 // So we really try to open each image type whatever the extension is.
2497 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2499 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2500 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2501 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2502 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2505 $ystart = 0 ; $yheight = $h ;
2506 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2507 $nw = 120 ; // Desired width
2508 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2510 $im2 = imagecreatetruecolor ( $nw , $nh );
2511 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2512 imageinterlace ( $im2 , true ); // For progressive JPEG.
2513 $tempname = $filepath . '_TEMP.jpg' ;
2514 imagejpeg ( $im2 , $tempname , 90 );
2518 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2523 mergeDeprecatedConfig ( $GLOBALS , isLoggedIn ());
2524 } catch ( Exception
$e ) {
2526 'ERROR while merging deprecated options.php file.' . PHP_EOL
.
2531 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2532 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2533 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2534 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2535 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];