]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.0 - Shaare your links...
5 * The personal, minimalist, super-fast, no-database Delicious clone.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
25 /* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
33 * Shaarli directories & configuration files
36 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ;
38 // Main configuration file
39 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ;
42 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ;
45 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ;
48 $GLOBALS [ 'config' ][ 'LOG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' ;
50 // For updates check of Shaarli
51 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
53 // RainTPL cache directory (keep the trailing slash!)
54 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
55 // Raintpl template directory (keep the trailing slash!)
56 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
58 // Thumbnail cache directory
59 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
61 // Atom & RSS feed cache directory
62 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
66 * Global configuration
68 // Ban IP after this many failures
69 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
70 // Ban duration for IP address after login failures (in seconds)
71 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
74 // Enable RSS permalinks by default.
75 // This corresponds to the default behavior of shaarli before this was added as an option.
76 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
77 // If true, an extra "ATOM feed" button will be displayed in the toolbar
78 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
80 // Link display options
81 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
82 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
83 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
85 // Open Shaarli (true): anyone can add/edit/delete links without having to login
86 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
89 // Display thumbnails in links
90 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
91 // Store thumbnails in a local cache
92 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
94 // Update check frequency for Shaarli. 86400 seconds=24 hours
95 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
99 * Plugin configuration
101 * Warning: order matters!
103 * These settings may be be overriden in:
105 * - each plugin's configuration file
107 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
108 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
109 // 'wallabag', 'markdown', 'addlink_toolbar',
111 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
113 //$GLOBALS['plugins']['WALLABAG_URL'] = 'https://demo.wallabag.org/';
115 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
116 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
121 define ( 'shaarli_version' , '0.6.0' );
123 // http://server.com/x/shaarli --> /shaarli/
124 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
126 // High execution time in case of problematic imports/exports.
127 ini_set ( 'max_input_time' , '60' );
129 // Try to set max upload file size and read
130 ini_set ( 'memory_limit' , '128M' );
131 ini_set ( 'post_max_size' , '16M' );
132 ini_set ( 'upload_max_filesize' , '16M' );
134 // See all error except warnings
135 error_reporting ( E_ALL^E_WARNING
);
136 // See all errors (for debugging only)
137 //error_reporting(-1);
142 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
143 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
147 require_once 'application/ApplicationUtils.php' ;
148 require_once 'application/Cache.php' ;
149 require_once 'application/CachedPage.php' ;
150 require_once 'application/FileUtils.php' ;
151 require_once 'application/HttpUtils.php' ;
152 require_once 'application/LinkDB.php' ;
153 require_once 'application/TimeZone.php' ;
154 require_once 'application/Url.php' ;
155 require_once 'application/Utils.php' ;
156 require_once 'application/Config.php' ;
157 require_once 'application/PluginManager.php' ;
158 require_once 'application/Router.php' ;
160 // Ensure the PHP version is supported
162 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
163 } catch ( Exception
$exc ) {
164 header ( 'Content-Type: text/plain; charset=utf-8' );
165 echo $exc- > getMessage ();
169 // Force cookie path (but do not change lifetime)
170 $cookie = session_get_cookie_params ();
172 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
173 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
175 // Set default cookie expiration and path.
176 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
177 // Set session parameters on server side.
178 // If the user does not access any page within this time, his/her session is considered expired.
179 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
180 // Use cookies to store session.
181 ini_set ( 'session.use_cookies' , 1 );
182 // Force cookies for session (phpsessionID forbidden in URL).
183 ini_set ( 'session.use_only_cookies' , 1 );
184 // Prevent PHP form using sessionID in URL if cookies are disabled.
185 ini_set ( 'session.use_trans_sid' , false );
187 session_name ( 'shaarli' );
188 // Start session if needed (Some server auto-start sessions).
189 if ( session_id () == '' ) {
193 // Regenerate session ID if invalid or not defined in cookie.
194 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
195 session_regenerate_id ( true );
196 $_COOKIE [ 'shaarli' ] = session_id ();
199 include "inc/rain.tpl.class.php" ; //include Rain TPL
200 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
201 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
203 $pluginManager = PluginManager
:: getInstance ();
204 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
206 ob_start (); // Output buffering for the page cache.
209 // In case stupid admin has left magic_quotes enabled in php.ini:
210 if ( get_magic_quotes_gpc ())
212 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
213 $_POST = array_map ( 'stripslashes_deep' , $_POST );
214 $_GET = array_map ( 'stripslashes_deep' , $_GET );
215 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
218 // Prevent caching on client side or proxy: (yes, it's ugly)
219 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
220 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
221 header ( "Cache-Control: post-check=0, pre-check=0" , false );
222 header ( "Pragma: no-cache" );
224 // Handling of old config file which do not have the new parameters.
225 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
226 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
227 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
228 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
229 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
230 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
231 // I really need to rewrite Shaarli with a proper configuation manager.
233 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
234 // Ensure Shaarli has proper access to its resources
235 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
237 if ( $errors != array ()) {
238 $message = '<p>Insufficient permissions:</p><ul>' ;
240 foreach ( $errors as $error ) {
241 $message .= '<li>' . $error . '</li>' ;
245 header ( 'Content-Type: text/html; charset=utf-8' );
250 // Display the installation form if no existing config is found
254 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
255 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
256 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
258 // a token depending of deployment salt, user password, and the current ip
259 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
261 autoLocale (); // Sniff browser language and set date format accordingly.
262 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
264 //==================================================================================================
265 // Checking session state (i.e. is the user still logged in)
266 //==================================================================================================
268 function setup_login_state () {
269 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
272 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
273 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
274 if (! isset ( $GLOBALS [ 'login' ])) {
275 $userIsLoggedIn = false ; // Shaarli is not configured yet.
276 $loginFailure = true ;
278 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
279 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
283 $userIsLoggedIn = true ;
285 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
286 if ( empty ( $_SESSION [ 'uid' ]) ||
287 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
288 time () >= $_SESSION [ 'expires_on' ])
291 $userIsLoggedIn = false ;
292 $loginFailure = true ;
294 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
295 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
298 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
300 if (! $loginFailure ) {
301 $userIsLoggedIn = true ;
304 return $userIsLoggedIn ;
306 $userIsLoggedIn = setup_login_state ();
309 // -----------------------------------------------------------------------------------------------
311 function logm ( $message )
313 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
314 file_put_contents ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $t , FILE_APPEND
);
317 // ------------------------------------------------------------------------------------------
318 // Sniff browser language to display dates in the right format automatically.
319 // (Note that is may not work on your server if the corresponding local is not installed.)
320 function autoLocale ()
322 $attempts = array ( 'en_US' ); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
323 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
324 { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
325 if ( preg_match ( '/([a-z] {2} )-?([a-z] {2} )?/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) {
326 $loc = $matches [ 1 ] . (! empty ( $matches [ 2 ]) ? '_' . strtoupper ( $matches [ 2 ]) : '' );
327 $attempts = array ( $loc . '.UTF-8' , $loc , str_replace ( '_' , '-' , $loc ). '.UTF-8' , str_replace ( '_' , '-' , $loc ),
328 $loc . '_' . strtoupper ( $loc ). '.UTF-8' , $loc . '_' . strtoupper ( $loc ),
329 $loc . '_' . $loc . '.UTF-8' , $loc . '_' . $loc , $loc . '-' . strtoupper ( $loc ). '.UTF-8' ,
330 $loc . '-' . strtoupper ( $loc ), $loc . '-' . $loc . '.UTF-8' , $loc . '-' . $loc );
333 setlocale ( LC_TIME
, $attempts ); // LC_TIME = Set local for date/time format only.
336 // ------------------------------------------------------------------------------------------
337 // PubSubHubbub protocol support (if enabled) [UNTESTED]
338 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
339 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
342 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
344 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
346 index_url ( $_SERVER ). '?do=atom' ,
347 index_url ( $_SERVER ). '?do=rss'
349 $p- > publish_update ( $topic_url );
353 // ------------------------------------------------------------------------------------------
354 // Session management
356 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
359 $ip = $_SERVER [ "REMOTE_ADDR" ];
360 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
361 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
362 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
366 function fillSessionInfo () {
367 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
368 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
369 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
370 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
373 // Check that user/password is correct.
374 function check_auth ( $login , $password )
376 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
377 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
378 { // Login/password is correct.
380 logm ( 'Login successful' );
383 logm ( 'Login failed for user ' . $login );
387 // Returns true if the user is logged in.
388 function isLoggedIn ()
390 global $userIsLoggedIn ;
391 return $userIsLoggedIn ;
396 if ( isset ( $_SESSION )) {
397 unset ( $_SESSION [ 'uid' ]);
398 unset ( $_SESSION [ 'ip' ]);
399 unset ( $_SESSION [ 'username' ]);
400 unset ( $_SESSION [ 'privateonly' ]);
402 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
406 // ------------------------------------------------------------------------------------------
407 // Brute force protection system
408 // Several consecutive failed logins will ban the IP address for 30 minutes.
409 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 ?>" );
410 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
411 // Signal a failed login. Will ban the IP if too many failures:
412 function ban_loginFailed ()
414 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
415 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
416 $gb [ 'FAILURES' ][ $ip ] ++
;
417 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
419 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
420 logm ( 'IP address banned from login' );
422 $GLOBALS [ 'IPBANS' ] = $gb ;
423 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
426 // Signals a successful login. Resets failed login counter.
427 function ban_loginOk ()
429 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
430 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
431 $GLOBALS [ 'IPBANS' ] = $gb ;
432 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
435 // Checks if the user CAN login. If 'true', the user can try to login.
436 function ban_canLogin ()
438 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
439 if ( isset ( $gb [ 'BANS' ][ $ip ]))
441 // User is banned. Check if the ban has expired:
442 if ( $gb [ 'BANS' ][ $ip ]<= time ())
443 { // Ban expired, user can try to login again.
445 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
446 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
447 return true ; // Ban has expired, user can login.
449 return false ; // User is banned.
451 return true ; // User is not banned.
454 // ------------------------------------------------------------------------------------------
455 // Process login form: Check if login/password is correct.
456 if ( isset ( $_POST [ 'login' ]))
458 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
459 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
460 { // Login/password is OK.
462 // If user wants to keep the session cookie even after the browser closes:
463 if (! empty ( $_POST [ 'longlastingsession' ]))
465 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
466 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
467 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
469 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
470 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
471 // Note: Never forget the trailing slash on the cookie path!
472 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
474 else // Standard session expiration (=when browser closes)
476 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
477 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
478 session_regenerate_id ( true );
481 // Optional redirect after login:
482 if ( isset ( $_GET [ 'post' ])) {
483 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
484 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
485 if (! empty ( $_GET [ $param ])) {
486 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
489 header ( 'Location: ' . $uri );
493 if ( isset ( $_GET [ 'edit_link' ])) {
494 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
498 if ( isset ( $_POST [ 'returnurl' ])) {
499 // Prevent loops over login screen.
500 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
501 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
505 header ( 'Location: ?' ); exit ;
511 if ( isset ( $_GET [ 'post' ])) {
512 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
513 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
514 if (! empty ( $_GET [ $param ])) {
515 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
519 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
524 // ------------------------------------------------------------------------------------------
525 // Misc utility functions:
527 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
528 function return_bytes ( $val )
530 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
533 case 'g' : $val *= 1024 ;
534 case 'm' : $val *= 1024 ;
535 case 'k' : $val *= 1024 ;
540 // Try to determine max file size for uploads (POST).
541 // Returns an integer (in bytes)
542 function getMaxFileSize ()
544 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
545 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
546 // Return the smaller of two:
547 $maxsize = min ( $size1 , $size2 );
548 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
552 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
553 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
554 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
555 function linkdate2timestamp ( $linkdate )
557 if ( strcmp ( $linkdate , '_000000' ) !== 0 || ! $linkdate ){
559 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
560 return mktime ( $h , $m , $s , $M , $D , $Y );
565 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
566 (used to build the pubDate attribute in RSS feed.) */
567 function linkdate2rfc822 ( $linkdate )
569 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
572 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
573 (used to build the updated tags in ATOM feed.) */
574 function linkdate2iso8601 ( $linkdate )
576 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
579 // Extract title from an HTML document.
580 // (Returns an empty string if not found.)
581 function html_extract_title ( $html )
583 return preg_match ( '!<title>(.*?)</title>!is' , $html , $matches ) ? trim ( str_replace ( " \n " , ' ' , $matches [ 1 ])) : '' ;
586 // ------------------------------------------------------------------------------------------
587 // Token management for XSRF protection
588 // Token should be used in any form which acts on data (create,update,delete,import...).
589 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
594 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
595 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
599 // Tells if a token is OK. Using this function will destroy the token.
601 function tokenOk ( $token )
603 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
605 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
606 return true ; // Token is OK.
608 return false ; // Wrong token, or already used.
611 // ------------------------------------------------------------------------------------------
612 /* This class is in charge of building the final page.
613 (This is basically a wrapper around RainTPL which pre-fills some fields.)
615 p.assign('myfield','myvalue');
616 p.renderPage('mytemplate');
621 private $tpl ; // RainTPL template
623 function __construct ()
629 * Initialize all default tpl tags.
631 private function initialize ()
633 $this- > tpl
= new RainTPL
;
637 ApplicationUtils
:: checkUpdate (
639 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ],
640 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ],
641 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ],
646 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
647 $searchcrits = '' ; // Search criteria
648 if (! empty ( $_GET [ 'searchtags' ])) {
649 $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
651 elseif (! empty ( $_GET [ 'searchterm' ])) {
652 $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
654 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
655 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
656 $this- > tpl
-> assign ( 'version' , shaarli_version
);
657 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
658 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
659 $this- > tpl
-> assign ( 'privateonly' , ! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
660 if (! empty ( $GLOBALS [ 'title' ])) {
661 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
663 if (! empty ( $GLOBALS [ 'titleLink' ])) {
664 $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
666 if (! empty ( $GLOBALS [ 'pagetitle' ])) {
667 $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
669 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ]);
670 if (! empty ( $GLOBALS [ 'plugin_errors' ])) {
671 $this- > tpl
-> assign ( 'plugin_errors' , $GLOBALS [ 'plugin_errors' ]);
675 // The following assign() method is basically the same as RainTPL (except that it's lazy)
676 public function assign ( $what , $where )
678 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
679 $this- > tpl
-> assign ( $what , $where );
682 // Render a specific page (using a template).
683 // e.g. pb.renderPage('picwall')
684 public function renderPage ( $page )
686 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
687 $this- > tpl
-> draw ( $page );
691 // ------------------------------------------------------------------------------------------
692 // Output the last N links in RSS 2.0 format.
695 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
697 // $usepermalink : If true, use permalink instead of final link.
698 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
699 // Also enabled through a config option
700 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
703 $query = $_SERVER [ "QUERY_STRING" ];
704 $cache = new CachedPage (
705 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
707 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
709 $cached = $cache- > cachedVersion ();
710 if (! empty ( $cached )) {
715 // If cached was not found (or not usable), then read the database and build the response:
716 $LINKSDB = new LinkDB (
717 $GLOBALS [ 'config' ][ 'DATASTORE' ],
719 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
720 $GLOBALS [ 'redirector' ]
722 // Read links from database (and filter private links if user it not logged in).
724 // Optionally filter the results:
725 $linksToDisplay = array ();
726 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
727 else if (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
728 else $linksToDisplay = $LINKSDB ;
730 $nblinksToDisplay = 50 ; // Number of links to display.
731 if (! empty ( $_GET [ 'nb' ])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
733 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( $_GET [ 'nb' ] +
0 , 1 ) ;
736 $pageaddr = escape ( index_url ( $_SERVER ));
737 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
738 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
739 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
740 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
742 echo '<!-- PubSubHubbub Discovery -->' ;
743 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
744 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
745 echo '<!-- End Of PubSubHubbub Discovery -->' ;
748 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
749 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
751 $link = $linksToDisplay [ $keys [ $i ]];
752 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
753 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
754 $absurl = $link [ 'url' ];
755 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
756 if ( $usepermalinks === true )
757 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
759 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
760 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . escape ( $rfc822date ). "</pubDate> \n " ;
761 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
763 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
766 // Add permalink in description
767 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
768 // If user wants permalinks first, put the final link in description
769 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
770 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
771 echo '<description><![CDATA[' .
772 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
773 $descriptionlink . ']]></description>' . " \n </item> \n " ;
776 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
778 $cache- > cache ( ob_get_contents ());
783 // ------------------------------------------------------------------------------------------
784 // Output the last N links in ATOM format.
787 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
789 // $usepermalink : If true, use permalink instead of final link.
790 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
791 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
794 $query = $_SERVER [ "QUERY_STRING" ];
795 $cache = new CachedPage (
796 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
798 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
800 $cached = $cache- > cachedVersion ();
801 if (! empty ( $cached )) {
806 // If cached was not found (or not usable), then read the database and build the response:
807 // Read links from database (and filter private links if used it not logged in).
808 $LINKSDB = new LinkDB (
809 $GLOBALS [ 'config' ][ 'DATASTORE' ],
811 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
812 $GLOBALS [ 'redirector' ]
815 // Optionally filter the results:
816 $linksToDisplay = array ();
817 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
818 else if (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
819 else $linksToDisplay = $LINKSDB ;
821 $nblinksToDisplay = 50 ; // Number of links to display.
822 if (! empty ( $_GET [ 'nb' ])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
824 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( $_GET [ 'nb' ] +
0 , 1 ) ;
827 $pageaddr = escape ( index_url ( $_SERVER ));
831 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
832 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
834 $link = $linksToDisplay [ $keys [ $i ]];
835 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
836 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
837 $latestDate = max ( $latestDate , $iso8601date );
838 $absurl = $link [ 'url' ];
839 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
840 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
841 if ( $usepermalinks === true )
842 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
844 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
845 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
847 // Add permalink in description
848 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
849 // If user wants permalinks first, put the final link in description
850 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
851 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
853 $entries .= '<content type="html"><![CDATA[' .
854 format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]) .
855 $descriptionlink . "]]></content> \n " ;
856 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
858 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
859 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
861 $entries .= "</entry> \n " ;
864 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
865 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
866 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
867 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
868 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
870 $feed .= '<!-- PubSubHubbub Discovery -->' ;
871 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
872 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
874 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
875 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
877 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
880 $cache- > cache ( ob_get_contents ());
885 // ------------------------------------------------------------------------------------------
886 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
887 // Gives the last 7 days (which have links).
888 // This RSS feed cannot be filtered.
889 function showDailyRSS () {
891 $query = $_SERVER [ "QUERY_STRING" ];
892 $cache = new CachedPage (
893 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
895 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
897 $cached = $cache- > cachedVersion ();
898 if (! empty ( $cached )) {
903 // If cached was not found (or not usable), then read the database and build the response:
904 // Read links from database (and filter private links if used it not logged in).
905 $LINKSDB = new LinkDB (
906 $GLOBALS [ 'config' ][ 'DATASTORE' ],
908 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
909 $GLOBALS [ 'redirector' ]
912 /* Some Shaarlies may have very few links, so we need to look
913 back in time (rsort()) until we have enough days ($nb_of_days).
915 $linkdates = array ();
916 foreach ( $LINKSDB as $linkdate => $value ) {
917 $linkdates [] = $linkdate ;
920 $nb_of_days = 7 ; // We take 7 days.
921 $today = Date ( 'Ymd' );
924 foreach ( $linkdates as $linkdate ) {
925 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
926 if ( strcmp ( $day , $today ) < 0 ) {
927 if ( empty ( $days [ $day ])) {
928 $days [ $day ] = array ();
930 $days [ $day ][] = $linkdate ;
933 if ( count ( $days ) > $nb_of_days ) {
934 break ; // Have we collected enough days?
938 // Build the RSS feed.
939 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
940 $pageaddr = escape ( index_url ( $_SERVER ));
941 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
943 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
944 echo '<link>' . $pageaddr . '</link>' ;
945 echo '<description>Daily shared links</description>' ;
946 echo '<language>en-en</language>' ;
947 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
950 foreach ( $days as $day => $linkdates ) {
951 $daydate = linkdate2timestamp ( $day . '_000000' ); // Full text date
952 $rfc822date = linkdate2rfc822 ( $day . '_000000' );
953 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
955 // Build the HTML body of this RSS entry.
960 // We pre-format some fields for proper output.
961 foreach ( $linkdates as $linkdate ) {
962 $l = $LINKSDB [ $linkdate ];
963 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
964 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
965 $l [ 'timestamp' ] = linkdate2timestamp ( $l [ 'linkdate' ]);
966 if ( startsWith ( $l [ 'url' ], '?' )) {
967 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
969 $links [ $linkdate ] = $l ;
972 // Then build the HTML for this day:
974 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
975 $tpl- > assign ( 'daydate' , $daydate );
976 $tpl- > assign ( 'absurl' , $absurl );
977 $tpl- > assign ( 'links' , $links );
978 $tpl- > assign ( 'rfc822date' , escape ( $rfc822date ));
979 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
981 echo $html . PHP_EOL
;
983 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
985 $cache- > cache ( ob_get_contents ());
993 $LINKSDB = new LinkDB (
994 $GLOBALS [ 'config' ][ 'DATASTORE' ],
996 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
997 $GLOBALS [ 'redirector' ]
1000 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
1001 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
1003 $days = $LINKSDB- > days ();
1004 $i = array_search ( $day , $days );
1005 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
1010 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
1011 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
1015 $linksToDisplay = $LINKSDB- > filterDay ( $day );
1016 } catch ( Exception
$exc ) {
1018 $linksToDisplay = array ();
1021 // We pre-format some fields for proper output.
1022 foreach ( $linksToDisplay as $key => $link )
1025 $taglist = explode ( ' ' , $link [ 'tags' ]);
1026 uasort ( $taglist , 'strcasecmp' );
1027 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
1028 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1029 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
1030 $linksToDisplay [ $key ][ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
1033 /* We need to spread the articles on 3 columns.
1034 I did not want to use a JavaScript lib like http://masonry.desandro.com/
1035 so I manually spread entries with a simple method: I roughly evaluate the
1036 height of a div according to title and description length.
1038 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
1039 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
1040 foreach ( $linksToDisplay as $key => $link )
1042 // Roughly estimate length of entry (by counting characters)
1043 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
1044 // Description: 836 characters gives roughly 342 pixel height.
1045 // This is not perfect, but it's usually OK.
1046 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
1047 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
1048 // Then put in column which is the less filled:
1049 $smallest = min ( $fill ); // find smallest value in array.
1050 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
1051 array_push ( $columns [ $index ], $link ); // Put entry in this column.
1052 $fill [ $index ] +
= $length ;
1054 $PAGE = new pageBuilder
;
1056 'linksToDisplay' => $linksToDisplay ,
1057 'linkcount' => count ( $LINKSDB ),
1059 'day' => linkdate2timestamp ( $day . '_000000' ),
1060 'previousday' => $previousday ,
1061 'nextday' => $nextday ,
1063 $pluginManager = PluginManager
:: getInstance ();
1064 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
1066 foreach ( $data as $key => $value ) {
1067 $PAGE- > assign ( $key , $value );
1070 $PAGE- > renderPage ( 'daily' );
1074 // Renders the linklist
1075 function showLinkList ( $PAGE , $LINKSDB ) {
1076 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1077 $PAGE- > renderPage ( 'linklist' );
1081 // ------------------------------------------------------------------------------------------
1082 // Render HTML page (according to URL parameters and user rights)
1083 function renderPage ()
1085 $LINKSDB = new LinkDB (
1086 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1088 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1089 $GLOBALS [ 'redirector' ]
1092 $PAGE = new pageBuilder
;
1094 // Determine which page will be rendered.
1095 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1096 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1098 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1099 // Then assign generated data to RainTPL.
1100 $common_hooks = array (
1105 $pluginManager = PluginManager
:: getInstance ();
1106 foreach ( $common_hooks as $name ) {
1107 $plugin_data = array ();
1108 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1110 'target' => $targetPage ,
1111 'loggedin' => isLoggedIn ()
1114 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1117 // -------- Display login form.
1118 if ( $targetPage == Router
:: $PAGE_LOGIN )
1120 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1121 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1122 $PAGE- > assign ( 'token' , $token );
1123 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1124 $PAGE- > renderPage ( 'loginform' );
1127 // -------- User wants to logout.
1128 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1130 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1132 header ( 'Location: ?' );
1136 // -------- Picture wall
1137 if ( $targetPage == Router
:: $PAGE_PICWALL )
1139 // Optionally filter the results:
1141 if (! empty ( $_GET [ 'searchterm' ])) $links = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
1142 elseif (! empty ( $_GET [ 'searchtags' ])) $links = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1143 else $links = $LINKSDB ;
1146 $linksToDisplay = array ();
1148 // Get only links which have a thumbnail.
1149 foreach ( $links as $link )
1151 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1152 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1153 if ( $thumb != '' ) // Only output links which have a thumbnail.
1155 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1156 $linksToDisplay []= $link ; // Add to array.
1161 'linkcount' => count ( $LINKSDB ),
1162 'linksToDisplay' => $linksToDisplay ,
1164 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1166 foreach ( $data as $key => $value ) {
1167 $PAGE- > assign ( $key , $value );
1170 $PAGE- > renderPage ( 'picwall' );
1174 // -------- Tag cloud
1175 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1177 $tags = $LINKSDB- > allTags ();
1179 // We sort tags alphabetically, then choose a font size according to count.
1180 // First, find max value.
1181 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
1184 foreach ( $tags as $key => $value )
1185 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1187 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1191 'linkcount' => count ( $LINKSDB ),
1194 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1196 foreach ( $data as $key => $value ) {
1197 $PAGE- > assign ( $key , $value );
1200 $PAGE- > renderPage ( 'tagcloud' );
1204 // Display openseach plugin (XML)
1205 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
1206 header ( 'Content-Type: application/xml; charset=utf-8' );
1207 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
1208 $PAGE- > renderPage ( 'opensearch' );
1212 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1213 if ( isset ( $_GET [ 'addtag' ]))
1215 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1216 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1217 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1219 // Prevent redirection loop
1220 if ( isset ( $params [ 'addtag' ])) {
1221 unset ( $params [ 'addtag' ]);
1224 // Check if this tag is already in the search query and ignore it if it is.
1225 // Each tag is always separated by a space
1226 if ( isset ( $params [ 'searchtags' ])) {
1227 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1229 $current_tags = array ();
1232 foreach ( $current_tags as $value ) {
1233 if ( $value === $_GET [ 'addtag' ]) {
1238 // Append the tag if necessary
1239 if ( empty ( $params [ 'searchtags' ])) {
1240 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1243 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1246 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1247 header ( 'Location: ?' . http_build_query ( $params ));
1251 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1252 if ( isset ( $_GET [ 'removetag' ])) {
1253 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1254 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1255 header ( 'Location: ?' );
1259 // In case browser does not send HTTP_REFERER
1260 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1262 // Prevent redirection loop
1263 if ( isset ( $params [ 'removetag' ])) {
1264 unset ( $params [ 'removetag' ]);
1267 if ( isset ( $params [ 'searchtags' ])) {
1268 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1269 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
1270 if ( count ( $tags )== 0 ) {
1271 unset ( $params [ 'searchtags' ]);
1273 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1275 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1277 header ( 'Location: ?' . http_build_query ( $params ));
1281 // -------- User wants to change the number of links per page (linksperpage=...)
1282 if ( isset ( $_GET [ 'linksperpage' ])) {
1283 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1284 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1287 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1291 // -------- User wants to see only private links (toggle)
1292 if ( isset ( $_GET [ 'privateonly' ])) {
1293 if ( empty ( $_SESSION [ 'privateonly' ])) {
1294 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1296 unset ( $_SESSION [ 'privateonly' ]); // See all links
1299 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1303 // -------- Handle other actions allowed for non-logged in users:
1306 // User tries to post new link but is not logged in:
1307 // Show login screen, then redirect to ?post=...
1308 if ( isset ( $_GET [ 'post' ]))
1310 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.
1314 // Same case as above except that user tried to access ?do=addlink without being logged in
1315 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1316 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1317 header ( 'Location: ?do=login&post=' );
1320 showLinkList ( $PAGE , $LINKSDB );
1321 if ( isset ( $_GET [ 'edit_link' ])) {
1322 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1326 exit ; // Never remove this one! All operations below are reserved for logged in user.
1329 // -------- All other functions are reserved for the registered user:
1331 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1332 if ( $targetPage == Router
:: $PAGE_TOOLS )
1335 'linkcount' => count ( $LINKSDB ),
1336 'pageabsaddr' => index_url ( $_SERVER ),
1338 $pluginManager- > executeHooks ( 'render_tools' , $data );
1340 foreach ( $data as $key => $value ) {
1341 $PAGE- > assign ( $key , $value );
1344 $PAGE- > renderPage ( 'tools' );
1348 // -------- User wants to change his/her password.
1349 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1351 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1352 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1354 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1356 // Make sure old password is correct.
1357 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1358 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1359 // Save new password
1360 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1361 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1363 writeConfig ( $GLOBALS , isLoggedIn ());
1365 catch ( Exception
$e ) {
1367 'ERROR while writing config file after changing password.' . PHP_EOL
.
1371 // TODO: do not handle exceptions/errors in JS.
1372 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1375 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1378 else // show the change password form.
1380 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1381 $PAGE- > assign ( 'token' , getToken ());
1382 $PAGE- > renderPage ( 'changepassword' );
1387 // -------- User wants to change configuration
1388 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1390 if (! empty ( $_POST [ 'title' ]) )
1392 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1394 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1395 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1396 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1397 $GLOBALS [ 'timezone' ] = $tz ;
1398 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1399 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1400 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1401 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1402 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1403 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1404 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1405 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1407 writeConfig ( $GLOBALS , isLoggedIn ());
1409 catch ( Exception
$e ) {
1411 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1415 // TODO: do not handle exceptions/errors in JS.
1416 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1419 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1422 else // Show the configuration form.
1424 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1425 $PAGE- > assign ( 'token' , getToken ());
1426 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1427 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1428 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1429 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1430 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1431 $PAGE- > renderPage ( 'configure' );
1436 // -------- User wants to rename a tag or delete it
1437 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1439 if ( empty ( $_POST [ 'fromtag' ]))
1441 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1442 $PAGE- > assign ( 'token' , getToken ());
1443 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1444 $PAGE- > renderPage ( 'changetag' );
1447 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1450 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
1452 $needle = trim ( $_POST [ 'fromtag' ]);
1453 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // True for case-sensitive tag search.
1454 foreach ( $linksToAlter as $key => $value )
1456 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1457 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1458 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1459 $LINKSDB [ $key ]= $value ;
1461 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1462 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1467 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
1469 $needle = trim ( $_POST [ 'fromtag' ]);
1470 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
1471 foreach ( $linksToAlter as $key => $value )
1473 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1474 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1475 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1476 $LINKSDB [ $key ]= $value ;
1478 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1479 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1484 // -------- User wants to add a link without using the bookmarklet: Show form.
1485 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1487 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1488 $PAGE- > renderPage ( 'addlink' );
1492 // -------- User clicked the "Save" button when editing a link: Save link to database.
1493 if ( isset ( $_POST [ 'save_edit' ]))
1495 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1496 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
1497 $tags = implode ( ' ' , array_unique ( explode ( ' ' , $tags ))); // Remove duplicates.
1498 $linkdate = $_POST [ 'lf_linkdate' ];
1499 $url = trim ( $_POST [ 'lf_url' ]);
1500 if (! startsWith ( $url , 'http:' ) && ! startsWith ( $url , 'https:' ) && ! startsWith ( $url , 'ftp:' ) && ! startsWith ( $url , 'magnet:' ) && ! startsWith ( $url , '?' ) && ! startsWith ( $url , 'javascript:' ))
1501 $url = 'http://' . $url ;
1502 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => $url , 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1503 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
1504 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
1506 $pluginManager- > executeHooks ( 'save_link' , $link );
1508 $LINKSDB [ $linkdate ] = $link ;
1509 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1512 // If we are called from the bookmarklet, we must close the popup:
1513 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1514 echo '<script>self.close();</script>' ;
1518 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? escape ( $_POST [ 'returnurl' ]): '?' ;
1519 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1520 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1521 header ( 'Location: ' . $location ); // After saving the link, redirect to the page the user was on.
1525 // -------- User clicked the "Cancel" button when editing a link.
1526 if ( isset ( $_POST [ 'cancel_edit' ]))
1528 // If we are called from the bookmarklet, we must close the popup:
1529 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1530 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1531 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1532 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1533 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1537 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1538 if ( isset ( $_POST [ 'delete_link' ]))
1540 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1541 // We do not need to ask for confirmation:
1542 // - confirmation is handled by JavaScript
1543 // - we are protected from XSRF by the token.
1544 $linkdate = $_POST [ 'lf_linkdate' ];
1546 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1548 unset ( $LINKSDB [ $linkdate ]);
1549 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1551 // If we are called from the bookmarklet, we must close the popup:
1552 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1553 // Pick where we're going to redirect
1554 // =============================================================
1555 // Basically, we can't redirect to where we were previously if it was a permalink
1556 // or an edit_link, because it would 404.
1558 // - / : nothing in $_GET, redirect to self
1559 // - /?page : redirect to self
1560 // - /?searchterm : redirect to self (there might be other links)
1561 // - /?searchtags : redirect to self
1562 // - /permalink : redirect to / (the link does not exist anymore)
1563 // - /?edit_link : redirect to / (the link does not exist anymore)
1564 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1565 // redirect is not satisfied, and only then redirect to /
1568 if ( count ( $_GET ) == 0
1569 || isset ( $_GET [ 'page' ])
1570 || isset ( $_GET [ 'searchterm' ])
1571 || isset ( $_GET [ 'searchtags' ])
1573 if ( isset ( $_POST [ 'returnurl' ])) {
1574 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1576 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1580 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1584 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1585 if ( isset ( $_GET [ 'edit_link' ]))
1587 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1588 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1590 'linkcount' => count ( $LINKSDB ),
1592 'link_is_new' => false ,
1593 'token' => getToken (),
1594 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1595 'tags' => $LINKSDB- > allTags (),
1597 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1599 foreach ( $data as $key => $value ) {
1600 $PAGE- > assign ( $key , $value );
1603 $PAGE- > renderPage ( 'editlink' );
1607 // -------- User want to post a new link: Display link edit form.
1608 if ( isset ( $_GET [ 'post' ])) {
1609 $url = cleanup_url ( $_GET [ 'post' ]);
1611 $link_is_new = false ;
1612 // Check if URL is not already in database (in this case, we will edit the existing link)
1613 $link = $LINKSDB- > getLinkFromUrl ( $url );
1616 $link_is_new = true ;
1617 $linkdate = strval ( date ( 'Ymd_His' ));
1618 // Get title if it was provided in URL (by the bookmarklet).
1619 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1620 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1621 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1622 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1623 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1624 // 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.)
1625 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1626 // Short timeout to keep the application responsive
1627 list ( $headers , $data ) = get_http_url ( $url , 4 );
1628 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1629 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1630 // Look for charset in html header.
1631 preg_match ( '#<meta .*charset=.*>#Usi' , $data , $meta );
1633 // If found, extract encoding.
1634 if (! empty ( $meta [ 0 ])) {
1635 // Get encoding specified in header.
1636 preg_match ( '#charset="?(.*)"#si' , $meta [ 0 ], $enc );
1637 // If charset not found, use utf-8.
1638 $html_charset = (! empty ( $enc [ 1 ])) ? strtolower ( $enc [ 1 ]) : 'utf-8' ;
1641 $html_charset = 'utf-8' ;
1645 $title = html_extract_title ( $data );
1646 if (! empty ( $title )) {
1647 // Re-encode title in utf-8 if necessary.
1648 $title = ( $html_charset == 'iso-8859-1' ) ? utf8_encode ( $title ) : $title ;
1653 $url = '?' . smallHash ( $linkdate );
1657 'linkdate' => $linkdate ,
1660 'description' => $description ,
1662 'private' => $private
1667 'linkcount' => count ( $LINKSDB ),
1669 'link_is_new' => $link_is_new ,
1670 'token' => getToken (), // XSRF protection.
1671 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1672 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1673 'tags' => $LINKSDB- > allTags (),
1675 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1677 foreach ( $data as $key => $value ) {
1678 $PAGE- > assign ( $key , $value );
1681 $PAGE- > renderPage ( 'editlink' );
1685 // -------- Export as Netscape Bookmarks HTML file.
1686 if ( $targetPage == Router
:: $PAGE_EXPORT )
1688 if ( empty ( $_GET [ 'what' ]))
1690 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1691 $PAGE- > renderPage ( 'export' );
1694 $exportWhat = $_GET [ 'what' ];
1695 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1697 header ( 'Content-Type: text/html; charset=utf-8' );
1698 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1699 $currentdate = date ( 'Y/m/d H:i:s' );
1701 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1702 <!-- This is an automatically generated file.
1703 It will be read and overwritten.
1705 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1706 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1707 <TITLE>Bookmarks</TITLE>
1710 foreach ( $LINKSDB as $link )
1712 if ( $exportWhat == 'all' ||
1713 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1714 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1716 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1717 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1718 echo '>' . $link [ 'title' ]. "</A> \n " ;
1719 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1725 // -------- User is uploading a file for import
1726 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1728 // If file is too big, some form field may be missing.
1729 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1731 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1732 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>' ;
1735 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1740 // -------- Show upload/import dialog:
1741 if ( $targetPage == Router
:: $PAGE_IMPORT )
1743 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1744 $PAGE- > assign ( 'token' , getToken ());
1745 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1746 $PAGE- > renderPage ( 'import' );
1750 // -------- Otherwise, simply display search form and links:
1751 showLinkList ( $PAGE , $LINKSDB );
1755 // -----------------------------------------------------------------------------------------------
1756 // Process the import file form.
1757 function importFile ()
1759 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1760 $LINKSDB = new LinkDB (
1761 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1763 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
1764 $GLOBALS [ 'redirector' ]
1766 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1767 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1768 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1769 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1770 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1775 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1777 // Then import the bookmarks.
1778 if ( $type == 'netscape' )
1780 // This is a standard Netscape-style bookmark file.
1781 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1782 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1784 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1785 $d = explode ( '<DD>' , $html );
1786 if ( startswith ( $d [ 0 ], '<A ' ))
1788 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1789 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1790 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1791 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1793 foreach ( $matches as $m )
1795 $attr = $m [ 1 ]; $value = $m [ 2 ];
1796 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1797 elseif ( $attr == 'ADD_DATE' )
1799 $raw_add_date = intval ( $value );
1800 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1802 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1803 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1805 if ( $link [ 'url' ]!= '' )
1807 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1808 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1810 { // Link not in database, let's import it...
1811 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1813 // Make sure date/time is not already used by another link.
1814 // (Some bookmark files have several different links with the same ADD_DATE)
1815 // We increment date by 1 second until we find a date which is not used in DB.
1816 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1817 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1818 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1819 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1822 else // Link already present in database.
1825 { // If overwrite is required, we import link data, except date/time.
1826 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1827 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1835 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1837 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1841 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1845 // -----------------------------------------------------------------------------------------------
1846 // Template for the list of links (<div id="linklist">)
1847 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1848 function buildLinkList ( $PAGE , $LINKSDB )
1850 // ---- Filter link database according to parameters
1851 $linksToDisplay = array ();
1854 if ( isset ( $_GET [ 'searchterm' ])) // Fulltext search
1856 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1857 $search_crits = escape ( trim ( $_GET [ 'searchterm' ]));
1858 $search_type = 'fulltext' ;
1860 elseif ( isset ( $_GET [ 'searchtags' ])) // Search by tag
1862 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1863 $search_crits = explode ( ' ' , escape ( trim ( $_GET [ 'searchtags' ])));
1864 $search_type = 'tags' ;
1866 elseif ( isset ( $_SERVER [ 'QUERY_STRING' ]) && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])) // Detect smallHashes in URL
1868 $linksToDisplay = $LINKSDB- > filterSmallHash ( substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 ));
1869 if ( count ( $linksToDisplay )== 0 )
1871 header ( $_SERVER [ "SERVER_PROTOCOL" ]. " 404 Not Found" );
1872 echo '<h1>404 Not found.</h1>Oh crap. The link you are trying to reach does not exist or has been deleted.' ;
1873 echo '<br>Would you mind <a href="?">clicking here</a>?' ;
1876 $search_type = 'permalink' ;
1879 $linksToDisplay = $LINKSDB ; // Otherwise, display without filtering.
1882 // Option: Show only private links
1883 if (! empty ( $_SESSION [ 'privateonly' ]))
1886 foreach ( $linksToDisplay as $linkdate => $link )
1888 if ( $link [ 'private' ]!= 0 ) $tmp [ $linkdate ]= $link ;
1890 $linksToDisplay = $tmp ;
1893 // ---- Handle paging.
1894 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess???
1895 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1896 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1898 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks PHP.
1900 // If there is only a single link, we change on-the-fly the title of the page.
1901 if ( count ( $linksToDisplay )== 1 ) $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1903 // Select articles according to paging.
1904 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1905 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1906 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1907 $page = ( $page < 1 ? 1 : $page );
1908 $page = ( $page > $pagecount ? $pagecount : $page );
1909 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1910 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1911 $linkDisp = array (); // Links to display
1912 while ( $i < $end && $i < count ( $keys ))
1914 $link = $linksToDisplay [ $keys [ $i ]];
1915 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1916 $classLi = $i %
2 != 0 ? '' : 'publicLinkHightLight' ;
1917 $link [ 'class' ] = ( $link [ 'private' ]== 0 ? $classLi : 'private' );
1918 $link [ 'timestamp' ]= linkdate2timestamp ( $link [ 'linkdate' ]);
1919 $taglist = explode ( ' ' , $link [ 'tags' ]);
1920 uasort ( $taglist , 'strcasecmp' );
1921 $link [ 'taglist' ]= $taglist ;
1922 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1923 if ( $link [ "url" ][ 0 ] === '?' && // Check for both signs of a note: starting with ? and 7 chars long. I doubt that you'll post any links that look like this.
1924 strlen ( $link [ "url" ]) === 7 ) {
1925 $link [ "url" ] = index_url ( $_SERVER ) . $link [ "url" ];
1928 $linkDisp [ $keys [ $i ]] = $link ;
1932 // Compute paging navigation
1933 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1934 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1936 $previous_page_url = '' ; if ( $i != count ( $keys )) $previous_page_url = '?page=' .( $page +
1 ). $searchterm . $searchtags ;
1937 $next_page_url = '' ; if ( $page > 1 ) $next_page_url = '?page=' .( $page-1 ). $searchterm . $searchtags ;
1939 $token = '' ; if ( isLoggedIn ()) $token = getToken ();
1941 // Fill all template fields.
1943 'linkcount' => count ( $LINKSDB ),
1944 'previous_page_url' => $previous_page_url ,
1945 'next_page_url' => $next_page_url ,
1946 'page_current' => $page ,
1947 'page_max' => $pagecount ,
1948 'result_count' => count ( $linksToDisplay ),
1949 'search_type' => $search_type ,
1950 'search_crits' => $search_crits ,
1951 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
1953 'links' => $linkDisp ,
1954 'tags' => $LINKSDB- > allTags (),
1957 $pluginManager = PluginManager
:: getInstance ();
1958 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1960 foreach ( $data as $key => $value ) {
1961 $PAGE- > assign ( $key , $value );
1967 // Compute the thumbnail for a link.
1969 // With a link to the original URL.
1970 // Understands various services (youtube.com...)
1971 // Input: $url = URL for which the thumbnail must be found.
1972 // $href = if provided, this URL will be followed instead of $url
1973 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1974 // Some of them may be missing.
1975 // Return an empty array if no thumbnail available.
1976 function computeThumbnail ( $url , $href = false )
1978 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
1979 if ( $href == false ) $href = $url ;
1981 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1982 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1983 // ^^^^^^^^^^^ ^^^^^^^^^^^
1984 $domain = parse_url ( $url , PHP_URL_HOST
);
1985 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1987 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1988 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1989 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1991 if ( $domain == 'youtu.be' ) // Youtube short links
1993 $path = parse_url ( $url , PHP_URL_PATH
);
1994 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1995 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1997 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1999 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
2000 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
2001 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
2004 if ( $domain == 'imgur.com' )
2006 $path = parse_url ( $url , PHP_URL_PATH
);
2007 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
2008 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
2009 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2010 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
2011 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2013 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
2014 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2016 if ( $domain == 'i.imgur.com' )
2018 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
2019 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
2020 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
2022 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
2024 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
2026 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
2027 return array ( 'src' => $thumburl ,
2028 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
2031 if ( endsWith ( $domain , '.imageshack.us' ))
2033 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2034 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2036 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
2037 return array ( 'src' => $thumburl ,
2038 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
2042 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
2043 // So we deport the thumbnail generation in order not to slow down page generation
2044 // (and we also cache the thumbnail)
2046 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
2048 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
2049 || $domain == 'vimeo.com'
2050 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
2051 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
2054 if ( $domain == 'vimeo.com' )
2055 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
2056 $path = parse_url ( $url , PHP_URL_PATH
);
2057 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
2059 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2060 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
2061 $path = parse_url ( $url , PHP_URL_PATH
);
2062 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
2064 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2065 { // Make sure this TED URL points to a video (/talks/...)
2066 $path = parse_url ( $url , PHP_URL_PATH
);
2067 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
2069 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2070 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2071 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2074 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
2075 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
2076 // But using the extension will do.
2077 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
2078 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
2080 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
2081 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
2082 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
2084 return array (); // No thumbnail.
2089 // Returns the HTML code to display a thumbnail for a link
2090 // with a link to the original URL.
2091 // Understands various services (youtube.com...)
2092 // Input: $url = URL for which the thumbnail must be found.
2093 // $href = if provided, this URL will be followed instead of $url
2094 // Returns '' if no thumbnail available.
2095 function thumbnail ( $url , $href = false )
2097 $t = computeThumbnail ( $url , $href );
2098 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2100 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2101 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2102 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2103 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2104 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2109 // Returns the HTML code to display a thumbnail for a link
2110 // for the picture wall (using lazy image loading)
2111 // Understands various services (youtube.com...)
2112 // Input: $url = URL for which the thumbnail must be found.
2113 // $href = if provided, this URL will be followed instead of $url
2114 // Returns '' if no thumbnail available.
2115 function lazyThumbnail ( $url , $href = false )
2117 $t = computeThumbnail ( $url , $href );
2118 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2120 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2123 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2125 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2126 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2127 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2128 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2131 // No-JavaScript fallback.
2132 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2133 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2134 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2135 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2136 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2137 $html .= '></noscript></a>' ;
2143 // -----------------------------------------------------------------------------------------------
2145 // This function should NEVER be called if the file data/config.php exists.
2148 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2149 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2152 // This part makes sure sessions works correctly.
2153 // (Because on some hosts, session.save_path may not be set correctly,
2154 // or we may not have write access to it.)
2155 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2156 { // Step 2: Check if data in session is correct.
2157 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2158 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2159 echo 'It currently points to ' . session_save_path (). '<br>' ;
2160 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>' ;
2161 echo '<br><a href="?">Click to try again.</a></pre>' ;
2164 if (! isset ( $_SESSION [ 'session_tested' ]))
2165 { // Step 1 : Try to store data in session and reload page.
2166 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2167 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2169 if ( isset ( $_GET [ 'test_session' ]))
2170 { // Step 3: Sessions are OK. Remove test parameter from URL.
2171 header ( 'Location: ' . index_url ( $_SERVER ));
2175 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2178 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2179 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2180 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2183 $GLOBALS [ 'timezone' ] = $tz ;
2184 // Everything is ok, let's create config file.
2185 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2186 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2187 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2188 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2189 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2191 writeConfig ( $GLOBALS , isLoggedIn ());
2193 catch ( Exception
$e ) {
2195 'ERROR while writing config file after installation.' . PHP_EOL
.
2199 // TODO: do not handle exceptions/errors in JS.
2200 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2203 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2207 // Display config form:
2208 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2209 $timezone_html = '' ;
2210 if ( $timezone_form != '' ) {
2211 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2214 $PAGE = new pageBuilder
;
2215 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2216 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2217 $PAGE- > renderPage ( 'install' );
2221 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2222 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2223 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2224 This function is called by passing the URL:
2225 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2226 [URL] is the URL of the link (e.g. a flickr page)
2227 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2228 The function below will fetch the image from the webservice and store it in the cache.
2230 function genThumbnail ()
2232 // Make sure the parameters in the URL were generated by us.
2233 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2234 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2236 // Let's see if we don't already have the image for this URL in the cache.
2237 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2238 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2239 { // We have the thumbnail, just serve it:
2240 header ( 'Content-Type: image/jpeg' );
2241 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2244 // We may also serve a blank image (if service did not respond)
2245 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2246 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2248 header ( 'Content-Type: image/gif' );
2249 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2253 // Otherwise, generate the thumbnail.
2254 $url = $_GET [ 'url' ];
2255 $domain = parse_url ( $url , PHP_URL_HOST
);
2257 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2259 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2260 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2262 // Is this a link to an image, or to a flickr page ?
2264 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2265 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2266 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2267 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2269 else // This is a flickr page (html)
2271 // Get the flickr html page.
2272 list ( $headers , $data ) = get_http_url ( $url , 20 );
2273 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2275 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2276 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $data , $matches );
2277 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2279 // In albums (and some other pages), the link rel="image_src" is not provided,
2280 // but flickr provides:
2281 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2284 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $data , $matches );
2285 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2291 { // Let's download the image.
2292 // Image is 240x120, so 10 seconds to download should be enough.
2293 list ( $headers , $data ) = get_http_url ( $imageurl , 10 );
2294 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2295 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
2296 header ( 'Content-Type: image/jpeg' );
2303 elseif ( $domain == 'vimeo.com' )
2305 // This is more complex: we have to perform a HTTP request, then parse the result.
2306 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2307 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2308 list ( $headers , $data ) = get_http_url ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2309 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2310 $t = unserialize ( $data );
2311 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2312 // Then we download the image and serve it to our client.
2313 list ( $headers , $data ) = get_http_url ( $imageurl , 10 );
2314 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2315 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
2316 header ( 'Content-Type: image/jpeg' );
2323 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2325 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2326 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2327 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2328 list ( $headers , $data ) = get_http_url ( $url , 5 );
2329 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2330 // Extract the link to the thumbnail
2331 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $data , $matches );
2332 if (! empty ( $matches [ 1 ]))
2333 { // Let's download the image.
2334 $imageurl = $matches [ 1 ];
2335 // No control on image size, so wait long enough
2336 list ( $headers , $data ) = get_http_url ( $imageurl , 20 );
2337 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2338 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2339 file_put_contents ( $filepath , $data ); // Save image to cache.
2340 if ( resizeImage ( $filepath ))
2342 header ( 'Content-Type: image/jpeg' );
2343 echo file_get_contents ( $filepath );
2351 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2353 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2354 // http://xkcd.com/327/
2355 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2356 list ( $headers , $data ) = get_http_url ( $url , 5 );
2357 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2358 // Extract the link to the thumbnail
2359 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $data , $matches );
2360 if (! empty ( $matches [ 1 ]))
2361 { // Let's download the image.
2362 $imageurl = $matches [ 1 ];
2363 // No control on image size, so wait long enough
2364 list ( $headers , $data ) = get_http_url ( $imageurl , 20 );
2365 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2366 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2367 file_put_contents ( $filepath , $data ); // Save image to cache.
2368 if ( resizeImage ( $filepath ))
2370 header ( 'Content-Type: image/jpeg' );
2371 echo file_get_contents ( $filepath );
2381 // For all other domains, we try to download the image and make a thumbnail.
2382 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2383 list ( $headers , $data ) = get_http_url ( $url , 30 );
2384 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2385 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2386 file_put_contents ( $filepath , $data ); // Save image to cache.
2387 if ( resizeImage ( $filepath ))
2389 header ( 'Content-Type: image/jpeg' );
2390 echo file_get_contents ( $filepath );
2397 // Otherwise, return an empty image (8x8 transparent gif)
2398 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2399 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2400 header ( 'Content-Type: image/gif' );
2404 // Make a thumbnail of the image (to width: 120 pixels)
2405 // Returns true if success, false otherwise.
2406 function resizeImage ( $filepath )
2408 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2410 // Trick: some stupid people rename GIF as JPEG... or else.
2411 // So we really try to open each image type whatever the extension is.
2412 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2414 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2415 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2416 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2417 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2420 $ystart = 0 ; $yheight = $h ;
2421 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2422 $nw = 120 ; // Desired width
2423 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2425 $im2 = imagecreatetruecolor ( $nw , $nh );
2426 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2427 imageinterlace ( $im2 , true ); // For progressive JPEG.
2428 $tempname = $filepath . '_TEMP.jpg' ;
2429 imagejpeg ( $im2 , $tempname , 90 );
2433 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2438 mergeDeprecatedConfig ( $GLOBALS , isLoggedIn ());
2439 } catch ( Exception
$e ) {
2441 'ERROR while merging deprecated options.php file.' . PHP_EOL
.
2446 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2447 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2448 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2449 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2450 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=daily' )) { showDaily (); exit ; }
2451 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];