]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.7.0 - Shaare your links...
5 * The personal, minimalist, super-fast, database free, bookmarking service.
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' );
28 define ( 'shaarli_version' , '0.7.0' );
30 // http://server.com/x/shaarli --> /shaarli/
31 define ( 'WEB_PATH' , substr ( $_SERVER [ 'REQUEST_URI' ], 0 , 1 +
strrpos ( $_SERVER [ 'REQUEST_URI' ], '/' , 0 )));
33 // High execution time in case of problematic imports/exports.
34 ini_set ( 'max_input_time' , '60' );
36 // Try to set max upload file size and read
37 ini_set ( 'memory_limit' , '128M' );
38 ini_set ( 'post_max_size' , '16M' );
39 ini_set ( 'upload_max_filesize' , '16M' );
41 // See all error except warnings
42 error_reporting ( E_ALL^E_WARNING
);
43 // See all errors (for debugging only)
44 //error_reporting(-1);
48 require_once 'application/ApplicationUtils.php' ;
49 require_once 'application/Cache.php' ;
50 require_once 'application/CachedPage.php' ;
51 require_once 'application/config/ConfigManager.php' ;
52 require_once 'application/config/ConfigPlugin.php' ;
53 require_once 'application/FeedBuilder.php' ;
54 require_once 'application/FileUtils.php' ;
55 require_once 'application/HttpUtils.php' ;
56 require_once 'application/LinkDB.php' ;
57 require_once 'application/LinkFilter.php' ;
58 require_once 'application/LinkUtils.php' ;
59 require_once 'application/NetscapeBookmarkUtils.php' ;
60 require_once 'application/PageBuilder.php' ;
61 require_once 'application/TimeZone.php' ;
62 require_once 'application/Url.php' ;
63 require_once 'application/Utils.php' ;
64 require_once 'application/PluginManager.php' ;
65 require_once 'application/Router.php' ;
66 require_once 'application/Updater.php' ;
67 require_once 'inc/rain.tpl.class.php' ;
69 // Ensure the PHP version is supported
71 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
72 } catch ( Exception
$exc ) {
73 header ( 'Content-Type: text/plain; charset=utf-8' );
74 echo $exc- > getMessage ();
78 // Force cookie path (but do not change lifetime)
79 $cookie = session_get_cookie_params ();
81 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
82 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
84 // Set default cookie expiration and path.
85 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
86 // Set session parameters on server side.
87 // If the user does not access any page within this time, his/her session is considered expired.
88 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
89 // Use cookies to store session.
90 ini_set ( 'session.use_cookies' , 1 );
91 // Force cookies for session (phpsessionID forbidden in URL).
92 ini_set ( 'session.use_only_cookies' , 1 );
93 // Prevent PHP form using sessionID in URL if cookies are disabled.
94 ini_set ( 'session.use_trans_sid' , false );
96 session_name ( 'shaarli' );
97 // Start session if needed (Some server auto-start sessions).
98 if ( session_id () == '' ) {
102 // Regenerate session ID if invalid or not defined in cookie.
103 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
104 session_regenerate_id ( true );
105 $_COOKIE [ 'shaarli' ] = session_id ();
108 $conf = new ConfigManager ();
109 $conf- > setEmpty ( 'general.timezone' , date_default_timezone_get ());
110 $conf- > setEmpty ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
111 RainTPL
:: $tpl_dir = $conf- > get ( 'resource.raintpl_tpl' ); // template directory
112 RainTPL
:: $cache_dir = $conf- > get ( 'resource.raintpl_tmp' ); // cache directory
114 $pluginManager = new PluginManager ( $conf );
115 $pluginManager- > load ( $conf- > get ( 'general.enabled_plugins' ));
117 date_default_timezone_set ( $conf- > get ( 'general.timezone' , 'UTC' ));
119 ob_start (); // Output buffering for the page cache.
121 // In case stupid admin has left magic_quotes enabled in php.ini:
122 if ( get_magic_quotes_gpc ())
124 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
125 $_POST = array_map ( 'stripslashes_deep' , $_POST );
126 $_GET = array_map ( 'stripslashes_deep' , $_GET );
127 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
130 // Prevent caching on client side or proxy: (yes, it's ugly)
131 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
132 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
133 header ( "Cache-Control: post-check=0, pre-check=0" , false );
134 header ( "Pragma: no-cache" );
136 if (! is_file ( $conf- > getConfigFileExt ())) {
137 // Ensure Shaarli has proper access to its resources
138 $errors = ApplicationUtils
:: checkResourcePermissions ( $conf );
140 if ( $errors != array ()) {
141 $message = '<p>Insufficient permissions:</p><ul>' ;
143 foreach ( $errors as $error ) {
144 $message .= '<li>' . $error . '</li>' ;
148 header ( 'Content-Type: text/html; charset=utf-8' );
153 // Display the installation form if no existing config is found
157 // a token depending of deployment salt, user password, and the current ip
158 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $conf- > get ( 'credentials.hash' ) . $_SERVER [ 'REMOTE_ADDR' ] . $conf- > get ( 'credentials.salt' )));
160 // Sniff browser language and set date format accordingly.
161 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
162 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
164 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
167 * Checking session state (i.e. is the user still logged in)
169 * @param ConfigManager $conf The configuration manager.
171 * @return bool: true if the user is logged in, false otherwise.
173 function setup_login_state ( $conf )
175 if ( $conf- > get ( 'security.open_shaarli' )) {
178 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
179 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
180 if (! $conf- > exists ( 'credentials.login' )) {
181 $userIsLoggedIn = false ; // Shaarli is not configured yet.
182 $loginFailure = true ;
184 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
185 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
188 fillSessionInfo ( $conf );
189 $userIsLoggedIn = true ;
191 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
192 if ( empty ( $_SESSION [ 'uid' ])
193 || ( $conf- > get ( 'security.session_protection_disabled' ) == false && $_SESSION [ 'ip' ] != allIPs ())
194 || time () >= $_SESSION [ 'expires_on' ])
197 $userIsLoggedIn = false ;
198 $loginFailure = true ;
200 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
201 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
204 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
206 if (! $loginFailure ) {
207 $userIsLoggedIn = true ;
210 return $userIsLoggedIn ;
212 $userIsLoggedIn = setup_login_state ( $conf );
215 * PubSubHubbub protocol support (if enabled) [UNTESTED]
216 * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
218 * @param ConfigManager $conf Configuration Manager instance.
220 function pubsubhub ( $conf )
222 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
225 include_once './publisher.php' ;
226 $p = new Publisher ( $pshUrl );
228 index_url ( $_SERVER ). '?do=atom' ,
229 index_url ( $_SERVER ). '?do=rss'
231 $p- > publish_update ( $topic_url );
235 // ------------------------------------------------------------------------------------------
236 // Session management
238 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
241 $ip = $_SERVER [ 'REMOTE_ADDR' ];
242 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
243 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
244 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
251 * @param ConfigManager $conf Configuration Manager instance.
253 function fillSessionInfo ( $conf )
255 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
256 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
257 $_SESSION [ 'username' ]= $conf- > get ( 'credentials.login' );
258 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
262 * Check that user/password is correct.
264 * @param string $login Username
265 * @param string $password User password
266 * @param ConfigManager $conf Configuration Manager instance.
268 * @return bool: authentication successful or not.
270 function check_auth ( $login , $password , $conf )
272 $hash = sha1 ( $password . $login . $conf- > get ( 'credentials.salt' ));
273 if ( $login == $conf- > get ( 'credentials.login' ) && $hash == $conf- > get ( 'credentials.hash' ))
274 { // Login/password is correct.
275 fillSessionInfo ( $conf );
276 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
279 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
283 // Returns true if the user is logged in.
284 function isLoggedIn ()
286 global $userIsLoggedIn ;
287 return $userIsLoggedIn ;
292 if ( isset ( $_SESSION )) {
293 unset ( $_SESSION [ 'uid' ]);
294 unset ( $_SESSION [ 'ip' ]);
295 unset ( $_SESSION [ 'username' ]);
296 unset ( $_SESSION [ 'privateonly' ]);
298 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
302 // ------------------------------------------------------------------------------------------
303 // Brute force protection system
304 // Several consecutive failed logins will ban the IP address for 30 minutes.
305 if (! is_file ( $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ))) {
308 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
309 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>"
312 include $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' );
314 * Signal a failed login. Will ban the IP if too many failures:
316 * @param ConfigManager $conf Configuration Manager instance.
318 function ban_loginFailed ( $conf )
320 $ip = $_SERVER [ 'REMOTE_ADDR' ];
321 $trusted = $conf- > get ( 'security.trusted_proxies' , array ());
322 if ( in_array ( $ip , $trusted )) {
323 $ip = getIpAddressFromProxy ( $_SERVER , $trusted );
328 $gb = $GLOBALS [ 'IPBANS' ];
329 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) {
330 $gb [ 'FAILURES' ][ $ip ]= 0 ;
332 $gb [ 'FAILURES' ][ $ip ] ++
;
333 if ( $gb [ 'FAILURES' ][ $ip ] > ( $conf- > get ( 'security.ban_after' ) - 1 ))
335 $gb [ 'BANS' ][ $ip ] = time () +
$conf- > get ( 'security.ban_after' , 1800 );
336 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
338 $GLOBALS [ 'IPBANS' ] = $gb ;
340 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
341 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
346 * Signals a successful login. Resets failed login counter.
348 * @param ConfigManager $conf Configuration Manager instance.
350 function ban_loginOk ( $conf )
352 $ip = $_SERVER [ 'REMOTE_ADDR' ];
353 $gb = $GLOBALS [ 'IPBANS' ];
354 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
355 $GLOBALS [ 'IPBANS' ] = $gb ;
357 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
358 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
363 * Checks if the user CAN login. If 'true', the user can try to login.
365 * @param ConfigManager $conf Configuration Manager instance.
367 * @return bool: true if the user is allowed to login.
369 function ban_canLogin ( $conf )
371 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
372 if ( isset ( $gb [ 'BANS' ][ $ip ]))
374 // User is banned. Check if the ban has expired:
375 if ( $gb [ 'BANS' ][ $ip ]<= time ())
376 { // Ban expired, user can try to login again.
377 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
378 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
380 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
381 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
383 return true ; // Ban has expired, user can login.
385 return false ; // User is banned.
387 return true ; // User is not banned.
390 // ------------------------------------------------------------------------------------------
391 // Process login form: Check if login/password is correct.
392 if ( isset ( $_POST [ 'login' ]))
394 if (! ban_canLogin ( $conf )) die ( 'I said: NO. You are banned for the moment. Go away.' );
395 if ( isset ( $_POST [ 'password' ])
396 && tokenOk ( $_POST [ 'token' ])
397 && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ], $conf ))
398 ) { // Login/password is OK.
400 // If user wants to keep the session cookie even after the browser closes:
401 if (! empty ( $_POST [ 'longlastingsession' ]))
403 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
404 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
405 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
407 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
408 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
409 // Note: Never forget the trailing slash on the cookie path!
410 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
412 else // Standard session expiration (=when browser closes)
414 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
415 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
416 session_regenerate_id ( true );
419 // Optional redirect after login:
420 if ( isset ( $_GET [ 'post' ])) {
421 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
422 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
423 if (! empty ( $_GET [ $param ])) {
424 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
427 header ( 'Location: ' . $uri );
431 if ( isset ( $_GET [ 'edit_link' ])) {
432 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
436 if ( isset ( $_POST [ 'returnurl' ])) {
437 // Prevent loops over login screen.
438 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
439 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
443 header ( 'Location: ?' ); exit ;
447 ban_loginFailed ( $conf );
448 $redir = '&username=' . $_POST [ 'login' ];
449 if ( isset ( $_GET [ 'post' ])) {
450 $redir .= '&post=' . urlencode ( $_GET [ 'post' ]);
451 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
452 if (! empty ( $_GET [ $param ])) {
453 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
457 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
462 // ------------------------------------------------------------------------------------------
463 // Misc utility functions:
465 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
466 function return_bytes ( $val )
468 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
471 case 'g' : $val *= 1024 ;
472 case 'm' : $val *= 1024 ;
473 case 'k' : $val *= 1024 ;
478 // Try to determine max file size for uploads (POST).
479 // Returns an integer (in bytes)
480 function getMaxFileSize ()
482 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
483 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
484 // Return the smaller of two:
485 $maxsize = min ( $size1 , $size2 );
486 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
490 // ------------------------------------------------------------------------------------------
491 // Token management for XSRF protection
492 // Token should be used in any form which acts on data (create,update,delete,import...).
493 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
498 * @param ConfigManager $conf Configuration Manager instance.
500 * @return string token.
502 function getToken ( $conf )
504 $rnd = sha1 ( uniqid ( '' , true ) . '_' . mt_rand () . $conf- > get ( 'credentials.salt' )); // We generate a random string.
505 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
509 // Tells if a token is OK. Using this function will destroy the token.
511 function tokenOk ( $token )
513 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
515 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
516 return true ; // Token is OK.
518 return false ; // Wrong token, or already used.
522 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
523 * Gives the last 7 days (which have links).
524 * This RSS feed cannot be filtered.
526 * @param ConfigManager $conf Configuration Manager instance.
528 function showDailyRSS ( $conf ) {
530 $query = $_SERVER [ 'QUERY_STRING' ];
531 $cache = new CachedPage (
532 $conf- > get ( 'config.PAGE_CACHE' ),
534 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
536 $cached = $cache- > cachedVersion ();
537 if (! empty ( $cached )) {
542 // If cached was not found (or not usable), then read the database and build the response:
543 // Read links from database (and filter private links if used it not logged in).
544 $LINKSDB = new LinkDB (
545 $conf- > get ( 'resource.datastore' ),
547 $conf- > get ( 'privacy.hide_public_links' ),
548 $conf- > get ( 'redirector.url' ),
549 $conf- > get ( 'redirector.encode_url' )
552 /* Some Shaarlies may have very few links, so we need to look
553 back in time (rsort()) until we have enough days ($nb_of_days).
555 $linkdates = array ();
556 foreach ( $LINKSDB as $linkdate => $value ) {
557 $linkdates [] = $linkdate ;
560 $nb_of_days = 7 ; // We take 7 days.
561 $today = date ( 'Ymd' );
564 foreach ( $linkdates as $linkdate ) {
565 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
566 if ( strcmp ( $day , $today ) < 0 ) {
567 if ( empty ( $days [ $day ])) {
568 $days [ $day ] = array ();
570 $days [ $day ][] = $linkdate ;
573 if ( count ( $days ) > $nb_of_days ) {
574 break ; // Have we collected enough days?
578 // Build the RSS feed.
579 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
580 $pageaddr = escape ( index_url ( $_SERVER ));
581 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
583 echo '<title>Daily - ' . $conf- > get ( 'general.title' ) . '</title>' ;
584 echo '<link>' . $pageaddr . '</link>' ;
585 echo '<description>Daily shared links</description>' ;
586 echo '<language>en-en</language>' ;
587 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
590 foreach ( $days as $day => $linkdates ) {
591 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
592 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
594 // Build the HTML body of this RSS entry.
599 // We pre-format some fields for proper output.
600 foreach ( $linkdates as $linkdate ) {
601 $l = $LINKSDB [ $linkdate ];
602 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $conf- > get ( 'redirector.url' ));
603 $l [ 'thumbnail' ] = thumbnail ( $conf , $l [ 'url' ]);
604 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
605 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
606 if ( startsWith ( $l [ 'url' ], '?' )) {
607 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
609 $links [ $linkdate ] = $l ;
612 // Then build the HTML for this day:
614 $tpl- > assign ( 'title' , $conf- > get ( 'general.title' ));
615 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
616 $tpl- > assign ( 'absurl' , $absurl );
617 $tpl- > assign ( 'links' , $links );
618 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
619 $tpl- > assign ( 'hide_timestamps' , $conf- > get ( 'privacy.hide_timestamps' , false ));
620 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
622 echo $html . PHP_EOL
;
624 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
626 $cache- > cache ( ob_get_contents ());
632 * Show the 'Daily' page.
634 * @param PageBuilder $pageBuilder Template engine wrapper.
635 * @param LinkDB $LINKSDB LinkDB instance.
636 * @param ConfigManager $conf Configuration Manager instance.
637 * @param PluginManager $pluginManager Plugin Manager instane.
639 function showDaily ( $pageBuilder , $LINKSDB , $conf , $pluginManager )
641 $day = date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
642 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
644 $days = $LINKSDB- > days ();
645 $i = array_search ( $day , $days );
646 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
651 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
652 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
656 $linksToDisplay = $LINKSDB- > filterDay ( $day );
657 } catch ( Exception
$exc ) {
659 $linksToDisplay = array ();
662 // We pre-format some fields for proper output.
663 foreach ( $linksToDisplay as $key => $link )
666 $taglist = explode ( ' ' , $link [ 'tags' ]);
667 uasort ( $taglist , 'strcasecmp' );
668 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
669 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
670 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $conf , $link [ 'url' ]);
671 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
672 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
675 /* We need to spread the articles on 3 columns.
676 I did not want to use a JavaScript lib like http://masonry.desandro.com/
677 so I manually spread entries with a simple method: I roughly evaluate the
678 height of a div according to title and description length.
680 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
681 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
682 foreach ( $linksToDisplay as $key => $link )
684 // Roughly estimate length of entry (by counting characters)
685 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
686 // Description: 836 characters gives roughly 342 pixel height.
687 // This is not perfect, but it's usually OK.
688 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
689 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
690 // Then put in column which is the less filled:
691 $smallest = min ( $fill ); // find smallest value in array.
692 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
693 array_push ( $columns [ $index ], $link ); // Put entry in this column.
694 $fill [ $index ] +
= $length ;
697 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
699 'linksToDisplay' => $linksToDisplay ,
701 'day' => $dayDate- > getTimestamp (),
702 'previousday' => $previousday ,
703 'nextday' => $nextday ,
706 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
708 foreach ( $data as $key => $value ) {
709 $pageBuilder- > assign ( $key , $value );
712 $pageBuilder- > renderPage ( 'daily' );
717 * Renders the linklist
719 * @param pageBuilder $PAGE pageBuilder instance.
720 * @param LinkDB $LINKSDB LinkDB instance.
721 * @param ConfigManager $conf Configuration Manager instance.
722 * @param PluginManager $pluginManager Plugin Manager instance.
724 function showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ) {
725 buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ); // Compute list of links to display
726 $PAGE- > renderPage ( 'linklist' );
730 * Render HTML page (according to URL parameters and user rights)
732 * @param ConfigManager $conf Configuration Manager instance.
733 * @param PluginManager $pluginManager Plugin Manager instance,
735 function renderPage ( $conf , $pluginManager )
737 $LINKSDB = new LinkDB (
738 $conf- > get ( 'resource.datastore' ),
740 $conf- > get ( 'privacy.hide_public_links' ),
741 $conf- > get ( 'redirector.url' ),
742 $conf- > get ( 'redirector.encode_url' )
745 $updater = new Updater (
746 read_updates_file ( $conf- > get ( 'resource.updates' )),
752 $newUpdates = $updater- > update ();
753 if (! empty ( $newUpdates )) {
755 $conf- > get ( 'resource.updates' ),
756 $updater- > getDoneUpdates ()
760 catch ( Exception
$e ) {
761 die ( $e- > getMessage ());
764 $PAGE = new PageBuilder ( $conf );
765 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
766 $PAGE- > assign ( 'privateLinkcount' , count_private ( $LINKSDB ));
768 // Determine which page will be rendered.
769 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
770 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
772 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
773 // Then assign generated data to RainTPL.
774 $common_hooks = array (
780 foreach ( $common_hooks as $name ) {
781 $plugin_data = array ();
782 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
784 'target' => $targetPage ,
785 'loggedin' => isLoggedIn ()
788 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
791 // -------- Display login form.
792 if ( $targetPage == Router
:: $PAGE_LOGIN )
794 if ( $conf- > get ( 'security.open_shaarli' )) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
795 $token = '' ; if ( ban_canLogin ( $conf )) $token = getToken ( $conf ); // Do not waste token generation if not useful.
796 $PAGE- > assign ( 'token' , $token );
797 if ( isset ( $_GET [ 'username' ])) {
798 $PAGE- > assign ( 'username' , escape ( $_GET [ 'username' ]));
800 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
801 $PAGE- > renderPage ( 'loginform' );
804 // -------- User wants to logout.
805 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=logout' ))
807 invalidateCaches ( $conf- > get ( 'resource.page_cache' ));
809 header ( 'Location: ?' );
813 // -------- Picture wall
814 if ( $targetPage == Router
:: $PAGE_PICWALL )
816 // Optionally filter the results:
817 $links = $LINKSDB- > filterSearch ( $_GET );
818 $linksToDisplay = array ();
820 // Get only links which have a thumbnail.
821 foreach ( $links as $link )
823 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
824 $thumb = lazyThumbnail ( $conf , $link [ 'url' ], $permalink );
825 if ( $thumb != '' ) // Only output links which have a thumbnail.
827 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
828 $linksToDisplay []= $link ; // Add to array.
833 'linksToDisplay' => $linksToDisplay ,
835 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
837 foreach ( $data as $key => $value ) {
838 $PAGE- > assign ( $key , $value );
841 $PAGE- > renderPage ( 'picwall' );
845 // -------- Tag cloud
846 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
848 $tags = $LINKSDB- > allTags ();
850 // We sort tags alphabetically, then choose a font size according to count.
851 // First, find max value.
853 foreach ( $tags as $value ) {
854 $maxcount = max ( $maxcount , $value );
857 // Sort tags alphabetically: case insensitive, support locale if avalaible.
858 uksort ( $tags , function ( $a , $b ) {
859 // Collator is part of PHP intl.
860 if ( class_exists ( 'Collator' )) {
861 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
862 if (! intl_is_failure ( intl_get_error_code ())) {
863 return $c- > compare ( $a , $b );
866 return strcasecmp ( $a , $b );
870 foreach ( $tags as $key => $value ) {
871 // Tag font size scaling:
872 // default 15 and 30 logarithm bases affect scaling,
873 // 22 and 6 are arbitrary font sizes for max and min sizes.
874 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
875 $tagList [ $key ] = array (
877 'size' => number_format ( $size , 2 , '.' , '' ),
884 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
886 foreach ( $data as $key => $value ) {
887 $PAGE- > assign ( $key , $value );
890 $PAGE- > renderPage ( 'tagcloud' );
895 if ( $targetPage == Router
:: $PAGE_DAILY ) {
896 showDaily ( $PAGE , $LINKSDB , $conf , $pluginManager );
899 // ATOM and RSS feed.
900 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
901 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
902 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
905 $query = $_SERVER [ 'QUERY_STRING' ];
906 $cache = new CachedPage (
907 $conf- > get ( 'resource.page_cache' ),
909 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
911 $cached = $cache- > cachedVersion ();
912 if (! empty ( $cached )) {
918 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
919 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
920 $feedGenerator- > setHideDates ( $conf- > get ( 'privacy.hide_timestamps' ) && ! isLoggedIn ());
921 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $conf- > get ( 'feed.rss_permalinks' ));
922 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
923 if (! empty ( $pshUrl )) {
924 $feedGenerator- > setPubsubhubUrl ( $pshUrl );
926 $data = $feedGenerator- > buildData ();
928 // Process plugin hook.
929 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
930 'loggedin' => isLoggedIn (),
931 'target' => $targetPage ,
934 // Render the template.
935 $PAGE- > assignAll ( $data );
936 $PAGE- > renderPage ( 'feed.' . $feedType );
937 $cache- > cache ( ob_get_contents ());
942 // Display openseach plugin (XML)
943 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
944 header ( 'Content-Type: application/xml; charset=utf-8' );
945 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
946 $PAGE- > renderPage ( 'opensearch' );
950 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
951 if ( isset ( $_GET [ 'addtag' ]))
953 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
954 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
955 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
957 // Prevent redirection loop
958 if ( isset ( $params [ 'addtag' ])) {
959 unset ( $params [ 'addtag' ]);
962 // Check if this tag is already in the search query and ignore it if it is.
963 // Each tag is always separated by a space
964 if ( isset ( $params [ 'searchtags' ])) {
965 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
967 $current_tags = array ();
970 foreach ( $current_tags as $value ) {
971 if ( $value === $_GET [ 'addtag' ]) {
976 // Append the tag if necessary
977 if ( empty ( $params [ 'searchtags' ])) {
978 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
981 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
984 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
985 header ( 'Location: ?' . http_build_query ( $params ));
989 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
990 if ( isset ( $_GET [ 'removetag' ])) {
991 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
992 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
993 header ( 'Location: ?' );
997 // In case browser does not send HTTP_REFERER
998 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
1000 // Prevent redirection loop
1001 if ( isset ( $params [ 'removetag' ])) {
1002 unset ( $params [ 'removetag' ]);
1005 if ( isset ( $params [ 'searchtags' ])) {
1006 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1007 // Remove value from array $tags.
1008 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1009 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1011 if ( empty ( $params [ 'searchtags' ])) {
1012 unset ( $params [ 'searchtags' ]);
1015 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1017 header ( 'Location: ?' . http_build_query ( $params ));
1021 // -------- User wants to change the number of links per page (linksperpage=...)
1022 if ( isset ( $_GET [ 'linksperpage' ])) {
1023 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1024 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1027 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1031 // -------- User wants to see only private links (toggle)
1032 if ( isset ( $_GET [ 'privateonly' ])) {
1033 if ( empty ( $_SESSION [ 'privateonly' ])) {
1034 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1036 unset ( $_SESSION [ 'privateonly' ]); // See all links
1039 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1043 // -------- Handle other actions allowed for non-logged in users:
1046 // User tries to post new link but is not logged in:
1047 // Show login screen, then redirect to ?post=...
1048 if ( isset ( $_GET [ 'post' ]))
1050 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.
1054 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1055 if ( isset ( $_GET [ 'edit_link' ])) {
1056 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1060 exit ; // Never remove this one! All operations below are reserved for logged in user.
1063 // -------- All other functions are reserved for the registered user:
1065 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1066 if ( $targetPage == Router
:: $PAGE_TOOLS )
1069 'pageabsaddr' => index_url ( $_SERVER ),
1071 $pluginManager- > executeHooks ( 'render_tools' , $data );
1073 foreach ( $data as $key => $value ) {
1074 $PAGE- > assign ( $key , $value );
1077 $PAGE- > renderPage ( 'tools' );
1081 // -------- User wants to change his/her password.
1082 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1084 if ( $conf- > get ( 'security.open_shaarli' )) {
1085 die ( 'You are not supposed to change a password on an Open Shaarli.' );
1088 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1090 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1092 // Make sure old password is correct.
1093 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $conf- > get ( 'credentials.login' ). $conf- > get ( 'credentials.salt' ));
1094 if ( $oldhash != $conf- > get ( 'credentials.hash' )) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1095 // Save new password
1096 // Salt renders rainbow-tables attacks useless.
1097 $conf- > set ( 'credentials.salt' , sha1 ( uniqid ( '' , true ) . '_' . mt_rand ()));
1098 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $conf- > get ( 'credentials.login' ) . $conf- > get ( 'credentials.salt' )));
1100 $conf- > write ( isLoggedIn ());
1102 catch ( Exception
$e ) {
1104 'ERROR while writing config file after changing password.' . PHP_EOL
.
1108 // TODO: do not handle exceptions/errors in JS.
1109 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1112 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1115 else // show the change password form.
1117 $PAGE- > assign ( 'token' , getToken ( $conf ));
1118 $PAGE- > renderPage ( 'changepassword' );
1123 // -------- User wants to change configuration
1124 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1126 if (! empty ( $_POST [ 'title' ]) )
1128 if (! tokenOk ( $_POST [ 'token' ])) {
1129 die ( 'Wrong token.' ); // Go away!
1132 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1133 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1135 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1137 $conf- > set ( 'general.timezone' , $tz );
1138 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
1139 $conf- > set ( 'general.header_link' , escape ( $_POST [ 'titleLink' ]));
1140 $conf- > set ( 'redirector.url' , escape ( $_POST [ 'redirector' ]));
1141 $conf- > set ( 'security.session_protection_disabled' , ! empty ( $_POST [ 'disablesessionprotection' ]));
1142 $conf- > set ( 'privacy.default_private_links' , ! empty ( $_POST [ 'privateLinkByDefault' ]));
1143 $conf- > set ( 'feed.rss_permalinks' , ! empty ( $_POST [ 'enableRssPermalinks' ]));
1144 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
1145 $conf- > set ( 'privacy.hide_public_links' , ! empty ( $_POST [ 'hidePublicLinks' ]));
1147 $conf- > write ( isLoggedIn ());
1149 catch ( Exception
$e ) {
1151 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1155 // TODO: do not handle exceptions/errors in JS.
1156 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=configure \' ;</script>' ;
1159 echo '<script>alert("Configuration was saved.");document.location= \' ?do=configure \' ;</script>' ;
1162 else // Show the configuration form.
1164 $PAGE- > assign ( 'token' , getToken ( $conf ));
1165 $PAGE- > assign ( 'title' , $conf- > get ( 'general.title' ));
1166 $PAGE- > assign ( 'redirector' , $conf- > get ( 'redirector.url' ));
1167 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $conf- > get ( 'general.timezone' ));
1168 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1169 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1170 $PAGE- > assign ( 'private_links_default' , $conf- > get ( 'privacy.default_private_links' , false ));
1171 $PAGE- > assign ( 'session_protection_disabled' , $conf- > get ( 'security.session_protection_disabled' , false ));
1172 $PAGE- > assign ( 'enable_rss_permalinks' , $conf- > get ( 'feed.rss_permalinks' , false ));
1173 $PAGE- > assign ( 'enable_update_check' , $conf- > get ( 'updates.check_updates' , true ));
1174 $PAGE- > assign ( 'hide_public_links' , $conf- > get ( 'privacy.hide_public_links' , false ));
1175 $PAGE- > renderPage ( 'configure' );
1180 // -------- User wants to rename a tag or delete it
1181 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1183 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1184 $PAGE- > assign ( 'token' , getToken ( $conf ));
1185 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1186 $PAGE- > renderPage ( 'changetag' );
1190 if (! tokenOk ( $_POST [ 'token' ])) {
1191 die ( 'Wrong token.' );
1195 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1196 $needle = trim ( $_POST [ 'fromtag' ]);
1197 // True for case-sensitive tag search.
1198 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1199 foreach ( $linksToAlter as $key => $value )
1201 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1202 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1203 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1204 $LINKSDB [ $key ]= $value ;
1206 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1207 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1212 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1213 $needle = trim ( $_POST [ 'fromtag' ]);
1214 // True for case-sensitive tag search.
1215 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1216 foreach ( $linksToAlter as $key => $value )
1218 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1219 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1220 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1221 $LINKSDB [ $key ]= $value ;
1223 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' )); // Save to disk.
1224 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1229 // -------- User wants to add a link without using the bookmarklet: Show form.
1230 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1232 $PAGE- > renderPage ( 'addlink' );
1236 // -------- User clicked the "Save" button when editing a link: Save link to database.
1237 if ( isset ( $_POST [ 'save_edit' ]))
1240 if (! tokenOk ( $_POST [ 'token' ])) {
1241 die ( 'Wrong token.' );
1243 // Remove multiple spaces.
1244 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1245 // Remove first '-' char in tags.
1246 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1247 // Remove duplicates.
1248 $tags = implode(' ', array_unique(explode(' ', $tags )));
1249 $linkdate = $_POST [' lf_linkdate
'];
1250 $url = trim( $_POST [' lf_url
']);
1251 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1252 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1253 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1255 $url = ' http
: //' . $url;
1259 'title' => trim ( $_POST [ 'lf_title' ]),
1261 'description' => $_POST [ 'lf_description' ],
1262 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1263 'linkdate' => $linkdate ,
1264 'tags' => str_replace ( ',' , ' ' , $tags )
1266 // If title is empty, use the URL as title.
1267 if ( $link [ 'title' ] == '' ) {
1268 $link [ 'title' ] = $link [ 'url' ];
1271 $pluginManager- > executeHooks ( 'save_link' , $link );
1273 $LINKSDB [ $linkdate ] = $link ;
1274 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1277 // If we are called from the bookmarklet, we must close the popup:
1278 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1279 echo '<script>self.close();</script>' ;
1283 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1284 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1285 // Scroll to the link which has been edited.
1286 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1287 // After saving the link, redirect to the page the user was on.
1288 header ( 'Location: ' . $location );
1292 // -------- User clicked the "Cancel" button when editing a link.
1293 if ( isset ( $_POST [ 'cancel_edit' ]))
1295 // If we are called from the bookmarklet, we must close the popup:
1296 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1297 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1298 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1299 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1300 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1304 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1305 if ( isset ( $_POST [ 'delete_link' ]))
1307 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1308 // We do not need to ask for confirmation:
1309 // - confirmation is handled by JavaScript
1310 // - we are protected from XSRF by the token.
1311 $linkdate = $_POST [ 'lf_linkdate' ];
1313 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1315 unset ( $LINKSDB [ $linkdate ]);
1316 $LINKSDB- > savedb ( 'resource.page_cache' ); // save to disk
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 // Pick where we're going to redirect
1321 // =============================================================
1322 // Basically, we can't redirect to where we were previously if it was a permalink
1323 // or an edit_link, because it would 404.
1325 // - / : nothing in $_GET, redirect to self
1326 // - /?page : redirect to self
1327 // - /?searchterm : redirect to self (there might be other links)
1328 // - /?searchtags : redirect to self
1329 // - /permalink : redirect to / (the link does not exist anymore)
1330 // - /?edit_link : redirect to / (the link does not exist anymore)
1331 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1332 // redirect is not satisfied, and only then redirect to /
1335 if ( count ( $_GET ) == 0
1336 || isset ( $_GET [ 'page' ])
1337 || isset ( $_GET [ 'searchterm' ])
1338 || isset ( $_GET [ 'searchtags' ])
1340 if ( isset ( $_POST [ 'returnurl' ])) {
1341 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1343 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1347 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1351 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1352 if ( isset ( $_GET [ 'edit_link' ]))
1354 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1355 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1358 'link_is_new' => false ,
1359 'token' => getToken ( $conf ),
1360 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1361 'tags' => $LINKSDB- > allTags (),
1363 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1365 foreach ( $data as $key => $value ) {
1366 $PAGE- > assign ( $key , $value );
1369 $PAGE- > renderPage ( 'editlink' );
1373 // -------- User want to post a new link: Display link edit form.
1374 if ( isset ( $_GET [ 'post' ])) {
1375 $url = cleanup_url ( $_GET [ 'post' ]);
1377 $link_is_new = false ;
1378 // Check if URL is not already in database (in this case, we will edit the existing link)
1379 $link = $LINKSDB- > getLinkFromUrl ( $url );
1382 $link_is_new = true ;
1383 $linkdate = strval ( date ( 'Ymd_His' ));
1384 // Get title if it was provided in URL (by the bookmarklet).
1385 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1386 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1387 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1388 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1389 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1390 // 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.)
1391 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1392 // Short timeout to keep the application responsive
1393 list ( $headers , $content ) = get_http_response ( $url , 4 );
1394 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1395 // Retrieve charset.
1396 $charset = get_charset ( $headers , $content );
1398 $title = html_extract_title ( $content );
1399 // Re-encode title in utf-8 if necessary.
1400 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1401 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1407 $url = '?' . smallHash ( $linkdate );
1410 $url = escape ( $url );
1411 $title = escape ( $title );
1414 'linkdate' => $linkdate ,
1417 'description' => $description ,
1419 'private' => $private
1425 'link_is_new' => $link_is_new ,
1426 'token' => getToken ( $conf ), // XSRF protection.
1427 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1428 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1429 'tags' => $LINKSDB- > allTags (),
1430 'default_private_links' => $conf- > get ( 'default_private_links' , false ),
1432 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1434 foreach ( $data as $key => $value ) {
1435 $PAGE- > assign ( $key , $value );
1438 $PAGE- > renderPage ( 'editlink' );
1442 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1443 // Export links as a Netscape Bookmarks file
1445 if ( empty ( $_GET [ 'selection' ])) {
1446 $PAGE- > renderPage ( 'export' );
1450 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1451 $selection = $_GET [ 'selection' ];
1452 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1453 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1455 $prependNoteUrl = false ;
1461 NetscapeBookmarkUtils
:: filterAndFormat (
1468 } catch ( Exception
$exc ) {
1469 header ( 'Content-Type: text/plain; charset=utf-8' );
1470 echo $exc- > getMessage ();
1473 $now = new DateTime ();
1474 header ( 'Content-Type: text/html; charset=utf-8' );
1476 'Content-disposition: attachment; filename=bookmarks_'
1477 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1479 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1480 $PAGE- > assign ( 'eol' , PHP_EOL
);
1481 $PAGE- > assign ( 'selection' , $selection );
1482 $PAGE- > renderPage ( 'export.bookmarks' );
1486 // -------- User is uploading a file for import
1487 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=upload' ))
1489 // If file is too big, some form field may be missing.
1490 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1492 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1493 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>' ;
1496 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1497 importFile ( $LINKSDB );
1501 // -------- Show upload/import dialog:
1502 if ( $targetPage == Router
:: $PAGE_IMPORT )
1504 $PAGE- > assign ( 'token' , getToken ( $conf ));
1505 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1506 $PAGE- > renderPage ( 'import' );
1510 // Plugin administration page
1511 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1512 $pluginMeta = $pluginManager- > getPluginsMeta ();
1514 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1515 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1517 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $conf- > get ( 'plugins' , array ()));
1520 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1522 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1524 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1525 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1526 $PAGE- > renderPage ( 'pluginsadmin' );
1530 // Plugin administration form action
1531 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1533 if ( isset ( $_POST [ 'parameters_form' ])) {
1534 unset ( $_POST [ 'parameters_form' ]);
1535 foreach ( $_POST as $param => $value ) {
1536 $conf- > set ( 'plugins.' . $param , escape ( $value ));
1540 $conf- > set ( 'general.enabled_plugins' , save_plugin_config ( $_POST ));
1542 $conf- > write ( isLoggedIn ());
1544 catch ( Exception
$e ) {
1546 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1550 // TODO: do not handle exceptions/errors in JS.
1551 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1554 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1558 // -------- Otherwise, simply display search form and links:
1559 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1564 * Process the import file form.
1566 * @param LinkDB $LINKSDB Loaded LinkDB instance.
1567 * @param ConfigManager $conf Configuration Manager instance.
1569 function importFile ( $LINKSDB , $conf )
1571 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1573 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1574 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1575 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1576 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1577 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1582 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1584 // Then import the bookmarks.
1585 if ( $type == 'netscape' )
1587 // This is a standard Netscape-style bookmark file.
1588 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1589 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1591 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1592 $d = explode ( '<DD>' , $html );
1593 if ( startsWith ( $d [ 0 ], '<A ' ))
1595 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1596 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1597 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1598 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1600 foreach ( $matches as $m )
1602 $attr = $m [ 1 ]; $value = $m [ 2 ];
1603 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1604 elseif ( $attr == 'ADD_DATE' )
1606 $raw_add_date = intval ( $value );
1607 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1609 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1610 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1612 if ( $link [ 'url' ]!= '' )
1614 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1615 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1617 { // Link not in database, let's import it...
1618 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1620 // Make sure date/time is not already used by another link.
1621 // (Some bookmark files have several different links with the same ADD_DATE)
1622 // We increment date by 1 second until we find a date which is not used in DB.
1623 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1624 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1625 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1626 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1629 else // Link already present in database.
1632 { // If overwrite is required, we import link data, except date/time.
1633 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1634 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1642 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1644 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1648 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1653 * Template for the list of links (<div id="linklist">)
1654 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1656 * @param pageBuilder $PAGE pageBuilder instance.
1657 * @param LinkDB $LINKSDB LinkDB instance.
1658 * @param ConfigManager $conf Configuration Manager instance.
1659 * @param PluginManager $pluginManager Plugin Manager instance.
1661 function buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager )
1663 // Used in templates
1664 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1665 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1668 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1669 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1671 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1672 } catch ( LinkNotFoundException
$e ) {
1673 $PAGE- > render404 ( $e- > getMessage ());
1677 // Filter links according search parameters.
1678 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1679 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1682 // ---- Handle paging.
1684 foreach ( $linksToDisplay as $key => $value ) {
1690 // Select articles according to paging.
1691 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1692 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1693 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1694 $page = $page < 1 ? 1 : $page ;
1695 $page = $page > $pagecount ? $pagecount : $page ;
1697 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1698 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1699 $linkDisp = array ();
1700 while ( $i < $end && $i < count ( $keys ))
1702 $link = $linksToDisplay [ $keys [ $i ]];
1703 $link [ 'description' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
1704 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1705 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1706 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1707 $link [ 'timestamp' ] = $date- > getTimestamp ();
1708 $taglist = explode ( ' ' , $link [ 'tags' ]);
1709 uasort ( $taglist , 'strcasecmp' );
1710 $link [ 'taglist' ] = $taglist ;
1711 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1712 // Check for both signs of a note: starting with ? and 7 chars long.
1713 if ( $link [ 'url' ][ 0 ] === '?' &&
1714 strlen ( $link [ 'url' ]) === 7 ) {
1715 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1718 $linkDisp [ $keys [ $i ]] = $link ;
1722 // Compute paging navigation
1723 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1724 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1725 $previous_page_url = '' ;
1726 if ( $i != count ( $keys )) {
1727 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1731 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1734 $token = isLoggedIn () ? getToken ( $conf ) : '' ;
1736 // Fill all template fields.
1738 'previous_page_url' => $previous_page_url ,
1739 'next_page_url' => $next_page_url ,
1740 'page_current' => $page ,
1741 'page_max' => $pagecount ,
1742 'result_count' => count ( $linksToDisplay ),
1743 'search_term' => $searchterm ,
1744 'search_tags' => $searchtags ,
1745 'redirector' => $conf- > get ( 'redirector.url' ), // Optional redirector URL.
1747 'links' => $linkDisp ,
1748 'tags' => $LINKSDB- > allTags (),
1751 // If there is only a single link, we change on-the-fly the title of the page.
1752 if ( count ( $linksToDisplay ) == 1 ) {
1753 $data [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ] . ' - ' . $conf- > get ( 'general.title' );
1756 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1758 foreach ( $data as $key => $value ) {
1759 $PAGE- > assign ( $key , $value );
1766 * Compute the thumbnail for a link.
1768 * With a link to the original URL.
1769 * Understands various services (youtube.com...)
1770 * Input: $url = URL for which the thumbnail must be found.
1771 * $href = if provided, this URL will be followed instead of $url
1772 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1773 * Some of them may be missing.
1774 * Return an empty array if no thumbnail available.
1776 * @param ConfigManager $conf Configuration Manager instance.
1777 * @param string $url
1778 * @param string|bool $href
1782 function computeThumbnail ( $conf , $url , $href = false )
1784 if (! $conf- > get ( 'thumbnail.enable_thumbnails' )) return array ();
1785 if ( $href == false ) $href = $url ;
1787 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1788 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1789 // ^^^^^^^^^^^ ^^^^^^^^^^^
1790 $domain = parse_url ( $url , PHP_URL_HOST
);
1791 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1793 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1794 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1795 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1797 if ( $domain == 'youtu.be' ) // Youtube short links
1799 $path = parse_url ( $url , PHP_URL_PATH
);
1800 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1801 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1803 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1805 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1806 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1807 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1810 if ( $domain == 'imgur.com' )
1812 $path = parse_url ( $url , PHP_URL_PATH
);
1813 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1814 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1815 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1816 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1817 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1819 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1820 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1822 if ( $domain == 'i.imgur.com' )
1824 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1825 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1826 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1828 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1830 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1832 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1833 return array ( 'src' => $thumburl ,
1834 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1837 if ( endsWith ( $domain , '.imageshack.us' ))
1839 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1840 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1842 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1843 return array ( 'src' => $thumburl ,
1844 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1848 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1849 // So we deport the thumbnail generation in order not to slow down page generation
1850 // (and we also cache the thumbnail)
1852 if (! $conf- > get ( 'thumbnail.enable_localcache' )) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1854 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1855 || $domain == 'vimeo.com'
1856 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1857 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1860 if ( $domain == 'vimeo.com' )
1861 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1862 $path = parse_url ( $url , PHP_URL_PATH
);
1863 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1865 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1866 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1867 $path = parse_url ( $url , PHP_URL_PATH
);
1868 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1870 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1871 { // Make sure this TED URL points to a video (/talks/...)
1872 $path = parse_url ( $url , PHP_URL_PATH
);
1873 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1875 $sign = hash_hmac ( 'sha256' , $url , $conf- > get ( 'credentials.salt' )); // We use the salt to sign data (it's random, secret, and specific to each installation)
1876 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1877 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1880 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1881 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1882 // But using the extension will do.
1883 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1884 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1886 $sign = hash_hmac ( 'sha256' , $url , $conf- > get ( 'credentials.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' );
1890 return array (); // No thumbnail.
1895 // Returns the HTML code to display a thumbnail for a link
1896 // with a link to the original URL.
1897 // Understands various services (youtube.com...)
1898 // Input: $url = URL for which the thumbnail must be found.
1899 // $href = if provided, this URL will be followed instead of $url
1900 // Returns '' if no thumbnail available.
1901 function thumbnail ( $url , $href = false )
1905 $t = computeThumbnail ( $conf , $url , $href );
1906 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1908 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
1909 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1910 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1911 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1912 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1917 // Returns the HTML code to display a thumbnail for a link
1918 // for the picture wall (using lazy image loading)
1919 // Understands various services (youtube.com...)
1920 // Input: $url = URL for which the thumbnail must be found.
1921 // $href = if provided, this URL will be followed instead of $url
1922 // Returns '' if no thumbnail available.
1923 function lazyThumbnail ( $conf , $url , $href = false )
1927 $t = computeThumbnail ( $conf , $url , $href );
1928 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1930 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
1933 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
1935 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1936 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1937 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1938 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1941 // No-JavaScript fallback.
1942 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
1943 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1944 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1945 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1946 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1947 $html .= '></noscript></a>' ;
1955 * This function should NEVER be called if the file data/config.php exists.
1957 * @param ConfigManager $conf Configuration Manager instance.
1959 function install ( $conf )
1961 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1962 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1965 // This part makes sure sessions works correctly.
1966 // (Because on some hosts, session.save_path may not be set correctly,
1967 // or we may not have write access to it.)
1968 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
1969 { // Step 2: Check if data in session is correct.
1970 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
1971 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
1972 echo 'It currently points to ' . session_save_path (). '<br>' ;
1973 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>' ;
1974 echo '<br><a href="?">Click to try again.</a></pre>' ;
1977 if (! isset ( $_SESSION [ 'session_tested' ]))
1978 { // Step 1 : Try to store data in session and reload page.
1979 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
1980 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
1982 if ( isset ( $_GET [ 'test_session' ]))
1983 { // Step 3: Sessions are OK. Remove test parameter from URL.
1984 header ( 'Location: ' . index_url ( $_SERVER ));
1988 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1991 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1992 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1994 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1996 $conf- > set ( 'general.timezone' , $tz );
1997 $login = $_POST [ 'setlogin' ];
1998 $conf- > set ( 'credentials.login' , $login );
1999 $salt = sha1 ( uniqid ( '' , true ) . '_' . mt_rand ());
2000 $conf- > set ( 'credentials.salt' , $salt );
2001 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $login . $salt ));
2002 if (! empty ( $_POST [ 'title' ])) {
2003 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
2005 $conf- > set ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
2007 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
2009 // Everything is ok, let's create config file.
2010 $conf- > write ( isLoggedIn ());
2012 catch ( Exception
$e ) {
2014 'ERROR while writing config file after installation.' . PHP_EOL
.
2018 // TODO: do not handle exceptions/errors in JS.
2019 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2022 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2026 // Display config form:
2027 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2028 $timezone_html = '' ;
2029 if ( $timezone_form != '' ) {
2030 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2033 $PAGE = new PageBuilder ( $conf );
2034 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2035 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2036 $PAGE- > renderPage ( 'install' );
2041 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2042 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2043 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2044 * This function is called by passing the URL:
2045 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2046 * [URL] is the URL of the link (e.g. a flickr page)
2047 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2048 * The function below will fetch the image from the webservice and store it in the cache.
2050 * @param ConfigManager $conf Configuration Manager instance,
2052 function genThumbnail ( $conf )
2054 // Make sure the parameters in the URL were generated by us.
2055 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $conf- > get ( 'credentials.salt' ));
2056 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2058 $cacheDir = $conf- > get ( 'resource.thumbnails_cache' , 'cache' );
2059 // Let's see if we don't already have the image for this URL in the cache.
2060 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2061 if ( is_file ( $cacheDir . '/' . $thumbname ))
2062 { // We have the thumbnail, just serve it:
2063 header ( 'Content-Type: image/jpeg' );
2064 echo file_get_contents ( $cacheDir . '/' . $thumbname );
2067 // We may also serve a blank image (if service did not respond)
2068 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2069 if ( is_file ( $cacheDir . '/' . $blankname ))
2071 header ( 'Content-Type: image/gif' );
2072 echo file_get_contents ( $cacheDir . '/' . $blankname );
2076 // Otherwise, generate the thumbnail.
2077 $url = $_GET [ 'url' ];
2078 $domain = parse_url ( $url , PHP_URL_HOST
);
2080 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2082 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2083 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2085 // Is this a link to an image, or to a flickr page ?
2087 if ( endsWith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2088 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2089 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2090 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2092 else // This is a flickr page (html)
2094 // Get the flickr html page.
2095 list ( $headers , $content ) = get_http_response ( $url , 20 );
2096 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2098 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2099 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2100 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2102 // In albums (and some other pages), the link rel="image_src" is not provided,
2103 // but flickr provides:
2104 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2107 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2108 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2114 { // Let's download the image.
2115 // Image is 240x120, so 10 seconds to download should be enough.
2116 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2117 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2118 // Save image to cache.
2119 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2120 header ( 'Content-Type: image/jpeg' );
2127 elseif ( $domain == 'vimeo.com' )
2129 // This is more complex: we have to perform a HTTP request, then parse the result.
2130 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2131 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2132 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2133 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2134 $t = unserialize ( $content );
2135 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2136 // Then we download the image and serve it to our client.
2137 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2138 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2139 // Save image to cache.
2140 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2141 header ( 'Content-Type: image/jpeg' );
2148 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2150 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2151 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2152 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2153 list ( $headers , $content ) = get_http_response ( $url , 5 );
2154 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2155 // Extract the link to the thumbnail
2156 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2157 if (! empty ( $matches [ 1 ]))
2158 { // Let's download the image.
2159 $imageurl = $matches [ 1 ];
2160 // No control on image size, so wait long enough
2161 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2162 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2163 $filepath = $cacheDir . '/' . $thumbname ;
2164 file_put_contents ( $filepath , $content ); // Save image to cache.
2165 if ( resizeImage ( $filepath ))
2167 header ( 'Content-Type: image/jpeg' );
2168 echo file_get_contents ( $filepath );
2176 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2178 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2179 // http://xkcd.com/327/
2180 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2181 list ( $headers , $content ) = get_http_response ( $url , 5 );
2182 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2183 // Extract the link to the thumbnail
2184 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2185 if (! empty ( $matches [ 1 ]))
2186 { // Let's download the image.
2187 $imageurl = $matches [ 1 ];
2188 // No control on image size, so wait long enough
2189 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2190 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2191 $filepath = $cacheDir . '/' . $thumbname ;
2192 // Save image to cache.
2193 file_put_contents ( $filepath , $content );
2194 if ( resizeImage ( $filepath ))
2196 header ( 'Content-Type: image/jpeg' );
2197 echo file_get_contents ( $filepath );
2207 // For all other domains, we try to download the image and make a thumbnail.
2208 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2209 list ( $headers , $content ) = get_http_response ( $url , 30 );
2210 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2211 $filepath = $cacheDir . '/' . $thumbname ;
2212 // Save image to cache.
2213 file_put_contents ( $filepath , $content );
2214 if ( resizeImage ( $filepath ))
2216 header ( 'Content-Type: image/jpeg' );
2217 echo file_get_contents ( $filepath );
2224 // Otherwise, return an empty image (8x8 transparent gif)
2225 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2226 // Also put something in cache so that this URL is not requested twice.
2227 file_put_contents ( $cacheDir . '/' . $blankname , $blankgif );
2228 header ( 'Content-Type: image/gif' );
2232 // Make a thumbnail of the image (to width: 120 pixels)
2233 // Returns true if success, false otherwise.
2234 function resizeImage ( $filepath )
2236 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2238 // Trick: some stupid people rename GIF as JPEG... or else.
2239 // So we really try to open each image type whatever the extension is.
2240 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2242 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2243 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2244 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2245 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2248 $ystart = 0 ; $yheight = $h ;
2249 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2250 $nw = 120 ; // Desired width
2251 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2253 $im2 = imagecreatetruecolor ( $nw , $nh );
2254 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2255 imageinterlace ( $im2 , true ); // For progressive JPEG.
2256 $tempname = $filepath . '_TEMP.jpg' ;
2257 imagejpeg ( $im2 , $tempname , 90 );
2261 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2265 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=genthumbnail' )) { genThumbnail ( $conf
); exit ; } // Thumbnail generation/cache does not need the link database.
2266 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=dailyrss' )) { showDailyRSS ( $conf
); exit ; }
2267 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) {
2268 $_SESSION [ 'LINKS_PER_PAGE' ] = $conf- > get ( 'general.links_per_page' , 20 );
2270 renderPage ( $conf , $pluginManager );