]>
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 ;
105 * Plugin configuration
107 * Warning: order matters!
109 * These settings may be be overriden in:
111 * - each plugin's configuration file
113 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
114 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
115 // 'wallabag', 'markdown', 'addlink_toolbar',
117 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
119 // Initialize plugin parameters array.
120 $GLOBALS [ 'plugins' ] = array ();
122 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
123 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
128 define ( 'shaarli_version' , '0.6.5' );
130 // http://server.com/x/shaarli --> /shaarli/
131 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
133 // High execution time in case of problematic imports/exports.
134 ini_set ( 'max_input_time' , '60' );
136 // Try to set max upload file size and read
137 ini_set ( 'memory_limit' , '128M' );
138 ini_set ( 'post_max_size' , '16M' );
139 ini_set ( 'upload_max_filesize' , '16M' );
141 // See all error except warnings
142 error_reporting ( E_ALL^E_WARNING
);
143 // See all errors (for debugging only)
144 //error_reporting(-1);
149 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
150 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
154 require_once 'application/ApplicationUtils.php' ;
155 require_once 'application/Cache.php' ;
156 require_once 'application/CachedPage.php' ;
157 require_once 'application/FeedBuilder.php' ;
158 require_once 'application/FileUtils.php' ;
159 require_once 'application/HttpUtils.php' ;
160 require_once 'application/LinkDB.php' ;
161 require_once 'application/LinkFilter.php' ;
162 require_once 'application/LinkUtils.php' ;
163 require_once 'application/TimeZone.php' ;
164 require_once 'application/Url.php' ;
165 require_once 'application/Utils.php' ;
166 require_once 'application/Config.php' ;
167 require_once 'application/PluginManager.php' ;
168 require_once 'application/Router.php' ;
169 require_once 'application/Updater.php' ;
171 // Ensure the PHP version is supported
173 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
174 } catch ( Exception
$exc ) {
175 header ( 'Content-Type: text/plain; charset=utf-8' );
176 echo $exc- > getMessage ();
180 // Force cookie path (but do not change lifetime)
181 $cookie = session_get_cookie_params ();
183 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
184 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
186 // Set default cookie expiration and path.
187 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
188 // Set session parameters on server side.
189 // If the user does not access any page within this time, his/her session is considered expired.
190 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
191 // Use cookies to store session.
192 ini_set ( 'session.use_cookies' , 1 );
193 // Force cookies for session (phpsessionID forbidden in URL).
194 ini_set ( 'session.use_only_cookies' , 1 );
195 // Prevent PHP form using sessionID in URL if cookies are disabled.
196 ini_set ( 'session.use_trans_sid' , false );
198 session_name ( 'shaarli' );
199 // Start session if needed (Some server auto-start sessions).
200 if ( session_id () == '' ) {
204 // Regenerate session ID if invalid or not defined in cookie.
205 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
206 session_regenerate_id ( true );
207 $_COOKIE [ 'shaarli' ] = session_id ();
210 include "inc/rain.tpl.class.php" ; //include Rain TPL
211 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
212 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
214 $pluginManager = PluginManager
:: getInstance ();
215 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
217 ob_start (); // Output buffering for the page cache.
220 // In case stupid admin has left magic_quotes enabled in php.ini:
221 if ( get_magic_quotes_gpc ())
223 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
224 $_POST = array_map ( 'stripslashes_deep' , $_POST );
225 $_GET = array_map ( 'stripslashes_deep' , $_GET );
226 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
229 // Prevent caching on client side or proxy: (yes, it's ugly)
230 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
231 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
232 header ( "Cache-Control: post-check=0, pre-check=0" , false );
233 header ( "Pragma: no-cache" );
235 // Handling of old config file which do not have the new parameters.
236 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
237 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
238 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
239 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
240 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
241 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
242 // I really need to rewrite Shaarli with a proper configuation manager.
244 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
245 // Ensure Shaarli has proper access to its resources
246 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
248 if ( $errors != array ()) {
249 $message = '<p>Insufficient permissions:</p><ul>' ;
251 foreach ( $errors as $error ) {
252 $message .= '<li>' . $error . '</li>' ;
256 header ( 'Content-Type: text/html; charset=utf-8' );
261 // Display the installation form if no existing config is found
265 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
266 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
267 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
269 // a token depending of deployment salt, user password, and the current ip
270 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
272 // Sniff browser language and set date format accordingly.
273 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
274 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
276 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
278 //==================================================================================================
279 // Checking session state (i.e. is the user still logged in)
280 //==================================================================================================
282 function setup_login_state () {
283 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
286 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
287 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
288 if (! isset ( $GLOBALS [ 'login' ])) {
289 $userIsLoggedIn = false ; // Shaarli is not configured yet.
290 $loginFailure = true ;
292 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
293 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
297 $userIsLoggedIn = true ;
299 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
300 if ( empty ( $_SESSION [ 'uid' ]) ||
301 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
302 time () >= $_SESSION [ 'expires_on' ])
305 $userIsLoggedIn = false ;
306 $loginFailure = true ;
308 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
309 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
312 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
314 if (! $loginFailure ) {
315 $userIsLoggedIn = true ;
318 return $userIsLoggedIn ;
320 $userIsLoggedIn = setup_login_state ();
322 // ------------------------------------------------------------------------------------------
323 // PubSubHubbub protocol support (if enabled) [UNTESTED]
324 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
325 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
328 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
330 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
332 index_url ( $_SERVER ). '?do=atom' ,
333 index_url ( $_SERVER ). '?do=rss'
335 $p- > publish_update ( $topic_url );
339 // ------------------------------------------------------------------------------------------
340 // Session management
342 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
345 $ip = $_SERVER [ "REMOTE_ADDR" ];
346 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
347 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
348 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
352 function fillSessionInfo () {
353 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
354 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
355 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
356 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
359 // Check that user/password is correct.
360 function check_auth ( $login , $password )
362 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
363 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
364 { // Login/password is correct.
366 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
369 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
373 // Returns true if the user is logged in.
374 function isLoggedIn ()
376 global $userIsLoggedIn ;
377 return $userIsLoggedIn ;
382 if ( isset ( $_SESSION )) {
383 unset ( $_SESSION [ 'uid' ]);
384 unset ( $_SESSION [ 'ip' ]);
385 unset ( $_SESSION [ 'username' ]);
386 unset ( $_SESSION [ 'privateonly' ]);
388 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
392 // ------------------------------------------------------------------------------------------
393 // Brute force protection system
394 // Several consecutive failed logins will ban the IP address for 30 minutes.
395 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 ?>" );
396 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
397 // Signal a failed login. Will ban the IP if too many failures:
398 function ban_loginFailed ()
400 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
401 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
402 $gb [ 'FAILURES' ][ $ip ] ++
;
403 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
405 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
406 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
408 $GLOBALS [ 'IPBANS' ] = $gb ;
409 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
412 // Signals a successful login. Resets failed login counter.
413 function ban_loginOk ()
415 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
416 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
417 $GLOBALS [ 'IPBANS' ] = $gb ;
418 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
421 // Checks if the user CAN login. If 'true', the user can try to login.
422 function ban_canLogin ()
424 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
425 if ( isset ( $gb [ 'BANS' ][ $ip ]))
427 // User is banned. Check if the ban has expired:
428 if ( $gb [ 'BANS' ][ $ip ]<= time ())
429 { // Ban expired, user can try to login again.
430 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
431 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
432 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
433 return true ; // Ban has expired, user can login.
435 return false ; // User is banned.
437 return true ; // User is not banned.
440 // ------------------------------------------------------------------------------------------
441 // Process login form: Check if login/password is correct.
442 if ( isset ( $_POST [ 'login' ]))
444 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
445 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
446 { // Login/password is OK.
448 // If user wants to keep the session cookie even after the browser closes:
449 if (! empty ( $_POST [ 'longlastingsession' ]))
451 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
452 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
453 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
455 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
456 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
457 // Note: Never forget the trailing slash on the cookie path!
458 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
460 else // Standard session expiration (=when browser closes)
462 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
463 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
464 session_regenerate_id ( true );
467 // Optional redirect after login:
468 if ( isset ( $_GET [ 'post' ])) {
469 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
470 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
471 if (! empty ( $_GET [ $param ])) {
472 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
475 header ( 'Location: ' . $uri );
479 if ( isset ( $_GET [ 'edit_link' ])) {
480 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
484 if ( isset ( $_POST [ 'returnurl' ])) {
485 // Prevent loops over login screen.
486 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
487 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
491 header ( 'Location: ?' ); exit ;
497 if ( isset ( $_GET [ 'post' ])) {
498 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
499 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
500 if (! empty ( $_GET [ $param ])) {
501 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
505 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
510 // ------------------------------------------------------------------------------------------
511 // Misc utility functions:
513 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
514 function return_bytes ( $val )
516 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
519 case 'g' : $val *= 1024 ;
520 case 'm' : $val *= 1024 ;
521 case 'k' : $val *= 1024 ;
526 // Try to determine max file size for uploads (POST).
527 // Returns an integer (in bytes)
528 function getMaxFileSize ()
530 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
531 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
532 // Return the smaller of two:
533 $maxsize = min ( $size1 , $size2 );
534 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
538 // ------------------------------------------------------------------------------------------
539 // Token management for XSRF protection
540 // Token should be used in any form which acts on data (create,update,delete,import...).
541 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
546 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
547 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
551 // Tells if a token is OK. Using this function will destroy the token.
553 function tokenOk ( $token )
555 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
557 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
558 return true ; // Token is OK.
560 return false ; // Wrong token, or already used.
563 // ------------------------------------------------------------------------------------------
564 /* This class is in charge of building the final page.
565 (This is basically a wrapper around RainTPL which pre-fills some fields.)
567 p.assign('myfield','myvalue');
568 p.renderPage('mytemplate');
573 private $tpl ; // RainTPL template
575 function __construct ()
581 * Initialize all default tpl tags.
583 private function initialize ()
585 $this- > tpl
= new RainTPL
;
588 $version = ApplicationUtils
:: checkUpdate (
590 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
591 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
592 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
594 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ]
596 $this- > tpl
-> assign ( 'newVersion' , escape ( $version ));
597 $this- > tpl
-> assign ( 'versionError' , '' );
599 } catch ( Exception
$exc ) {
600 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], $exc- > getMessage ());
601 $this- > tpl
-> assign ( 'newVersion' , '' );
602 $this- > tpl
-> assign ( 'versionError' , escape ( $exc- > getMessage ()));
605 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
606 $searchcrits = '' ; // Search criteria
607 if (! empty ( $_GET [ 'searchtags' ])) {
608 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
610 if (! empty ( $_GET [ 'searchterm' ])) {
611 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
613 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
614 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
615 $this- > tpl
-> assign ( 'version' , shaarli_version
);
616 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
617 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
618 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
619 if (! empty ( $GLOBALS [ 'title' ])) {
620 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
622 if (! empty ( $GLOBALS [ 'titleLink' ])) {
623 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
625 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
626 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
628 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
629 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
630 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
634 // The following assign() method is basically the same as RainTPL (except that it's lazy)
635 public function assign ( $what , $where )
637 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
638 $this- > tpl
-> assign ( $what , $where );
642 * Assign an array of data to the template builder.
644 * @param array $data Data to assign.
646 * @return false if invalid data.
648 public function assignAll ( $data )
650 // Lazy initialization
651 if ( $this- > tpl
=== false ) {
655 if ( empty ( $data ) || ! is_array ( $data )){
659 foreach ( $data as $key => $value ) {
660 $this- > assign ( $key , $value );
664 // Render a specific page (using a template).
665 // e.g. pb.renderPage('picwall')
666 public function renderPage ( $page )
668 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
669 $this- > tpl
-> draw ( $page );
673 * Render a 404 page (uses the template : tpl/404.tpl)
675 * usage : $PAGE->render404('The link was deleted')
676 * @param string $message A messate to display what is not found
678 public function render404 ( $message = 'The page you are trying to reach does not exist or has been deleted.' ) {
679 header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
680 $this- > tpl
-> assign ( 'error_message' , $message );
681 $this- > renderPage ( '404' );
685 // ------------------------------------------------------------------------------------------
686 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
687 // Gives the last 7 days (which have links).
688 // This RSS feed cannot be filtered.
689 function showDailyRSS () {
691 $query = $_SERVER [ "QUERY_STRING" ];
692 $cache = new CachedPage (
693 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
695 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
697 $cached = $cache- > cachedVersion ();
698 if (! empty ( $cached )) {
703 // If cached was not found (or not usable), then read the database and build the response:
704 // Read links from database (and filter private links if used it not logged in).
705 $LINKSDB = new LinkDB (
706 $GLOBALS [ 'config' ][ 'DATASTORE' ],
708 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
709 $GLOBALS [ 'redirector' ]
712 /* Some Shaarlies may have very few links, so we need to look
713 back in time (rsort()) until we have enough days ($nb_of_days).
715 $linkdates = array ();
716 foreach ( $LINKSDB as $linkdate => $value ) {
717 $linkdates [] = $linkdate ;
720 $nb_of_days = 7 ; // We take 7 days.
721 $today = Date ( 'Ymd' );
724 foreach ( $linkdates as $linkdate ) {
725 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
726 if ( strcmp ( $day , $today ) < 0 ) {
727 if ( empty ( $days [ $day ])) {
728 $days [ $day ] = array ();
730 $days [ $day ][] = $linkdate ;
733 if ( count ( $days ) > $nb_of_days ) {
734 break ; // Have we collected enough days?
738 // Build the RSS feed.
739 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
740 $pageaddr = escape ( index_url ( $_SERVER ));
741 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
743 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
744 echo '<link>' . $pageaddr . '</link>' ;
745 echo '<description>Daily shared links</description>' ;
746 echo '<language>en-en</language>' ;
747 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
750 foreach ( $days as $day => $linkdates ) {
751 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
752 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
754 // Build the HTML body of this RSS entry.
759 // We pre-format some fields for proper output.
760 foreach ( $linkdates as $linkdate ) {
761 $l = $LINKSDB [ $linkdate ];
762 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
763 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
764 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
765 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
766 if ( startsWith ( $l [ 'url' ], '?' )) {
767 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
769 $links [ $linkdate ] = $l ;
772 // Then build the HTML for this day:
774 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
775 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
776 $tpl- > assign ( 'absurl' , $absurl );
777 $tpl- > assign ( 'links' , $links );
778 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
779 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
781 echo $html . PHP_EOL
;
783 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
785 $cache- > cache ( ob_get_contents ());
791 * Show the 'Daily' page.
793 * @param PageBuilder $pageBuilder Template engine wrapper.
795 function showDaily ( $pageBuilder )
797 $LINKSDB = new LinkDB (
798 $GLOBALS [ 'config' ][ 'DATASTORE' ],
800 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
801 $GLOBALS [ 'redirector' ]
804 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
805 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
807 $days = $LINKSDB- > days ();
808 $i = array_search ( $day , $days );
809 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
814 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
815 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
819 $linksToDisplay = $LINKSDB- > filter ( LinkFilter
:: $FILTER_DAY , $day );
820 } catch ( Exception
$exc ) {
822 $linksToDisplay = array ();
825 // We pre-format some fields for proper output.
826 foreach ( $linksToDisplay as $key => $link )
829 $taglist = explode ( ' ' , $link [ 'tags' ]);
830 uasort ( $taglist , 'strcasecmp' );
831 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
832 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
833 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
834 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
835 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
838 /* We need to spread the articles on 3 columns.
839 I did not want to use a JavaScript lib like http://masonry.desandro.com/
840 so I manually spread entries with a simple method: I roughly evaluate the
841 height of a div according to title and description length.
843 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
844 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
845 foreach ( $linksToDisplay as $key => $link )
847 // Roughly estimate length of entry (by counting characters)
848 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
849 // Description: 836 characters gives roughly 342 pixel height.
850 // This is not perfect, but it's usually OK.
851 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
852 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
853 // Then put in column which is the less filled:
854 $smallest = min ( $fill ); // find smallest value in array.
855 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
856 array_push ( $columns [ $index ], $link ); // Put entry in this column.
857 $fill [ $index ] +
= $length ;
860 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
862 'linksToDisplay' => $linksToDisplay ,
863 'linkcount' => count ( $LINKSDB ),
865 'day' => $dayDate- > getTimestamp (),
866 'previousday' => $previousday ,
867 'nextday' => $nextday ,
869 $pluginManager = PluginManager
:: getInstance ();
870 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
872 foreach ( $data as $key => $value ) {
873 $pageBuilder- > assign ( $key , $value );
876 $pageBuilder- > renderPage ( 'daily' );
880 // Renders the linklist
881 function showLinkList ( $PAGE , $LINKSDB ) {
882 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
883 $PAGE- > renderPage ( 'linklist' );
887 // ------------------------------------------------------------------------------------------
888 // Render HTML page (according to URL parameters and user rights)
889 function renderPage ()
891 $LINKSDB = new LinkDB (
892 $GLOBALS [ 'config' ][ 'DATASTORE' ],
894 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
895 $GLOBALS [ 'redirector' ]
898 $updater = new Updater (
899 read_updates_file ( $GLOBALS [ 'config' ][ 'UPDATES_FILE' ]),
905 $newUpdates = $updater- > update ();
906 if (! empty ( $newUpdates )) {
908 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ],
909 $updater- > getDoneUpdates ()
913 catch ( Exception
$e ) {
914 die ( $e- > getMessage ());
917 $PAGE = new pageBuilder
;
919 // Determine which page will be rendered.
920 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
921 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
923 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
924 // Then assign generated data to RainTPL.
925 $common_hooks = array (
930 $pluginManager = PluginManager
:: getInstance ();
931 foreach ( $common_hooks as $name ) {
932 $plugin_data = array ();
933 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
935 'target' => $targetPage ,
936 'loggedin' => isLoggedIn ()
939 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
942 // -------- Display login form.
943 if ( $targetPage == Router
:: $PAGE_LOGIN )
945 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
946 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
947 $PAGE- > assign ( 'token' , $token );
948 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
949 $PAGE- > renderPage ( 'loginform' );
952 // -------- User wants to logout.
953 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
955 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
957 header ( 'Location: ?' );
961 // -------- Picture wall
962 if ( $targetPage == Router
:: $PAGE_PICWALL )
964 // Optionally filter the results:
965 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
966 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
967 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
968 $links = $LINKSDB- > filter (
969 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
970 array ( $searchtags , $searchterm )
973 elseif ( $searchtags ) {
974 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $searchtags );
976 elseif ( $searchterm ) {
977 $links = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TEXT , $searchterm );
983 $linksToDisplay = array ();
985 // Get only links which have a thumbnail.
986 foreach ( $links as $link )
988 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
989 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
990 if ( $thumb != '' ) // Only output links which have a thumbnail.
992 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
993 $linksToDisplay []= $link ; // Add to array.
998 'linkcount' => count ( $LINKSDB ),
999 'linksToDisplay' => $linksToDisplay ,
1001 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1003 foreach ( $data as $key => $value ) {
1004 $PAGE- > assign ( $key , $value );
1007 $PAGE- > renderPage ( 'picwall' );
1011 // -------- Tag cloud
1012 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1014 $tags = $LINKSDB- > allTags ();
1016 // We sort tags alphabetically, then choose a font size according to count.
1017 // First, find max value.
1019 foreach ( $tags as $value ) {
1020 $maxcount = max ( $maxcount , $value );
1023 // Sort tags alphabetically: case insensitive, support locale if avalaible.
1024 uksort ( $tags , function ( $a , $b ) {
1025 // Collator is part of PHP intl.
1026 if ( class_exists ( 'Collator' )) {
1027 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
1028 if (! intl_is_failure ( intl_get_error_code ())) {
1029 return $c- > compare ( $a , $b );
1032 return strcasecmp ( $a , $b );
1036 foreach ( $tags as $key => $value )
1037 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1039 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1043 'linkcount' => count ( $LINKSDB ),
1046 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1048 foreach ( $data as $key => $value ) {
1049 $PAGE- > assign ( $key , $value );
1052 $PAGE- > renderPage ( 'tagcloud' );
1057 if ( $targetPage == Router
:: $PAGE_DAILY ) {
1061 // ATOM and RSS feed.
1062 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
1063 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
1064 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
1067 $query = $_SERVER [ 'QUERY_STRING' ];
1068 $cache = new CachedPage (
1069 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
1071 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
1073 $cached = $cache- > cachedVersion ();
1074 if (! empty ( $cached )) {
1080 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
1081 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
1082 $feedGenerator- > setHideDates ( $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] && ! isLoggedIn ());
1083 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]);
1084 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) {
1085 $feedGenerator- > setPubsubhubUrl ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
1087 $data = $feedGenerator- > buildData ();
1089 // Process plugin hook.
1090 $pluginManager = PluginManager
:: getInstance ();
1091 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
1092 'loggedin' => isLoggedIn (),
1093 'target' => $targetPage ,
1096 // Render the template.
1097 $PAGE- > assignAll ( $data );
1098 $PAGE- > renderPage ( 'feed.' . $feedType );
1099 $cache- > cache ( ob_get_contents ());
1104 // Display openseach plugin (XML)
1105 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1106 header ( 'Content-Type: application/xml; charset=utf-8' );
1107 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1108 $PAGE- > renderPage ( 'opensearch' );
1112 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1113 if ( isset ( $_GET [ 'addtag' ]))
1115 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1116 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1117 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1119 // Prevent redirection loop
1120 if ( isset ( $params [ 'addtag' ])) {
1121 unset ( $params [ 'addtag' ]);
1124 // Check if this tag is already in the search query and ignore it if it is.
1125 // Each tag is always separated by a space
1126 if ( isset ( $params [ 'searchtags' ])) {
1127 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1129 $current_tags = array ();
1132 foreach ( $current_tags as $value ) {
1133 if ( $value === $_GET [ 'addtag' ]) {
1138 // Append the tag if necessary
1139 if ( empty ( $params [ 'searchtags' ])) {
1140 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1143 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1146 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1147 header ( 'Location: ?' . http_build_query ( $params ));
1151 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1152 if ( isset ( $_GET [ 'removetag' ])) {
1153 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1154 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1155 header ( 'Location: ?' );
1159 // In case browser does not send HTTP_REFERER
1160 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1162 // Prevent redirection loop
1163 if ( isset ( $params [ 'removetag' ])) {
1164 unset ( $params [ 'removetag' ]);
1167 if ( isset ( $params [ 'searchtags' ])) {
1168 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1169 // Remove value from array $tags.
1170 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1171 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1173 if ( empty ( $params [ 'searchtags' ])) {
1174 unset ( $params [ 'searchtags' ]);
1177 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1179 header ( 'Location: ?' . http_build_query ( $params ));
1183 // -------- User wants to change the number of links per page (linksperpage=...)
1184 if ( isset ( $_GET [ 'linksperpage' ])) {
1185 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1186 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1189 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1193 // -------- User wants to see only private links (toggle)
1194 if ( isset ( $_GET [ 'privateonly' ])) {
1195 if ( empty ( $_SESSION [ 'privateonly' ])) {
1196 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1198 unset ( $_SESSION [ 'privateonly' ]); // See all links
1201 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1205 // -------- Handle other actions allowed for non-logged in users:
1208 // User tries to post new link but is not logged in:
1209 // Show login screen, then redirect to ?post=...
1210 if ( isset ( $_GET [ 'post' ]))
1212 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.
1216 // Same case as above except that user tried to access ?do=addlink without being logged in
1217 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1218 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1219 header ( 'Location: ?do=login&post=' );
1222 showLinkList ( $PAGE , $LINKSDB );
1223 if ( isset ( $_GET [ 'edit_link' ])) {
1224 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1228 exit ; // Never remove this one! All operations below are reserved for logged in user.
1231 // -------- All other functions are reserved for the registered user:
1233 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1234 if ( $targetPage == Router
:: $PAGE_TOOLS )
1237 'linkcount' => count ( $LINKSDB ),
1238 'pageabsaddr' => index_url ( $_SERVER ),
1240 $pluginManager- > executeHooks ( 'render_tools' , $data );
1242 foreach ( $data as $key => $value ) {
1243 $PAGE- > assign ( $key , $value );
1246 $PAGE- > renderPage ( 'tools' );
1250 // -------- User wants to change his/her password.
1251 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1253 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1254 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1256 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1258 // Make sure old password is correct.
1259 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1260 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1261 // Save new password
1262 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1263 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1265 writeConfig ( $GLOBALS , isLoggedIn ());
1267 catch ( Exception
$e ) {
1269 'ERROR while writing config file after changing password.' . PHP_EOL
.
1273 // TODO: do not handle exceptions/errors in JS.
1274 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1277 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1280 else // show the change password form.
1282 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1283 $PAGE- > assign ( 'token' , getToken ());
1284 $PAGE- > renderPage ( 'changepassword' );
1289 // -------- User wants to change configuration
1290 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1292 if (! empty ( $_POST [ 'title' ]) )
1294 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1296 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1297 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1298 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1299 $GLOBALS [ 'timezone' ] = $tz ;
1300 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1301 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1302 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1303 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1304 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1305 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1306 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1307 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1309 writeConfig ( $GLOBALS , isLoggedIn ());
1311 catch ( Exception
$e ) {
1313 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1317 // TODO: do not handle exceptions/errors in JS.
1318 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1321 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1324 else // Show the configuration form.
1326 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1327 $PAGE- > assign ( 'token' , getToken ());
1328 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1329 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1330 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1331 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1332 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1333 $PAGE- > renderPage ( 'configure' );
1338 // -------- User wants to rename a tag or delete it
1339 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1341 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1342 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1343 $PAGE- > assign ( 'token' , getToken ());
1344 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1345 $PAGE- > renderPage ( 'changetag' );
1349 if (! tokenOk ( $_POST [ 'token' ])) {
1350 die ( 'Wrong token.' );
1354 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1355 $needle = trim ( $_POST [ 'fromtag' ]);
1356 // True for case-sensitive tag search.
1357 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1358 foreach ( $linksToAlter as $key => $value )
1360 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1361 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1362 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1363 $LINKSDB [ $key ]= $value ;
1365 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1366 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1371 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1372 $needle = trim ( $_POST [ 'fromtag' ]);
1373 // True for case-sensitive tag search.
1374 $linksToAlter = $LINKSDB- > filter ( LinkFilter
:: $FILTER_TAG , $needle , true );
1375 foreach ( $linksToAlter as $key => $value )
1377 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1378 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1379 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1380 $LINKSDB [ $key ]= $value ;
1382 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1383 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1388 // -------- User wants to add a link without using the bookmarklet: Show form.
1389 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1391 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1392 $PAGE- > renderPage ( 'addlink' );
1396 // -------- User clicked the "Save" button when editing a link: Save link to database.
1397 if ( isset ( $_POST [ 'save_edit' ]))
1400 if (! tokenOk ( $_POST [ 'token' ])) {
1401 die ( 'Wrong token.' );
1403 // Remove multiple spaces.
1404 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1405 // Remove first '-' char in tags.
1406 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1407 // Remove duplicates.
1408 $tags = implode(' ', array_unique(explode(' ', $tags )));
1409 $linkdate = $_POST [' lf_linkdate
'];
1410 $url = trim( $_POST [' lf_url
']);
1411 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1412 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1413 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1415 $url = ' http
: //' . $url;
1419 'title' => trim ( $_POST [ 'lf_title' ]),
1421 'description' => $_POST [ 'lf_description' ],
1422 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1423 'linkdate' => $linkdate ,
1424 'tags' => str_replace ( ',' , ' ' , $tags )
1426 // If title is empty, use the URL as title.
1427 if ( $link [ 'title' ] == '' ) {
1428 $link [ 'title' ] = $link [ 'url' ];
1431 $pluginManager- > executeHooks ( 'save_link' , $link );
1433 $LINKSDB [ $linkdate ] = $link ;
1434 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1437 // If we are called from the bookmarklet, we must close the popup:
1438 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1439 echo '<script>self.close();</script>' ;
1443 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1444 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1445 // Scroll to the link which has been edited.
1446 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1447 // After saving the link, redirect to the page the user was on.
1448 header ( 'Location: ' . $location );
1452 // -------- User clicked the "Cancel" button when editing a link.
1453 if ( isset ( $_POST [ 'cancel_edit' ]))
1455 // If we are called from the bookmarklet, we must close the popup:
1456 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1457 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1458 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1459 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1460 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1464 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1465 if ( isset ( $_POST [ 'delete_link' ]))
1467 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1468 // We do not need to ask for confirmation:
1469 // - confirmation is handled by JavaScript
1470 // - we are protected from XSRF by the token.
1471 $linkdate = $_POST [ 'lf_linkdate' ];
1473 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1475 unset ( $LINKSDB [ $linkdate ]);
1476 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1478 // If we are called from the bookmarklet, we must close the popup:
1479 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1480 // Pick where we're going to redirect
1481 // =============================================================
1482 // Basically, we can't redirect to where we were previously if it was a permalink
1483 // or an edit_link, because it would 404.
1485 // - / : nothing in $_GET, redirect to self
1486 // - /?page : redirect to self
1487 // - /?searchterm : redirect to self (there might be other links)
1488 // - /?searchtags : redirect to self
1489 // - /permalink : redirect to / (the link does not exist anymore)
1490 // - /?edit_link : redirect to / (the link does not exist anymore)
1491 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1492 // redirect is not satisfied, and only then redirect to /
1495 if ( count ( $_GET ) == 0
1496 || isset ( $_GET [ 'page' ])
1497 || isset ( $_GET [ 'searchterm' ])
1498 || isset ( $_GET [ 'searchtags' ])
1500 if ( isset ( $_POST [ 'returnurl' ])) {
1501 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1503 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1507 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1511 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1512 if ( isset ( $_GET [ 'edit_link' ]))
1514 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1515 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1517 'linkcount' => count ( $LINKSDB ),
1519 'link_is_new' => false ,
1520 'token' => getToken (),
1521 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1522 'tags' => $LINKSDB- > allTags (),
1524 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1526 foreach ( $data as $key => $value ) {
1527 $PAGE- > assign ( $key , $value );
1530 $PAGE- > renderPage ( 'editlink' );
1534 // -------- User want to post a new link: Display link edit form.
1535 if ( isset ( $_GET [ 'post' ])) {
1536 $url = cleanup_url ( escape ( $_GET [ 'post' ]));
1538 $link_is_new = false ;
1539 // Check if URL is not already in database (in this case, we will edit the existing link)
1540 $link = $LINKSDB- > getLinkFromUrl ( $url );
1543 $link_is_new = true ;
1544 $linkdate = strval ( date ( 'Ymd_His' ));
1545 // Get title if it was provided in URL (by the bookmarklet).
1546 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1547 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1548 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1549 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1550 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1551 // 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.)
1552 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1553 // Short timeout to keep the application responsive
1554 list ( $headers , $content ) = get_http_response ( $url , 4 );
1555 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1556 // Retrieve charset.
1557 $charset = get_charset ( $headers , $content );
1559 $title = html_extract_title ( $content );
1560 // Re-encode title in utf-8 if necessary.
1561 if (! empty ( $title ) && $charset != 'utf-8' ) {
1562 $title = mb_convert_encoding ( $title , $charset , 'utf-8' );
1568 $url = '?' . smallHash ( $linkdate );
1573 'linkdate' => $linkdate ,
1576 'description' => $description ,
1578 'private' => $private
1583 'linkcount' => count ( $LINKSDB ),
1585 'link_is_new' => $link_is_new ,
1586 'token' => getToken (), // XSRF protection.
1587 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1588 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1589 'tags' => $LINKSDB- > allTags (),
1591 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1593 foreach ( $data as $key => $value ) {
1594 $PAGE- > assign ( $key , $value );
1597 $PAGE- > renderPage ( 'editlink' );
1601 // -------- Export as Netscape Bookmarks HTML file.
1602 if ( $targetPage == Router
:: $PAGE_EXPORT )
1604 if ( empty ( $_GET [ 'what' ]))
1606 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1607 $PAGE- > renderPage ( 'export' );
1610 $exportWhat = $_GET [ 'what' ];
1611 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1613 header ( 'Content-Type: text/html; charset=utf-8' );
1614 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1615 $currentdate = date ( 'Y/m/d H:i:s' );
1617 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1618 <!-- This is an automatically generated file.
1619 It will be read and overwritten.
1621 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1622 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1623 <TITLE>Bookmarks</TITLE>
1626 foreach ( $LINKSDB as $link )
1628 if ( $exportWhat == 'all' ||
1629 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1630 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1632 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1633 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . $date- > getTimestamp (). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1634 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1635 echo '>' . $link [ 'title' ]. "</A> \n " ;
1636 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1642 // -------- User is uploading a file for import
1643 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1645 // If file is too big, some form field may be missing.
1646 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1648 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1649 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>' ;
1652 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1657 // -------- Show upload/import dialog:
1658 if ( $targetPage == Router
:: $PAGE_IMPORT )
1660 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1661 $PAGE- > assign ( 'token' , getToken ());
1662 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1663 $PAGE- > renderPage ( 'import' );
1667 // Plugin administration page
1668 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1669 $pluginMeta = $pluginManager- > getPluginsMeta ();
1671 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1672 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1674 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1677 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1679 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1681 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1682 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1683 $PAGE- > renderPage ( 'pluginsadmin' );
1687 // Plugin administration form action
1688 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1690 if ( isset ( $_POST [ 'parameters_form' ])) {
1691 unset ( $_POST [ 'parameters_form' ]);
1692 foreach ( $_POST as $param => $value ) {
1693 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1697 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1699 writeConfig ( $GLOBALS , isLoggedIn ());
1701 catch ( Exception
$e ) {
1703 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1707 // TODO: do not handle exceptions/errors in JS.
1708 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1711 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1715 // -------- Otherwise, simply display search form and links:
1716 showLinkList ( $PAGE , $LINKSDB );
1720 // -----------------------------------------------------------------------------------------------
1721 // Process the import file form.
1722 function importFile ()
1724 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1725 $LINKSDB = new LinkDB (
1726 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1728 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1729 $GLOBALS [ 'redirector' ]
1731 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1732 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1733 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1734 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1735 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1740 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1742 // Then import the bookmarks.
1743 if ( $type == 'netscape' )
1745 // This is a standard Netscape-style bookmark file.
1746 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1747 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1749 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1750 $d = explode ( '<DD>' , $html );
1751 if ( startswith ( $d [ 0 ], '<A ' ))
1753 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1754 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1755 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1756 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1758 foreach ( $matches as $m )
1760 $attr = $m [ 1 ]; $value = $m [ 2 ];
1761 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1762 elseif ( $attr == 'ADD_DATE' )
1764 $raw_add_date = intval ( $value );
1765 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1767 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1768 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1770 if ( $link [ 'url' ]!= '' )
1772 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1773 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1775 { // Link not in database, let's import it...
1776 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1778 // Make sure date/time is not already used by another link.
1779 // (Some bookmark files have several different links with the same ADD_DATE)
1780 // We increment date by 1 second until we find a date which is not used in DB.
1781 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1782 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1783 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1784 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1787 else // Link already present in database.
1790 { // If overwrite is required, we import link data, except date/time.
1791 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1792 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1800 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1802 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1806 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1810 // -----------------------------------------------------------------------------------------------
1811 // Template for the list of links (<div id="linklist">)
1812 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1813 function buildLinkList ( $PAGE , $LINKSDB )
1815 // Filter link database according to parameters.
1816 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1817 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( trim ( $_GET [ 'searchterm' ])) : '' ;
1818 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]) ? true : false ;
1820 // Search tags + fullsearch.
1821 if (! empty ( $searchtags ) && ! empty ( $searchterm )) {
1822 $linksToDisplay = $LINKSDB- > filter (
1823 LinkFilter
:: $FILTER_TAG | LinkFilter
:: $FILTER_TEXT ,
1824 array ( $searchtags , $searchterm ),
1830 elseif (! empty ( $searchtags )) {
1831 $linksToDisplay = $LINKSDB- > filter (
1832 LinkFilter
:: $FILTER_TAG ,
1839 elseif (! empty ( $searchterm )) {
1840 $linksToDisplay = $LINKSDB- > filter (
1841 LinkFilter
:: $FILTER_TEXT ,
1847 // Detect smallHashes in URL.
1848 elseif (! empty ( $_SERVER [ 'QUERY_STRING' ])
1849 && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])
1851 $linksToDisplay = $LINKSDB- > filter (
1852 LinkFilter
:: $FILTER_HASH ,
1853 substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 )
1856 if ( count ( $linksToDisplay ) == 0 ) {
1857 $PAGE- > render404 ( 'The link you are trying to reach does not exist or has been deleted.' );
1861 // Otherwise, display without filtering.
1863 $linksToDisplay = $LINKSDB- > filter ( '' , '' , false , $privateonly );
1866 // ---- Handle paging.
1868 foreach ( $linksToDisplay as $key => $value ) {
1872 // If there is only a single link, we change on-the-fly the title of the page.
1873 if ( count ( $linksToDisplay ) == 1 ) {
1874 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1877 // Select articles according to paging.
1878 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1879 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1880 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1881 $page = $page < 1 ? 1 : $page ;
1882 $page = $page > $pagecount ? $pagecount : $page ;
1884 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1885 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1886 $linkDisp = array ();
1887 while ( $i < $end && $i < count ( $keys ))
1889 $link = $linksToDisplay [ $keys [ $i ]];
1890 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1891 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1892 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1893 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1894 $link [ 'timestamp' ] = $date- > getTimestamp ();
1895 $taglist = explode ( ' ' , $link [ 'tags' ]);
1896 uasort ( $taglist , 'strcasecmp' );
1897 $link [ 'taglist' ] = $taglist ;
1898 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1899 // Check for both signs of a note: starting with ? and 7 chars long.
1900 if ( $link [ 'url' ][ 0 ] === '?' &&
1901 strlen ( $link [ 'url' ]) === 7 ) {
1902 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1905 $linkDisp [ $keys [ $i ]] = $link ;
1909 // Compute paging navigation
1910 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1911 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1912 $previous_page_url = '' ;
1913 if ( $i != count ( $keys )) {
1914 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1918 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1921 $token = isLoggedIn () ? getToken () : '' ;
1923 // Fill all template fields.
1925 'linkcount' => count ( $LINKSDB ),
1926 'previous_page_url' => $previous_page_url ,
1927 'next_page_url' => $next_page_url ,
1928 'page_current' => $page ,
1929 'page_max' => $pagecount ,
1930 'result_count' => count ( $linksToDisplay ),
1931 'search_term' => $searchterm ,
1932 'search_tags' => $searchtags ,
1933 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
1935 'links' => $linkDisp ,
1936 'tags' => $LINKSDB- > allTags (),
1938 // FIXME! temporary fix - see #399.
1939 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
1940 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
1943 $pluginManager = PluginManager
:: getInstance ();
1944 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1946 foreach ( $data as $key => $value ) {
1947 $PAGE- > assign ( $key , $value );
1953 // Compute the thumbnail for a link.
1955 // With a link to the original URL.
1956 // Understands various services (youtube.com...)
1957 // Input: $url = URL for which the thumbnail must be found.
1958 // $href = if provided, this URL will be followed instead of $url
1959 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1960 // Some of them may be missing.
1961 // Return an empty array if no thumbnail available.
1962 function computeThumbnail ( $url , $href = false )
1964 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
1965 if ( $href == false ) $href = $url ;
1967 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1968 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1969 // ^^^^^^^^^^^ ^^^^^^^^^^^
1970 $domain = parse_url ( $url , PHP_URL_HOST
);
1971 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1973 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1974 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1975 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1977 if ( $domain == 'youtu.be' ) // Youtube short links
1979 $path = parse_url ( $url , PHP_URL_PATH
);
1980 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1981 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1983 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1985 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1986 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1987 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1990 if ( $domain == 'imgur.com' )
1992 $path = parse_url ( $url , PHP_URL_PATH
);
1993 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1994 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1995 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1996 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1997 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1999 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2000 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2002 if ( $domain == 'i.imgur.com' )
2004 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2005 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2006 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2008 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2010 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2012 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2013 return array ( 'src' => $thumburl ,
2014 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2017 if ( endsWith ( $domain , '.imageshack.us' ))
2019 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2020 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2022 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2023 return array ( 'src' => $thumburl ,
2024 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2028 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2029 // So we deport the thumbnail generation in order not to slow down page generation
2030 // (and we also cache the thumbnail)
2032 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2034 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2035 || $domain == 'vimeo.com'
2036 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2037 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2040 if ( $domain == 'vimeo.com' )
2041 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2042 $path = parse_url ( $url , PHP_URL_PATH
);
2043 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2045 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2046 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2047 $path = parse_url ( $url , PHP_URL_PATH
);
2048 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2050 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2051 { // Make sure this TED URL points to a video (/talks/...)
2052 $path = parse_url ( $url , PHP_URL_PATH
);
2053 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2055 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2056 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2057 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2060 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2061 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2062 // But using the extension will do.
2063 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2064 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2066 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2067 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2068 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2070 return array (); // No thumbnail.
2075 // Returns the HTML code to display a thumbnail for a link
2076 // with a link to the original URL.
2077 // Understands various services (youtube.com...)
2078 // Input: $url = URL for which the thumbnail must be found.
2079 // $href = if provided, this URL will be followed instead of $url
2080 // Returns '' if no thumbnail available.
2081 function thumbnail ( $url , $href = false )
2083 $t = computeThumbnail ( $url , $href );
2084 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2086 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2087 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2088 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2089 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2090 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2095 // Returns the HTML code to display a thumbnail for a link
2096 // for the picture wall (using lazy image loading)
2097 // Understands various services (youtube.com...)
2098 // Input: $url = URL for which the thumbnail must be found.
2099 // $href = if provided, this URL will be followed instead of $url
2100 // Returns '' if no thumbnail available.
2101 function lazyThumbnail ( $url , $href = false )
2103 $t = computeThumbnail ( $url , $href );
2104 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2106 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2109 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2111 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2112 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2113 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2114 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2117 // No-JavaScript fallback.
2118 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2119 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2120 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2121 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2122 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2123 $html .= '></noscript></a>' ;
2129 // -----------------------------------------------------------------------------------------------
2131 // This function should NEVER be called if the file data/config.php exists.
2134 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2135 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2138 // This part makes sure sessions works correctly.
2139 // (Because on some hosts, session.save_path may not be set correctly,
2140 // or we may not have write access to it.)
2141 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2142 { // Step 2: Check if data in session is correct.
2143 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2144 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2145 echo 'It currently points to ' . session_save_path (). '<br>' ;
2146 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>' ;
2147 echo '<br><a href="?">Click to try again.</a></pre>' ;
2150 if (! isset ( $_SESSION [ 'session_tested' ]))
2151 { // Step 1 : Try to store data in session and reload page.
2152 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2153 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2155 if ( isset ( $_GET [ 'test_session' ]))
2156 { // Step 3: Sessions are OK. Remove test parameter from URL.
2157 header ( 'Location: ' . index_url ( $_SERVER ));
2161 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2164 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2165 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2166 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2169 $GLOBALS [ 'timezone' ] = $tz ;
2170 // Everything is ok, let's create config file.
2171 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2172 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2173 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2174 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2175 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2177 writeConfig ( $GLOBALS , isLoggedIn ());
2179 catch ( Exception
$e ) {
2181 'ERROR while writing config file after installation.' . PHP_EOL
.
2185 // TODO: do not handle exceptions/errors in JS.
2186 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2189 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2193 // Display config form:
2194 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2195 $timezone_html = '' ;
2196 if ( $timezone_form != '' ) {
2197 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2200 $PAGE = new pageBuilder
;
2201 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2202 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2203 $PAGE- > renderPage ( 'install' );
2207 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2208 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2209 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2210 This function is called by passing the URL:
2211 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2212 [URL] is the URL of the link (e.g. a flickr page)
2213 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2214 The function below will fetch the image from the webservice and store it in the cache.
2216 function genThumbnail ()
2218 // Make sure the parameters in the URL were generated by us.
2219 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2220 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2222 // Let's see if we don't already have the image for this URL in the cache.
2223 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2224 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2225 { // We have the thumbnail, just serve it:
2226 header ( 'Content-Type: image/jpeg' );
2227 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2230 // We may also serve a blank image (if service did not respond)
2231 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2232 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2234 header ( 'Content-Type: image/gif' );
2235 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2239 // Otherwise, generate the thumbnail.
2240 $url = $_GET [ 'url' ];
2241 $domain = parse_url ( $url , PHP_URL_HOST
);
2243 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2245 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2246 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2248 // Is this a link to an image, or to a flickr page ?
2250 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2251 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2252 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2253 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2255 else // This is a flickr page (html)
2257 // Get the flickr html page.
2258 list ( $headers , $content ) = get_http_response ( $url , 20 );
2259 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2261 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2262 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2263 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2265 // In albums (and some other pages), the link rel="image_src" is not provided,
2266 // but flickr provides:
2267 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2270 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2271 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2277 { // Let's download the image.
2278 // Image is 240x120, so 10 seconds to download should be enough.
2279 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2280 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2281 // Save image to cache.
2282 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2283 header ( 'Content-Type: image/jpeg' );
2290 elseif ( $domain == 'vimeo.com' )
2292 // This is more complex: we have to perform a HTTP request, then parse the result.
2293 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2294 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2295 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2296 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2297 $t = unserialize ( $content );
2298 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2299 // Then we download the image and serve it to our client.
2300 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2301 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2302 // Save image to cache.
2303 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2304 header ( 'Content-Type: image/jpeg' );
2311 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2313 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2314 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2315 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2316 list ( $headers , $content ) = get_http_response ( $url , 5 );
2317 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2318 // Extract the link to the thumbnail
2319 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2320 if (! empty ( $matches [ 1 ]))
2321 { // Let's download the image.
2322 $imageurl = $matches [ 1 ];
2323 // No control on image size, so wait long enough
2324 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2325 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2326 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2327 file_put_contents ( $filepath , $content ); // Save image to cache.
2328 if ( resizeImage ( $filepath ))
2330 header ( 'Content-Type: image/jpeg' );
2331 echo file_get_contents ( $filepath );
2339 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2341 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2342 // http://xkcd.com/327/
2343 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2344 list ( $headers , $content ) = get_http_response ( $url , 5 );
2345 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2346 // Extract the link to the thumbnail
2347 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2348 if (! empty ( $matches [ 1 ]))
2349 { // Let's download the image.
2350 $imageurl = $matches [ 1 ];
2351 // No control on image size, so wait long enough
2352 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2353 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2354 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2355 // Save image to cache.
2356 file_put_contents ( $filepath , $content );
2357 if ( resizeImage ( $filepath ))
2359 header ( 'Content-Type: image/jpeg' );
2360 echo file_get_contents ( $filepath );
2370 // For all other domains, we try to download the image and make a thumbnail.
2371 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2372 list ( $headers , $content ) = get_http_response ( $url , 30 );
2373 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2374 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2375 // Save image to cache.
2376 file_put_contents ( $filepath , $content );
2377 if ( resizeImage ( $filepath ))
2379 header ( 'Content-Type: image/jpeg' );
2380 echo file_get_contents ( $filepath );
2387 // Otherwise, return an empty image (8x8 transparent gif)
2388 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2389 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2390 header ( 'Content-Type: image/gif' );
2394 // Make a thumbnail of the image (to width: 120 pixels)
2395 // Returns true if success, false otherwise.
2396 function resizeImage ( $filepath )
2398 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2400 // Trick: some stupid people rename GIF as JPEG... or else.
2401 // So we really try to open each image type whatever the extension is.
2402 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2404 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2405 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2406 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2407 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2410 $ystart = 0 ; $yheight = $h ;
2411 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2412 $nw = 120 ; // Desired width
2413 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2415 $im2 = imagecreatetruecolor ( $nw , $nh );
2416 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2417 imageinterlace ( $im2 , true ); // For progressive JPEG.
2418 $tempname = $filepath . '_TEMP.jpg' ;
2419 imagejpeg ( $im2 , $tempname , 90 );
2423 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2427 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2428 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2429 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];