]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.5 - Shaare your links...
5 * The personal, minimalist, super-fast, no-database Delicious clone.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
25 /* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
33 * Shaarli directories & configuration files
36 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ;
38 // Main configuration file
39 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ;
42 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ;
45 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ;
47 // Processed updates file.
48 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/updates.txt' ;
51 $GLOBALS [ 'config' ][ 'LOG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' ;
53 // For updates check of Shaarli
54 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
56 // Set ENABLE_UPDATECHECK to disabled by default.
57 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = false ;
59 // RainTPL cache directory (keep the trailing slash!)
60 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
61 // Raintpl template directory (keep the trailing slash!)
62 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
64 // Thumbnail cache directory
65 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
67 // Atom & RSS feed cache directory
68 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
71 * Global configuration
73 // Ban IP after this many failures
74 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
75 // Ban duration for IP address after login failures (in seconds)
76 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
79 // Enable RSS permalinks by default.
80 // This corresponds to the default behavior of shaarli before this was added as an option.
81 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
82 // If true, an extra "ATOM feed" button will be displayed in the toolbar
83 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
85 // Link display options
86 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
87 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
88 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
90 // Open Shaarli (true): anyone can add/edit/delete links without having to login
91 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
94 // Display thumbnails in links
95 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
96 // Store thumbnails in a local cache
97 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
99 // Update check frequency for Shaarli. 86400 seconds=24 hours
100 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ] = 'stable' ;
101 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
103 $GLOBALS [ 'config' ][ 'REDIRECTOR_URLENCODE' ] = true ;
106 * Plugin configuration
108 * Warning: order matters!
110 * These settings may be be overriden in:
112 * - each plugin's configuration file
114 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
115 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
116 // 'wallabag', 'markdown', 'addlink_toolbar',
118 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
120 // Initialize plugin parameters array.
121 $GLOBALS [ 'plugins' ] = array ();
123 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
124 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
129 define ( 'shaarli_version' , '0.6.5' );
131 // http://server.com/x/shaarli --> /shaarli/
132 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
134 // High execution time in case of problematic imports/exports.
135 ini_set ( 'max_input_time' , '60' );
137 // Try to set max upload file size and read
138 ini_set ( 'memory_limit' , '128M' );
139 ini_set ( 'post_max_size' , '16M' );
140 ini_set ( 'upload_max_filesize' , '16M' );
142 // See all error except warnings
143 error_reporting ( E_ALL^E_WARNING
);
144 // See all errors (for debugging only)
145 //error_reporting(-1);
150 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
151 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
155 require_once 'application/ApplicationUtils.php' ;
156 require_once 'application/Cache.php' ;
157 require_once 'application/CachedPage.php' ;
158 require_once 'application/FeedBuilder.php' ;
159 require_once 'application/FileUtils.php' ;
160 require_once 'application/HttpUtils.php' ;
161 require_once 'application/LinkDB.php' ;
162 require_once 'application/LinkFilter.php' ;
163 require_once 'application/LinkUtils.php' ;
164 require_once 'application/NetscapeBookmarkUtils.php' ;
165 require_once 'application/TimeZone.php' ;
166 require_once 'application/Url.php' ;
167 require_once 'application/Utils.php' ;
168 require_once 'application/Config.php' ;
169 require_once 'application/PluginManager.php' ;
170 require_once 'application/Router.php' ;
171 require_once 'application/Updater.php' ;
173 // Ensure the PHP version is supported
175 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
176 } catch ( Exception
$exc ) {
177 header ( 'Content-Type: text/plain; charset=utf-8' );
178 echo $exc- > getMessage ();
182 // Force cookie path (but do not change lifetime)
183 $cookie = session_get_cookie_params ();
185 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
186 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
188 // Set default cookie expiration and path.
189 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
190 // Set session parameters on server side.
191 // If the user does not access any page within this time, his/her session is considered expired.
192 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
193 // Use cookies to store session.
194 ini_set ( 'session.use_cookies' , 1 );
195 // Force cookies for session (phpsessionID forbidden in URL).
196 ini_set ( 'session.use_only_cookies' , 1 );
197 // Prevent PHP form using sessionID in URL if cookies are disabled.
198 ini_set ( 'session.use_trans_sid' , false );
200 session_name ( 'shaarli' );
201 // Start session if needed (Some server auto-start sessions).
202 if ( session_id () == '' ) {
206 // Regenerate session ID if invalid or not defined in cookie.
207 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
208 session_regenerate_id ( true );
209 $_COOKIE [ 'shaarli' ] = session_id ();
212 include "inc/rain.tpl.class.php" ; //include Rain TPL
213 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
214 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
216 $pluginManager = PluginManager
:: getInstance ();
217 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
219 ob_start (); // Output buffering for the page cache.
222 // In case stupid admin has left magic_quotes enabled in php.ini:
223 if ( get_magic_quotes_gpc ())
225 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
226 $_POST = array_map ( 'stripslashes_deep' , $_POST );
227 $_GET = array_map ( 'stripslashes_deep' , $_GET );
228 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
231 // Prevent caching on client side or proxy: (yes, it's ugly)
232 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
233 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
234 header ( "Cache-Control: post-check=0, pre-check=0" , false );
235 header ( "Pragma: no-cache" );
237 // Handling of old config file which do not have the new parameters.
238 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
239 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
240 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
241 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
242 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
243 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
244 // I really need to rewrite Shaarli with a proper configuation manager.
246 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
247 // Ensure Shaarli has proper access to its resources
248 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
250 if ( $errors != array ()) {
251 $message = '<p>Insufficient permissions:</p><ul>' ;
253 foreach ( $errors as $error ) {
254 $message .= '<li>' . $error . '</li>' ;
258 header ( 'Content-Type: text/html; charset=utf-8' );
263 // Display the installation form if no existing config is found
267 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
268 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
269 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
271 // a token depending of deployment salt, user password, and the current ip
272 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
274 // Sniff browser language and set date format accordingly.
275 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
276 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
278 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
280 //==================================================================================================
281 // Checking session state (i.e. is the user still logged in)
282 //==================================================================================================
284 function setup_login_state () {
285 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
288 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
289 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
290 if (! isset ( $GLOBALS [ 'login' ])) {
291 $userIsLoggedIn = false ; // Shaarli is not configured yet.
292 $loginFailure = true ;
294 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
295 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
299 $userIsLoggedIn = true ;
301 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
302 if ( empty ( $_SESSION [ 'uid' ]) ||
303 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
304 time () >= $_SESSION [ 'expires_on' ])
307 $userIsLoggedIn = false ;
308 $loginFailure = true ;
310 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
311 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
314 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
316 if (! $loginFailure ) {
317 $userIsLoggedIn = true ;
320 return $userIsLoggedIn ;
322 $userIsLoggedIn = setup_login_state ();
324 // ------------------------------------------------------------------------------------------
325 // PubSubHubbub protocol support (if enabled) [UNTESTED]
326 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
327 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
330 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
332 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
334 index_url ( $_SERVER ). '?do=atom' ,
335 index_url ( $_SERVER ). '?do=rss'
337 $p- > publish_update ( $topic_url );
341 // ------------------------------------------------------------------------------------------
342 // Session management
344 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
347 $ip = $_SERVER [ "REMOTE_ADDR" ];
348 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
349 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
350 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
354 function fillSessionInfo () {
355 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
356 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
357 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
358 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
361 // Check that user/password is correct.
362 function check_auth ( $login , $password )
364 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
365 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
366 { // Login/password is correct.
368 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
371 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
375 // Returns true if the user is logged in.
376 function isLoggedIn ()
378 global $userIsLoggedIn ;
379 return $userIsLoggedIn ;
384 if ( isset ( $_SESSION )) {
385 unset ( $_SESSION [ 'uid' ]);
386 unset ( $_SESSION [ 'ip' ]);
387 unset ( $_SESSION [ 'username' ]);
388 unset ( $_SESSION [ 'privateonly' ]);
390 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
394 // ------------------------------------------------------------------------------------------
395 // Brute force protection system
396 // Several consecutive failed logins will ban the IP address for 30 minutes.
397 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 ?>" );
398 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
399 // Signal a failed login. Will ban the IP if too many failures:
400 function ban_loginFailed ()
402 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
403 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
404 $gb [ 'FAILURES' ][ $ip ] ++
;
405 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
407 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
408 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
410 $GLOBALS [ 'IPBANS' ] = $gb ;
411 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
414 // Signals a successful login. Resets failed login counter.
415 function ban_loginOk ()
417 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
418 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
419 $GLOBALS [ 'IPBANS' ] = $gb ;
420 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
423 // Checks if the user CAN login. If 'true', the user can try to login.
424 function ban_canLogin ()
426 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
427 if ( isset ( $gb [ 'BANS' ][ $ip ]))
429 // User is banned. Check if the ban has expired:
430 if ( $gb [ 'BANS' ][ $ip ]<= time ())
431 { // Ban expired, user can try to login again.
432 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
433 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
434 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
435 return true ; // Ban has expired, user can login.
437 return false ; // User is banned.
439 return true ; // User is not banned.
442 // ------------------------------------------------------------------------------------------
443 // Process login form: Check if login/password is correct.
444 if ( isset ( $_POST [ 'login' ]))
446 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
447 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
448 { // Login/password is OK.
450 // If user wants to keep the session cookie even after the browser closes:
451 if (! empty ( $_POST [ 'longlastingsession' ]))
453 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
454 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
455 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
457 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
458 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
459 // Note: Never forget the trailing slash on the cookie path!
460 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
462 else // Standard session expiration (=when browser closes)
464 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
465 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
466 session_regenerate_id ( true );
469 // Optional redirect after login:
470 if ( isset ( $_GET [ 'post' ])) {
471 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
472 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
473 if (! empty ( $_GET [ $param ])) {
474 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
477 header ( 'Location: ' . $uri );
481 if ( isset ( $_GET [ 'edit_link' ])) {
482 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
486 if ( isset ( $_POST [ 'returnurl' ])) {
487 // Prevent loops over login screen.
488 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
489 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
493 header ( 'Location: ?' ); exit ;
499 if ( isset ( $_GET [ 'post' ])) {
500 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
501 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
502 if (! empty ( $_GET [ $param ])) {
503 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
507 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
512 // ------------------------------------------------------------------------------------------
513 // Misc utility functions:
515 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
516 function return_bytes ( $val )
518 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
521 case 'g' : $val *= 1024 ;
522 case 'm' : $val *= 1024 ;
523 case 'k' : $val *= 1024 ;
528 // Try to determine max file size for uploads (POST).
529 // Returns an integer (in bytes)
530 function getMaxFileSize ()
532 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
533 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
534 // Return the smaller of two:
535 $maxsize = min ( $size1 , $size2 );
536 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
540 // ------------------------------------------------------------------------------------------
541 // Token management for XSRF protection
542 // Token should be used in any form which acts on data (create,update,delete,import...).
543 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
548 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
549 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
553 // Tells if a token is OK. Using this function will destroy the token.
555 function tokenOk ( $token )
557 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
559 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
560 return true ; // Token is OK.
562 return false ; // Wrong token, or already used.
565 // ------------------------------------------------------------------------------------------
566 /* This class is in charge of building the final page.
567 (This is basically a wrapper around RainTPL which pre-fills some fields.)
569 p.assign('myfield','myvalue');
570 p.renderPage('mytemplate');
575 private $tpl ; // RainTPL template
577 function __construct ()
583 * Initialize all default tpl tags.
585 private function initialize ()
587 $this- > tpl
= new RainTPL
;
590 $version = ApplicationUtils
:: checkUpdate (
592 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
593 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
594 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
596 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
598 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
599 $this- > tpl
-> assign ( 'versionError' , '' );
601 } catch ( Exception
$exc ) {
602 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
603 $this- > tpl
-> assign ( 'newVersion' , '' );
604 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
607 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
608 $searchcrits = '' ; // Search criteria
609 if (! empty ( $_GET [ 'searchtags' ])) {
610 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
612 if (! empty ( $_GET [ 'searchterm' ])) {
613 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
615 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
616 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
617 $this- > tpl
-> assign ( 'version' , shaarli_version
);
618 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
619 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
620 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
621 if (! empty ( $GLOBALS [ 'title' ])) {
622 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
624 if (! empty ( $GLOBALS [ 'titleLink' ])) {
625 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
627 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
628 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
630 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
631 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
632 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
636 // The following assign() method is basically the same as RainTPL (except that it's lazy)
637 public function assign ( $what , $where )
639 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
640 $this- > tpl
-> assign ( $what , $where );
644 * Assign an array of data to the template builder.
646 * @param array $data Data to assign.
648 * @return false if invalid data.
650 public function assignAll ( $data )
652 // Lazy initialization
653 if ( $this- > tpl
=== false ) {
657 if ( empty ( $data ) || ! is_array ( $data )){
661 foreach ( $data as $key => $value ) {
662 $this- > assign ( $key , $value );
666 // Render a specific page (using a template).
667 // e.g. pb.renderPage('picwall')
668 public function renderPage ( $page )
670 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
671 $this- > tpl
-> draw ( $page );
675 * Render a 404 page (uses the template : tpl/404.tpl)
677 * usage : $PAGE->render404('The link was deleted')
678 * @param string $message A messate to display what is not found
680 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
681 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
682 $this- > tpl
-> assign ( 'error_message' , $message );
683 $this- > renderPage ( '404' );
687 // ------------------------------------------------------------------------------------------
688 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
689 // Gives the last 7 days (which have links).
690 // This RSS feed cannot be filtered.
691 function showDailyRSS () {
693 $query = $_SERVER [ "QUERY_STRING" ];
694 $cache = new CachedPage (
695 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
697 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
699 $cached = $cache- > cachedVersion ();
700 if (! empty ( $cached )) {
705 // If cached was not found (or not usable), then read the database and build the response:
706 // Read links from database (and filter private links if used it not logged in).
707 $LINKSDB = new LinkDB (
708 $GLOBALS [ 'config' ][ 'DATASTORE' ],
710 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
711 $GLOBALS [ 'redirector' ],
712 $GLOBALS [ 'config' ][ 'REDIRECTOR_URLENCODE' ]
715 /* Some Shaarlies may have very few links, so we need to look
716 back in time (rsort()) until we have enough days ($nb_of_days).
718 $linkdates = array ();
719 foreach ( $LINKSDB as $linkdate => $value ) {
720 $linkdates [] = $linkdate ;
723 $nb_of_days = 7 ; // We take 7 days.
724 $today = Date ( 'Ymd' );
727 foreach ( $linkdates as $linkdate ) {
728 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
729 if ( strcmp ( $day , $today ) < 0 ) {
730 if ( empty ( $days [ $day ])) {
731 $days [ $day ] = array ();
733 $days [ $day ][] = $linkdate ;
736 if ( count ( $days ) > $nb_of_days ) {
737 break ; // Have we collected enough days?
741 // Build the RSS feed.
742 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
743 $pageaddr = escape ( index_url ( $_SERVER ));
744 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
746 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
747 echo '<link>' . $pageaddr . '</link>' ;
748 echo '<description>Daily shared links</description>' ;
749 echo '<language>en-en</language>' ;
750 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
753 foreach ( $days as $day => $linkdates ) {
754 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
755 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
757 // Build the HTML body of this RSS entry.
762 // We pre-format some fields for proper output.
763 foreach ( $linkdates as $linkdate ) {
764 $l = $LINKSDB [ $linkdate ];
765 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
766 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
767 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
768 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
769 if ( startsWith ( $l [ 'url' ], '?' )) {
770 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
772 $links [ $linkdate ] = $l ;
775 // Then build the HTML for this day:
777 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
778 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
779 $tpl- > assign ( 'absurl' , $absurl );
780 $tpl- > assign ( 'links' , $links );
781 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
782 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
784 echo $html . PHP_EOL
;
786 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
788 $cache- > cache ( ob_get_contents ());
794 * Show the 'Daily' page.
796 * @param PageBuilder $pageBuilder Template engine wrapper.
797 * @param LinkDB $LINKSDB LinkDB instance.
799 function showDaily ( $pageBuilder , $LINKSDB )
801 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
802 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
804 $days = $LINKSDB- > days ();
805 $i = array_search ( $day , $days );
806 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
811 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
812 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
816 $linksToDisplay = $LINKSDB- > filterDay ( $day );
817 } catch ( Exception
$exc ) {
819 $linksToDisplay = array ();
822 // We pre-format some fields for proper output.
823 foreach ( $linksToDisplay as $key => $link )
826 $taglist = explode ( ' ' , $link [ 'tags' ]);
827 uasort ( $taglist , 'strcasecmp' );
828 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
829 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
830 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
831 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
832 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
835 /* We need to spread the articles on 3 columns.
836 I did not want to use a JavaScript lib like http://masonry.desandro.com/
837 so I manually spread entries with a simple method: I roughly evaluate the
838 height of a div according to title and description length.
840 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
841 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
842 foreach ( $linksToDisplay as $key => $link )
844 // Roughly estimate length of entry (by counting characters)
845 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
846 // Description: 836 characters gives roughly 342 pixel height.
847 // This is not perfect, but it's usually OK.
848 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
849 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
850 // Then put in column which is the less filled:
851 $smallest = min ( $fill ); // find smallest value in array.
852 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
853 array_push ( $columns [ $index ], $link ); // Put entry in this column.
854 $fill [ $index ] +
= $length ;
857 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
859 'linksToDisplay' => $linksToDisplay ,
860 'linkcount' => count ( $LINKSDB ),
862 'day' => $dayDate- > getTimestamp (),
863 'previousday' => $previousday ,
864 'nextday' => $nextday ,
866 $pluginManager = PluginManager
:: getInstance ();
867 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
869 foreach ( $data as $key => $value ) {
870 $pageBuilder- > assign ( $key , $value );
873 $pageBuilder- > renderPage ( 'daily' );
877 // Renders the linklist
878 function showLinkList ( $PAGE , $LINKSDB ) {
879 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
880 $PAGE- > renderPage ( 'linklist' );
884 // ------------------------------------------------------------------------------------------
885 // Render HTML page (according to URL parameters and user rights)
886 function renderPage ()
888 $LINKSDB = new LinkDB (
889 $GLOBALS [ 'config' ][ 'DATASTORE' ],
891 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
892 $GLOBALS [ 'redirector' ],
893 $GLOBALS [ 'config' ][ 'REDIRECTOR_URLENCODE' ]
896 $updater = new Updater (
897 read_updates_file ( $GLOBALS [ 'config' ][ 'UPDATES_FILE' ]),
903 $newUpdates = $updater- > update ();
904 if (! empty ( $newUpdates )) {
906 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ],
907 $updater- > getDoneUpdates ()
911 catch ( Exception
$e ) {
912 die ( $e- > getMessage ());
915 $PAGE = new pageBuilder
;
917 // Determine which page will be rendered.
918 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
919 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
921 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
922 // Then assign generated data to RainTPL.
923 $common_hooks = array (
928 $pluginManager = PluginManager
:: getInstance ();
929 foreach ( $common_hooks as $name ) {
930 $plugin_data = array ();
931 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
933 'target' => $targetPage ,
934 'loggedin' => isLoggedIn ()
937 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
940 // -------- Display login form.
941 if ( $targetPage == Router
:: $PAGE_LOGIN )
943 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
944 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
945 $PAGE- > assign ( 'token' , $token );
946 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
947 $PAGE- > renderPage ( 'loginform' );
950 // -------- User wants to logout.
951 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
953 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
955 header ( 'Location: ?' );
959 // -------- Picture wall
960 if ( $targetPage == Router
:: $PAGE_PICWALL )
962 // Optionally filter the results:
963 $links = $LINKSDB- > filterSearch ( $_GET );
964 $linksToDisplay = array ();
966 // Get only links which have a thumbnail.
967 foreach ( $links as $link )
969 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
970 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
971 if ( $thumb != '' ) // Only output links which have a thumbnail.
973 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
974 $linksToDisplay []= $link ; // Add to array.
979 'linkcount' => count ( $LINKSDB ),
980 'linksToDisplay' => $linksToDisplay ,
982 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
984 foreach ( $data as $key => $value ) {
985 $PAGE- > assign ( $key , $value );
988 $PAGE- > renderPage ( 'picwall' );
992 // -------- Tag cloud
993 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
995 $tags = $LINKSDB- > allTags ();
997 // We sort tags alphabetically, then choose a font size according to count.
998 // First, find max value.
1000 foreach ( $tags as $value ) {
1001 $maxcount = max ( $maxcount , $value );
1004 // Sort tags alphabetically: case insensitive, support locale if avalaible.
1005 uksort ( $tags , function ( $a , $b ) {
1006 // Collator is part of PHP intl.
1007 if ( class_exists ( 'Collator' )) {
1008 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
1009 if (! intl_is_failure ( intl_get_error_code ())) {
1010 return $c- > compare ( $a , $b );
1013 return strcasecmp ( $a , $b );
1017 foreach ( $tags as $key => $value ) {
1018 // Tag font size scaling:
1019 // default 15 and 30 logarithm bases affect scaling,
1020 // 22 and 6 are arbitrary font sizes for max and min sizes.
1021 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
1022 $tagList [ $key ] = array (
1024 'size' => number_format ( $size , 2 , '.' , '' ),
1029 'linkcount' => count ( $LINKSDB ),
1032 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1034 foreach ( $data as $key => $value ) {
1035 $PAGE- > assign ( $key , $value );
1038 $PAGE- > renderPage ( 'tagcloud' );
1043 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1044 showDaily ( $PAGE , $LINKSDB );
1047 // ATOM and RSS feed.
1048 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
1049 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
1050 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
1053 $query = $_SERVER [ 'QUERY_STRING' ];
1054 $cache = new CachedPage (
1055 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
1057 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
1059 $cached = $cache- > cachedVersion ();
1060 if (! empty ( $cached )) {
1066 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
1067 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
1068 $feedGenerator- > setHideDates ( $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] && ! isLoggedIn ());
1069 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]);
1070 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) {
1071 $feedGenerator- > setPubsubhubUrl ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
1073 $data = $feedGenerator- > buildData ();
1075 // Process plugin hook.
1076 $pluginManager = PluginManager
:: getInstance ();
1077 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
1078 'loggedin' => isLoggedIn (),
1079 'target' => $targetPage ,
1082 // Render the template.
1083 $PAGE- > assignAll ( $data );
1084 $PAGE- > renderPage ( 'feed.' . $feedType );
1085 $cache- > cache ( ob_get_contents ());
1090 // Display openseach plugin (XML)
1091 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1092 header ( 'Content-Type: application/xml; charset=utf-8' );
1093 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1094 $PAGE- > renderPage ( 'opensearch' );
1098 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1099 if ( isset ( $_GET [ 'addtag' ]))
1101 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1102 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1103 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1105 // Prevent redirection loop
1106 if ( isset ( $params [ 'addtag' ])) {
1107 unset ( $params [ 'addtag' ]);
1110 // Check if this tag is already in the search query and ignore it if it is.
1111 // Each tag is always separated by a space
1112 if ( isset ( $params [ 'searchtags' ])) {
1113 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1115 $current_tags = array ();
1118 foreach ( $current_tags as $value ) {
1119 if ( $value === $_GET [ 'addtag' ]) {
1124 // Append the tag if necessary
1125 if ( empty ( $params [ 'searchtags' ])) {
1126 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1129 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1132 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1133 header ( 'Location: ?' . http_build_query ( $params ));
1137 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1138 if ( isset ( $_GET [ 'removetag' ])) {
1139 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1140 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1141 header ( 'Location: ?' );
1145 // In case browser does not send HTTP_REFERER
1146 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1148 // Prevent redirection loop
1149 if ( isset ( $params [ 'removetag' ])) {
1150 unset ( $params [ 'removetag' ]);
1153 if ( isset ( $params [ 'searchtags' ])) {
1154 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1155 // Remove value from array $tags.
1156 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1157 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1159 if ( empty ( $params [ 'searchtags' ])) {
1160 unset ( $params [ 'searchtags' ]);
1163 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1165 header ( 'Location: ?' . http_build_query ( $params ));
1169 // -------- User wants to change the number of links per page (linksperpage=...)
1170 if ( isset ( $_GET [ 'linksperpage' ])) {
1171 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1172 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1175 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1179 // -------- User wants to see only private links (toggle)
1180 if ( isset ( $_GET [ 'privateonly' ])) {
1181 if ( empty ( $_SESSION [ 'privateonly' ])) {
1182 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1184 unset ( $_SESSION [ 'privateonly' ]); // See all links
1187 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1191 // -------- Handle other actions allowed for non-logged in users:
1194 // User tries to post new link but is not logged in:
1195 // Show login screen, then redirect to ?post=...
1196 if ( isset ( $_GET [ 'post' ]))
1198 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.
1202 showLinkList ( $PAGE , $LINKSDB );
1203 if ( isset ( $_GET [ 'edit_link' ])) {
1204 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1208 exit ; // Never remove this one! All operations below are reserved for logged in user.
1211 // -------- All other functions are reserved for the registered user:
1213 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1214 if ( $targetPage == Router
:: $PAGE_TOOLS )
1217 'linkcount' => count ( $LINKSDB ),
1218 'pageabsaddr' => index_url ( $_SERVER ),
1220 $pluginManager- > executeHooks ( 'render_tools' , $data );
1222 foreach ( $data as $key => $value ) {
1223 $PAGE- > assign ( $key , $value );
1226 $PAGE- > renderPage ( 'tools' );
1230 // -------- User wants to change his/her password.
1231 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1233 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1234 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1236 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1238 // Make sure old password is correct.
1239 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1240 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1241 // Save new password
1242 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1243 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1245 writeConfig ( $GLOBALS , isLoggedIn ());
1247 catch ( Exception
$e ) {
1249 'ERROR while writing config file after changing password.' . PHP_EOL
.
1253 // TODO: do not handle exceptions/errors in JS.
1254 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1257 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1260 else // show the change password form.
1262 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1263 $PAGE- > assign ( 'token' , getToken ());
1264 $PAGE- > renderPage ( 'changepassword' );
1269 // -------- User wants to change configuration
1270 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1272 if (! empty ( $_POST [ 'title' ]) )
1274 if (! tokenOk ( $_POST [ 'token' ])) {
1275 die ( 'Wrong token.' ); // Go away!
1278 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1279 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1281 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1283 $GLOBALS [ 'timezone' ] = $tz ;
1284 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1285 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1286 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1287 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1288 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1289 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1290 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1291 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1293 writeConfig ( $GLOBALS , isLoggedIn ());
1295 catch ( Exception
$e ) {
1297 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1301 // TODO: do not handle exceptions/errors in JS.
1302 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1305 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1308 else // Show the configuration form.
1310 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1311 $PAGE- > assign ( 'token' , getToken ());
1312 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1313 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1314 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1315 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1316 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1317 $PAGE- > renderPage ( 'configure' );
1322 // -------- User wants to rename a tag or delete it
1323 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1325 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1326 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1327 $PAGE- > assign ( 'token' , getToken ());
1328 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1329 $PAGE- > renderPage ( 'changetag' );
1333 if (! tokenOk ( $_POST [ 'token' ])) {
1334 die ( 'Wrong token.' );
1338 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1339 $needle = trim ( $_POST [ 'fromtag' ]);
1340 // True for case-sensitive tag search.
1341 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1342 foreach ( $linksToAlter as $key => $value )
1344 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1345 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1346 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1347 $LINKSDB [ $key ]= $value ;
1349 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1350 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1355 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1356 $needle = trim ( $_POST [ 'fromtag' ]);
1357 // True for case-sensitive tag search.
1358 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1359 foreach ( $linksToAlter as $key => $value )
1361 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1362 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1363 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1364 $LINKSDB [ $key ]= $value ;
1366 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1367 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1372 // -------- User wants to add a link without using the bookmarklet: Show form.
1373 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1375 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1376 $PAGE- > renderPage ( 'addlink' );
1380 // -------- User clicked the "Save" button when editing a link: Save link to database.
1381 if ( isset ( $_POST [ 'save_edit' ]))
1384 if (! tokenOk ( $_POST [ 'token' ])) {
1385 die ( 'Wrong token.' );
1387 // Remove multiple spaces.
1388 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1389 // Remove first '-' char in tags.
1390 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1391 // Remove duplicates.
1392 $tags = implode(' ', array_unique(explode(' ', $tags )));
1393 $linkdate = $_POST [' lf_linkdate
'];
1394 $url = trim( $_POST [' lf_url
']);
1395 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1396 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1397 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1399 $url = ' http
: //' . $url;
1403 'title' => trim ( $_POST [ 'lf_title' ]),
1405 'description' => $_POST [ 'lf_description' ],
1406 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1407 'linkdate' => $linkdate ,
1408 'tags' => str_replace ( ',' , ' ' , $tags )
1410 // If title is empty, use the URL as title.
1411 if ( $link [ 'title' ] == '' ) {
1412 $link [ 'title' ] = $link [ 'url' ];
1415 $pluginManager- > executeHooks ( 'save_link' , $link );
1417 $LINKSDB [ $linkdate ] = $link ;
1418 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1421 // If we are called from the bookmarklet, we must close the popup:
1422 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1423 echo '<script>self.close();</script>' ;
1427 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1428 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1429 // Scroll to the link which has been edited.
1430 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1431 // After saving the link, redirect to the page the user was on.
1432 header ( 'Location: ' . $location );
1436 // -------- User clicked the "Cancel" button when editing a link.
1437 if ( isset ( $_POST [ 'cancel_edit' ]))
1439 // If we are called from the bookmarklet, we must close the popup:
1440 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1441 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1442 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1443 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1444 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1448 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1449 if ( isset ( $_POST [ 'delete_link' ]))
1451 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1452 // We do not need to ask for confirmation:
1453 // - confirmation is handled by JavaScript
1454 // - we are protected from XSRF by the token.
1455 $linkdate = $_POST [ 'lf_linkdate' ];
1457 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1459 unset ( $LINKSDB [ $linkdate ]);
1460 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1462 // If we are called from the bookmarklet, we must close the popup:
1463 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1464 // Pick where we're going to redirect
1465 // =============================================================
1466 // Basically, we can't redirect to where we were previously if it was a permalink
1467 // or an edit_link, because it would 404.
1469 // - / : nothing in $_GET, redirect to self
1470 // - /?page : redirect to self
1471 // - /?searchterm : redirect to self (there might be other links)
1472 // - /?searchtags : redirect to self
1473 // - /permalink : redirect to / (the link does not exist anymore)
1474 // - /?edit_link : redirect to / (the link does not exist anymore)
1475 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1476 // redirect is not satisfied, and only then redirect to /
1479 if ( count ( $_GET ) == 0
1480 || isset ( $_GET [ 'page' ])
1481 || isset ( $_GET [ 'searchterm' ])
1482 || isset ( $_GET [ 'searchtags' ])
1484 if ( isset ( $_POST [ 'returnurl' ])) {
1485 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1487 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1491 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1495 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1496 if ( isset ( $_GET [ 'edit_link' ]))
1498 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1499 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1501 'linkcount' => count ( $LINKSDB ),
1503 'link_is_new' => false ,
1504 'token' => getToken (),
1505 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1506 'tags' => $LINKSDB- > allTags (),
1508 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1510 foreach ( $data as $key => $value ) {
1511 $PAGE- > assign ( $key , $value );
1514 $PAGE- > renderPage ( 'editlink' );
1518 // -------- User want to post a new link: Display link edit form.
1519 if ( isset ( $_GET [ 'post' ])) {
1520 $url = cleanup_url ( $_GET [ 'post' ]);
1522 $link_is_new = false ;
1523 // Check if URL is not already in database (in this case, we will edit the existing link)
1524 $link = $LINKSDB- > getLinkFromUrl ( $url );
1527 $link_is_new = true ;
1528 $linkdate = strval ( date ( 'Ymd_His' ));
1529 // Get title if it was provided in URL (by the bookmarklet).
1530 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1531 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1532 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1533 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1534 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1535 // 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.)
1536 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1537 // Short timeout to keep the application responsive
1538 list ( $headers , $content ) = get_http_response ( $url , 4 );
1539 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1540 // Retrieve charset.
1541 $charset = get_charset ( $headers , $content );
1543 $title = html_extract_title ( $content );
1544 // Re-encode title in utf-8 if necessary.
1545 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1546 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1552 $url = '?' . smallHash ( $linkdate );
1555 $url = escape ( $url );
1556 $title = escape ( $title );
1559 'linkdate' => $linkdate ,
1562 'description' => $description ,
1564 'private' => $private
1569 'linkcount' => count ( $LINKSDB ),
1571 'link_is_new' => $link_is_new ,
1572 'token' => getToken (), // XSRF protection.
1573 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1574 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1575 'tags' => $LINKSDB- > allTags (),
1577 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1579 foreach ( $data as $key => $value ) {
1580 $PAGE- > assign ( $key , $value );
1583 $PAGE- > renderPage ( 'editlink' );
1587 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1588 // Export links as a Netscape Bookmarks file
1590 if ( empty ( $_GET [ 'selection' ])) {
1591 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1592 $PAGE- > renderPage ( 'export' );
1596 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1597 $selection = $_GET [ 'selection' ];
1598 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1599 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1601 $prependNoteUrl = false ;
1607 NetscapeBookmarkUtils
:: filterAndFormat (
1614 } catch ( Exception
$exc ) {
1615 header ( 'Content-Type: text/plain; charset=utf-8' );
1616 echo $exc- > getMessage ();
1619 $now = new DateTime ();
1620 header ( 'Content-Type: text/html; charset=utf-8' );
1622 'Content-disposition: attachment; filename=bookmarks_'
1623 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1625 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1626 $PAGE- > assign ( 'eol' , PHP_EOL
);
1627 $PAGE- > assign ( 'selection' , $selection );
1628 $PAGE- > renderPage ( 'export.bookmarks' );
1632 // -------- User is uploading a file for import
1633 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1635 // If file is too big, some form field may be missing.
1636 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1638 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1639 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>' ;
1642 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1643 importFile ( $LINKSDB );
1647 // -------- Show upload/import dialog:
1648 if ( $targetPage == Router
:: $PAGE_IMPORT )
1650 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1651 $PAGE- > assign ( 'token' , getToken ());
1652 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1653 $PAGE- > renderPage ( 'import' );
1657 // Plugin administration page
1658 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1659 $pluginMeta = $pluginManager- > getPluginsMeta ();
1661 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1662 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1664 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1667 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1669 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1671 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1672 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1673 $PAGE- > renderPage ( 'pluginsadmin' );
1677 // Plugin administration form action
1678 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1680 if ( isset ( $_POST [ 'parameters_form' ])) {
1681 unset ( $_POST [ 'parameters_form' ]);
1682 foreach ( $_POST as $param => $value ) {
1683 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1687 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1689 writeConfig ( $GLOBALS , isLoggedIn ());
1691 catch ( Exception
$e ) {
1693 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1697 // TODO: do not handle exceptions/errors in JS.
1698 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1701 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1705 // -------- Otherwise, simply display search form and links:
1706 showLinkList ( $PAGE , $LINKSDB );
1710 // -----------------------------------------------------------------------------------------------
1711 // Process the import file form.
1712 function importFile ( $LINKSDB )
1714 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1716 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1717 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1718 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1719 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1720 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1725 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1727 // Then import the bookmarks.
1728 if ( $type == 'netscape' )
1730 // This is a standard Netscape-style bookmark file.
1731 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1732 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1734 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1735 $d = explode ( '<DD>' , $html );
1736 if ( startswith ( $d [ 0 ], '<A ' ))
1738 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1739 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1740 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1741 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1743 foreach ( $matches as $m )
1745 $attr = $m [ 1 ]; $value = $m [ 2 ];
1746 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1747 elseif ( $attr == 'ADD_DATE' )
1749 $raw_add_date = intval ( $value );
1750 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1752 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1753 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1755 if ( $link [ 'url' ]!= '' )
1757 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1758 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1760 { // Link not in database, let's import it...
1761 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1763 // Make sure date/time is not already used by another link.
1764 // (Some bookmark files have several different links with the same ADD_DATE)
1765 // We increment date by 1 second until we find a date which is not used in DB.
1766 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1767 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1768 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1769 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1772 else // Link already present in database.
1775 { // If overwrite is required, we import link data, except date/time.
1776 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1777 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1785 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1787 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1791 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1796 * Template for the list of links (<div id="linklist">)
1797 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1799 * @param pageBuilder $PAGE pageBuilder instance.
1800 * @param LinkDB $LINKSDB LinkDB instance.
1802 function buildLinkList ( $PAGE , $LINKSDB )
1804 // Used in templates
1805 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1806 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1809 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1810 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1812 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1813 } catch ( LinkNotFoundException
$e ) {
1814 $PAGE- > render404 ( $e- > getMessage ());
1818 // Filter links according search parameters.
1819 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1820 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1823 // ---- Handle paging.
1825 foreach ( $linksToDisplay as $key => $value ) {
1829 // If there is only a single link, we change on-the-fly the title of the page.
1830 if ( count ( $linksToDisplay ) == 1 ) {
1831 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1834 // Select articles according to paging.
1835 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1836 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1837 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1838 $page = $page < 1 ? 1 : $page ;
1839 $page = $page > $pagecount ? $pagecount : $page ;
1841 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1842 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1843 $linkDisp = array ();
1844 while ( $i < $end && $i < count ( $keys ))
1846 $link = $linksToDisplay [ $keys [ $i ]];
1847 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1848 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1849 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1850 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1851 $link [ 'timestamp' ] = $date- > getTimestamp ();
1852 $taglist = explode ( ' ' , $link [ 'tags' ]);
1853 uasort ( $taglist , 'strcasecmp' );
1854 $link [ 'taglist' ] = $taglist ;
1855 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1856 // Check for both signs of a note: starting with ? and 7 chars long.
1857 if ( $link [ 'url' ][ 0 ] === '?' &&
1858 strlen ( $link [ 'url' ]) === 7 ) {
1859 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1862 $linkDisp [ $keys [ $i ]] = $link ;
1866 // Compute paging navigation
1867 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1868 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1869 $previous_page_url = '' ;
1870 if ( $i != count ( $keys )) {
1871 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1875 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1878 $token = isLoggedIn () ? getToken () : '' ;
1880 // Fill all template fields.
1882 'linkcount' => count ( $LINKSDB ),
1883 'previous_page_url' => $previous_page_url ,
1884 'next_page_url' => $next_page_url ,
1885 'page_current' => $page ,
1886 'page_max' => $pagecount ,
1887 'result_count' => count ( $linksToDisplay ),
1888 'search_term' => $searchterm ,
1889 'search_tags' => $searchtags ,
1890 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
1892 'links' => $linkDisp ,
1893 'tags' => $LINKSDB- > allTags (),
1895 // FIXME! temporary fix - see #399.
1896 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
1897 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
1900 $pluginManager = PluginManager
:: getInstance ();
1901 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1903 foreach ( $data as $key => $value ) {
1904 $PAGE- > assign ( $key , $value );
1910 // Compute the thumbnail for a link.
1912 // With a link to the original URL.
1913 // Understands various services (youtube.com...)
1914 // Input: $url = URL for which the thumbnail must be found.
1915 // $href = if provided, this URL will be followed instead of $url
1916 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1917 // Some of them may be missing.
1918 // Return an empty array if no thumbnail available.
1919 function computeThumbnail ( $url , $href = false )
1921 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
1922 if ( $href == false ) $href = $url ;
1924 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1925 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1926 // ^^^^^^^^^^^ ^^^^^^^^^^^
1927 $domain = parse_url ( $url , PHP_URL_HOST
);
1928 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1930 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1931 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1932 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1934 if ( $domain == 'youtu.be' ) // Youtube short links
1936 $path = parse_url ( $url , PHP_URL_PATH
);
1937 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1938 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1940 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1942 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1943 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1944 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1947 if ( $domain == 'imgur.com' )
1949 $path = parse_url ( $url , PHP_URL_PATH
);
1950 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1951 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1952 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1953 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1954 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1956 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1957 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1959 if ( $domain == 'i.imgur.com' )
1961 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1962 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1963 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1965 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1967 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1969 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1970 return array ( 'src' => $thumburl ,
1971 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1974 if ( endsWith ( $domain , '.imageshack.us' ))
1976 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1977 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1979 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1980 return array ( 'src' => $thumburl ,
1981 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1985 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1986 // So we deport the thumbnail generation in order not to slow down page generation
1987 // (and we also cache the thumbnail)
1989 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1991 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1992 || $domain == 'vimeo.com'
1993 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1994 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1997 if ( $domain == 'vimeo.com' )
1998 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1999 $path = parse_url ( $url , PHP_URL_PATH
);
2000 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2002 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2003 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2004 $path = parse_url ( $url , PHP_URL_PATH
);
2005 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2007 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2008 { // Make sure this TED URL points to a video (/talks/...)
2009 $path = parse_url ( $url , PHP_URL_PATH
);
2010 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2012 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2013 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2014 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2017 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2018 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2019 // But using the extension will do.
2020 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2021 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2023 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2024 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2025 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2027 return array (); // No thumbnail.
2032 // Returns the HTML code to display a thumbnail for a link
2033 // with a link to the original URL.
2034 // Understands various services (youtube.com...)
2035 // Input: $url = URL for which the thumbnail must be found.
2036 // $href = if provided, this URL will be followed instead of $url
2037 // Returns '' if no thumbnail available.
2038 function thumbnail ( $url , $href = false )
2040 $t = computeThumbnail ( $url , $href );
2041 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2043 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2044 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2045 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2046 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2047 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2052 // Returns the HTML code to display a thumbnail for a link
2053 // for the picture wall (using lazy image loading)
2054 // Understands various services (youtube.com...)
2055 // Input: $url = URL for which the thumbnail must be found.
2056 // $href = if provided, this URL will be followed instead of $url
2057 // Returns '' if no thumbnail available.
2058 function lazyThumbnail ( $url , $href = false )
2060 $t = computeThumbnail ( $url , $href );
2061 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2063 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2066 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2068 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2069 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2070 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2071 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2074 // No-JavaScript fallback.
2075 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2076 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2077 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2078 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2079 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2080 $html .= '></noscript></a>' ;
2086 // -----------------------------------------------------------------------------------------------
2088 // This function should NEVER be called if the file data/config.php exists.
2091 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2092 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2095 // This part makes sure sessions works correctly.
2096 // (Because on some hosts, session.save_path may not be set correctly,
2097 // or we may not have write access to it.)
2098 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2099 { // Step 2: Check if data in session is correct.
2100 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2101 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2102 echo 'It currently points to ' . session_save_path (). '<br>' ;
2103 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>' ;
2104 echo '<br><a href="?">Click to try again.</a></pre>' ;
2107 if (! isset ( $_SESSION [ 'session_tested' ]))
2108 { // Step 1 : Try to store data in session and reload page.
2109 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2110 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2112 if ( isset ( $_GET [ 'test_session' ]))
2113 { // Step 3: Sessions are OK. Remove test parameter from URL.
2114 header ( 'Location: ' . index_url ( $_SERVER ));
2118 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2121 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
2122 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
2124 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2126 $GLOBALS [ 'timezone' ] = $tz ;
2127 // Everything is ok, let's create config file.
2128 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2129 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2130 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2131 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2132 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2134 writeConfig ( $GLOBALS , isLoggedIn ());
2136 catch ( Exception
$e ) {
2138 'ERROR while writing config file after installation.' . PHP_EOL
.
2142 // TODO: do not handle exceptions/errors in JS.
2143 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2146 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2150 // Display config form:
2151 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2152 $timezone_html = '' ;
2153 if ( $timezone_form != '' ) {
2154 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2157 $PAGE = new pageBuilder
;
2158 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2159 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2160 $PAGE- > renderPage ( 'install' );
2164 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2165 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2166 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2167 This function is called by passing the URL:
2168 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2169 [URL] is the URL of the link (e.g. a flickr page)
2170 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2171 The function below will fetch the image from the webservice and store it in the cache.
2173 function genThumbnail ()
2175 // Make sure the parameters in the URL were generated by us.
2176 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2177 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2179 // Let's see if we don't already have the image for this URL in the cache.
2180 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2181 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2182 { // We have the thumbnail, just serve it:
2183 header ( 'Content-Type: image/jpeg' );
2184 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2187 // We may also serve a blank image (if service did not respond)
2188 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2189 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2191 header ( 'Content-Type: image/gif' );
2192 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2196 // Otherwise, generate the thumbnail.
2197 $url = $_GET [ 'url' ];
2198 $domain = parse_url ( $url , PHP_URL_HOST
);
2200 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2202 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2203 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2205 // Is this a link to an image, or to a flickr page ?
2207 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2208 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2209 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2210 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2212 else // This is a flickr page (html)
2214 // Get the flickr html page.
2215 list ( $headers , $content ) = get_http_response ( $url , 20 );
2216 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2218 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2219 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2220 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2222 // In albums (and some other pages), the link rel="image_src" is not provided,
2223 // but flickr provides:
2224 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2227 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2228 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2234 { // Let's download the image.
2235 // Image is 240x120, so 10 seconds to download should be enough.
2236 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2237 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2238 // Save image to cache.
2239 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2240 header ( 'Content-Type: image/jpeg' );
2247 elseif ( $domain == 'vimeo.com' )
2249 // This is more complex: we have to perform a HTTP request, then parse the result.
2250 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2251 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2252 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2253 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2254 $t = unserialize ( $content );
2255 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2256 // Then we download the image and serve it to our client.
2257 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2258 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2259 // Save image to cache.
2260 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2261 header ( 'Content-Type: image/jpeg' );
2268 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2270 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2271 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2272 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2273 list ( $headers , $content ) = get_http_response ( $url , 5 );
2274 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2275 // Extract the link to the thumbnail
2276 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2277 if (! empty ( $matches [ 1 ]))
2278 { // Let's download the image.
2279 $imageurl = $matches [ 1 ];
2280 // No control on image size, so wait long enough
2281 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2282 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2283 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2284 file_put_contents ( $filepath , $content ); // Save image to cache.
2285 if ( resizeImage ( $filepath ))
2287 header ( 'Content-Type: image/jpeg' );
2288 echo file_get_contents ( $filepath );
2296 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2298 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2299 // http://xkcd.com/327/
2300 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2301 list ( $headers , $content ) = get_http_response ( $url , 5 );
2302 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2303 // Extract the link to the thumbnail
2304 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2305 if (! empty ( $matches [ 1 ]))
2306 { // Let's download the image.
2307 $imageurl = $matches [ 1 ];
2308 // No control on image size, so wait long enough
2309 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2310 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2311 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2312 // Save image to cache.
2313 file_put_contents ( $filepath , $content );
2314 if ( resizeImage ( $filepath ))
2316 header ( 'Content-Type: image/jpeg' );
2317 echo file_get_contents ( $filepath );
2327 // For all other domains, we try to download the image and make a thumbnail.
2328 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2329 list ( $headers , $content ) = get_http_response ( $url , 30 );
2330 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2331 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2332 // Save image to cache.
2333 file_put_contents ( $filepath , $content );
2334 if ( resizeImage ( $filepath ))
2336 header ( 'Content-Type: image/jpeg' );
2337 echo file_get_contents ( $filepath );
2344 // Otherwise, return an empty image (8x8 transparent gif)
2345 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2346 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2347 header ( 'Content-Type: image/gif' );
2351 // Make a thumbnail of the image (to width: 120 pixels)
2352 // Returns true if success, false otherwise.
2353 function resizeImage ( $filepath )
2355 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2357 // Trick: some stupid people rename GIF as JPEG... or else.
2358 // So we really try to open each image type whatever the extension is.
2359 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2361 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2362 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2363 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2364 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2367 $ystart = 0 ; $yheight = $h ;
2368 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2369 $nw = 120 ; // Desired width
2370 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2372 $im2 = imagecreatetruecolor ( $nw , $nh );
2373 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2374 imageinterlace ( $im2 , true ); // For progressive JPEG.
2375 $tempname = $filepath . '_TEMP.jpg' ;
2376 imagejpeg ( $im2 , $tempname , 90 );
2380 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2384 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2385 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2386 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];