]>
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, 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' );
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/FeedBuilder.php' ;
52 require_once 'application/FileUtils.php' ;
53 require_once 'application/HttpUtils.php' ;
54 require_once 'application/LinkDB.php' ;
55 require_once 'application/LinkFilter.php' ;
56 require_once 'application/LinkUtils.php' ;
57 require_once 'application/NetscapeBookmarkUtils.php' ;
58 require_once 'application/PageBuilder.php' ;
59 require_once 'application/TimeZone.php' ;
60 require_once 'application/Url.php' ;
61 require_once 'application/Utils.php' ;
62 require_once 'application/config/ConfigManager.php' ;
63 require_once 'application/config/ConfigPlugin.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 = ConfigManager
:: getInstance ();
110 RainTPL
:: $tpl_dir = $conf- > get ( 'config.RAINTPL_TPL' ); // template directory
111 RainTPL
:: $cache_dir = $conf- > get ( 'config.RAINTPL_TMP' ); // cache directory
113 $pluginManager = PluginManager
:: getInstance ();
114 $pluginManager- > load ( $conf- > get ( 'config.ENABLED_PLUGINS' ));
116 date_default_timezone_set ( $conf- > get ( 'timezone' , 'UTC' ));
118 ob_start (); // Output buffering for the page cache.
120 // In case stupid admin has left magic_quotes enabled in php.ini:
121 if ( get_magic_quotes_gpc ())
123 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
124 $_POST = array_map ( 'stripslashes_deep' , $_POST );
125 $_GET = array_map ( 'stripslashes_deep' , $_GET );
126 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
129 // Prevent caching on client side or proxy: (yes, it's ugly)
130 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
131 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
132 header ( "Cache-Control: post-check=0, pre-check=0" , false );
133 header ( "Pragma: no-cache" );
135 // Handling of old config file which do not have the new parameters.
136 if (! $conf- > exists ( 'title' )) {
137 $conf- > set ( 'title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
139 if (! $conf- > exists ( 'timezone' )) {
140 $conf- > set ( 'timezone' , date_default_timezone_get ());
142 if (! $conf- > exists ( 'disablesessionprotection' )) {
143 $conf- > set ( 'disablesessionprotection' , false );
145 if (! $conf- > exists ( 'privateLinkByDefault' )) {
146 $conf- > set ( 'privateLinkByDefault' , false );
148 if (! $conf- > exists ( 'titleLink' )) {
149 $conf- > set ( 'titleLink' , '?' );
152 if (! is_file ( $conf- > getConfigFile ())) {
153 // Ensure Shaarli has proper access to its resources
154 $errors = ApplicationUtils
:: checkResourcePermissions ();
156 if ( $errors != array ()) {
157 $message = '<p>Insufficient permissions:</p><ul>' ;
159 foreach ( $errors as $error ) {
160 $message .= '<li>' . $error . '</li>' ;
164 header ( 'Content-Type: text/html; charset=utf-8' );
169 // Display the installation form if no existing config is found
173 // FIXME! Update these value with Updater and escpae it during the install/config save.
174 $conf- > set ( 'title' , escape ( $conf- > get ( 'title' )));
175 $conf- > set ( 'titleLink' , escape ( $conf- > get ( 'titleLink' )));
176 $conf- > set ( 'redirector' , escape ( $conf- > get ( 'redirector' )));
178 // a token depending of deployment salt, user password, and the current ip
179 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $conf- > get ( 'hash' ) . $_SERVER [ 'REMOTE_ADDR' ] . $conf- > get ( 'salt' )));
181 // Sniff browser language and set date format accordingly.
182 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
183 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
185 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
187 //==================================================================================================
188 // Checking session state (i.e. is the user still logged in)
189 //==================================================================================================
191 function setup_login_state () {
192 $conf = ConfigManager
:: getInstance ();
194 if ( $conf- > get ( 'config.OPEN_SHAARLI' )) {
197 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
198 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
199 if (! $conf- > exists ( 'login' )) {
200 $userIsLoggedIn = false ; // Shaarli is not configured yet.
201 $loginFailure = true ;
203 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
204 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
208 $userIsLoggedIn = true ;
210 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
211 if ( empty ( $_SESSION [ 'uid' ])
212 || ( $conf- > get ( 'disablesessionprotection' ) == false && $_SESSION [ 'ip' ] != allIPs ())
213 || time () >= $_SESSION [ 'expires_on' ])
216 $userIsLoggedIn = false ;
217 $loginFailure = true ;
219 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
220 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
223 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
225 if (! $loginFailure ) {
226 $userIsLoggedIn = true ;
229 return $userIsLoggedIn ;
231 $userIsLoggedIn = setup_login_state ();
233 // ------------------------------------------------------------------------------------------
234 // PubSubHubbub protocol support (if enabled) [UNTESTED]
235 // (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
238 $conf = ConfigManager
:: getInstance ();
239 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
242 include_once './publisher.php' ;
243 $p = new Publisher ( $pshUrl );
245 index_url ( $_SERVER ). '?do=atom' ,
246 index_url ( $_SERVER ). '?do=rss'
248 $p- > publish_update ( $topic_url );
252 // ------------------------------------------------------------------------------------------
253 // Session management
255 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
258 $ip = $_SERVER [ 'REMOTE_ADDR' ];
259 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
260 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
261 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
265 function fillSessionInfo () {
266 $conf = ConfigManager
:: getInstance ();
267 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
268 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
269 $_SESSION [ 'username' ]= $conf- > get ( 'login' );
270 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
273 // Check that user/password is correct.
274 function check_auth ( $login , $password )
276 $conf = ConfigManager
:: getInstance ();
277 $hash = sha1 ( $password . $login . $conf- > get ( 'salt' ));
278 if ( $login == $conf- > get ( 'login' ) && $hash == $conf- > get ( 'hash' ))
279 { // Login/password is correct.
281 logm ( $conf- > get ( 'config.LOG_FILE' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
284 logm ( $conf- > get ( 'config.LOG_FILE' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
288 // Returns true if the user is logged in.
289 function isLoggedIn ()
291 global $userIsLoggedIn ;
292 return $userIsLoggedIn ;
297 if ( isset ( $_SESSION )) {
298 unset ( $_SESSION [ 'uid' ]);
299 unset ( $_SESSION [ 'ip' ]);
300 unset ( $_SESSION [ 'username' ]);
301 unset ( $_SESSION [ 'privateonly' ]);
303 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
307 // ------------------------------------------------------------------------------------------
308 // Brute force protection system
309 // Several consecutive failed logins will ban the IP address for 30 minutes.
310 if (! is_file ( $conf- > get ( 'config.IPBANS_FILENAME' , 'data/ipbans.php' ))) {
313 $conf- > get ( 'config.IPBANS_FILENAME' , 'data/ipbans.php' ),
314 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>"
317 include $conf- > get ( 'config.IPBANS_FILENAME' , 'data/ipbans.php' );
318 // Signal a failed login. Will ban the IP if too many failures:
319 function ban_loginFailed ()
321 $conf = ConfigManager
:: getInstance ();
322 $ip = $_SERVER [ 'REMOTE_ADDR' ];
323 $gb = $GLOBALS [ 'IPBANS' ];
324 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
325 $gb [ 'FAILURES' ][ $ip ] ++
;
326 if ( $gb [ 'FAILURES' ][ $ip ] > ( $conf- > get ( 'config.BAN_AFTER' ) - 1 ))
328 $gb [ 'BANS' ][ $ip ] = time () +
$conf- > get ( 'config.BAN_DURATION' , 1800 );
329 logm ( $conf- > get ( 'config.LOG_FILE' ), $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
331 $GLOBALS [ 'IPBANS' ] = $gb ;
333 $conf- > get ( 'config.IPBANS_FILENAME' , 'data/ipbans.php' ),
334 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
338 // Signals a successful login. Resets failed login counter.
339 function ban_loginOk ()
341 $conf = ConfigManager
:: getInstance ();
342 $ip = $_SERVER [ 'REMOTE_ADDR' ];
343 $gb = $GLOBALS [ 'IPBANS' ];
344 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
345 $GLOBALS [ 'IPBANS' ] = $gb ;
347 $conf- > get ( 'config.IPBANS_FILENAME' , 'data/ipbans.php' ),
348 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
352 // Checks if the user CAN login. If 'true', the user can try to login.
353 function ban_canLogin ()
355 $conf = ConfigManager
:: getInstance ();
356 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
357 if ( isset ( $gb [ 'BANS' ][ $ip ]))
359 // User is banned. Check if the ban has expired:
360 if ( $gb [ 'BANS' ][ $ip ]<= time ())
361 { // Ban expired, user can try to login again.
362 logm ( $conf- > get ( 'config.LOG_FILE' ), $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
363 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
365 $conf- > get ( 'config.IPBANS_FILENAME' , 'data/ipbans.php' ),
366 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
368 return true ; // Ban has expired, user can login.
370 return false ; // User is banned.
372 return true ; // User is not banned.
375 // ------------------------------------------------------------------------------------------
376 // Process login form: Check if login/password is correct.
377 if ( isset ( $_POST [ 'login' ]))
379 if (! ban_canLogin ()) die ( 'I said: NO. You are banned for the moment. Go away.' );
380 if ( isset ( $_POST [ 'password' ]) && tokenOk ( $_POST [ 'token' ]) && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ])))
381 { // Login/password is OK.
383 // If user wants to keep the session cookie even after the browser closes:
384 if (! empty ( $_POST [ 'longlastingsession' ]))
386 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
387 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
388 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
390 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
391 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
392 // Note: Never forget the trailing slash on the cookie path!
393 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
395 else // Standard session expiration (=when browser closes)
397 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
398 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
399 session_regenerate_id ( true );
402 // Optional redirect after login:
403 if ( isset ( $_GET [ 'post' ])) {
404 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
405 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
406 if (! empty ( $_GET [ $param ])) {
407 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
410 header ( 'Location: ' . $uri );
414 if ( isset ( $_GET [ 'edit_link' ])) {
415 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
419 if ( isset ( $_POST [ 'returnurl' ])) {
420 // Prevent loops over login screen.
421 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
422 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
426 header ( 'Location: ?' ); exit ;
431 $redir = '&username=' . $_POST [ 'login' ];
432 if ( isset ( $_GET [ 'post' ])) {
433 $redir .= '&post=' . urlencode ( $_GET [ 'post' ]);
434 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
435 if (! empty ( $_GET [ $param ])) {
436 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
440 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
445 // ------------------------------------------------------------------------------------------
446 // Misc utility functions:
448 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
449 function return_bytes ( $val )
451 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
454 case 'g' : $val *= 1024 ;
455 case 'm' : $val *= 1024 ;
456 case 'k' : $val *= 1024 ;
461 // Try to determine max file size for uploads (POST).
462 // Returns an integer (in bytes)
463 function getMaxFileSize ()
465 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
466 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
467 // Return the smaller of two:
468 $maxsize = min ( $size1 , $size2 );
469 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
473 // ------------------------------------------------------------------------------------------
474 // Token management for XSRF protection
475 // Token should be used in any form which acts on data (create,update,delete,import...).
476 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
481 $conf = ConfigManager
:: getInstance ();
482 $rnd = sha1 ( uniqid ( '' , true ) . '_' . mt_rand () . $conf- > get ( 'salt' )); // We generate a random string.
483 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
487 // Tells if a token is OK. Using this function will destroy the token.
489 function tokenOk ( $token )
491 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
493 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
494 return true ; // Token is OK.
496 return false ; // Wrong token, or already used.
499 // ------------------------------------------------------------------------------------------
500 // Daily RSS feed: 1 RSS entry per day giving all the links on that day.
501 // Gives the last 7 days (which have links).
502 // This RSS feed cannot be filtered.
503 function showDailyRSS () {
504 $conf = ConfigManager
:: getInstance ();
506 $query = $_SERVER [ 'QUERY_STRING' ];
507 $cache = new CachedPage (
508 $conf- > get ( 'config.PAGE_CACHE' ),
510 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
512 $cached = $cache- > cachedVersion ();
513 if (! empty ( $cached )) {
518 // If cached was not found (or not usable), then read the database and build the response:
519 // Read links from database (and filter private links if used it not logged in).
520 $LINKSDB = new LinkDB (
521 $conf- > get ( 'config.DATASTORE' ),
523 $conf- > get ( 'config.HIDE_PUBLIC_LINKS' ),
524 $conf- > get ( 'redirector' ),
525 $conf- > get ( 'config.REDIRECTOR_URLENCODE' )
528 /* Some Shaarlies may have very few links, so we need to look
529 back in time (rsort()) until we have enough days ($nb_of_days).
531 $linkdates = array ();
532 foreach ( $LINKSDB as $linkdate => $value ) {
533 $linkdates [] = $linkdate ;
536 $nb_of_days = 7 ; // We take 7 days.
537 $today = date ( 'Ymd' );
540 foreach ( $linkdates as $linkdate ) {
541 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
542 if ( strcmp ( $day , $today ) < 0 ) {
543 if ( empty ( $days [ $day ])) {
544 $days [ $day ] = array ();
546 $days [ $day ][] = $linkdate ;
549 if ( count ( $days ) > $nb_of_days ) {
550 break ; // Have we collected enough days?
554 // Build the RSS feed.
555 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
556 $pageaddr = escape ( index_url ( $_SERVER ));
557 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
559 echo '<title>Daily - ' . $conf- > get ( 'title' ) . '</title>' ;
560 echo '<link>' . $pageaddr . '</link>' ;
561 echo '<description>Daily shared links</description>' ;
562 echo '<language>en-en</language>' ;
563 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
566 foreach ( $days as $day => $linkdates ) {
567 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
568 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
570 // Build the HTML body of this RSS entry.
575 // We pre-format some fields for proper output.
576 foreach ( $linkdates as $linkdate ) {
577 $l = $LINKSDB [ $linkdate ];
578 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $conf- > get ( 'redirector' ));
579 $l [ 'thumbnail' ] = thumbnail ( $l [ 'url' ]);
580 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
581 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
582 if ( startsWith ( $l [ 'url' ], '?' )) {
583 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
585 $links [ $linkdate ] = $l ;
588 // Then build the HTML for this day:
590 $tpl- > assign ( 'title' , $conf- > get ( 'title' ));
591 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
592 $tpl- > assign ( 'absurl' , $absurl );
593 $tpl- > assign ( 'links' , $links );
594 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
595 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
597 echo $html . PHP_EOL
;
599 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
601 $cache- > cache ( ob_get_contents ());
607 * Show the 'Daily' page.
609 * @param PageBuilder $pageBuilder Template engine wrapper.
610 * @param LinkDB $LINKSDB LinkDB instance.
612 function showDaily ( $pageBuilder , $LINKSDB )
614 $conf = ConfigManager
:: getInstance ();
615 $day = date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
616 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
618 $days = $LINKSDB- > days ();
619 $i = array_search ( $day , $days );
620 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
625 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
626 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
630 $linksToDisplay = $LINKSDB- > filterDay ( $day );
631 } catch ( Exception
$exc ) {
633 $linksToDisplay = array ();
636 // We pre-format some fields for proper output.
637 foreach ( $linksToDisplay as $key => $link )
640 $taglist = explode ( ' ' , $link [ 'tags' ]);
641 uasort ( $taglist , 'strcasecmp' );
642 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
643 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector' ));
644 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $link [ 'url' ]);
645 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
646 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
649 /* We need to spread the articles on 3 columns.
650 I did not want to use a JavaScript lib like http://masonry.desandro.com/
651 so I manually spread entries with a simple method: I roughly evaluate the
652 height of a div according to title and description length.
654 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
655 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
656 foreach ( $linksToDisplay as $key => $link )
658 // Roughly estimate length of entry (by counting characters)
659 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
660 // Description: 836 characters gives roughly 342 pixel height.
661 // This is not perfect, but it's usually OK.
662 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
663 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
664 // Then put in column which is the less filled:
665 $smallest = min ( $fill ); // find smallest value in array.
666 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
667 array_push ( $columns [ $index ], $link ); // Put entry in this column.
668 $fill [ $index ] +
= $length ;
671 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
673 'linksToDisplay' => $linksToDisplay ,
675 'day' => $dayDate- > getTimestamp (),
676 'previousday' => $previousday ,
677 'nextday' => $nextday ,
679 $pluginManager = PluginManager
:: getInstance ();
680 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
682 foreach ( $data as $key => $value ) {
683 $pageBuilder- > assign ( $key , $value );
686 $pageBuilder- > renderPage ( 'daily' );
690 // Renders the linklist
691 function showLinkList ( $PAGE , $LINKSDB ) {
692 buildLinkList ( $PAGE , $LINKSDB ); // Compute list of links to display
693 $PAGE- > renderPage ( 'linklist' );
697 // ------------------------------------------------------------------------------------------
698 // Render HTML page (according to URL parameters and user rights)
699 function renderPage ()
701 $conf = ConfigManager
:: getInstance ();
702 $LINKSDB = new LinkDB (
703 $conf- > get ( 'config.DATASTORE' ),
705 $conf- > get ( 'config.HIDE_PUBLIC_LINKS' ),
706 $conf- > get ( 'redirector' ),
707 $conf- > get ( 'config.REDIRECTOR_URLENCODE' )
710 $updater = new Updater (
711 read_updates_file ( $conf- > get ( 'config.UPDATES_FILE' )),
716 $newUpdates = $updater- > update ();
717 if (! empty ( $newUpdates )) {
719 $conf- > get ( 'config.UPDATES_FILE' ),
720 $updater- > getDoneUpdates ()
724 catch ( Exception
$e ) {
725 die ( $e- > getMessage ());
728 $PAGE = new PageBuilder ();
729 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
730 $PAGE- > assign ( 'privateLinkcount' , count_private ( $LINKSDB ));
732 // Determine which page will be rendered.
733 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
734 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
736 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
737 // Then assign generated data to RainTPL.
738 $common_hooks = array (
743 $pluginManager = PluginManager
:: getInstance ();
744 foreach ( $common_hooks as $name ) {
745 $plugin_data = array ();
746 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
748 'target' => $targetPage ,
749 'loggedin' => isLoggedIn ()
752 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
755 // -------- Display login form.
756 if ( $targetPage == Router
:: $PAGE_LOGIN )
758 if ( $conf- > get ( 'config.OPEN_SHAARLI' )) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
759 $token = '' ; if ( ban_canLogin ()) $token = getToken (); // Do not waste token generation if not useful.
760 $PAGE- > assign ( 'token' , $token );
761 if ( isset ( $_GET [ 'username' ])) {
762 $PAGE- > assign ( 'username' , escape ( $_GET [ 'username' ]));
764 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
765 $PAGE- > renderPage ( 'loginform' );
768 // -------- User wants to logout.
769 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=logout' ))
771 invalidateCaches ( $conf- > get ( 'config.PAGECACHE' ));
773 header ( 'Location: ?' );
777 // -------- Picture wall
778 if ( $targetPage == Router
:: $PAGE_PICWALL )
780 // Optionally filter the results:
781 $links = $LINKSDB- > filterSearch ( $_GET );
782 $linksToDisplay = array ();
784 // Get only links which have a thumbnail.
785 foreach ( $links as $link )
787 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
788 $thumb = lazyThumbnail ( $link [ 'url' ], $permalink );
789 if ( $thumb != '' ) // Only output links which have a thumbnail.
791 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
792 $linksToDisplay []= $link ; // Add to array.
797 'linksToDisplay' => $linksToDisplay ,
799 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
801 foreach ( $data as $key => $value ) {
802 $PAGE- > assign ( $key , $value );
805 $PAGE- > renderPage ( 'picwall' );
809 // -------- Tag cloud
810 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
812 $tags = $LINKSDB- > allTags ();
814 // We sort tags alphabetically, then choose a font size according to count.
815 // First, find max value.
817 foreach ( $tags as $value ) {
818 $maxcount = max ( $maxcount , $value );
821 // Sort tags alphabetically: case insensitive, support locale if avalaible.
822 uksort ( $tags , function ( $a , $b ) {
823 // Collator is part of PHP intl.
824 if ( class_exists ( 'Collator' )) {
825 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
826 if (! intl_is_failure ( intl_get_error_code ())) {
827 return $c- > compare ( $a , $b );
830 return strcasecmp ( $a , $b );
834 foreach ( $tags as $key => $value ) {
835 // Tag font size scaling:
836 // default 15 and 30 logarithm bases affect scaling,
837 // 22 and 6 are arbitrary font sizes for max and min sizes.
838 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
839 $tagList [ $key ] = array (
841 'size' => number_format ( $size , 2 , '.' , '' ),
848 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
850 foreach ( $data as $key => $value ) {
851 $PAGE- > assign ( $key , $value );
854 $PAGE- > renderPage ( 'tagcloud' );
859 if ( $targetPage == Router
:: $PAGE_DAILY ) {
860 showDaily ( $PAGE , $LINKSDB );
863 // ATOM and RSS feed.
864 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
865 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
866 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
869 $query = $_SERVER [ 'QUERY_STRING' ];
870 $cache = new CachedPage (
871 $conf- > get ( 'config.PAGECACHE' ),
873 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
875 $cached = $cache- > cachedVersion ();
876 if (! empty ( $cached )) {
882 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
883 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
884 $feedGenerator- > setHideDates ( $conf- > get ( 'config.HIDE_TIMESTAMPS' ) && ! isLoggedIn ());
885 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $conf- > get ( 'config.ENABLE_RSS_PERMALINKS' ));
886 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
887 if (! empty ( $pshUrl )) {
888 $feedGenerator- > setPubsubhubUrl ( $pshUrl );
890 $data = $feedGenerator- > buildData ();
892 // Process plugin hook.
893 $pluginManager = PluginManager
:: getInstance ();
894 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
895 'loggedin' => isLoggedIn (),
896 'target' => $targetPage ,
899 // Render the template.
900 $PAGE- > assignAll ( $data );
901 $PAGE- > renderPage ( 'feed.' . $feedType );
902 $cache- > cache ( ob_get_contents ());
907 // Display openseach plugin (XML)
908 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
909 header ( 'Content-Type: application/xml; charset=utf-8' );
910 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
911 $PAGE- > renderPage ( 'opensearch' );
915 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
916 if ( isset ( $_GET [ 'addtag' ]))
918 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
919 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
920 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
922 // Prevent redirection loop
923 if ( isset ( $params [ 'addtag' ])) {
924 unset ( $params [ 'addtag' ]);
927 // Check if this tag is already in the search query and ignore it if it is.
928 // Each tag is always separated by a space
929 if ( isset ( $params [ 'searchtags' ])) {
930 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
932 $current_tags = array ();
935 foreach ( $current_tags as $value ) {
936 if ( $value === $_GET [ 'addtag' ]) {
941 // Append the tag if necessary
942 if ( empty ( $params [ 'searchtags' ])) {
943 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
946 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
949 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
950 header ( 'Location: ?' . http_build_query ( $params ));
954 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
955 if ( isset ( $_GET [ 'removetag' ])) {
956 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
957 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
958 header ( 'Location: ?' );
962 // In case browser does not send HTTP_REFERER
963 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
965 // Prevent redirection loop
966 if ( isset ( $params [ 'removetag' ])) {
967 unset ( $params [ 'removetag' ]);
970 if ( isset ( $params [ 'searchtags' ])) {
971 $tags = explode ( ' ' , $params [ 'searchtags' ]);
972 // Remove value from array $tags.
973 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
974 $params [ 'searchtags' ] = implode ( ' ' , $tags );
976 if ( empty ( $params [ 'searchtags' ])) {
977 unset ( $params [ 'searchtags' ]);
980 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
982 header ( 'Location: ?' . http_build_query ( $params ));
986 // -------- User wants to change the number of links per page (linksperpage=...)
987 if ( isset ( $_GET [ 'linksperpage' ])) {
988 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
989 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
992 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
996 // -------- User wants to see only private links (toggle)
997 if ( isset ( $_GET [ 'privateonly' ])) {
998 if ( empty ( $_SESSION [ 'privateonly' ])) {
999 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1001 unset ( $_SESSION [ 'privateonly' ]); // See all links
1004 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1008 // -------- Handle other actions allowed for non-logged in users:
1011 // User tries to post new link but is not logged in:
1012 // Show login screen, then redirect to ?post=...
1013 if ( isset ( $_GET [ 'post' ]))
1015 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.
1019 showLinkList ( $PAGE , $LINKSDB );
1020 if ( isset ( $_GET [ 'edit_link' ])) {
1021 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1025 exit ; // Never remove this one! All operations below are reserved for logged in user.
1028 // -------- All other functions are reserved for the registered user:
1030 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1031 if ( $targetPage == Router
:: $PAGE_TOOLS )
1034 'pageabsaddr' => index_url ( $_SERVER ),
1036 $pluginManager- > executeHooks ( 'render_tools' , $data );
1038 foreach ( $data as $key => $value ) {
1039 $PAGE- > assign ( $key , $value );
1042 $PAGE- > renderPage ( 'tools' );
1046 // -------- User wants to change his/her password.
1047 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1049 if ( $conf- > get ( 'config.OPEN_SHAARLI' )) {
1050 die ( 'You are not supposed to change a password on an Open Shaarli.' );
1053 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1055 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1057 // Make sure old password is correct.
1058 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $conf- > get ( 'login' ). $conf- > get ( 'salt' ));
1059 if ( $oldhash != $conf- > get ( 'hash' )) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1060 // Save new password
1061 // Salt renders rainbow-tables attacks useless.
1062 $conf- > set ( 'salt' , sha1 ( uniqid ( '' , true ) . '_' . mt_rand ()));
1063 $conf- > set ( 'hash' , sha1 ( $_POST [ 'setpassword' ] . $conf- > get ( 'login' ) . $conf- > get ( 'salt' )));
1065 $conf- > write ( isLoggedIn ());
1067 catch ( Exception
$e ) {
1069 'ERROR while writing config file after changing password.' . PHP_EOL
.
1073 // TODO: do not handle exceptions/errors in JS.
1074 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1077 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1080 else // show the change password form.
1082 $PAGE- > assign ( 'token' , getToken ());
1083 $PAGE- > renderPage ( 'changepassword' );
1088 // -------- User wants to change configuration
1089 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1091 if (! empty ( $_POST [ 'title' ]) )
1093 if (! tokenOk ( $_POST [ 'token' ])) {
1094 die ( 'Wrong token.' ); // Go away!
1097 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1098 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1100 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1102 $conf- > set ( 'timezone' , $tz );
1103 $conf- > set ( 'title' , $_POST [ 'title' ]);
1104 $conf- > set ( 'titleLink' , $_POST [ 'titleLink' ]);
1105 $conf- > set ( 'redirector' , $_POST [ 'redirector' ]);
1106 $conf- > set ( 'disablesessionprotection' , ! empty ( $_POST [ 'disablesessionprotection' ]));
1107 $conf- > set ( 'privateLinkByDefault' , ! empty ( $_POST [ 'privateLinkByDefault' ]));
1108 $conf- > set ( 'config.ENABLE_RSS_PERMALINKS' , ! empty ( $_POST [ 'enableRssPermalinks' ]));
1109 $conf- > set ( 'config.ENABLE_UPDATECHECK' , ! empty ( $_POST [ 'updateCheck' ]));
1110 $conf- > set ( 'config.HIDE_PUBLIC_LINKS' , ! empty ( $_POST [ 'hidePublicLinks' ]));
1112 $conf- > write ( isLoggedIn ());
1114 catch ( Exception
$e ) {
1116 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1120 // TODO: do not handle exceptions/errors in JS.
1121 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=configure \' ;</script>' ;
1124 echo '<script>alert("Configuration was saved.");document.location= \' ?do=configure \' ;</script>' ;
1127 else // Show the configuration form.
1129 $PAGE- > assign ( 'token' , getToken ());
1130 $PAGE- > assign ( 'title' , $conf- > get ( 'title' ));
1131 $PAGE- > assign ( 'redirector' , $conf- > get ( 'redirector' ));
1132 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $conf- > get ( 'timezone' ));
1133 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1134 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1135 $PAGE- > assign ( 'private_links_default' , $conf- > get ( 'privateLinkByDefault' ));
1136 $PAGE- > assign ( 'enable_rss_permalinks' , $conf- > get ( 'config.ENABLE_RSS_PERMALINKS' ));
1137 $PAGE- > assign ( 'enable_update_check' , $conf- > get ( 'config.ENABLE_UPDATECHECK' ));
1138 $PAGE- > assign ( 'hide_public_links' , $conf- > get ( 'config.HIDE_PUBLIC_LINKS' ));
1139 $PAGE- > renderPage ( 'configure' );
1144 // -------- User wants to rename a tag or delete it
1145 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1147 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1148 $PAGE- > assign ( 'token' , getToken ());
1149 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1150 $PAGE- > renderPage ( 'changetag' );
1154 if (! tokenOk ( $_POST [ 'token' ])) {
1155 die ( 'Wrong token.' );
1159 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1160 $needle = trim ( $_POST [ 'fromtag' ]);
1161 // True for case-sensitive tag search.
1162 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1163 foreach ( $linksToAlter as $key => $value )
1165 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1166 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1167 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1168 $LINKSDB [ $key ]= $value ;
1170 $LINKSDB- > savedb ( $conf- > get ( 'config.PAGECACHE' ));
1171 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1176 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1177 $needle = trim ( $_POST [ 'fromtag' ]);
1178 // True for case-sensitive tag search.
1179 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1180 foreach ( $linksToAlter as $key => $value )
1182 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1183 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1184 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1185 $LINKSDB [ $key ]= $value ;
1187 $LINKSDB- > savedb ( $conf- > get ( 'config.PAGECACHE' )); // Save to disk.
1188 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1193 // -------- User wants to add a link without using the bookmarklet: Show form.
1194 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1196 $PAGE- > renderPage ( 'addlink' );
1200 // -------- User clicked the "Save" button when editing a link: Save link to database.
1201 if ( isset ( $_POST [ 'save_edit' ]))
1204 if (! tokenOk ( $_POST [ 'token' ])) {
1205 die ( 'Wrong token.' );
1207 // Remove multiple spaces.
1208 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1209 // Remove first '-' char in tags.
1210 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1211 // Remove duplicates.
1212 $tags = implode(' ', array_unique(explode(' ', $tags )));
1213 $linkdate = $_POST [' lf_linkdate
'];
1214 $url = trim( $_POST [' lf_url
']);
1215 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1216 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1217 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1219 $url = ' http
: //' . $url;
1223 'title' => trim ( $_POST [ 'lf_title' ]),
1225 'description' => $_POST [ 'lf_description' ],
1226 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1227 'linkdate' => $linkdate ,
1228 'tags' => str_replace ( ',' , ' ' , $tags )
1230 // If title is empty, use the URL as title.
1231 if ( $link [ 'title' ] == '' ) {
1232 $link [ 'title' ] = $link [ 'url' ];
1235 $pluginManager- > executeHooks ( 'save_link' , $link );
1237 $LINKSDB [ $linkdate ] = $link ;
1238 $LINKSDB- > savedb ( $conf- > get ( 'config.PAGECACHE' ));
1241 // If we are called from the bookmarklet, we must close the popup:
1242 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1243 echo '<script>self.close();</script>' ;
1247 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1248 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1249 // Scroll to the link which has been edited.
1250 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1251 // After saving the link, redirect to the page the user was on.
1252 header ( 'Location: ' . $location );
1256 // -------- User clicked the "Cancel" button when editing a link.
1257 if ( isset ( $_POST [ 'cancel_edit' ]))
1259 // If we are called from the bookmarklet, we must close the popup:
1260 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1261 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1262 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1263 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1264 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1268 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1269 if ( isset ( $_POST [ 'delete_link' ]))
1271 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1272 // We do not need to ask for confirmation:
1273 // - confirmation is handled by JavaScript
1274 // - we are protected from XSRF by the token.
1275 $linkdate = $_POST [ 'lf_linkdate' ];
1277 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1279 unset ( $LINKSDB [ $linkdate ]);
1280 $LINKSDB- > savedb ( 'config.PAGECACHE' ); // save to disk
1282 // If we are called from the bookmarklet, we must close the popup:
1283 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1284 // Pick where we're going to redirect
1285 // =============================================================
1286 // Basically, we can't redirect to where we were previously if it was a permalink
1287 // or an edit_link, because it would 404.
1289 // - / : nothing in $_GET, redirect to self
1290 // - /?page : redirect to self
1291 // - /?searchterm : redirect to self (there might be other links)
1292 // - /?searchtags : redirect to self
1293 // - /permalink : redirect to / (the link does not exist anymore)
1294 // - /?edit_link : redirect to / (the link does not exist anymore)
1295 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1296 // redirect is not satisfied, and only then redirect to /
1299 if ( count ( $_GET ) == 0
1300 || isset ( $_GET [ 'page' ])
1301 || isset ( $_GET [ 'searchterm' ])
1302 || isset ( $_GET [ 'searchtags' ])
1304 if ( isset ( $_POST [ 'returnurl' ])) {
1305 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1307 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1311 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1315 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1316 if ( isset ( $_GET [ 'edit_link' ]))
1318 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1319 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1322 'link_is_new' => false ,
1323 'token' => getToken (),
1324 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1325 'tags' => $LINKSDB- > allTags (),
1327 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1329 foreach ( $data as $key => $value ) {
1330 $PAGE- > assign ( $key , $value );
1333 $PAGE- > renderPage ( 'editlink' );
1337 // -------- User want to post a new link: Display link edit form.
1338 if ( isset ( $_GET [ 'post' ])) {
1339 $url = cleanup_url ( $_GET [ 'post' ]);
1341 $link_is_new = false ;
1342 // Check if URL is not already in database (in this case, we will edit the existing link)
1343 $link = $LINKSDB- > getLinkFromUrl ( $url );
1346 $link_is_new = true ;
1347 $linkdate = strval ( date ( 'Ymd_His' ));
1348 // Get title if it was provided in URL (by the bookmarklet).
1349 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1350 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1351 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1352 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1353 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1354 // 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.)
1355 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1356 // Short timeout to keep the application responsive
1357 list ( $headers , $content ) = get_http_response ( $url , 4 );
1358 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1359 // Retrieve charset.
1360 $charset = get_charset ( $headers , $content );
1362 $title = html_extract_title ( $content );
1363 // Re-encode title in utf-8 if necessary.
1364 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1365 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1371 $url = '?' . smallHash ( $linkdate );
1374 $url = escape ( $url );
1375 $title = escape ( $title );
1378 'linkdate' => $linkdate ,
1381 'description' => $description ,
1383 'private' => $private
1389 'link_is_new' => $link_is_new ,
1390 'token' => getToken (), // XSRF protection.
1391 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1392 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1393 'tags' => $LINKSDB- > allTags (),
1395 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1397 foreach ( $data as $key => $value ) {
1398 $PAGE- > assign ( $key , $value );
1401 $PAGE- > renderPage ( 'editlink' );
1405 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1406 // Export links as a Netscape Bookmarks file
1408 if ( empty ( $_GET [ 'selection' ])) {
1409 $PAGE- > renderPage ( 'export' );
1413 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1414 $selection = $_GET [ 'selection' ];
1415 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1416 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1418 $prependNoteUrl = false ;
1424 NetscapeBookmarkUtils
:: filterAndFormat (
1431 } catch ( Exception
$exc ) {
1432 header ( 'Content-Type: text/plain; charset=utf-8' );
1433 echo $exc- > getMessage ();
1436 $now = new DateTime ();
1437 header ( 'Content-Type: text/html; charset=utf-8' );
1439 'Content-disposition: attachment; filename=bookmarks_'
1440 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1442 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1443 $PAGE- > assign ( 'eol' , PHP_EOL
);
1444 $PAGE- > assign ( 'selection' , $selection );
1445 $PAGE- > renderPage ( 'export.bookmarks' );
1449 // -------- User is uploading a file for import
1450 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=upload' ))
1452 // If file is too big, some form field may be missing.
1453 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1455 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1456 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>' ;
1459 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1460 importFile ( $LINKSDB );
1464 // -------- Show upload/import dialog:
1465 if ( $targetPage == Router
:: $PAGE_IMPORT )
1467 $PAGE- > assign ( 'token' , getToken ());
1468 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1469 $PAGE- > renderPage ( 'import' );
1473 // Plugin administration page
1474 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1475 $pluginMeta = $pluginManager- > getPluginsMeta ();
1477 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1478 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1480 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $conf- > get ( 'plugins' , array ()));
1483 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1485 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1487 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1488 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1489 $PAGE- > renderPage ( 'pluginsadmin' );
1493 // Plugin administration form action
1494 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1496 if ( isset ( $_POST [ 'parameters_form' ])) {
1497 unset ( $_POST [ 'parameters_form' ]);
1498 foreach ( $_POST as $param => $value ) {
1499 $conf- > set ( 'plugins.' . $param , escape ( $value ));
1503 $conf- > set ( 'config.ENABLED_PLUGINS' , save_plugin_config ( $_POST ));
1505 $conf- > write ( isLoggedIn ());
1507 catch ( Exception
$e ) {
1509 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1513 // TODO: do not handle exceptions/errors in JS.
1514 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1517 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1521 // -------- Otherwise, simply display search form and links:
1522 showLinkList ( $PAGE , $LINKSDB );
1526 // -----------------------------------------------------------------------------------------------
1527 // Process the import file form.
1528 function importFile ( $LINKSDB )
1530 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1531 $conf = ConfigManager
:: getInstance ();
1533 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1534 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1535 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1536 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1537 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1542 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1544 // Then import the bookmarks.
1545 if ( $type == 'netscape' )
1547 // This is a standard Netscape-style bookmark file.
1548 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1549 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1551 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1552 $d = explode ( '<DD>' , $html );
1553 if ( startsWith ( $d [ 0 ], '<A ' ))
1555 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1556 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1557 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1558 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1560 foreach ( $matches as $m )
1562 $attr = $m [ 1 ]; $value = $m [ 2 ];
1563 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1564 elseif ( $attr == 'ADD_DATE' )
1566 $raw_add_date = intval ( $value );
1567 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1569 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1570 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1572 if ( $link [ 'url' ]!= '' )
1574 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1575 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1577 { // Link not in database, let's import it...
1578 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1580 // Make sure date/time is not already used by another link.
1581 // (Some bookmark files have several different links with the same ADD_DATE)
1582 // We increment date by 1 second until we find a date which is not used in DB.
1583 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1584 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1585 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1586 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1589 else // Link already present in database.
1592 { // If overwrite is required, we import link data, except date/time.
1593 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1594 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1602 $LINKSDB- > savedb ( $conf- > get ( 'config.PAGECACHE' ));
1604 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1608 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1613 * Template for the list of links (<div id="linklist">)
1614 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1616 * @param pageBuilder $PAGE pageBuilder instance.
1617 * @param LinkDB $LINKSDB LinkDB instance.
1619 function buildLinkList ( $PAGE , $LINKSDB )
1621 $conf = ConfigManager
:: getInstance ();
1622 // Used in templates
1623 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1624 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1627 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1628 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1630 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1631 } catch ( LinkNotFoundException
$e ) {
1632 $PAGE- > render404 ( $e- > getMessage ());
1636 // Filter links according search parameters.
1637 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1638 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1641 // ---- Handle paging.
1643 foreach ( $linksToDisplay as $key => $value ) {
1647 // If there is only a single link, we change on-the-fly the title of the page.
1648 if ( count ( $linksToDisplay ) == 1 ) {
1649 $conf- > set ( 'pagetitle' , $linksToDisplay [ $keys [ 0 ]][ 'title' ] . ' - ' . $conf- > get ( 'title' ));
1652 // Select articles according to paging.
1653 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1654 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1655 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1656 $page = $page < 1 ? 1 : $page ;
1657 $page = $page > $pagecount ? $pagecount : $page ;
1659 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1660 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1661 $linkDisp = array ();
1662 while ( $i < $end && $i < count ( $keys ))
1664 $link = $linksToDisplay [ $keys [ $i ]];
1665 $link [ 'description' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector' ));
1666 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1667 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1668 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1669 $link [ 'timestamp' ] = $date- > getTimestamp ();
1670 $taglist = explode ( ' ' , $link [ 'tags' ]);
1671 uasort ( $taglist , 'strcasecmp' );
1672 $link [ 'taglist' ] = $taglist ;
1673 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1674 // Check for both signs of a note: starting with ? and 7 chars long.
1675 if ( $link [ 'url' ][ 0 ] === '?' &&
1676 strlen ( $link [ 'url' ]) === 7 ) {
1677 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1680 $linkDisp [ $keys [ $i ]] = $link ;
1684 // Compute paging navigation
1685 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1686 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1687 $previous_page_url = '' ;
1688 if ( $i != count ( $keys )) {
1689 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1693 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1696 $token = isLoggedIn () ? getToken () : '' ;
1698 // Fill all template fields.
1700 'previous_page_url' => $previous_page_url ,
1701 'next_page_url' => $next_page_url ,
1702 'page_current' => $page ,
1703 'page_max' => $pagecount ,
1704 'result_count' => count ( $linksToDisplay ),
1705 'search_term' => $searchterm ,
1706 'search_tags' => $searchtags ,
1707 'redirector' => $conf- > get ( 'redirector' ), // Optional redirector URL.
1709 'links' => $linkDisp ,
1710 'tags' => $LINKSDB- > allTags (),
1712 // FIXME! temporary fix - see #399.
1713 if ( $conf- > exists ( 'pagetitle' ) && count ( $linkDisp ) == 1 ) {
1714 $data [ 'pagetitle' ] = $conf- > get ( 'pagetitle' );
1717 $pluginManager = PluginManager
:: getInstance ();
1718 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1720 foreach ( $data as $key => $value ) {
1721 $PAGE- > assign ( $key , $value );
1727 // Compute the thumbnail for a link.
1729 // With a link to the original URL.
1730 // Understands various services (youtube.com...)
1731 // Input: $url = URL for which the thumbnail must be found.
1732 // $href = if provided, this URL will be followed instead of $url
1733 // Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1734 // Some of them may be missing.
1735 // Return an empty array if no thumbnail available.
1736 function computeThumbnail ( $url , $href = false )
1738 $conf = ConfigManager
:: getInstance ();
1739 if (! $conf- > get ( 'config.ENABLE_THUMBNAILS' )) return array ();
1740 if ( $href == false ) $href = $url ;
1742 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1743 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1744 // ^^^^^^^^^^^ ^^^^^^^^^^^
1745 $domain = parse_url ( $url , PHP_URL_HOST
);
1746 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1748 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1749 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1750 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1752 if ( $domain == 'youtu.be' ) // Youtube short links
1754 $path = parse_url ( $url , PHP_URL_PATH
);
1755 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1756 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1758 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1760 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1761 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1762 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1765 if ( $domain == 'imgur.com' )
1767 $path = parse_url ( $url , PHP_URL_PATH
);
1768 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1769 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1770 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1771 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1772 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1774 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1775 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1777 if ( $domain == 'i.imgur.com' )
1779 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1780 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1781 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1783 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1785 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1787 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1788 return array ( 'src' => $thumburl ,
1789 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1792 if ( endsWith ( $domain , '.imageshack.us' ))
1794 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1795 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1797 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1798 return array ( 'src' => $thumburl ,
1799 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1803 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1804 // So we deport the thumbnail generation in order not to slow down page generation
1805 // (and we also cache the thumbnail)
1807 if (! $conf- > get ( 'config.ENABLE_LOCALCACHE' )) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1809 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1810 || $domain == 'vimeo.com'
1811 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1812 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1815 if ( $domain == 'vimeo.com' )
1816 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1817 $path = parse_url ( $url , PHP_URL_PATH
);
1818 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1820 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1821 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1822 $path = parse_url ( $url , PHP_URL_PATH
);
1823 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1825 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1826 { // Make sure this TED URL points to a video (/talks/...)
1827 $path = parse_url ( $url , PHP_URL_PATH
);
1828 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1830 $sign = hash_hmac ( 'sha256' , $url , $conf- > get ( 'salt' )); // We use the salt to sign data (it's random, secret, and specific to each installation)
1831 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1832 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1835 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1836 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1837 // But using the extension will do.
1838 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1839 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1841 $sign = hash_hmac ( 'sha256' , $url , $conf- > get ( 'salt' )); // We use the salt to sign data (it's random, secret, and specific to each installation)
1842 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1843 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1845 return array (); // No thumbnail.
1850 // Returns the HTML code to display a thumbnail for a link
1851 // with a link to the original URL.
1852 // Understands various services (youtube.com...)
1853 // Input: $url = URL for which the thumbnail must be found.
1854 // $href = if provided, this URL will be followed instead of $url
1855 // Returns '' if no thumbnail available.
1856 function thumbnail ( $url , $href = false )
1858 $t = computeThumbnail ( $url , $href );
1859 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1861 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
1862 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1863 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1864 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1865 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1870 // Returns the HTML code to display a thumbnail for a link
1871 // for the picture wall (using lazy image loading)
1872 // Understands various services (youtube.com...)
1873 // Input: $url = URL for which the thumbnail must be found.
1874 // $href = if provided, this URL will be followed instead of $url
1875 // Returns '' if no thumbnail available.
1876 function lazyThumbnail ( $url , $href = false )
1878 $t = computeThumbnail ( $url , $href );
1879 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1881 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
1884 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
1886 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1887 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1888 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1889 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1892 // No-JavaScript fallback.
1893 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
1894 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1895 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1896 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1897 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1898 $html .= '></noscript></a>' ;
1904 // -----------------------------------------------------------------------------------------------
1906 // This function should NEVER be called if the file data/config.php exists.
1909 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1910 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1913 // This part makes sure sessions works correctly.
1914 // (Because on some hosts, session.save_path may not be set correctly,
1915 // or we may not have write access to it.)
1916 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
1917 { // Step 2: Check if data in session is correct.
1918 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
1919 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
1920 echo 'It currently points to ' . session_save_path (). '<br>' ;
1921 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>' ;
1922 echo '<br><a href="?">Click to try again.</a></pre>' ;
1925 if (! isset ( $_SESSION [ 'session_tested' ]))
1926 { // Step 1 : Try to store data in session and reload page.
1927 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
1928 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
1930 if ( isset ( $_GET [ 'test_session' ]))
1931 { // Step 3: Sessions are OK. Remove test parameter from URL.
1932 header ( 'Location: ' . index_url ( $_SERVER ));
1936 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1938 $conf = ConfigManager
:: getInstance ();
1940 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1941 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1943 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1945 $conf- > set ( 'timezone' , $tz );
1946 $login = $_POST [ 'setlogin' ];
1947 $conf- > set ( 'login' , $login );
1948 $salt = sha1 ( uniqid ( '' , true ) . '_' . mt_rand ());
1949 $conf- > set ( 'salt' , $salt );
1950 $conf- > set ( 'hash' , sha1 ( $_POST [ 'setpassword' ] . $login . $salt ));
1951 if (! empty ( $_POST [ 'title' ])) {
1952 $conf- > set ( 'title' , $_POST [ 'title' ]);
1954 $conf- > set ( 'title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
1956 $conf- > set ( 'config.ENABLE_UPDATECHECK' , ! empty ( $_POST [ 'updateCheck' ]));
1958 // Everything is ok, let's create config file.
1959 $conf- > write ( isLoggedIn ());
1961 catch ( Exception
$e ) {
1963 'ERROR while writing config file after installation.' . PHP_EOL
.
1967 // TODO: do not handle exceptions/errors in JS.
1968 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
1971 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
1975 // Display config form:
1976 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
1977 $timezone_html = '' ;
1978 if ( $timezone_form != '' ) {
1979 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
1982 $PAGE = new PageBuilder ();
1983 $PAGE- > assign ( 'timezone_html' , $timezone_html );
1984 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1985 $PAGE- > renderPage ( 'install' );
1989 /* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1990 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1991 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1992 This function is called by passing the URL:
1993 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1994 [URL] is the URL of the link (e.g. a flickr page)
1995 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1996 The function below will fetch the image from the webservice and store it in the cache.
1998 function genThumbnail ()
2000 $conf = ConfigManager
:: getInstance ();
2001 // Make sure the parameters in the URL were generated by us.
2002 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $conf- > get ( 'salt' ));
2003 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2005 $cacheDir = $conf- > get ( 'config.CACHEDIR' , 'cache' );
2006 // Let's see if we don't already have the image for this URL in the cache.
2007 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2008 if ( is_file ( $cacheDir . '/' . $thumbname ))
2009 { // We have the thumbnail, just serve it:
2010 header ( 'Content-Type: image/jpeg' );
2011 echo file_get_contents ( $cacheDir . '/' . $thumbname );
2014 // We may also serve a blank image (if service did not respond)
2015 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2016 if ( is_file ( $cacheDir . '/' . $blankname ))
2018 header ( 'Content-Type: image/gif' );
2019 echo file_get_contents ( $cacheDir . '/' . $blankname );
2023 // Otherwise, generate the thumbnail.
2024 $url = $_GET [ 'url' ];
2025 $domain = parse_url ( $url , PHP_URL_HOST
);
2027 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2029 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2030 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2032 // Is this a link to an image, or to a flickr page ?
2034 if ( endsWith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2035 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2036 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2037 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2039 else // This is a flickr page (html)
2041 // Get the flickr html page.
2042 list ( $headers , $content ) = get_http_response ( $url , 20 );
2043 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2045 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2046 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2047 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2049 // In albums (and some other pages), the link rel="image_src" is not provided,
2050 // but flickr provides:
2051 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2054 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2055 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2061 { // Let's download the image.
2062 // Image is 240x120, so 10 seconds to download should be enough.
2063 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2064 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2065 // Save image to cache.
2066 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2067 header ( 'Content-Type: image/jpeg' );
2074 elseif ( $domain == 'vimeo.com' )
2076 // This is more complex: we have to perform a HTTP request, then parse the result.
2077 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2078 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2079 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2080 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2081 $t = unserialize ( $content );
2082 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2083 // Then we download the image and serve it to our client.
2084 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2085 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2086 // Save image to cache.
2087 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2088 header ( 'Content-Type: image/jpeg' );
2095 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2097 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2098 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2099 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2100 list ( $headers , $content ) = get_http_response ( $url , 5 );
2101 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2102 // Extract the link to the thumbnail
2103 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2104 if (! empty ( $matches [ 1 ]))
2105 { // Let's download the image.
2106 $imageurl = $matches [ 1 ];
2107 // No control on image size, so wait long enough
2108 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2109 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2110 $filepath = $cacheDir . '/' . $thumbname ;
2111 file_put_contents ( $filepath , $content ); // Save image to cache.
2112 if ( resizeImage ( $filepath ))
2114 header ( 'Content-Type: image/jpeg' );
2115 echo file_get_contents ( $filepath );
2123 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2125 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2126 // http://xkcd.com/327/
2127 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2128 list ( $headers , $content ) = get_http_response ( $url , 5 );
2129 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2130 // Extract the link to the thumbnail
2131 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2132 if (! empty ( $matches [ 1 ]))
2133 { // Let's download the image.
2134 $imageurl = $matches [ 1 ];
2135 // No control on image size, so wait long enough
2136 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2137 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2138 $filepath = $cacheDir . '/' . $thumbname ;
2139 // Save image to cache.
2140 file_put_contents ( $filepath , $content );
2141 if ( resizeImage ( $filepath ))
2143 header ( 'Content-Type: image/jpeg' );
2144 echo file_get_contents ( $filepath );
2154 // For all other domains, we try to download the image and make a thumbnail.
2155 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2156 list ( $headers , $content ) = get_http_response ( $url , 30 );
2157 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2158 $filepath = $cacheDir . '/' . $thumbname ;
2159 // Save image to cache.
2160 file_put_contents ( $filepath , $content );
2161 if ( resizeImage ( $filepath ))
2163 header ( 'Content-Type: image/jpeg' );
2164 echo file_get_contents ( $filepath );
2171 // Otherwise, return an empty image (8x8 transparent gif)
2172 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2173 // Also put something in cache so that this URL is not requested twice.
2174 file_put_contents ( $cacheDir . '/' . $blankname , $blankgif );
2175 header ( 'Content-Type: image/gif' );
2179 // Make a thumbnail of the image (to width: 120 pixels)
2180 // Returns true if success, false otherwise.
2181 function resizeImage ( $filepath )
2183 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2185 // Trick: some stupid people rename GIF as JPEG... or else.
2186 // So we really try to open each image type whatever the extension is.
2187 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2189 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2190 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2191 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2192 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2195 $ystart = 0 ; $yheight = $h ;
2196 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2197 $nw = 120 ; // Desired width
2198 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2200 $im2 = imagecreatetruecolor ( $nw , $nh );
2201 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2202 imageinterlace ( $im2 , true ); // For progressive JPEG.
2203 $tempname = $filepath . '_TEMP.jpg' ;
2204 imagejpeg ( $im2 , $tempname , 90 );
2208 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2212 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=genthumbnail' )) { genThumbnail (); exit ; } // Thumbnail generation/cache does not need the link database.
2213 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=dailyrss' )) { showDailyRSS (); exit ; }
2214 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) {
2215 $_SESSION [ 'LINKS_PER_PAGE' ] = $conf- > get ( 'config.LINKS_PER_PAGE' , 20 );