]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.5.4 - 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 parameter (These parameters can be overwritten by editing the file /data/config.php)
27 // You should not touch any code below (or at your own risks!)
28 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ; // Data subdirectory
29 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ; // Configuration file (user login/password)
30 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ; // Data storage file.
31 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ; // Default links per page.
32 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ; // File storage for failures and bans.
33 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ; // Ban IP after this many failures.
34 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ; // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
35 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ; // If true, anyone can add/edit/delete links without having to login
36 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ; // If true, the moment when links were saved are not shown to users that are not logged in.
37 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ; // If true, an extra "ATOM feed" button will be displayed in the toolbar
38 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ; // Enable thumbnails in links.
39 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ; // Cache directory for thumbnails for SLOW services (like flickr)
40 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ; // Page cache directory.
41 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce web space usage.
42 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
43 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ; // Raintpl cache directory (keep the trailing slash!)
44 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ; // Raintpl template directory (keep the trailing slash!)
45 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ; // For updates check of Shaarli.
46 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
47 // Note: You must have publisher.php in the same directory as Shaarli index.php
48 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ; // Enable RSS permalinks by default. This corresponds to the default behavior of shaarli before this was added as an option.
49 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
50 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
51 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
52 // 'wallabag', 'markdown', 'addlink_toolbar',
54 // Warning: order matters.
55 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
57 // Default plugins, default config - will be overriden by config.php and then plugin's config.php file.
58 $GLOBALS [ 'plugins' ][ 'READITYOUSELF_URL' ] = 'http://someurl.com' ;
59 $GLOBALS [ 'plugins' ][ 'WALLABAG_URL' ] = 'https://demo.wallabag.org/' ;
60 // -----------------------------------------------------------------------------------------------
61 define ( 'shaarli_version' , '0.5.4' );
62 // http://server.com/x/shaarli --> /shaarli/
63 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
66 ini_set ( 'max_input_time' , '60' ); // High execution time in case of problematic imports/exports.
67 ini_set ( 'memory_limit' , '128M' ); // Try to set max upload file size and read (May not work on some hosts).
68 ini_set ( 'post_max_size' , '16M' );
69 ini_set ( 'upload_max_filesize' , '16M' );
70 error_reporting ( E_ALL^E_WARNING
); // See all error except warnings.
71 //error_reporting(-1); // See all errors (for debugging only)
74 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
75 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
79 require_once 'application/Cache.php' ;
80 require_once 'application/CachedPage.php' ;
81 require_once 'application/HttpUtils.php' ;
82 require_once 'application/LinkDB.php' ;
83 require_once 'application/TimeZone.php' ;
84 require_once 'application/Url.php' ;
85 require_once 'application/Utils.php' ;
86 require_once 'application/Config.php' ;
87 require_once 'application/PluginManager.php' ;
88 require_once 'application/Router.php' ;
90 // Ensure the PHP version is supported
92 checkPHPVersion ( '5.3' , PHP_VERSION
);
93 } catch ( Exception
$e ) {
94 header ( 'Content-Type: text/plain; charset=utf-8' );
95 echo $e- > getMessage ();
99 // Force cookie path (but do not change lifetime)
100 $cookie = session_get_cookie_params ();
102 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
103 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
105 // Set default cookie expiration and path.
106 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
107 // Set session parameters on server side.
108 // If the user does not access any page within this time, his/her session is considered expired.
109 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
110 // Use cookies to store session.
111 ini_set ( 'session.use_cookies' , 1 );
112 // Force cookies for session (phpsessionID forbidden in URL).
113 ini_set ( 'session.use_only_cookies' , 1 );
114 // Prevent PHP form using sessionID in URL if cookies are disabled.
115 ini_set ( 'session.use_trans_sid' , false );
117 session_name ( 'shaarli' );
118 // Start session if needed (Some server auto-start sessions).
119 if ( session_id () == '' ) {
123 // Regenerate session ID if invalid or not defined in cookie.
124 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
125 session_regenerate_id ( true );
126 $_COOKIE [ 'shaarli' ] = session_id ();
129 include "inc/rain.tpl.class.php" ; //include Rain TPL
130 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
131 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
133 $pluginManager = PluginManager
:: getInstance ();
134 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
136 ob_start (); // Output buffering for the page cache.
139 // In case stupid admin has left magic_quotes enabled in php.ini:
140 if ( get_magic_quotes_gpc ())
142 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
143 $_POST = array_map ( 'stripslashes_deep' , $_POST );
144 $_GET = array_map ( 'stripslashes_deep' , $_GET );
145 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
148 // Prevent caching on client side or proxy: (yes, it's ugly)
149 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
150 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
151 header ( "Cache-Control: post-check=0, pre-check=0" , false );
152 header ( "Pragma: no-cache" );
154 // Directories creations (Note that your web host may require different rights than 705.)
155 if (! is_writable ( realpath ( dirname ( __FILE__
)))) die ( '<pre>ERROR: Shaarli does not have the right to write in its own directory.</pre>' );
157 // Handling of old config file which do not have the new parameters.
158 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
159 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
160 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
161 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
162 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
163 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
164 // I really need to rewrite Shaarli with a proper configuation manager.
166 // Run config screen if first run:
167 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
171 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
172 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
173 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
175 // a token depending of deployment salt, user password, and the current ip
176 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
178 autoLocale (); // Sniff browser language and set date format accordingly.
179 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
181 //==================================================================================================
182 // Checking session state (i.e. is the user still logged in)
183 //==================================================================================================
185 function setup_login_state () {
186 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
187 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
188 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
189 $userIsLoggedIn = true ;
191 if (! isset ( $GLOBALS [ 'login' ])) {
192 $userIsLoggedIn = false ; // Shaarli is not configured yet.
193 $loginFailure = true ;
195 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
196 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
200 $userIsLoggedIn = true ;
202 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
203 if ( empty ( $_SESSION [ 'uid' ]) ||
204 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
205 time () >= $_SESSION [ 'expires_on' ])
208 $userIsLoggedIn = false ;
209 $loginFailure = true ;
211 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
212 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
215 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
217 if (! $loginFailure ) {
218 $userIsLoggedIn = true ;
221 return $userIsLoggedIn ;
223 $userIsLoggedIn = setup_login_state ();
225 // Checks if an update is available for Shaarli.
226 // (at most once a day, and only for registered user.)
227 // Output: '' = no new version.
228 // other= the available version.
229 function checkUpdate ()
231 if (! isLoggedIn ()) return '' ; // Do not check versions for visitors.
232 if ( empty ( $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ])) return '' ; // Do not check if the user doesn't want to.
234 // Get latest version number at most once a day.
235 if (! is_file ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]) || ( filemtime ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ])< time ()-( $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ])))
237 $version = shaarli_version
;
238 list ( $headers , $data ) = get_http_url ( 'https://raw.githubusercontent.com/shaarli/Shaarli/master/shaarli_version.php' , 2 );
239 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
240 $version = str_replace ( ' */ ?>' , '' , str_replace ( '<?php /* ' , '' , $data ));
242 // If failed, never mind. We don't want to bother the user with that.
243 file_put_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ], $version ); // touch file date
246 $newestversion = file_get_contents ( $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ]);
247 if ( version_compare ( $newestversion , shaarli_version
)== 1 ) return $newestversion ;
252 // -----------------------------------------------------------------------------------------------
254 function logm ( $message )
256 $t = strval ( date ( 'Y/m/d_H:i:s' )). ' - ' . $_SERVER [ "REMOTE_ADDR" ]. ' - ' . strval ( $message ). " \n " ;
257 file_put_contents ( $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' , $t , FILE_APPEND
);
260 // In a string, converts URLs to clickable links.
261 // Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
262 function text2clickable ( $url )
264 $redir = empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ];
265 return preg_replace ( '!(((?:https?|ftp|file)://|apt:|magnet:)\S+[[:alnum:]]/?)!si' , '<a href="' . $redir . ' $1" rel="nofollow"> $1 </a>' , $url );
268 // This function inserts where relevant so that multiple spaces are properly displayed in HTML
269 // even in the absence of <pre> (This is used in description to keep text formatting)
270 function keepMultipleSpaces ( $text )
272 return str_replace ( ' ' , ' ' , $text );
275 // ------------------------------------------------------------------------------------------
276 // Sniff browser language to display dates in the right format automatically.
277 // (Note that is may not work on your server if the corresponding local is not installed.)
278 function autoLocale ()
280 $attempts = array ( 'en_US' ); // Default if browser does not send HTTP_ACCEPT_LANGUAGE
281 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) // e.g. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
282 { // (It's a bit crude, but it works very well. Preferred language is always presented first.)
283 if ( preg_match ( '/([a-z] {2} )-?([a-z] {2} )?/i' , $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], $matches )) {
284 $loc = $matches [ 1 ] . (! empty ( $matches [ 2 ]) ? '_' . strtoupper ( $matches [ 2 ]) : '' );
285 $attempts = array ( $loc . '.UTF-8' , $loc , str_replace ( '_' , '-' , $loc ). '.UTF-8' , str_replace ( '_' , '-' , $loc ),
286 $loc . '_' . strtoupper ( $loc ). '.UTF-8' , $loc . '_' . strtoupper ( $loc ),
287 $loc . '_' . $loc . '.UTF-8' , $loc . '_' . $loc , $loc . '-' . strtoupper ( $loc ). '.UTF-8' ,
288 $loc . '-' . strtoupper ( $loc ), $loc . '-' . $loc . '.UTF-8' , $loc . '-' . $loc );
291 setlocale ( LC_TIME
, $attempts ); // LC_TIME = Set local for date/time format only.
294 // ------------------------------------------------------------------------------------------
295 // PubSubHubbub protocol support (if enabled) [UNTESTED]
296 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
297 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
300 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
302 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
304 index_url ( $_SERVER ). '?do=atom' ,
305 index_url ( $_SERVER ). '?do=rss'
307 $p- > publish_update ( $topic_url );
311 // ------------------------------------------------------------------------------------------
312 // Session management
314 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
317 $ip = $_SERVER [ "REMOTE_ADDR" ];
318 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
319 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
320 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
324 function fillSessionInfo () {
325 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
326 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
327 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
328 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
331 // Check that user/password is correct.
332 function check_auth ( $login , $password )
334 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
335 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
336 { // Login/password is correct.
338 logm ( 'Login successful' );
341 logm ( 'Login failed for user ' . $login );
345 // Returns true if the user is logged in.
346 function isLoggedIn ()
348 global $userIsLoggedIn ;
349 return $userIsLoggedIn ;
354 if ( isset ( $_SESSION )) {
355 unset ( $_SESSION [ 'uid' ]);
356 unset ( $_SESSION [ 'ip' ]);
357 unset ( $_SESSION [ 'username' ]);
358 unset ( $_SESSION [ 'privateonly' ]);
360 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
364 // ------------------------------------------------------------------------------------------
365 // Brute force protection system
366 // Several consecutive failed logins will ban the IP address for 30 minutes.
367 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 ?>" );
368 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
369 // Signal a failed login. Will ban the IP if too many failures:
370 function ban_loginFailed ()
372 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
373 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
374 $gb [ 'FAILURES' ][ $ip ] ++
;
375 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
377 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
378 logm ( 'IP address banned from login' );
380 $GLOBALS [ 'IPBANS' ] = $gb ;
381 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
384 // Signals a successful login. Resets failed login counter.
385 function ban_loginOk ()
387 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
388 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
389 $GLOBALS [ 'IPBANS' ] = $gb ;
390 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
393 // Checks if the user CAN login. If 'true', the user can try to login.
394 function ban_canLogin ()
396 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
397 if ( isset ( $gb [ 'BANS' ][ $ip ]))
399 // User is banned. Check if the ban has expired:
400 if ( $gb [ 'BANS' ][ $ip ]<= time ())
401 { // Ban expired, user can try to login again.
403 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
404 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
405 return true ; // Ban has expired, user can login.
407 return false ; // User is banned.
409 return true ; // User is not banned.
412 // ------------------------------------------------------------------------------------------
413 // Process login form: Check if login/password is correct.
414 if ( isset ( $_POST [ 'login' ]))
416 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
417 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
418 { // Login/password is OK.
420 // If user wants to keep the session cookie even after the browser closes:
421 if (! empty ( $_POST [ 'longlastingsession' ]))
423 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
424 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
425 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
427 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
428 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
429 // Note: Never forget the trailing slash on the cookie path!
430 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
432 else // Standard session expiration (=when browser closes)
434 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
435 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
436 session_regenerate_id ( true );
439 // Optional redirect after login:
440 if ( isset ( $_GET [ 'post' ])) {
441 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
442 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
443 if (! empty ( $_GET [ $param ])) {
444 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
447 header ( 'Location: ' . $uri );
451 if ( isset ( $_GET [ 'edit_link' ])) {
452 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
456 if ( isset ( $_POST [ 'returnurl' ])) {
457 // Prevent loops over login screen.
458 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
459 header ( 'Location: ' . escape ( $_POST [ 'returnurl' ]));
463 header ( 'Location: ?' ); exit ;
469 if ( isset ( $_GET [ 'post' ])) {
470 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
471 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
472 if (! empty ( $_GET [ $param ])) {
473 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
477 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
482 // ------------------------------------------------------------------------------------------
483 // Misc utility functions:
485 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
486 function return_bytes ( $val )
488 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
491 case 'g' : $val *= 1024 ;
492 case 'm' : $val *= 1024 ;
493 case 'k' : $val *= 1024 ;
498 // Try to determine max file size for uploads (POST).
499 // Returns an integer (in bytes)
500 function getMaxFileSize ()
502 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
503 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
504 // Return the smaller of two:
505 $maxsize = min ( $size1 , $size2 );
506 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
510 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
511 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
512 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
513 function linkdate2timestamp ( $linkdate )
515 if ( strcmp ( $linkdate , '_000000' ) !== 0 || ! $linkdate ){
517 $r = sscanf ( $linkdate , '%4d%2d%2d_%2d%2d%2d' , $Y , $M , $D , $h , $m , $s );
518 return mktime ( $h , $m , $s , $M , $D , $Y );
523 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
524 (used to build the pubDate attribute in RSS feed.) */
525 function linkdate2rfc822 ( $linkdate )
527 return date ( 'r' , linkdate2timestamp ( $linkdate )); // 'r' is for RFC822 date format.
530 /* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
531 (used to build the updated tags in ATOM feed.) */
532 function linkdate2iso8601 ( $linkdate )
534 return date ( 'c' , linkdate2timestamp ( $linkdate )); // 'c' is for ISO 8601 date format.
537 // Extract title from an HTML document.
538 // (Returns an empty string if not found.)
539 function html_extract_title ( $html )
541 return preg_match ( '!<title>(.*?)</title>!is' , $html , $matches ) ? trim ( str_replace ( " \n " , ' ' , $matches [ 1 ])) : '' ;
544 // ------------------------------------------------------------------------------------------
545 // Token management for XSRF protection
546 // Token should be used in any form which acts on data (create,update,delete,import...).
547 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
552 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
553 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
557 // Tells if a token is OK. Using this function will destroy the token.
559 function tokenOk ( $token )
561 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
563 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
564 return true ; // Token is OK.
566 return false ; // Wrong token, or already used.
569 // ------------------------------------------------------------------------------------------
570 /* This class is in charge of building the final page.
571 (This is basically a wrapper around RainTPL which pre-fills some fields.)
573 p.assign('myfield','myvalue');
574 p.renderPage('mytemplate');
579 private $tpl ; // RainTPL template
581 function __construct ()
586 private function initialize ()
588 $this- > tpl
= new RainTPL
;
589 $this- > tpl
-> assign ( 'newversion' , escape ( checkUpdate ()));
590 $this- > tpl
-> assign ( 'feedurl' , escape ( index_url ( $_SERVER )));
591 $searchcrits = '' ; // Search criteria
592 if (! empty ( $_GET [ 'searchtags' ])) $searchcrits .= '&searchtags=' . urlencode ( $_GET [ 'searchtags' ]);
593 elseif (! empty ( $_GET [ 'searchterm' ])) $searchcrits .= '&searchterm=' . urlencode ( $_GET [ 'searchterm' ]);
594 $this- > tpl
-> assign ( 'searchcrits' , $searchcrits );
595 $this- > tpl
-> assign ( 'source' , index_url ( $_SERVER ));
596 $this- > tpl
-> assign ( 'version' , shaarli_version
);
597 $this- > tpl
-> assign ( 'scripturl' , index_url ( $_SERVER ));
598 $this- > tpl
-> assign ( 'pagetitle' , 'Shaarli' );
599 $this- > tpl
-> assign ( 'privateonly' ,! empty ( $_SESSION [ 'privateonly' ])); // Show only private links?
600 if (! empty ( $GLOBALS [ 'title' ])) $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'title' ]);
601 if (! empty ( $GLOBALS [ 'titleLink' ])) $this- > tpl
-> assign ( 'titleLink' , $GLOBALS [ 'titleLink' ]);
602 if (! empty ( $GLOBALS [ 'pagetitle' ])) $this- > tpl
-> assign ( 'pagetitle' , $GLOBALS [ 'pagetitle' ]);
603 $this- > tpl
-> assign ( 'shaarlititle' , empty ( $GLOBALS [ 'title' ]) ? 'Shaarli' : $GLOBALS [ 'title' ] );
607 // The following assign() method is basically the same as RainTPL (except that it's lazy)
608 public function assign ( $what , $where )
610 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
611 $this- > tpl
-> assign ( $what , $where );
614 // Render a specific page (using a template).
615 // e.g. pb.renderPage('picwall')
616 public function renderPage ( $page )
618 if ( $this- > tpl
=== false ) $this- > initialize (); // Lazy initialization
619 $this- > tpl
-> draw ( $page );
623 // ------------------------------------------------------------------------------------------
624 // Output the last N links in RSS 2.0 format.
627 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
629 // $usepermalink : If true, use permalink instead of final link.
630 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
631 // Also enabled through a config option
632 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
635 $query = $_SERVER [ "QUERY_STRING" ];
636 $cache = new CachedPage (
637 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
639 startsWith ( $query , 'do=rss' ) && ! isLoggedIn ()
641 $cached = $cache- > cachedVersion ();
642 if (! empty ( $cached )) {
647 // If cached was not found (or not usable), then read the database and build the response:
648 $LINKSDB = new LinkDB (
649 $GLOBALS [ 'config' ][ 'DATASTORE' ],
650 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
651 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
653 // Read links from database (and filter private links if user it not logged in).
655 // Optionally filter the results:
656 $linksToDisplay = array ();
657 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
658 else if (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
659 else $linksToDisplay = $LINKSDB ;
661 $nblinksToDisplay = 50 ; // Number of links to display.
662 if (! empty ( $_GET [ 'nb' ])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
664 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( $_GET [ 'nb' ] +
0 , 1 ) ;
667 $pageaddr = escape ( index_url ( $_SERVER ));
668 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">' ;
669 echo '<channel><title>' . $GLOBALS [ 'title' ]. '</title><link>' . $pageaddr . '</link>' ;
670 echo '<description>Shared links</description><language>en-en</language><copyright>' . $pageaddr . '</copyright>' . " \n\n " ;
671 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
673 echo '<!-- PubSubHubbub Discovery -->' ;
674 echo '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" xmlns="http://www.w3.org/2005/Atom" />' ;
675 echo '<link rel="self" href="' . $pageaddr . '?do=rss" xmlns="http://www.w3.org/2005/Atom" />' ;
676 echo '<!-- End Of PubSubHubbub Discovery -->' ;
679 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
680 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
682 $link = $linksToDisplay [ $keys [ $i ]];
683 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
684 $rfc822date = linkdate2rfc822 ( $link [ 'linkdate' ]);
685 $absurl = $link [ 'url' ];
686 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
687 if ( $usepermalinks === true )
688 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="true">' . $guid . '</guid><link>' . $guid . '</link>' ;
690 echo '<item><title>' . $link [ 'title' ]. '</title><guid isPermaLink="false">' . $guid . '</guid><link>' . $absurl . '</link>' ;
691 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) echo '<pubDate>' . escape ( $rfc822date ). "</pubDate> \n " ;
692 if ( $link [ 'tags' ]!= '' ) // Adding tags to each RSS entry (as mentioned in RSS specification)
694 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag ) { echo '<category domain="' . $pageaddr
. '">' . $tag
. '</category>' . " \n " ; }
697 // Add permalink in description
698 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
699 // If user wants permalinks first, put the final link in description
700 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
701 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
702 echo '<description><![CDATA[' . nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ]))). $descriptionlink . ']]></description>' . " \n </item> \n " ;
705 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
707 $cache- > cache ( ob_get_contents ());
712 // ------------------------------------------------------------------------------------------
713 // Output the last N links in ATOM format.
716 header ( 'Content-Type: application/atom+xml; charset=utf-8' );
718 // $usepermalink : If true, use permalink instead of final link.
719 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
720 $usepermalinks = isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ];
723 $query = $_SERVER [ "QUERY_STRING" ];
724 $cache = new CachedPage (
725 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
727 startsWith ( $query , 'do=atom' ) && ! isLoggedIn ()
729 $cached = $cache- > cachedVersion ();
730 if (! empty ( $cached )) {
735 // If cached was not found (or not usable), then read the database and build the response:
736 // Read links from database (and filter private links if used it not logged in).
737 $LINKSDB = new LinkDB (
738 $GLOBALS [ 'config' ][ 'DATASTORE' ],
739 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
740 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
743 // Optionally filter the results:
744 $linksToDisplay = array ();
745 if (! empty ( $_GET [ 'searchterm' ])) $linksToDisplay = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
746 else if (! empty ( $_GET [ 'searchtags' ])) $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
747 else $linksToDisplay = $LINKSDB ;
749 $nblinksToDisplay = 50 ; // Number of links to display.
750 if (! empty ( $_GET [ 'nb' ])) // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
752 $nblinksToDisplay = $_GET [ 'nb' ]== 'all' ? count ( $linksToDisplay ) : max ( $_GET [ 'nb' ] +
0 , 1 ) ;
755 $pageaddr = escape ( index_url ( $_SERVER ));
759 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // No, I can't use array_keys().
760 while ( $i < $nblinksToDisplay && $i < count ( $keys ))
762 $link = $linksToDisplay [ $keys [ $i ]];
763 $guid = $pageaddr . '?' . smallHash ( $link [ 'linkdate' ]);
764 $iso8601date = linkdate2iso8601 ( $link [ 'linkdate' ]);
765 $latestDate = max ( $latestDate , $iso8601date );
766 $absurl = $link [ 'url' ];
767 if ( startsWith ( $absurl , '?' )) $absurl = $pageaddr . $absurl ; // make permalink URL absolute
768 $entries .= '<entry><title>' . $link [ 'title' ]. '</title>' ;
769 if ( $usepermalinks === true )
770 $entries .= '<link href="' . $guid . '" /><id>' . $guid . '</id>' ;
772 $entries .= '<link href="' . $absurl . '" /><id>' . $guid . '</id>' ;
773 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $entries .= '<updated>' . escape ( $iso8601date ). '</updated>' ;
775 // Add permalink in description
776 $descriptionlink = '(<a href="' . $guid . '">Permalink</a>)' ;
777 // If user wants permalinks first, put the final link in description
778 if ( $usepermalinks === true ) $descriptionlink = '(<a href="' . $absurl . '">Link</a>)' ;
779 if ( strlen ( $link [ 'description' ])> 0 ) $descriptionlink = '<br>' . $descriptionlink ;
781 $entries .= '<content type="html"><![CDATA[' . nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ]))). $descriptionlink . "]]></content> \n " ;
782 if ( $link [ 'tags' ]!= '' ) // Adding tags to each ATOM entry (as mentioned in ATOM specification)
784 foreach ( explode ( ' ' , $link [ 'tags' ]) as $tag )
785 { $entries
.= '<category scheme="' . $pageaddr
. '" term="' . $tag
. '" />' . " \n " ; }
787 $entries .= "</entry> \n " ;
790 $feed = '<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">' ;
791 $feed .= '<title>' . $GLOBALS [ 'title' ]. '</title>' ;
792 if (! $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] || isLoggedIn ()) $feed .= '<updated>' . escape ( $latestDate ). '</updated>' ;
793 $feed .= '<link rel="self" href="' . escape ( server_url ( $_SERVER ). $_SERVER [ "REQUEST_URI" ]). '" />' ;
794 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
796 $feed .= '<!-- PubSubHubbub Discovery -->' ;
797 $feed .= '<link rel="hub" href="' . escape ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]). '" />' ;
798 $feed .= '<!-- End Of PubSubHubbub Discovery -->' ;
800 $feed .= '<author><name>' . $pageaddr . '</name><uri>' . $pageaddr . '</uri></author>' ;
801 $feed .= '<id>' . $pageaddr . '</id>' . " \n\n " ; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
803 $feed .= '</feed><!-- Cached version of ' . escape ( page_url ( $_SERVER )). ' -->' ;
806 $cache- > cache ( ob_get_contents ());
811 // ------------------------------------------------------------------------------------------
812 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
813 // Gives the last 7 days (which have links).
814 // This RSS feed cannot be filtered.
815 function showDailyRSS () {
817 $query = $_SERVER [ "QUERY_STRING" ];
818 $cache = new CachedPage (
819 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
821 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
823 $cached = $cache- > cachedVersion ();
824 if (! empty ( $cached )) {
829 // If cached was not found (or not usable), then read the database and build the response:
830 // Read links from database (and filter private links if used it not logged in).
831 $LINKSDB = new LinkDB (
832 $GLOBALS [ 'config' ][ 'DATASTORE' ],
833 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
834 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
837 /* Some Shaarlies may have very few links, so we need to look
838 back in time (rsort()) until we have enough days ($nb_of_days).
840 $linkdates = array ();
841 foreach ( $LINKSDB as $linkdate => $value ) {
842 $linkdates [] = $linkdate ;
845 $nb_of_days = 7 ; // We take 7 days.
846 $today = Date ( 'Ymd' );
849 foreach ( $linkdates as $linkdate ) {
850 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
851 if ( strcmp ( $day , $today ) < 0 ) {
852 if ( empty ( $days [ $day ])) {
853 $days [ $day ] = array ();
855 $days [ $day ][] = $linkdate ;
858 if ( count ( $days ) > $nb_of_days ) {
859 break ; // Have we collected enough days?
863 // Build the RSS feed.
864 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
865 $pageaddr = escape ( index_url ( $_SERVER ));
866 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
868 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
869 echo '<link>' . $pageaddr . '</link>' ;
870 echo '<description>Daily shared links</description>' ;
871 echo '<language>en-en</language>' ;
872 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
875 foreach ( $days as $day => $linkdates ) {
876 $daydate = linkdate2timestamp ( $day . '_000000' ); // Full text date
877 $rfc822date = linkdate2rfc822 ( $day . '_000000' );
878 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
880 // Build the HTML body of this RSS entry.
885 // We pre-format some fields for proper output.
886 foreach ( $linkdates as $linkdate ) {
887 $l = $LINKSDB [ $linkdate ];
888 $l [ 'formatedDescription' ] = nl2br ( keepMultipleSpaces ( text2clickable ( $l [ 'description' ])));
889 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
890 $l [ 'timestamp' ] = linkdate2timestamp ( $l [ 'linkdate' ]);
891 if ( startsWith ( $l [ 'url' ], '?' )) {
892 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
894 $links [ $linkdate ] = $l ;
897 // Then build the HTML for this day:
899 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
900 $tpl- > assign ( 'daydate' , $daydate );
901 $tpl- > assign ( 'absurl' , $absurl );
902 $tpl- > assign ( 'links' , $links );
903 $tpl- > assign ( 'rfc822date' , escape ( $rfc822date ));
904 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
906 echo $html . PHP_EOL
;
908 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
910 $cache- > cache ( ob_get_contents ());
918 $LINKSDB = new LinkDB (
919 $GLOBALS [ 'config' ][ 'DATASTORE' ],
920 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
921 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
924 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
925 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
927 $days = $LINKSDB- > days ();
928 $i = array_search ( $day , $days );
929 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
934 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
935 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
939 $linksToDisplay = $LINKSDB- > filterDay ( $day );
940 } catch ( Exception
$exc ) {
942 $linksToDisplay = array ();
945 // We pre-format some fields for proper output.
946 foreach ( $linksToDisplay as $key => $link )
949 $taglist = explode ( ' ' , $link [ 'tags' ]);
950 uasort ( $taglist , 'strcasecmp' );
951 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
952 $linksToDisplay [ $key ][ 'formatedDescription' ]= nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ])));
953 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
954 $linksToDisplay [ $key ][ 'timestamp' ] = linkdate2timestamp ( $link [ 'linkdate' ]);
957 /* We need to spread the articles on 3 columns.
958 I did not want to use a JavaScript lib like http://masonry.desandro.com/
959 so I manually spread entries with a simple method: I roughly evaluate the
960 height of a div according to title and description length.
962 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
963 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
964 foreach ( $linksToDisplay as $key => $link )
966 // Roughly estimate length of entry (by counting characters)
967 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
968 // Description: 836 characters gives roughly 342 pixel height.
969 // This is not perfect, but it's usually OK.
970 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
971 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
972 // Then put in column which is the less filled:
973 $smallest = min ( $fill ); // find smallest value in array.
974 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
975 array_push ( $columns [ $index ], $link ); // Put entry in this column.
976 $fill [ $index ] +
= $length ;
978 $PAGE = new pageBuilder
;
980 'linksToDisplay' => $linksToDisplay ,
981 'linkcount' => count ( $LINKSDB ),
983 'day' => linkdate2timestamp ( $day . '_000000' ),
984 'previousday' => $previousday ,
985 'nextday' => $nextday ,
987 $pluginManager = PluginManager
:: getInstance ();
988 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
990 foreach ( $data as $key => $value ) {
991 $PAGE- > assign ( $key , $value );
994 $PAGE- > renderPage ( 'daily' );
998 // Renders the linklist
999 function showLinkList ( $PAGE , $LINKSDB ) {
1000 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
1001 $PAGE- > renderPage ( 'linklist' );
1005 // ------------------------------------------------------------------------------------------
1006 // Render HTML page (according to URL parameters and user rights)
1007 function renderPage ()
1009 $LINKSDB = new LinkDB (
1010 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1011 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
1012 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
1015 $PAGE = new pageBuilder
;
1017 // Determine which page will be rendered.
1018 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
1019 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
1021 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
1022 // Then assign generated data to RainTPL.
1023 $common_hooks = array (
1028 $pluginManager = PluginManager
:: getInstance ();
1029 foreach ( $common_hooks as $name ) {
1030 $plugin_data = array ();
1031 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
1033 'target' => $targetPage ,
1034 'loggedin' => isLoggedIn ()
1037 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
1040 // -------- Display login form.
1041 if ( $targetPage == Router
:: $PAGE_LOGIN )
1043 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
1044 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
1045 $PAGE- > assign ( 'token' , $token );
1046 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
1047 $PAGE- > renderPage ( 'loginform' );
1050 // -------- User wants to logout.
1051 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
1053 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1055 header ( 'Location: ?' );
1059 // -------- Picture wall
1060 if ( $targetPage == Router
:: $PAGE_PICWALL )
1062 // Optionally filter the results:
1064 if (! empty ( $_GET [ 'searchterm' ])) $links = $LINKSDB- > filterFulltext ( $_GET [ 'searchterm' ]);
1065 elseif (! empty ( $_GET [ 'searchtags' ])) $links = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1066 else $links = $LINKSDB ;
1069 $linksToDisplay = array ();
1071 // Get only links which have a thumbnail.
1072 foreach ( $links as $link )
1074 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
1075 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
1076 if ( $thumb != '' ) // Only output links which have a thumbnail.
1078 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
1079 $linksToDisplay []= $link ; // Add to array.
1084 'linkcount' => count ( $LINKSDB ),
1085 'linksToDisplay' => $linksToDisplay ,
1087 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
1089 foreach ( $data as $key => $value ) {
1090 $PAGE- > assign ( $key , $value );
1093 $PAGE- > renderPage ( 'picwall' );
1097 // -------- Tag cloud
1098 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
1100 $tags = $LINKSDB- > allTags ();
1102 // We sort tags alphabetically, then choose a font size according to count.
1103 // First, find max value.
1104 $maxcount = 0 ; foreach ( $tags as $key => $value ) $maxcount = max ( $maxcount , $value );
1107 foreach ( $tags as $key => $value )
1108 // Tag font size scaling: default 15 and 30 logarithm bases affect scaling, 22 and 6 are arbitrary font sizes for max and min sizes.
1110 $tagList [ $key ] = array ( 'count' => $value , 'size' => log ( $value , 15 ) / log ( $maxcount , 30 ) * ( 22 - 6 ) +
6 );
1114 'linkcount' => count ( $LINKSDB ),
1117 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
1119 foreach ( $data as $key => $value ) {
1120 $PAGE- > assign ( $key , $value );
1123 $PAGE- > renderPage ( 'tagcloud' );
1127 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
1128 if ( isset ( $_GET [ 'addtag' ]))
1130 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
1131 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
1132 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1134 // Prevent redirection loop
1135 if ( isset ( $params [ 'addtag' ])) {
1136 unset ( $params [ 'addtag' ]);
1139 // Check if this tag is already in the search query and ignore it if it is.
1140 // Each tag is always separated by a space
1141 if ( isset ( $params [ 'searchtags' ])) {
1142 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
1144 $current_tags = array ();
1147 foreach ( $current_tags as $value ) {
1148 if ( $value === $_GET [ 'addtag' ]) {
1153 // Append the tag if necessary
1154 if ( empty ( $params [ 'searchtags' ])) {
1155 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1158 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1161 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1162 header ( 'Location: ?' . http_build_query ( $params ));
1166 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1167 if ( isset ( $_GET [ 'removetag' ])) {
1168 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1169 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1170 header ( 'Location: ?' );
1174 // In case browser does not send HTTP_REFERER
1175 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1177 // Prevent redirection loop
1178 if ( isset ( $params [ 'removetag' ])) {
1179 unset ( $params [ 'removetag' ]);
1182 if ( isset ( $params [ 'searchtags' ])) {
1183 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1184 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ])); // Remove value from array $tags.
1185 if ( count ( $tags )== 0 ) {
1186 unset ( $params [ 'searchtags' ]);
1188 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1190 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1192 header ( 'Location: ?' . http_build_query ( $params ));
1196 // -------- User wants to change the number of links per page (linksperpage=...)
1197 if ( isset ( $_GET [ 'linksperpage' ])) {
1198 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1199 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1202 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1206 // -------- User wants to see only private links (toggle)
1207 if ( isset ( $_GET [ 'privateonly' ])) {
1208 if ( empty ( $_SESSION [ 'privateonly' ])) {
1209 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1211 unset ( $_SESSION [ 'privateonly' ]); // See all links
1214 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1218 // -------- Handle other actions allowed for non-logged in users:
1221 // User tries to post new link but is not logged in:
1222 // Show login screen, then redirect to ?post=...
1223 if ( isset ( $_GET [ 'post' ]))
1225 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.
1229 // Same case as above except that user tried to access ?do=addlink without being logged in
1230 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1231 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1232 header ( 'Location: ?do=login&post=' );
1235 showLinkList ( $PAGE , $LINKSDB );
1236 if ( isset ( $_GET [ 'edit_link' ])) {
1237 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1241 exit ; // Never remove this one! All operations below are reserved for logged in user.
1244 // -------- All other functions are reserved for the registered user:
1246 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1247 if ( $targetPage == Router
:: $PAGE_TOOLS )
1250 'linkcount' => count ( $LINKSDB ),
1251 'pageabsaddr' => index_url ( $_SERVER ),
1253 $pluginManager- > executeHooks ( 'render_tools' , $data );
1255 foreach ( $data as $key => $value ) {
1256 $PAGE- > assign ( $key , $value );
1259 $PAGE- > renderPage ( 'tools' );
1263 // -------- User wants to change his/her password.
1264 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1266 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1267 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1269 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1271 // Make sure old password is correct.
1272 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1273 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1274 // Save new password
1275 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1276 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1278 writeConfig ( $GLOBALS , isLoggedIn ());
1280 catch ( Exception
$e ) {
1282 'ERROR while writing config file after changing password.' . PHP_EOL
.
1286 // TODO: do not handle exceptions/errors in JS.
1287 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1290 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1293 else // show the change password form.
1295 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1296 $PAGE- > assign ( 'token' , getToken ());
1297 $PAGE- > renderPage ( 'changepassword' );
1302 // -------- User wants to change configuration
1303 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1305 if (! empty ( $_POST [ 'title' ]) )
1307 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1309 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ]))
1310 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ]))
1311 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1312 $GLOBALS [ 'timezone' ] = $tz ;
1313 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1314 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1315 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1316 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1317 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1318 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1319 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1320 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1322 writeConfig ( $GLOBALS , isLoggedIn ());
1324 catch ( Exception
$e ) {
1326 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1330 // TODO: do not handle exceptions/errors in JS.
1331 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1334 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1337 else // Show the configuration form.
1339 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1340 $PAGE- > assign ( 'token' , getToken ());
1341 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1342 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1343 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1344 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1345 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1346 $PAGE- > renderPage ( 'configure' );
1351 // -------- User wants to rename a tag or delete it
1352 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1354 if ( empty ( $_POST [ 'fromtag' ]))
1356 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1357 $PAGE- > assign ( 'token' , getToken ());
1358 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1359 $PAGE- > renderPage ( 'changetag' );
1362 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1365 if (! empty ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ]))
1367 $needle = trim ( $_POST [ 'fromtag' ]);
1368 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // True for case-sensitive tag search.
1369 foreach ( $linksToAlter as $key => $value )
1371 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1372 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1373 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1374 $LINKSDB [ $key ]= $value ;
1376 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1377 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1382 if (! empty ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ]))
1384 $needle = trim ( $_POST [ 'fromtag' ]);
1385 $linksToAlter = $LINKSDB- > filterTags ( $needle , true ); // true for case-sensitive tag search.
1386 foreach ( $linksToAlter as $key => $value )
1388 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1389 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1390 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1391 $LINKSDB [ $key ]= $value ;
1393 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1394 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1399 // -------- User wants to add a link without using the bookmarklet: Show form.
1400 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1402 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1403 $PAGE- > renderPage ( 'addlink' );
1407 // -------- User clicked the "Save" button when editing a link: Save link to database.
1408 if ( isset ( $_POST [ 'save_edit' ]))
1410 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1411 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ])); // Remove multiple spaces.
1412 $tags = implode ( ' ' , array_unique ( explode ( ' ' , $tags ))); // Remove duplicates.
1413 $linkdate = $_POST [ 'lf_linkdate' ];
1414 $url = trim ( $_POST [ 'lf_url' ]);
1415 if (! startsWith ( $url , 'http:' ) && ! startsWith ( $url , 'https:' ) && ! startsWith ( $url , 'ftp:' ) && ! startsWith ( $url , 'magnet:' ) && ! startsWith ( $url , '?' ) && ! startsWith ( $url , 'javascript:' ))
1416 $url = 'http://' . $url ;
1417 $link = array ( 'title' => trim ( $_POST [ 'lf_title' ]), 'url' => $url , 'description' => trim ( $_POST [ 'lf_description' ]), 'private' =>( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1418 'linkdate' => $linkdate , 'tags' => str_replace ( ',' , ' ' , $tags ));
1419 if ( $link [ 'title' ]== '' ) $link [ 'title' ]= $link [ 'url' ]; // If title is empty, use the URL as title.
1421 $pluginManager- > executeHooks ( 'save_link' , $link );
1423 $LINKSDB [ $linkdate ] = $link ;
1424 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1427 // If we are called from the bookmarklet, we must close the popup:
1428 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1429 $returnurl = ( ! empty ( $_POST [ 'returnurl' ]) ? escape ( $_POST [ 'returnurl' ]) : '?' );
1430 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1431 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1432 header ( 'Location: ' . $location ); // After saving the link, redirect to the page the user was on.
1436 // -------- User clicked the "Cancel" button when editing a link.
1437 if ( isset ( $_POST [ 'cancel_edit' ]))
1439 // If we are called from the bookmarklet, we must close the popup:
1440 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1441 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1442 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1443 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1444 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1448 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1449 if ( isset ( $_POST [ 'delete_link' ]))
1451 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1452 // We do not need to ask for confirmation:
1453 // - confirmation is handled by JavaScript
1454 // - we are protected from XSRF by the token.
1455 $linkdate = $_POST [ 'lf_linkdate' ];
1457 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1459 unset ( $LINKSDB [ $linkdate ]);
1460 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1462 // If we are called from the bookmarklet, we must close the popup:
1463 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1464 // Pick where we're going to redirect
1465 // =============================================================
1466 // Basically, we can't redirect to where we were previously if it was a permalink
1467 // or an edit_link, because it would 404.
1469 // - / : nothing in $_GET, redirect to self
1470 // - /?page : redirect to self
1471 // - /?searchterm : redirect to self (there might be other links)
1472 // - /?searchtags : redirect to self
1473 // - /permalink : redirect to / (the link does not exist anymore)
1474 // - /?edit_link : redirect to / (the link does not exist anymore)
1475 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1476 // redirect is not satisfied, and only then redirect to /
1479 if ( count ( $_GET ) == 0
1480 || isset ( $_GET [ 'page' ])
1481 || isset ( $_GET [ 'searchterm' ])
1482 || isset ( $_GET [ 'searchtags' ])
1484 if ( isset ( $_POST [ 'returnurl' ])) {
1485 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1487 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1491 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1495 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1496 if ( isset ( $_GET [ 'edit_link' ]))
1498 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1499 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1501 'linkcount' => count ( $LINKSDB ),
1503 'link_is_new' => false ,
1504 'token' => getToken (),
1505 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1506 'tags' => $LINKSDB- > allTags (),
1508 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1510 foreach ( $data as $key => $value ) {
1511 $PAGE- > assign ( $key , $value );
1514 $PAGE- > renderPage ( 'editlink' );
1518 // -------- User want to post a new link: Display link edit form.
1519 if ( isset ( $_GET [ 'post' ])) {
1520 $url = cleanup_url ( $_GET [ 'post' ]);
1522 $link_is_new = false ;
1523 // Check if URL is not already in database (in this case, we will edit the existing link)
1524 $link = $LINKSDB- > getLinkFromUrl ( $url );
1527 $link_is_new = true ;
1528 $linkdate = strval ( date ( 'Ymd_His' ));
1529 // Get title if it was provided in URL (by the bookmarklet).
1530 $title = ( empty ( $_GET [ 'title' ]) ? '' : $_GET [ 'title' ] );
1531 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1532 $description = ( empty ( $_GET [ 'description' ]) ? '' : $_GET [ 'description' ]);
1533 $tags = ( empty ( $_GET [ 'tags' ]) ? '' : $_GET [ 'tags' ] );
1534 $private = (! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 );
1535 // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
1536 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1537 // Short timeout to keep the application responsive
1538 list ( $headers , $data ) = get_http_url ( $url , 4 );
1539 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
1540 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1541 // Look for charset in html header.
1542 preg_match ( '#<meta .*charset=.*>#Usi' , $data , $meta );
1544 // If found, extract encoding.
1545 if (! empty ( $meta [ 0 ])) {
1546 // Get encoding specified in header.
1547 preg_match ( '#charset="?(.*)"#si' , $meta [ 0 ], $enc );
1548 // If charset not found, use utf-8.
1549 $html_charset = (! empty ( $enc [ 1 ])) ? strtolower ( $enc [ 1 ]) : 'utf-8' ;
1552 $html_charset = 'utf-8' ;
1556 $title = html_extract_title ( $data );
1557 if (! empty ( $title )) {
1558 // Re-encode title in utf-8 if necessary.
1559 $title = ( $html_charset == 'iso-8859-1' ) ? utf8_encode ( $title ) : $title ;
1564 $url = '?' . smallHash ( $linkdate );
1568 'linkdate' => $linkdate ,
1571 'description' => $description ,
1573 'private' => $private
1578 'linkcount' => count ( $LINKSDB ),
1580 'link_is_new' => $link_is_new ,
1581 'token' => getToken (), // XSRF protection.
1582 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1583 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1584 'tags' => $LINKSDB- > allTags (),
1586 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1588 foreach ( $data as $key => $value ) {
1589 $PAGE- > assign ( $key , $value );
1592 $PAGE- > renderPage ( 'editlink' );
1596 // -------- Export as Netscape Bookmarks HTML file.
1597 if ( $targetPage == Router
:: $PAGE_EXPORT )
1599 if ( empty ( $_GET [ 'what' ]))
1601 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1602 $PAGE- > renderPage ( 'export' );
1605 $exportWhat = $_GET [ 'what' ];
1606 if (! array_intersect ( array ( 'all' , 'public' , 'private' ), array ( $exportWhat ))) die ( 'What are you trying to export???' );
1608 header ( 'Content-Type: text/html; charset=utf-8' );
1609 header ( 'Content-disposition: attachment; filename=bookmarks_' . $exportWhat . '_' . strval ( date ( 'Ymd_His' )). '.html' );
1610 $currentdate = date ( 'Y/m/d H:i:s' );
1612 <!DOCTYPE NETSCAPE-Bookmark-file-1>
1613 <!-- This is an automatically generated file.
1614 It will be read and overwritten.
1616 <!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
1617 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1618 <TITLE>Bookmarks</TITLE>
1621 foreach ( $LINKSDB as $link )
1623 if ( $exportWhat == 'all' ||
1624 ( $exportWhat == 'private' && $link [ 'private' ]!= 0 ) ||
1625 ( $exportWhat == 'public' && $link [ 'private' ]== 0 ))
1627 echo '<DT><A HREF="' . $link [ 'url' ]. '" ADD_DATE="' . linkdate2timestamp ( $link [ 'linkdate' ]). '" PRIVATE="' . $link [ 'private' ]. '"' ;
1628 if ( $link [ 'tags' ]!= '' ) echo ' TAGS="' . str_replace ( ' ' , ',' , $link [ 'tags' ]). '"' ;
1629 echo '>' . $link [ 'title' ]. "</A> \n " ;
1630 if ( $link [ 'description' ]!= '' ) echo '<DD>' . $link [ 'description' ]. " \n " ;
1636 // -------- User is uploading a file for import
1637 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1639 // If file is too big, some form field may be missing.
1640 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1642 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1643 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>' ;
1646 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1651 // -------- Show upload/import dialog:
1652 if ( $targetPage == Router
:: $PAGE_IMPORT )
1654 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
1655 $PAGE- > assign ( 'token' , getToken ());
1656 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1657 $PAGE- > renderPage ( 'import' );
1661 // -------- Otherwise, simply display search form and links:
1662 showLinkList ( $PAGE , $LINKSDB );
1666 // -----------------------------------------------------------------------------------------------
1667 // Process the import file form.
1668 function importFile ()
1670 if (!( isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ])) { die ( 'Not allowed.' ); }
1671 $LINKSDB = new LinkDB (
1672 $GLOBALS [ 'config' ][ 'DATASTORE' ],
1673 isLoggedIn () || $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ],
1674 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ]
1676 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1677 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1678 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1679 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1680 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1685 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1687 // Then import the bookmarks.
1688 if ( $type == 'netscape' )
1690 // This is a standard Netscape-style bookmark file.
1691 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1692 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1694 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1695 $d = explode ( '<DD>' , $html );
1696 if ( startswith ( $d [ 0 ], '<A ' ))
1698 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1699 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1700 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1701 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1703 foreach ( $matches as $m )
1705 $attr = $m [ 1 ]; $value = $m [ 2 ];
1706 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1707 elseif ( $attr == 'ADD_DATE' )
1709 $raw_add_date = intval ( $value );
1710 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1712 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1713 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1715 if ( $link [ 'url' ]!= '' )
1717 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1718 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1720 { // Link not in database, let's import it...
1721 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1723 // Make sure date/time is not already used by another link.
1724 // (Some bookmark files have several different links with the same ADD_DATE)
1725 // We increment date by 1 second until we find a date which is not used in DB.
1726 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1727 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1728 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1729 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1732 else // Link already present in database.
1735 { // If overwrite is required, we import link data, except date/time.
1736 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1737 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1745 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1747 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1751 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1755 // -----------------------------------------------------------------------------------------------
1756 // Template for the list of links (<div id="linklist">)
1757 // This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1758 function buildLinkList ( $PAGE , $LINKSDB )
1760 // ---- Filter link database according to parameters
1761 $linksToDisplay = array ();
1764 if ( isset ( $_GET [ 'searchterm' ])) // Fulltext search
1766 $linksToDisplay = $LINKSDB- > filterFulltext ( trim ( $_GET [ 'searchterm' ]));
1767 $search_crits = escape ( trim ( $_GET [ 'searchterm' ]));
1768 $search_type = 'fulltext' ;
1770 elseif ( isset ( $_GET [ 'searchtags' ])) // Search by tag
1772 $linksToDisplay = $LINKSDB- > filterTags ( trim ( $_GET [ 'searchtags' ]));
1773 $search_crits = explode ( ' ' , escape ( trim ( $_GET [ 'searchtags' ])));
1774 $search_type = 'tags' ;
1776 elseif ( isset ( $_SERVER [ 'QUERY_STRING' ]) && preg_match ( '/[a-zA-Z0-9-_@] {6} (&.+?)?/' , $_SERVER [ 'QUERY_STRING' ])) // Detect smallHashes in URL
1778 $linksToDisplay = $LINKSDB- > filterSmallHash ( substr ( trim ( $_SERVER [ "QUERY_STRING" ], '/' ), 0 , 6 ));
1779 if ( count ( $linksToDisplay )== 0 )
1781 header ( $_SERVER [ "SERVER_PROTOCOL" ]. " 404 Not Found" );
1782 echo '<h1>404 Not found.</h1>Oh crap. The link you are trying to reach does not exist or has been deleted.' ;
1783 echo '<br>Would you mind <a href="?">clicking here</a>?' ;
1786 $search_type = 'permalink' ;
1789 $linksToDisplay = $LINKSDB ; // Otherwise, display without filtering.
1792 // Option: Show only private links
1793 if (! empty ( $_SESSION [ 'privateonly' ]))
1796 foreach ( $linksToDisplay as $linkdate => $link )
1798 if ( $link [ 'private' ]!= 0 ) $tmp [ $linkdate ]= $link ;
1800 $linksToDisplay = $tmp ;
1803 // ---- Handle paging.
1804 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess???
1805 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1806 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1808 $keys = array (); foreach ( $linksToDisplay as $key => $value ) { $keys
[]= $key
; } // Stupid and ugly. Thanks PHP.
1810 // If there is only a single link, we change on-the-fly the title of the page.
1811 if ( count ( $linksToDisplay )== 1 ) $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1813 // Select articles according to paging.
1814 $pagecount = ceil ( count ( $keys )/ $_SESSION [ 'LINKS_PER_PAGE' ]);
1815 $pagecount = ( $pagecount == 0 ? 1 : $pagecount );
1816 $page =( empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]));
1817 $page = ( $page < 1 ? 1 : $page );
1818 $page = ( $page > $pagecount ? $pagecount : $page );
1819 $i = ( $page-1 )* $_SESSION [ 'LINKS_PER_PAGE' ]; // Start index.
1820 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1821 $linkDisp = array (); // Links to display
1822 while ( $i < $end && $i < count ( $keys ))
1824 $link = $linksToDisplay [ $keys [ $i ]];
1825 $link [ 'description' ]= nl2br ( keepMultipleSpaces ( text2clickable ( $link [ 'description' ])));
1826 $title = $link [ 'title' ];
1827 $classLi = $i %
2 != 0 ? '' : 'publicLinkHightLight' ;
1828 $link [ 'class' ] = ( $link [ 'private' ]== 0 ? $classLi : 'private' );
1829 $link [ 'timestamp' ]= linkdate2timestamp ( $link [ 'linkdate' ]);
1830 $taglist = explode ( ' ' , $link [ 'tags' ]);
1831 uasort ( $taglist , 'strcasecmp' );
1832 $link [ 'taglist' ]= $taglist ;
1833 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1834 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.
1835 strlen ( $link [ "url" ]) === 7 ) {
1836 $link [ "url" ] = index_url ( $_SERVER ) . $link [ "url" ];
1839 $linkDisp [ $keys [ $i ]] = $link ;
1843 // Compute paging navigation
1844 $searchterm = ( empty ( $_GET [ 'searchterm' ]) ? '' : '&searchterm=' . $_GET [ 'searchterm' ] );
1845 $searchtags = ( empty ( $_GET [ 'searchtags' ]) ? '' : '&searchtags=' . $_GET [ 'searchtags' ] );
1847 $previous_page_url = '' ; if ( $i != count ( $keys )) $previous_page_url = '?page=' .( $page +
1 ). $searchterm . $searchtags ;
1848 $next_page_url = '' ; if ( $page > 1 ) $next_page_url = '?page=' .( $page-1 ). $searchterm . $searchtags ;
1850 $token = '' ; if ( isLoggedIn ()) $token = getToken ();
1852 // Fill all template fields.
1854 'linkcount' => count ( $LINKSDB ),
1855 'previous_page_url' => $previous_page_url ,
1856 'next_page_url' => $next_page_url ,
1857 'page_current' => $page ,
1858 'page_max' => $pagecount ,
1859 'result_count' => count ( $linksToDisplay ),
1860 'search_type' => $search_type ,
1861 'search_crits' => $search_crits ,
1862 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
1864 'links' => $linkDisp ,
1865 'tags' => $LINKSDB- > allTags (),
1868 $pluginManager = PluginManager
:: getInstance ();
1869 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1871 foreach ( $data as $key => $value ) {
1872 $PAGE- > assign ( $key , $value );
1878 // Compute the thumbnail for a link.
1880 // With a link to the original URL.
1881 // Understands various services (youtube.com...)
1882 // Input: $url = URL for which the thumbnail must be found.
1883 // $href = if provided, this URL will be followed instead of $url
1884 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1885 // Some of them may be missing.
1886 // Return an empty array if no thumbnail available.
1887 function computeThumbnail ( $url , $href = false )
1889 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
1890 if ( $href == false ) $href = $url ;
1892 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1893 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1894 // ^^^^^^^^^^^ ^^^^^^^^^^^
1895 $domain = parse_url ( $url , PHP_URL_HOST
);
1896 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1898 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1899 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1900 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1902 if ( $domain == 'youtu.be' ) // Youtube short links
1904 $path = parse_url ( $url , PHP_URL_PATH
);
1905 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1906 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1908 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1910 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1911 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1912 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1915 if ( $domain == 'imgur.com' )
1917 $path = parse_url ( $url , PHP_URL_PATH
);
1918 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1919 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1920 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1921 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1922 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1924 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1925 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1927 if ( $domain == 'i.imgur.com' )
1929 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1930 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1931 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1933 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1935 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1937 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1938 return array ( 'src' => $thumburl ,
1939 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1942 if ( endsWith ( $domain , '.imageshack.us' ))
1944 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1945 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1947 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1948 return array ( 'src' => $thumburl ,
1949 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1953 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1954 // So we deport the thumbnail generation in order not to slow down page generation
1955 // (and we also cache the thumbnail)
1957 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1959 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1960 || $domain == 'vimeo.com'
1961 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1962 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1965 if ( $domain == 'vimeo.com' )
1966 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1967 $path = parse_url ( $url , PHP_URL_PATH
);
1968 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1970 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1971 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1972 $path = parse_url ( $url , PHP_URL_PATH
);
1973 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1975 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1976 { // Make sure this TED URL points to a video (/talks/...)
1977 $path = parse_url ( $url , PHP_URL_PATH
);
1978 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1980 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1981 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1982 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1985 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1986 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1987 // But using the extension will do.
1988 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1989 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1991 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1992 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1993 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1995 return array (); // No thumbnail.
2000 // Returns the HTML code to display a thumbnail for a link
2001 // with a link to the original URL.
2002 // Understands various services (youtube.com...)
2003 // Input: $url = URL for which the thumbnail must be found.
2004 // $href = if provided, this URL will be followed instead of $url
2005 // Returns '' if no thumbnail available.
2006 function thumbnail ( $url , $href = false )
2008 $t = computeThumbnail ( $url , $href );
2009 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2011 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
2012 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2013 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2014 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2015 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2020 // Returns the HTML code to display a thumbnail for a link
2021 // for the picture wall (using lazy image loading)
2022 // Understands various services (youtube.com...)
2023 // Input: $url = URL for which the thumbnail must be found.
2024 // $href = if provided, this URL will be followed instead of $url
2025 // Returns '' if no thumbnail available.
2026 function lazyThumbnail ( $url , $href = false )
2028 $t = computeThumbnail ( $url , $href );
2029 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
2031 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
2034 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
2036 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2037 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2038 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2039 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2042 // No-JavaScript fallback.
2043 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
2044 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
2045 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
2046 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
2047 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
2048 $html .= '></noscript></a>' ;
2054 // -----------------------------------------------------------------------------------------------
2056 // This function should NEVER be called if the file data/config.php exists.
2059 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
2060 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
2063 // This part makes sure sessions works correctly.
2064 // (Because on some hosts, session.save_path may not be set correctly,
2065 // or we may not have write access to it.)
2066 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
2067 { // Step 2: Check if data in session is correct.
2068 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
2069 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
2070 echo 'It currently points to ' . session_save_path (). '<br>' ;
2071 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>' ;
2072 echo '<br><a href="?">Click to try again.</a></pre>' ;
2075 if (! isset ( $_SESSION [ 'session_tested' ]))
2076 { // Step 1 : Try to store data in session and reload page.
2077 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
2078 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
2080 if ( isset ( $_GET [ 'test_session' ]))
2081 { // Step 3: Sessions are OK. Remove test parameter from URL.
2082 header ( 'Location: ' . index_url ( $_SERVER ));
2086 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
2089 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])) {
2090 if ( isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])) {
2091 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2094 $GLOBALS [ 'timezone' ] = $tz ;
2095 // Everything is ok, let's create config file.
2096 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2097 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2098 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2099 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2100 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2102 writeConfig ( $GLOBALS , isLoggedIn ());
2104 catch ( Exception
$e ) {
2106 'ERROR while writing config file after installation.' . PHP_EOL
.
2110 // TODO: do not handle exceptions/errors in JS.
2111 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2114 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2118 // Display config form:
2119 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2120 $timezone_html = '' ;
2121 if ( $timezone_form != '' ) {
2122 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2125 $PAGE = new pageBuilder
;
2126 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2127 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2128 $PAGE- > renderPage ( 'install' );
2132 if (! function_exists ( 'json_encode' )) {
2133 function json_encode ( $data ) {
2134 switch ( $type = gettype ( $data )) {
2138 return ( $data ? 'true' : 'false' );
2144 return '"' . addslashes ( $data ) . '"' ;
2146 $data = get_object_vars ( $data );
2148 $output_index_count = 0 ;
2149 $output_indexed = array ();
2150 $output_associative = array ();
2151 foreach ( $data as $key => $value ) {
2152 $output_indexed [] = json_encode ( $value );
2153 $output_associative [] = json_encode ( $key ) . ':' . json_encode ( $value );
2154 if ( $output_index_count !== NULL && $output_index_count ++
!== $key ) {
2155 $output_index_count = NULL ;
2158 if ( $output_index_count !== NULL ) {
2159 return '[' . implode ( ',' , $output_indexed ) . ']' ;
2161 return ' {' . implode(',', $output_associative) . '} ' ;
2164 return '' ; // Not supported
2171 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2172 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2173 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2174 This function is called by passing the URL:
2175 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2176 [URL] is the URL of the link (e.g. a flickr page)
2177 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2178 The function below will fetch the image from the webservice and store it in the cache.
2180 function genThumbnail ()
2182 // Make sure the parameters in the URL were generated by us.
2183 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2184 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2186 // Let's see if we don't already have the image for this URL in the cache.
2187 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2188 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2189 { // We have the thumbnail, just serve it:
2190 header ( 'Content-Type: image/jpeg' );
2191 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2194 // We may also serve a blank image (if service did not respond)
2195 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2196 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2198 header ( 'Content-Type: image/gif' );
2199 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2203 // Otherwise, generate the thumbnail.
2204 $url = $_GET [ 'url' ];
2205 $domain = parse_url ( $url , PHP_URL_HOST
);
2207 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2209 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2210 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2212 // Is this a link to an image, or to a flickr page ?
2214 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2215 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2216 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2217 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2219 else // This is a flickr page (html)
2221 // Get the flickr html page.
2222 list ( $headers , $data ) = get_http_url ( $url , 20 );
2223 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2225 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2226 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $data , $matches );
2227 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2229 // In albums (and some other pages), the link rel="image_src" is not provided,
2230 // but flickr provides:
2231 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2234 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $data , $matches );
2235 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2241 { // Let's download the image.
2242 // Image is 240x120, so 10 seconds to download should be enough.
2243 list ( $headers , $data ) = get_http_url ( $imageurl , 10 );
2244 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2245 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
2246 header ( 'Content-Type: image/jpeg' );
2253 elseif ( $domain == 'vimeo.com' )
2255 // This is more complex: we have to perform a HTTP request, then parse the result.
2256 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2257 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2258 list ( $headers , $data ) = get_http_url ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2259 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2260 $t = unserialize ( $data );
2261 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2262 // Then we download the image and serve it to our client.
2263 list ( $headers , $data ) = get_http_url ( $imageurl , 10 );
2264 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2265 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $data ); // Save image to cache.
2266 header ( 'Content-Type: image/jpeg' );
2273 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2275 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2276 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2277 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2278 list ( $headers , $data ) = get_http_url ( $url , 5 );
2279 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2280 // Extract the link to the thumbnail
2281 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $data , $matches );
2282 if (! empty ( $matches [ 1 ]))
2283 { // Let's download the image.
2284 $imageurl = $matches [ 1 ];
2285 // No control on image size, so wait long enough
2286 list ( $headers , $data ) = get_http_url ( $imageurl , 20 );
2287 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2288 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2289 file_put_contents ( $filepath , $data ); // Save image to cache.
2290 if ( resizeImage ( $filepath ))
2292 header ( 'Content-Type: image/jpeg' );
2293 echo file_get_contents ( $filepath );
2301 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2303 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2304 // http://xkcd.com/327/
2305 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2306 list ( $headers , $data ) = get_http_url ( $url , 5 );
2307 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2308 // Extract the link to the thumbnail
2309 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $data , $matches );
2310 if (! empty ( $matches [ 1 ]))
2311 { // Let's download the image.
2312 $imageurl = $matches [ 1 ];
2313 // No control on image size, so wait long enough
2314 list ( $headers , $data ) = get_http_url ( $imageurl , 20 );
2315 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2316 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2317 file_put_contents ( $filepath , $data ); // Save image to cache.
2318 if ( resizeImage ( $filepath ))
2320 header ( 'Content-Type: image/jpeg' );
2321 echo file_get_contents ( $filepath );
2331 // For all other domains, we try to download the image and make a thumbnail.
2332 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2333 list ( $headers , $data ) = get_http_url ( $url , 30 );
2334 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2335 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2336 file_put_contents ( $filepath , $data ); // Save image to cache.
2337 if ( resizeImage ( $filepath ))
2339 header ( 'Content-Type: image/jpeg' );
2340 echo file_get_contents ( $filepath );
2347 // Otherwise, return an empty image (8x8 transparent gif)
2348 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2349 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2350 header ( 'Content-Type: image/gif' );
2354 // Make a thumbnail of the image (to width: 120 pixels)
2355 // Returns true if success, false otherwise.
2356 function resizeImage ( $filepath )
2358 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2360 // Trick: some stupid people rename GIF as JPEG... or else.
2361 // So we really try to open each image type whatever the extension is.
2362 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2364 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2365 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2366 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2367 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2370 $ystart = 0 ; $yheight = $h ;
2371 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2372 $nw = 120 ; // Desired width
2373 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2375 $im2 = imagecreatetruecolor ( $nw , $nh );
2376 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2377 imageinterlace ( $im2 , true ); // For progressive JPEG.
2378 $tempname = $filepath . '_TEMP.jpg' ;
2379 imagejpeg ( $im2 , $tempname , 90 );
2383 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2388 mergeDeprecatedConfig ( $GLOBALS , isLoggedIn ());
2389 } catch ( Exception
$e ) {
2391 'ERROR while merging deprecated options.php file.' . PHP_EOL
.
2396 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2397 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=rss' )) { showRSS (); exit ; }
2398 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=atom' )) { showATOM (); exit ; }
2399 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2400 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=daily' )) { showDaily (); exit ; }
2401 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];