]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.6.5 - Shaare your links...
5 * The personal, minimalist, super-fast, no-database Delicious clone.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
25 /* -----------------------------------------------------------------------------
26 * Hardcoded parameters
27 * You should not touch any code below (or at your own risks!)
28 * (These parameters can be overwritten by editing the file /data/config.php)
29 * -----------------------------------------------------------------------------
33 * Shaarli directories & configuration files
36 $GLOBALS [ 'config' ][ 'DATADIR' ] = 'data' ;
38 // Main configuration file
39 $GLOBALS [ 'config' ][ 'CONFIG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/config.php' ;
42 $GLOBALS [ 'config' ][ 'DATASTORE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/datastore.php' ;
45 $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/ipbans.php' ;
47 // Processed updates file.
48 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/updates.txt' ;
51 $GLOBALS [ 'config' ][ 'LOG_FILE' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/log.txt' ;
53 // For updates check of Shaarli
54 $GLOBALS [ 'config' ][ 'UPDATECHECK_FILENAME' ] = $GLOBALS [ 'config' ][ 'DATADIR' ]. '/lastupdatecheck.txt' ;
56 // Set ENABLE_UPDATECHECK to disabled by default.
57 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = false ;
59 // RainTPL cache directory (keep the trailing slash!)
60 $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ] = 'tmp/' ;
61 // Raintpl template directory (keep the trailing slash!)
62 $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ] = 'tpl/' ;
64 // Thumbnail cache directory
65 $GLOBALS [ 'config' ][ 'CACHEDIR' ] = 'cache' ;
67 // Atom & RSS feed cache directory
68 $GLOBALS [ 'config' ][ 'PAGECACHE' ] = 'pagecache' ;
71 * Global configuration
73 // Ban IP after this many failures
74 $GLOBALS [ 'config' ][ 'BAN_AFTER' ] = 4 ;
75 // Ban duration for IP address after login failures (in seconds)
76 $GLOBALS [ 'config' ][ 'BAN_DURATION' ] = 1800 ;
79 // Enable RSS permalinks by default.
80 // This corresponds to the default behavior of shaarli before this was added as an option.
81 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ] = true ;
82 // If true, an extra "ATOM feed" button will be displayed in the toolbar
83 $GLOBALS [ 'config' ][ 'SHOW_ATOM' ] = false ;
85 // Link display options
86 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = false ;
87 $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] = false ;
88 $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ] = 20 ;
90 // Open Shaarli (true): anyone can add/edit/delete links without having to login
91 $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ] = false ;
94 // Display thumbnails in links
95 $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ] = true ;
96 // Store thumbnails in a local cache
97 $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ] = true ;
99 // Update check frequency for Shaarli. 86400 seconds=24 hours
100 $GLOBALS [ 'config' ][ 'UPDATECHECK_BRANCH' ] = 'stable' ;
101 $GLOBALS [ 'config' ][ 'UPDATECHECK_INTERVAL' ] = 86400 ;
103 $GLOBALS [ 'config' ][ 'REDIRECTOR_URLENCODE' ] = true ;
106 * Plugin configuration
108 * Warning: order matters!
110 * These settings may be be overriden in:
112 * - each plugin's configuration file
114 //$GLOBALS['config']['ENABLED_PLUGINS'] = array(
115 // 'qrcode', 'archiveorg', 'readityourself', 'demo_plugin', 'playvideos',
116 // 'wallabag', 'markdown', 'addlink_toolbar',
118 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = array ( 'qrcode' );
120 // Initialize plugin parameters array.
121 $GLOBALS [ 'plugins' ] = array ();
123 // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
124 $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ] = '' ;
129 define ( 'shaarli_version' , '0.6.5' );
131 // http://server.com/x/shaarli --> /shaarli/
132 define ( 'WEB_PATH' , substr ( $_SERVER [ "REQUEST_URI" ], 0 , 1 +
strrpos ( $_SERVER [ "REQUEST_URI" ], '/' , 0 )));
134 // High execution time in case of problematic imports/exports.
135 ini_set ( 'max_input_time' , '60' );
137 // Try to set max upload file size and read
138 ini_set ( 'memory_limit' , '128M' );
139 ini_set ( 'post_max_size' , '16M' );
140 ini_set ( 'upload_max_filesize' , '16M' );
142 // See all error except warnings
143 error_reporting ( E_ALL^E_WARNING
);
144 // See all errors (for debugging only)
145 //error_reporting(-1);
150 if ( is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
151 require_once $GLOBALS [ 'config' ][ 'CONFIG_FILE' ];
155 require_once 'application/ApplicationUtils.php' ;
156 require_once 'application/Cache.php' ;
157 require_once 'application/CachedPage.php' ;
158 require_once 'application/FeedBuilder.php' ;
159 require_once 'application/FileUtils.php' ;
160 require_once 'application/HttpUtils.php' ;
161 require_once 'application/LinkDB.php' ;
162 require_once 'application/LinkFilter.php' ;
163 require_once 'application/LinkUtils.php' ;
164 require_once 'application/NetscapeBookmarkUtils.php' ;
165 require_once 'application/PageBuilder.php' ;
166 require_once 'application/TimeZone.php' ;
167 require_once 'application/Url.php' ;
168 require_once 'application/Utils.php' ;
169 require_once 'application/Config.php' ;
170 require_once 'application/PluginManager.php' ;
171 require_once 'application/Router.php' ;
172 require_once 'application/Updater.php' ;
174 // Ensure the PHP version is supported
176 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
177 } catch ( Exception
$exc ) {
178 header ( 'Content-Type: text/plain; charset=utf-8' );
179 echo $exc- > getMessage ();
183 // Force cookie path (but do not change lifetime)
184 $cookie = session_get_cookie_params ();
186 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
187 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
189 // Set default cookie expiration and path.
190 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
191 // Set session parameters on server side.
192 // If the user does not access any page within this time, his/her session is considered expired.
193 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
194 // Use cookies to store session.
195 ini_set ( 'session.use_cookies' , 1 );
196 // Force cookies for session (phpsessionID forbidden in URL).
197 ini_set ( 'session.use_only_cookies' , 1 );
198 // Prevent PHP form using sessionID in URL if cookies are disabled.
199 ini_set ( 'session.use_trans_sid' , false );
201 session_name ( 'shaarli' );
202 // Start session if needed (Some server auto-start sessions).
203 if ( session_id () == '' ) {
207 // Regenerate session ID if invalid or not defined in cookie.
208 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
209 session_regenerate_id ( true );
210 $_COOKIE [ 'shaarli' ] = session_id ();
213 include "inc/rain.tpl.class.php" ; //include Rain TPL
214 raintpl
:: $tpl_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TPL' ]; // template directory
215 raintpl
:: $cache_dir = $GLOBALS [ 'config' ][ 'RAINTPL_TMP' ]; // cache directory
217 $pluginManager = PluginManager
:: getInstance ();
218 $pluginManager- > load ( $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ]);
220 ob_start (); // Output buffering for the page cache.
223 // In case stupid admin has left magic_quotes enabled in php.ini:
224 if ( get_magic_quotes_gpc ())
226 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
227 $_POST = array_map ( 'stripslashes_deep' , $_POST );
228 $_GET = array_map ( 'stripslashes_deep' , $_GET );
229 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
232 // Prevent caching on client side or proxy: (yes, it's ugly)
233 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
234 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
235 header ( "Cache-Control: post-check=0, pre-check=0" , false );
236 header ( "Pragma: no-cache" );
238 // Handling of old config file which do not have the new parameters.
239 if ( empty ( $GLOBALS [ 'title' ])) $GLOBALS [ 'title' ]= 'Shared links on ' . escape ( index_url ( $_SERVER ));
240 if ( empty ( $GLOBALS [ 'timezone' ])) $GLOBALS [ 'timezone' ]= date_default_timezone_get ();
241 if ( empty ( $GLOBALS [ 'redirector' ])) $GLOBALS [ 'redirector' ]= '' ;
242 if ( empty ( $GLOBALS [ 'disablesessionprotection' ])) $GLOBALS [ 'disablesessionprotection' ]= false ;
243 if ( empty ( $GLOBALS [ 'privateLinkByDefault' ])) $GLOBALS [ 'privateLinkByDefault' ]= false ;
244 if ( empty ( $GLOBALS [ 'titleLink' ])) $GLOBALS [ 'titleLink' ]= '?' ;
245 // I really need to rewrite Shaarli with a proper configuation manager.
247 if (! is_file ( $GLOBALS [ 'config' ][ 'CONFIG_FILE' ])) {
248 // Ensure Shaarli has proper access to its resources
249 $errors = ApplicationUtils
:: checkResourcePermissions ( $GLOBALS [ 'config' ]);
251 if ( $errors != array ()) {
252 $message = '<p>Insufficient permissions:</p><ul>' ;
254 foreach ( $errors as $error ) {
255 $message .= '<li>' . $error . '</li>' ;
259 header ( 'Content-Type: text/html; charset=utf-8' );
264 // Display the installation form if no existing config is found
268 $GLOBALS [ 'title' ] = ! empty ( $GLOBALS [ 'title' ]) ? escape ( $GLOBALS [ 'title' ]) : '' ;
269 $GLOBALS [ 'titleLink' ] = ! empty ( $GLOBALS [ 'titleLink' ]) ? escape ( $GLOBALS [ 'titleLink' ]) : '' ;
270 $GLOBALS [ 'redirector' ] = ! empty ( $GLOBALS [ 'redirector' ]) ? escape ( $GLOBALS [ 'redirector' ]) : '' ;
272 // a token depending of deployment salt, user password, and the current ip
273 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $GLOBALS [ 'hash' ]. $_SERVER [ "REMOTE_ADDR" ]. $GLOBALS [ 'salt' ]));
275 // Sniff browser language and set date format accordingly.
276 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
277 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
279 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
281 //==================================================================================================
282 // Checking session state (i.e. is the user still logged in)
283 //==================================================================================================
285 function setup_login_state () {
286 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) {
289 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
290 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
291 if (! isset ( $GLOBALS [ 'login' ])) {
292 $userIsLoggedIn = false ; // Shaarli is not configured yet.
293 $loginFailure = true ;
295 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
296 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
300 $userIsLoggedIn = true ;
302 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
303 if ( empty ( $_SESSION [ 'uid' ]) ||
304 ( $GLOBALS [ 'disablesessionprotection' ]== false && $_SESSION [ 'ip' ]!= allIPs ()) ||
305 time () >= $_SESSION [ 'expires_on' ])
308 $userIsLoggedIn = false ;
309 $loginFailure = true ;
311 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
312 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
315 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
317 if (! $loginFailure ) {
318 $userIsLoggedIn = true ;
321 return $userIsLoggedIn ;
323 $userIsLoggedIn = setup_login_state ();
325 // ------------------------------------------------------------------------------------------
326 // PubSubHubbub protocol support (if enabled) [UNTESTED]
327 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
328 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) include './publisher.php' ;
331 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]))
333 $p = new Publisher ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
335 index_url ( $_SERVER ). '?do=atom' ,
336 index_url ( $_SERVER ). '?do=rss'
338 $p- > publish_update ( $topic_url );
342 // ------------------------------------------------------------------------------------------
343 // Session management
345 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
348 $ip = $_SERVER [ "REMOTE_ADDR" ];
349 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
350 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
351 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
355 function fillSessionInfo () {
356 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
357 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
358 $_SESSION [ 'username' ]= $GLOBALS [ 'login' ];
359 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
362 // Check that user/password is correct.
363 function check_auth ( $login , $password )
365 $hash = sha1 ( $password . $login . $GLOBALS [ 'salt' ]);
366 if ( $login == $GLOBALS [ 'login' ] && $hash == $GLOBALS [ 'hash' ])
367 { // Login/password is correct.
369 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
372 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
376 // Returns true if the user is logged in.
377 function isLoggedIn ()
379 global $userIsLoggedIn ;
380 return $userIsLoggedIn ;
385 if ( isset ( $_SESSION )) {
386 unset ( $_SESSION [ 'uid' ]);
387 unset ( $_SESSION [ 'ip' ]);
388 unset ( $_SESSION [ 'username' ]);
389 unset ( $_SESSION [ 'privateonly' ]);
391 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
395 // ------------------------------------------------------------------------------------------
396 // Brute force protection system
397 // Several consecutive failed logins will ban the IP address for 30 minutes.
398 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 ?>" );
399 include $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ];
400 // Signal a failed login. Will ban the IP if too many failures:
401 function ban_loginFailed ()
403 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
404 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
405 $gb [ 'FAILURES' ][ $ip ] ++
;
406 if ( $gb [ 'FAILURES' ][ $ip ]>( $GLOBALS [ 'config' ][ 'BAN_AFTER' ]- 1 ))
408 $gb [ 'BANS' ][ $ip ]= time () +
$GLOBALS [ 'config' ][ 'BAN_DURATION' ];
409 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
411 $GLOBALS [ 'IPBANS' ] = $gb ;
412 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
415 // Signals a successful login. Resets failed login counter.
416 function ban_loginOk ()
418 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
419 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
420 $GLOBALS [ 'IPBANS' ] = $gb ;
421 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
424 // Checks if the user CAN login. If 'true', the user can try to login.
425 function ban_canLogin ()
427 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
428 if ( isset ( $gb [ 'BANS' ][ $ip ]))
430 // User is banned. Check if the ban has expired:
431 if ( $gb [ 'BANS' ][ $ip ]<= time ())
432 { // Ban expired, user can try to login again.
433 logm ( $GLOBALS [ 'config' ][ 'LOG_FILE' ], $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
434 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
435 file_put_contents ( $GLOBALS [ 'config' ][ 'IPBANS_FILENAME' ], "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>" );
436 return true ; // Ban has expired, user can login.
438 return false ; // User is banned.
440 return true ; // User is not banned.
443 // ------------------------------------------------------------------------------------------
444 // Process login form: Check if login/password is correct.
445 if ( isset ( $_POST [ 'login' ]))
447 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
448 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
449 { // Login/password is OK.
451 // If user wants to keep the session cookie even after the browser closes:
452 if (! empty ( $_POST [ 'longlastingsession' ]))
454 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
455 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
456 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
458 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
459 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
460 // Note: Never forget the trailing slash on the cookie path!
461 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
463 else // Standard session expiration (=when browser closes)
465 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
466 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
467 session_regenerate_id ( true );
470 // Optional redirect after login:
471 if ( isset ( $_GET [ 'post' ])) {
472 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
473 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
474 if (! empty ( $_GET [ $param ])) {
475 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
478 header ( 'Location: ' . $uri );
482 if ( isset ( $_GET [ 'edit_link' ])) {
483 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
487 if ( isset ( $_POST [ 'returnurl' ])) {
488 // Prevent loops over login screen.
489 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
490 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
494 header ( 'Location: ?' ); exit ;
500 if ( isset ( $_GET [ 'post' ])) {
501 $redir = '?post=' . urlencode ( $_GET [ 'post' ]);
502 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
503 if (! empty ( $_GET [ $param ])) {
504 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
508 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
513 // ------------------------------------------------------------------------------------------
514 // Misc utility functions:
516 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
517 function return_bytes ( $val )
519 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
522 case 'g' : $val *= 1024 ;
523 case 'm' : $val *= 1024 ;
524 case 'k' : $val *= 1024 ;
529 // Try to determine max file size for uploads (POST).
530 // Returns an integer (in bytes)
531 function getMaxFileSize ()
533 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
534 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
535 // Return the smaller of two:
536 $maxsize = min ( $size1 , $size2 );
537 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
541 // ------------------------------------------------------------------------------------------
542 // Token management for XSRF protection
543 // Token should be used in any form which acts on data (create,update,delete,import...).
544 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
549 $rnd = sha1 ( uniqid ( '' , true ). '_' . mt_rand (). $GLOBALS [ 'salt' ]); // We generate a random string.
550 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
554 // Tells if a token is OK. Using this function will destroy the token.
556 function tokenOk ( $token )
558 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
560 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
561 return true ; // Token is OK.
563 return false ; // Wrong token, or already used.
566 // ------------------------------------------------------------------------------------------
567 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
568 // Gives the last 7 days (which have links).
569 // This RSS feed cannot be filtered.
570 function showDailyRSS () {
572 $query = $_SERVER [ "QUERY_STRING" ];
573 $cache = new CachedPage (
574 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
576 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
578 $cached = $cache- > cachedVersion ();
579 if (! empty ( $cached )) {
584 // If cached was not found (or not usable), then read the database and build the response:
585 // Read links from database (and filter private links if used it not logged in).
586 $LINKSDB = new LinkDB (
587 $GLOBALS [ 'config' ][ 'DATASTORE' ],
589 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
590 $GLOBALS [ 'redirector' ],
591 $GLOBALS [ 'config' ][ 'REDIRECTOR_URLENCODE' ]
594 /* Some Shaarlies may have very few links, so we need to look
595 back in time (rsort()) until we have enough days ($nb_of_days).
597 $linkdates = array ();
598 foreach ( $LINKSDB as $linkdate => $value ) {
599 $linkdates [] = $linkdate ;
602 $nb_of_days = 7 ; // We take 7 days.
603 $today = Date ( 'Ymd' );
606 foreach ( $linkdates as $linkdate ) {
607 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
608 if ( strcmp ( $day , $today ) < 0 ) {
609 if ( empty ( $days [ $day ])) {
610 $days [ $day ] = array ();
612 $days [ $day ][] = $linkdate ;
615 if ( count ( $days ) > $nb_of_days ) {
616 break ; // Have we collected enough days?
620 // Build the RSS feed.
621 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
622 $pageaddr = escape ( index_url ( $_SERVER ));
623 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
625 echo '<title>Daily - ' . $GLOBALS [ 'title' ] . '</title>' ;
626 echo '<link>' . $pageaddr . '</link>' ;
627 echo '<description>Daily shared links</description>' ;
628 echo '<language>en-en</language>' ;
629 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
632 foreach ( $days as $day => $linkdates ) {
633 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
634 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
636 // Build the HTML body of this RSS entry.
641 // We pre-format some fields for proper output.
642 foreach ( $linkdates as $linkdate ) {
643 $l = $LINKSDB [ $linkdate ];
644 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $GLOBALS [ 'redirector' ]);
645 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
646 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
647 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
648 if ( startsWith ( $l [ 'url' ], '?' )) {
649 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
651 $links [ $linkdate ] = $l ;
654 // Then build the HTML for this day:
656 $tpl- > assign ( 'title' , $GLOBALS [ 'title' ]);
657 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
658 $tpl- > assign ( 'absurl' , $absurl );
659 $tpl- > assign ( 'links' , $links );
660 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
661 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
663 echo $html . PHP_EOL
;
665 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
667 $cache- > cache ( ob_get_contents ());
673 * Show the 'Daily' page.
675 * @param PageBuilder $pageBuilder Template engine wrapper.
676 * @param LinkDB $LINKSDB LinkDB instance.
678 function showDaily ( $pageBuilder , $LINKSDB )
680 $day = Date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
681 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
683 $days = $LINKSDB- > days ();
684 $i = array_search ( $day , $days );
685 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
690 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
691 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
695 $linksToDisplay = $LINKSDB- > filterDay ( $day );
696 } catch ( Exception
$exc ) {
698 $linksToDisplay = array ();
701 // We pre-format some fields for proper output.
702 foreach ( $linksToDisplay as $key => $link )
705 $taglist = explode ( ' ' , $link [ 'tags' ]);
706 uasort ( $taglist , 'strcasecmp' );
707 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
708 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
709 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
710 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
711 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
714 /* We need to spread the articles on 3 columns.
715 I did not want to use a JavaScript lib like http://masonry.desandro.com/
716 so I manually spread entries with a simple method: I roughly evaluate the
717 height of a div according to title and description length.
719 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
720 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
721 foreach ( $linksToDisplay as $key => $link )
723 // Roughly estimate length of entry (by counting characters)
724 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
725 // Description: 836 characters gives roughly 342 pixel height.
726 // This is not perfect, but it's usually OK.
727 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
728 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
729 // Then put in column which is the less filled:
730 $smallest = min ( $fill ); // find smallest value in array.
731 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
732 array_push ( $columns [ $index ], $link ); // Put entry in this column.
733 $fill [ $index ] +
= $length ;
736 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
738 'linksToDisplay' => $linksToDisplay ,
740 'day' => $dayDate- > getTimestamp (),
741 'previousday' => $previousday ,
742 'nextday' => $nextday ,
744 $pluginManager = PluginManager
:: getInstance ();
745 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
747 foreach ( $data as $key => $value ) {
748 $pageBuilder- > assign ( $key , $value );
751 $pageBuilder- > renderPage ( 'daily' );
755 // Renders the linklist
756 function showLinkList ( $PAGE , $LINKSDB ) {
757 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
758 $PAGE- > renderPage ( 'linklist' );
762 // ------------------------------------------------------------------------------------------
763 // Render HTML page (according to URL parameters and user rights)
764 function renderPage ()
766 $LINKSDB = new LinkDB (
767 $GLOBALS [ 'config' ][ 'DATASTORE' ],
769 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ],
770 $GLOBALS [ 'redirector' ],
771 $GLOBALS [ 'config' ][ 'REDIRECTOR_URLENCODE' ]
774 $updater = new Updater (
775 read_updates_file ( $GLOBALS [ 'config' ][ 'UPDATES_FILE' ]),
781 $newUpdates = $updater- > update ();
782 if (! empty ( $newUpdates )) {
784 $GLOBALS [ 'config' ][ 'UPDATES_FILE' ],
785 $updater- > getDoneUpdates ()
789 catch ( Exception
$e ) {
790 die ( $e- > getMessage ());
793 $PAGE = new PageBuilder ();
794 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
795 $PAGE- > assign ( 'privateLinkcount' , count_private ( $LINKSDB ));
797 // Determine which page will be rendered.
798 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
799 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
801 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
802 // Then assign generated data to RainTPL.
803 $common_hooks = array (
808 $pluginManager = PluginManager
:: getInstance ();
809 foreach ( $common_hooks as $name ) {
810 $plugin_data = array ();
811 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
813 'target' => $targetPage ,
814 'loggedin' => isLoggedIn ()
817 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
820 // -------- Display login form.
821 if ( $targetPage == Router
:: $PAGE_LOGIN )
823 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
824 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
825 $PAGE- > assign ( 'token' , $token );
826 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
827 $PAGE- > renderPage ( 'loginform' );
830 // -------- User wants to logout.
831 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=logout' ))
833 invalidateCaches ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
835 header ( 'Location: ?' );
839 // -------- Picture wall
840 if ( $targetPage == Router
:: $PAGE_PICWALL )
842 // Optionally filter the results:
843 $links = $LINKSDB- > filterSearch ( $_GET );
844 $linksToDisplay = array ();
846 // Get only links which have a thumbnail.
847 foreach ( $links as $link )
849 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
850 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
851 if ( $thumb != '' ) // Only output links which have a thumbnail.
853 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
854 $linksToDisplay []= $link ; // Add to array.
859 'linksToDisplay' => $linksToDisplay ,
861 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
863 foreach ( $data as $key => $value ) {
864 $PAGE- > assign ( $key , $value );
867 $PAGE- > renderPage ( 'picwall' );
871 // -------- Tag cloud
872 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
874 $tags = $LINKSDB- > allTags ();
876 // We sort tags alphabetically, then choose a font size according to count.
877 // First, find max value.
879 foreach ( $tags as $value ) {
880 $maxcount = max ( $maxcount , $value );
883 // Sort tags alphabetically: case insensitive, support locale if avalaible.
884 uksort ( $tags , function ( $a , $b ) {
885 // Collator is part of PHP intl.
886 if ( class_exists ( 'Collator' )) {
887 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
888 if (! intl_is_failure ( intl_get_error_code ())) {
889 return $c- > compare ( $a , $b );
892 return strcasecmp ( $a , $b );
896 foreach ( $tags as $key => $value ) {
897 // Tag font size scaling:
898 // default 15 and 30 logarithm bases affect scaling,
899 // 22 and 6 are arbitrary font sizes for max and min sizes.
900 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
901 $tagList [ $key ] = array (
903 'size' => number_format ( $size , 2 , '.' , '' ),
910 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
912 foreach ( $data as $key => $value ) {
913 $PAGE- > assign ( $key , $value );
916 $PAGE- > renderPage ( 'tagcloud' );
921 if ( $targetPage == Router
:: $PAGE_DAILY ) {
922 showDaily ( $PAGE , $LINKSDB );
925 // ATOM and RSS feed.
926 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
927 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
928 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
931 $query = $_SERVER [ 'QUERY_STRING' ];
932 $cache = new CachedPage (
933 $GLOBALS [ 'config' ][ 'PAGECACHE' ],
935 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
937 $cached = $cache- > cachedVersion ();
938 if (! empty ( $cached )) {
944 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
945 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
946 $feedGenerator- > setHideDates ( $GLOBALS [ 'config' ][ 'HIDE_TIMESTAMPS' ] && ! isLoggedIn ());
947 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]);
948 if (! empty ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ])) {
949 $feedGenerator- > setPubsubhubUrl ( $GLOBALS [ 'config' ][ 'PUBSUBHUB_URL' ]);
951 $data = $feedGenerator- > buildData ();
953 // Process plugin hook.
954 $pluginManager = PluginManager
:: getInstance ();
955 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
956 'loggedin' => isLoggedIn (),
957 'target' => $targetPage ,
960 // Render the template.
961 $PAGE- > assignAll ( $data );
962 $PAGE- > renderPage ( 'feed.' . $feedType );
963 $cache- > cache ( ob_get_contents ());
968 // Display openseach plugin (XML)
969 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
970 header ( 'Content-Type: application/xml; charset=utf-8' );
971 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
972 $PAGE- > renderPage ( 'opensearch' );
976 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
977 if ( isset ( $_GET [ 'addtag' ]))
979 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
980 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
981 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
983 // Prevent redirection loop
984 if ( isset ( $params [ 'addtag' ])) {
985 unset ( $params [ 'addtag' ]);
988 // Check if this tag is already in the search query and ignore it if it is.
989 // Each tag is always separated by a space
990 if ( isset ( $params [ 'searchtags' ])) {
991 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
993 $current_tags = array ();
996 foreach ( $current_tags as $value ) {
997 if ( $value === $_GET [ 'addtag' ]) {
1002 // Append the tag if necessary
1003 if ( empty ( $params [ 'searchtags' ])) {
1004 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
1007 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
1010 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1011 header ( 'Location: ?' . http_build_query ( $params ));
1015 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
1016 if ( isset ( $_GET [ 'removetag' ])) {
1017 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
1018 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
1019 header ( 'Location: ?' );
1023 // In case browser does not send HTTP_REFERER
1024 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1026 // Prevent redirection loop
1027 if ( isset ( $params [ 'removetag' ])) {
1028 unset ( $params [ 'removetag' ]);
1031 if ( isset ( $params [ 'searchtags' ])) {
1032 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1033 // Remove value from array $tags.
1034 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1035 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1037 if ( empty ( $params [ 'searchtags' ])) {
1038 unset ( $params [ 'searchtags' ]);
1041 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1043 header ( 'Location: ?' . http_build_query ( $params ));
1047 // -------- User wants to change the number of links per page (linksperpage=...)
1048 if ( isset ( $_GET [ 'linksperpage' ])) {
1049 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1050 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1053 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1057 // -------- User wants to see only private links (toggle)
1058 if ( isset ( $_GET [ 'privateonly' ])) {
1059 if ( empty ( $_SESSION [ 'privateonly' ])) {
1060 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1062 unset ( $_SESSION [ 'privateonly' ]); // See all links
1065 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1069 // -------- Handle other actions allowed for non-logged in users:
1072 // User tries to post new link but is not logged in:
1073 // Show login screen, then redirect to ?post=...
1074 if ( isset ( $_GET [ 'post' ]))
1076 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.
1080 // Same case as above except that user tried to access ?do=addlink without being logged in
1081 // Note: passing empty parameters makes Shaarli generate default URLs and descriptions.
1082 if ( isset ( $_GET [ 'do' ]) && $_GET [ 'do' ] === 'addlink' ) {
1083 header ( 'Location: ?do=login&post=' );
1086 showLinkList ( $PAGE , $LINKSDB );
1087 if ( isset ( $_GET [ 'edit_link' ])) {
1088 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1092 exit ; // Never remove this one! All operations below are reserved for logged in user.
1095 // -------- All other functions are reserved for the registered user:
1097 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1098 if ( $targetPage == Router
:: $PAGE_TOOLS )
1101 'pageabsaddr' => index_url ( $_SERVER ),
1103 $pluginManager- > executeHooks ( 'render_tools' , $data );
1105 foreach ( $data as $key => $value ) {
1106 $PAGE- > assign ( $key , $value );
1109 $PAGE- > renderPage ( 'tools' );
1113 // -------- User wants to change his/her password.
1114 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1116 if ( $GLOBALS [ 'config' ][ 'OPEN_SHAARLI' ]) die ( 'You are not supposed to change a password on an Open Shaarli.' );
1117 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1119 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1121 // Make sure old password is correct.
1122 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1123 if ( $oldhash != $GLOBALS [ 'hash' ]) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1124 // Save new password
1125 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
1126 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
1128 writeConfig ( $GLOBALS , isLoggedIn ());
1130 catch ( Exception
$e ) {
1132 'ERROR while writing config file after changing password.' . PHP_EOL
.
1136 // TODO: do not handle exceptions/errors in JS.
1137 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1140 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1143 else // show the change password form.
1145 $PAGE- > assign ( 'token' , getToken ());
1146 $PAGE- > renderPage ( 'changepassword' );
1151 // -------- User wants to change configuration
1152 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1154 if (! empty ( $_POST [ 'title' ]) )
1156 if (! tokenOk ( $_POST [ 'token' ])) {
1157 die ( 'Wrong token.' ); // Go away!
1160 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1161 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1163 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1165 $GLOBALS [ 'timezone' ] = $tz ;
1166 $GLOBALS [ 'title' ]= $_POST [ 'title' ];
1167 $GLOBALS [ 'titleLink' ]= $_POST [ 'titleLink' ];
1168 $GLOBALS [ 'redirector' ]= $_POST [ 'redirector' ];
1169 $GLOBALS [ 'disablesessionprotection' ]=! empty ( $_POST [ 'disablesessionprotection' ]);
1170 $GLOBALS [ 'privateLinkByDefault' ]=! empty ( $_POST [ 'privateLinkByDefault' ]);
1171 $GLOBALS [ 'config' ][ 'ENABLE_RSS_PERMALINKS' ]= ! empty ( $_POST [ 'enableRssPermalinks' ]);
1172 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
1173 $GLOBALS [ 'config' ][ 'HIDE_PUBLIC_LINKS' ] = ! empty ( $_POST [ 'hidePublicLinks' ]);
1175 writeConfig ( $GLOBALS , isLoggedIn ());
1177 catch ( Exception
$e ) {
1179 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1183 // TODO: do not handle exceptions/errors in JS.
1184 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1187 echo '<script>alert("Configuration was saved.");document.location= \' ?do=tools \' ;</script>' ;
1190 else // Show the configuration form.
1192 $PAGE- > assign ( 'token' , getToken ());
1193 $PAGE- > assign ( 'title' , empty ( $GLOBALS [ 'title' ]) ? '' : $GLOBALS [ 'title' ] );
1194 $PAGE- > assign ( 'redirector' , empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ] );
1195 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $GLOBALS [ 'timezone' ]);
1196 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1197 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1198 $PAGE- > renderPage ( 'configure' );
1203 // -------- User wants to rename a tag or delete it
1204 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1206 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1207 $PAGE- > assign ( 'token' , getToken ());
1208 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1209 $PAGE- > renderPage ( 'changetag' );
1213 if (! tokenOk ( $_POST [ 'token' ])) {
1214 die ( 'Wrong token.' );
1218 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1219 $needle = trim ( $_POST [ 'fromtag' ]);
1220 // True for case-sensitive tag search.
1221 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1222 foreach ( $linksToAlter as $key => $value )
1224 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1225 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1226 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1227 $LINKSDB [ $key ]= $value ;
1229 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1230 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1235 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1236 $needle = trim ( $_POST [ 'fromtag' ]);
1237 // True for case-sensitive tag search.
1238 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1239 foreach ( $linksToAlter as $key => $value )
1241 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1242 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1243 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1244 $LINKSDB [ $key ]= $value ;
1246 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // Save to disk.
1247 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1252 // -------- User wants to add a link without using the bookmarklet: Show form.
1253 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1255 $PAGE- > renderPage ( 'addlink' );
1259 // -------- User clicked the "Save" button when editing a link: Save link to database.
1260 if ( isset ( $_POST [ 'save_edit' ]))
1263 if (! tokenOk ( $_POST [ 'token' ])) {
1264 die ( 'Wrong token.' );
1266 // Remove multiple spaces.
1267 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1268 // Remove first '-' char in tags.
1269 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1270 // Remove duplicates.
1271 $tags = implode(' ', array_unique(explode(' ', $tags )));
1272 $linkdate = $_POST [' lf_linkdate
'];
1273 $url = trim( $_POST [' lf_url
']);
1274 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1275 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1276 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1278 $url = ' http
: //' . $url;
1282 'title' => trim ( $_POST [ 'lf_title' ]),
1284 'description' => $_POST [ 'lf_description' ],
1285 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1286 'linkdate' => $linkdate ,
1287 'tags' => str_replace ( ',' , ' ' , $tags )
1289 // If title is empty, use the URL as title.
1290 if ( $link [ 'title' ] == '' ) {
1291 $link [ 'title' ] = $link [ 'url' ];
1294 $pluginManager- > executeHooks ( 'save_link' , $link );
1296 $LINKSDB [ $linkdate ] = $link ;
1297 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1300 // If we are called from the bookmarklet, we must close the popup:
1301 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1302 echo '<script>self.close();</script>' ;
1306 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1307 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1308 // Scroll to the link which has been edited.
1309 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1310 // After saving the link, redirect to the page the user was on.
1311 header ( 'Location: ' . $location );
1315 // -------- User clicked the "Cancel" button when editing a link.
1316 if ( isset ( $_POST [ 'cancel_edit' ]))
1318 // If we are called from the bookmarklet, we must close the popup:
1319 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1320 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1321 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1322 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1323 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1327 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1328 if ( isset ( $_POST [ 'delete_link' ]))
1330 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1331 // We do not need to ask for confirmation:
1332 // - confirmation is handled by JavaScript
1333 // - we are protected from XSRF by the token.
1334 $linkdate = $_POST [ 'lf_linkdate' ];
1336 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1338 unset ( $LINKSDB [ $linkdate ]);
1339 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]); // save to disk
1341 // If we are called from the bookmarklet, we must close the popup:
1342 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1343 // Pick where we're going to redirect
1344 // =============================================================
1345 // Basically, we can't redirect to where we were previously if it was a permalink
1346 // or an edit_link, because it would 404.
1348 // - / : nothing in $_GET, redirect to self
1349 // - /?page : redirect to self
1350 // - /?searchterm : redirect to self (there might be other links)
1351 // - /?searchtags : redirect to self
1352 // - /permalink : redirect to / (the link does not exist anymore)
1353 // - /?edit_link : redirect to / (the link does not exist anymore)
1354 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1355 // redirect is not satisfied, and only then redirect to /
1358 if ( count ( $_GET ) == 0
1359 || isset ( $_GET [ 'page' ])
1360 || isset ( $_GET [ 'searchterm' ])
1361 || isset ( $_GET [ 'searchtags' ])
1363 if ( isset ( $_POST [ 'returnurl' ])) {
1364 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1366 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1370 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1374 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1375 if ( isset ( $_GET [ 'edit_link' ]))
1377 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1378 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1381 'link_is_new' => false ,
1382 'token' => getToken (),
1383 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1384 'tags' => $LINKSDB- > allTags (),
1386 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1388 foreach ( $data as $key => $value ) {
1389 $PAGE- > assign ( $key , $value );
1392 $PAGE- > renderPage ( 'editlink' );
1396 // -------- User want to post a new link: Display link edit form.
1397 if ( isset ( $_GET [ 'post' ])) {
1398 $url = cleanup_url ( $_GET [ 'post' ]);
1400 $link_is_new = false ;
1401 // Check if URL is not already in database (in this case, we will edit the existing link)
1402 $link = $LINKSDB- > getLinkFromUrl ( $url );
1405 $link_is_new = true ;
1406 $linkdate = strval ( date ( 'Ymd_His' ));
1407 // Get title if it was provided in URL (by the bookmarklet).
1408 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1409 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1410 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1411 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1412 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1413 // 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.)
1414 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1415 // Short timeout to keep the application responsive
1416 list ( $headers , $content ) = get_http_response ( $url , 4 );
1417 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1418 // Retrieve charset.
1419 $charset = get_charset ( $headers , $content );
1421 $title = html_extract_title ( $content );
1422 // Re-encode title in utf-8 if necessary.
1423 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1424 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1430 $url = '?' . smallHash ( $linkdate );
1433 $url = escape ( $url );
1434 $title = escape ( $title );
1437 'linkdate' => $linkdate ,
1440 'description' => $description ,
1442 'private' => $private
1448 'link_is_new' => $link_is_new ,
1449 'token' => getToken (), // XSRF protection.
1450 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1451 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1452 'tags' => $LINKSDB- > allTags (),
1454 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1456 foreach ( $data as $key => $value ) {
1457 $PAGE- > assign ( $key , $value );
1460 $PAGE- > renderPage ( 'editlink' );
1464 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1465 // Export links as a Netscape Bookmarks file
1467 if ( empty ( $_GET [ 'selection' ])) {
1468 $PAGE- > renderPage ( 'export' );
1472 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1473 $selection = $_GET [ 'selection' ];
1474 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1475 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1477 $prependNoteUrl = false ;
1483 NetscapeBookmarkUtils
:: filterAndFormat (
1490 } catch ( Exception
$exc ) {
1491 header ( 'Content-Type: text/plain; charset=utf-8' );
1492 echo $exc- > getMessage ();
1495 $now = new DateTime ();
1496 header ( 'Content-Type: text/html; charset=utf-8' );
1498 'Content-disposition: attachment; filename=bookmarks_'
1499 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1501 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1502 $PAGE- > assign ( 'eol' , PHP_EOL
);
1503 $PAGE- > assign ( 'selection' , $selection );
1504 $PAGE- > renderPage ( 'export.bookmarks' );
1508 // -------- User is uploading a file for import
1509 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=upload' ))
1511 // If file is too big, some form field may be missing.
1512 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1514 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1515 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>' ;
1518 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1519 importFile ( $LINKSDB );
1523 // -------- Show upload/import dialog:
1524 if ( $targetPage == Router
:: $PAGE_IMPORT )
1526 $PAGE- > assign ( 'token' , getToken ());
1527 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1528 $PAGE- > renderPage ( 'import' );
1532 // Plugin administration page
1533 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1534 $pluginMeta = $pluginManager- > getPluginsMeta ();
1536 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1537 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1539 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $GLOBALS [ 'plugins' ]);
1542 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1544 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1546 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1547 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1548 $PAGE- > renderPage ( 'pluginsadmin' );
1552 // Plugin administration form action
1553 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1555 if ( isset ( $_POST [ 'parameters_form' ])) {
1556 unset ( $_POST [ 'parameters_form' ]);
1557 foreach ( $_POST as $param => $value ) {
1558 $GLOBALS [ 'plugins' ][ $param ] = escape ( $value );
1562 $GLOBALS [ 'config' ][ 'ENABLED_PLUGINS' ] = save_plugin_config ( $_POST );
1564 writeConfig ( $GLOBALS , isLoggedIn ());
1566 catch ( Exception
$e ) {
1568 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1572 // TODO: do not handle exceptions/errors in JS.
1573 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1576 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1580 // -------- Otherwise, simply display search form and links:
1581 showLinkList ( $PAGE , $LINKSDB );
1585 // -----------------------------------------------------------------------------------------------
1586 // Process the import file form.
1587 function importFile ( $LINKSDB )
1589 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1591 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1592 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1593 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1594 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1595 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1600 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1602 // Then import the bookmarks.
1603 if ( $type == 'netscape' )
1605 // This is a standard Netscape-style bookmark file.
1606 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1607 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1609 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1610 $d = explode ( '<DD>' , $html );
1611 if ( startswith ( $d [ 0 ], '<A ' ))
1613 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1614 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1615 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1616 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1618 foreach ( $matches as $m )
1620 $attr = $m [ 1 ]; $value = $m [ 2 ];
1621 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1622 elseif ( $attr == 'ADD_DATE' )
1624 $raw_add_date = intval ( $value );
1625 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1627 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1628 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1630 if ( $link [ 'url' ]!= '' )
1632 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1633 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1635 { // Link not in database, let's import it...
1636 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1638 // Make sure date/time is not already used by another link.
1639 // (Some bookmark files have several different links with the same ADD_DATE)
1640 // We increment date by 1 second until we find a date which is not used in DB.
1641 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1642 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1643 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1644 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1647 else // Link already present in database.
1650 { // If overwrite is required, we import link data, except date/time.
1651 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1652 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1660 $LINKSDB- > savedb ( $GLOBALS [ 'config' ][ 'PAGECACHE' ]);
1662 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1666 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1671 * Template for the list of links (<div id="linklist">)
1672 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1674 * @param pageBuilder $PAGE pageBuilder instance.
1675 * @param LinkDB $LINKSDB LinkDB instance.
1677 function buildLinkList ( $PAGE , $LINKSDB )
1679 // Used in templates
1680 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1681 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1684 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1685 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1687 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1688 } catch ( LinkNotFoundException
$e ) {
1689 $PAGE- > render404 ( $e- > getMessage ());
1693 // Filter links according search parameters.
1694 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1695 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1698 // ---- Handle paging.
1700 foreach ( $linksToDisplay as $key => $value ) {
1704 // If there is only a single link, we change on-the-fly the title of the page.
1705 if ( count ( $linksToDisplay ) == 1 ) {
1706 $GLOBALS [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ]. ' - ' . $GLOBALS [ 'title' ];
1709 // Select articles according to paging.
1710 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1711 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1712 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1713 $page = $page < 1 ? 1 : $page ;
1714 $page = $page > $pagecount ? $pagecount : $page ;
1716 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1717 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1718 $linkDisp = array ();
1719 while ( $i < $end && $i < count ( $keys ))
1721 $link = $linksToDisplay [ $keys [ $i ]];
1722 $link [ 'description' ] = format_description ( $link [ 'description' ], $GLOBALS [ 'redirector' ]);
1723 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1724 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1725 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1726 $link [ 'timestamp' ] = $date- > getTimestamp ();
1727 $taglist = explode ( ' ' , $link [ 'tags' ]);
1728 uasort ( $taglist , 'strcasecmp' );
1729 $link [ 'taglist' ] = $taglist ;
1730 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1731 // Check for both signs of a note: starting with ? and 7 chars long.
1732 if ( $link [ 'url' ][ 0 ] === '?' &&
1733 strlen ( $link [ 'url' ]) === 7 ) {
1734 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1737 $linkDisp [ $keys [ $i ]] = $link ;
1741 // Compute paging navigation
1742 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1743 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1744 $previous_page_url = '' ;
1745 if ( $i != count ( $keys )) {
1746 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1750 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1753 $token = isLoggedIn () ? getToken () : '' ;
1755 // Fill all template fields.
1757 'previous_page_url' => $previous_page_url ,
1758 'next_page_url' => $next_page_url ,
1759 'page_current' => $page ,
1760 'page_max' => $pagecount ,
1761 'result_count' => count ( $linksToDisplay ),
1762 'search_term' => $searchterm ,
1763 'search_tags' => $searchtags ,
1764 'redirector' => empty ( $GLOBALS [ 'redirector' ]) ? '' : $GLOBALS [ 'redirector' ], // Optional redirector URL.
1766 'links' => $linkDisp ,
1767 'tags' => $LINKSDB- > allTags (),
1769 // FIXME! temporary fix - see #399.
1770 if (! empty ( $GLOBALS [ 'pagetitle' ]) && count ( $linkDisp ) == 1 ) {
1771 $data [ 'pagetitle' ] = $GLOBALS [ 'pagetitle' ];
1774 $pluginManager = PluginManager
:: getInstance ();
1775 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1777 foreach ( $data as $key => $value ) {
1778 $PAGE- > assign ( $key , $value );
1784 // Compute the thumbnail for a link.
1786 // With a link to the original URL.
1787 // Understands various services (youtube.com...)
1788 // Input: $url = URL for which the thumbnail must be found.
1789 // $href = if provided, this URL will be followed instead of $url
1790 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1791 // Some of them may be missing.
1792 // Return an empty array if no thumbnail available.
1793 function computeThumbnail ( $url , $href = false )
1795 if (! $GLOBALS [ 'config' ][ 'ENABLE_THUMBNAILS' ]) return array ();
1796 if ( $href == false ) $href = $url ;
1798 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1799 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1800 // ^^^^^^^^^^^ ^^^^^^^^^^^
1801 $domain = parse_url ( $url , PHP_URL_HOST
);
1802 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1804 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1805 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1806 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1808 if ( $domain == 'youtu.be' ) // Youtube short links
1810 $path = parse_url ( $url , PHP_URL_PATH
);
1811 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1812 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1814 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1816 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1817 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1818 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1821 if ( $domain == 'imgur.com' )
1823 $path = parse_url ( $url , PHP_URL_PATH
);
1824 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1825 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1826 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1827 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1828 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1830 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1831 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1833 if ( $domain == 'i.imgur.com' )
1835 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1836 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1837 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1839 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1841 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1843 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1844 return array ( 'src' => $thumburl ,
1845 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1848 if ( endsWith ( $domain , '.imageshack.us' ))
1850 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1851 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1853 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1854 return array ( 'src' => $thumburl ,
1855 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1859 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1860 // So we deport the thumbnail generation in order not to slow down page generation
1861 // (and we also cache the thumbnail)
1863 if (! $GLOBALS [ 'config' ][ 'ENABLE_LOCALCACHE' ]) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1865 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1866 || $domain == 'vimeo.com'
1867 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1868 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1871 if ( $domain == 'vimeo.com' )
1872 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1873 $path = parse_url ( $url , PHP_URL_PATH
);
1874 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1876 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1877 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1878 $path = parse_url ( $url , PHP_URL_PATH
);
1879 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1881 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1882 { // Make sure this TED URL points to a video (/talks/...)
1883 $path = parse_url ( $url , PHP_URL_PATH
);
1884 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1886 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1887 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1888 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1891 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1892 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1893 // But using the extension will do.
1894 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1895 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1897 $sign = hash_hmac ( 'sha256' , $url , $GLOBALS [ 'salt' ]); // We use the salt to sign data (it's random, secret, and specific to each installation)
1898 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1899 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1901 return array (); // No thumbnail.
1906 // Returns the HTML code to display a thumbnail for a link
1907 // with a link to the original URL.
1908 // Understands various services (youtube.com...)
1909 // Input: $url = URL for which the thumbnail must be found.
1910 // $href = if provided, this URL will be followed instead of $url
1911 // Returns '' if no thumbnail available.
1912 function thumbnail ( $url , $href = false )
1914 $t = computeThumbnail ( $url , $href );
1915 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1917 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
1918 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1919 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1920 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1921 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1926 // Returns the HTML code to display a thumbnail for a link
1927 // for the picture wall (using lazy image loading)
1928 // Understands various services (youtube.com...)
1929 // Input: $url = URL for which the thumbnail must be found.
1930 // $href = if provided, this URL will be followed instead of $url
1931 // Returns '' if no thumbnail available.
1932 function lazyThumbnail ( $url , $href = false )
1934 $t = computeThumbnail ( $url , $href );
1935 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1937 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
1940 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
1942 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1943 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1944 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1945 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1948 // No-JavaScript fallback.
1949 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
1950 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1951 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1952 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1953 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1954 $html .= '></noscript></a>' ;
1960 // -----------------------------------------------------------------------------------------------
1962 // This function should NEVER be called if the file data/config.php exists.
1965 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1966 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1969 // This part makes sure sessions works correctly.
1970 // (Because on some hosts, session.save_path may not be set correctly,
1971 // or we may not have write access to it.)
1972 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
1973 { // Step 2: Check if data in session is correct.
1974 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
1975 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
1976 echo 'It currently points to ' . session_save_path (). '<br>' ;
1977 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>' ;
1978 echo '<br><a href="?">Click to try again.</a></pre>' ;
1981 if (! isset ( $_SESSION [ 'session_tested' ]))
1982 { // Step 1 : Try to store data in session and reload page.
1983 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
1984 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
1986 if ( isset ( $_GET [ 'test_session' ]))
1987 { // Step 3: Sessions are OK. Remove test parameter from URL.
1988 header ( 'Location: ' . index_url ( $_SERVER ));
1992 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1995 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1996 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1998 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
2000 $GLOBALS [ 'timezone' ] = $tz ;
2001 // Everything is ok, let's create config file.
2002 $GLOBALS [ 'login' ] = $_POST [ 'setlogin' ];
2003 $GLOBALS [ 'salt' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Salt renders rainbow-tables attacks useless.
2004 $GLOBALS [ 'hash' ] = sha1 ( $_POST [ 'setpassword' ]. $GLOBALS [ 'login' ]. $GLOBALS [ 'salt' ]);
2005 $GLOBALS [ 'title' ] = ( empty ( $_POST [ 'title' ]) ? 'Shared links on ' . escape ( index_url ( $_SERVER )) : $_POST [ 'title' ] );
2006 $GLOBALS [ 'config' ][ 'ENABLE_UPDATECHECK' ] = ! empty ( $_POST [ 'updateCheck' ]);
2008 writeConfig ( $GLOBALS , isLoggedIn ());
2010 catch ( Exception
$e ) {
2012 'ERROR while writing config file after installation.' . PHP_EOL
.
2016 // TODO: do not handle exceptions/errors in JS.
2017 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2020 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2024 // Display config form:
2025 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2026 $timezone_html = '' ;
2027 if ( $timezone_form != '' ) {
2028 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2031 $PAGE = new PageBuilder ();
2032 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2033 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2034 $PAGE- > renderPage ( 'install' );
2038 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2039 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2040 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2041 This function is called by passing the URL:
2042 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2043 [URL] is the URL of the link (e.g. a flickr page)
2044 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2045 The function below will fetch the image from the webservice and store it in the cache.
2047 function genThumbnail ()
2049 // Make sure the parameters in the URL were generated by us.
2050 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $GLOBALS [ 'salt' ]);
2051 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2053 // Let's see if we don't already have the image for this URL in the cache.
2054 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2055 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ))
2056 { // We have the thumbnail, just serve it:
2057 header ( 'Content-Type: image/jpeg' );
2058 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname );
2061 // We may also serve a blank image (if service did not respond)
2062 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2063 if ( is_file ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname ))
2065 header ( 'Content-Type: image/gif' );
2066 echo file_get_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname );
2070 // Otherwise, generate the thumbnail.
2071 $url = $_GET [ 'url' ];
2072 $domain = parse_url ( $url , PHP_URL_HOST
);
2074 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2076 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2077 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2079 // Is this a link to an image, or to a flickr page ?
2081 if ( endswith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2082 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2083 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2084 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2086 else // This is a flickr page (html)
2088 // Get the flickr html page.
2089 list ( $headers , $content ) = get_http_response ( $url , 20 );
2090 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2092 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2093 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2094 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2096 // In albums (and some other pages), the link rel="image_src" is not provided,
2097 // but flickr provides:
2098 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2101 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2102 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2108 { // Let's download the image.
2109 // Image is 240x120, so 10 seconds to download should be enough.
2110 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2111 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2112 // Save image to cache.
2113 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname , $content );
2114 header ( 'Content-Type: image/jpeg' );
2121 elseif ( $domain == 'vimeo.com' )
2123 // This is more complex: we have to perform a HTTP request, then parse the result.
2124 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2125 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2126 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2127 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2128 $t = unserialize ( $content );
2129 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2130 // Then we download the image and serve it to our client.
2131 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2132 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2133 // Save image to cache.
2134 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ] . '/' . $thumbname , $content );
2135 header ( 'Content-Type: image/jpeg' );
2142 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2144 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2145 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2146 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2147 list ( $headers , $content ) = get_http_response ( $url , 5 );
2148 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2149 // Extract the link to the thumbnail
2150 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2151 if (! empty ( $matches [ 1 ]))
2152 { // Let's download the image.
2153 $imageurl = $matches [ 1 ];
2154 // No control on image size, so wait long enough
2155 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2156 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2157 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2158 file_put_contents ( $filepath , $content ); // Save image to cache.
2159 if ( resizeImage ( $filepath ))
2161 header ( 'Content-Type: image/jpeg' );
2162 echo file_get_contents ( $filepath );
2170 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2172 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2173 // http://xkcd.com/327/
2174 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2175 list ( $headers , $content ) = get_http_response ( $url , 5 );
2176 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2177 // Extract the link to the thumbnail
2178 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2179 if (! empty ( $matches [ 1 ]))
2180 { // Let's download the image.
2181 $imageurl = $matches [ 1 ];
2182 // No control on image size, so wait long enough
2183 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2184 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2185 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2186 // Save image to cache.
2187 file_put_contents ( $filepath , $content );
2188 if ( resizeImage ( $filepath ))
2190 header ( 'Content-Type: image/jpeg' );
2191 echo file_get_contents ( $filepath );
2201 // For all other domains, we try to download the image and make a thumbnail.
2202 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2203 list ( $headers , $content ) = get_http_response ( $url , 30 );
2204 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2205 $filepath = $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $thumbname ;
2206 // Save image to cache.
2207 file_put_contents ( $filepath , $content );
2208 if ( resizeImage ( $filepath ))
2210 header ( 'Content-Type: image/jpeg' );
2211 echo file_get_contents ( $filepath );
2218 // Otherwise, return an empty image (8x8 transparent gif)
2219 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2220 file_put_contents ( $GLOBALS [ 'config' ][ 'CACHEDIR' ]. '/' . $blankname , $blankgif ); // Also put something in cache so that this URL is not requested twice.
2221 header ( 'Content-Type: image/gif' );
2225 // Make a thumbnail of the image (to width: 120 pixels)
2226 // Returns true if success, false otherwise.
2227 function resizeImage ( $filepath )
2229 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2231 // Trick: some stupid people rename GIF as JPEG... or else.
2232 // So we really try to open each image type whatever the extension is.
2233 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2235 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2236 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2237 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2238 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2241 $ystart = 0 ; $yheight = $h ;
2242 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2243 $nw = 120 ; // Desired width
2244 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2246 $im2 = imagecreatetruecolor ( $nw , $nh );
2247 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2248 imageinterlace ( $im2 , true ); // For progressive JPEG.
2249 $tempname = $filepath . '_TEMP.jpg' ;
2250 imagejpeg ( $im2 , $tempname , 90 );
2254 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2258 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2259 if ( isset ( $_SERVER [ "QUERY_STRING" ]) && startswith ( $_SERVER [ "QUERY_STRING" ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2260 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) $_SESSION [ 'LINKS_PER_PAGE' ]= $GLOBALS [ 'config' ][ 'LINKS_PER_PAGE' ];