]>
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/Languages.php' ;
57 require_once 'application/LinkDB.php' ;
58 require_once 'application/LinkFilter.php' ;
59 require_once 'application/LinkUtils.php' ;
60 require_once 'application/NetscapeBookmarkUtils.php' ;
61 require_once 'application/PageBuilder.php' ;
62 require_once 'application/TimeZone.php' ;
63 require_once 'application/Url.php' ;
64 require_once 'application/Utils.php' ;
65 require_once 'application/PluginManager.php' ;
66 require_once 'application/Router.php' ;
67 require_once 'application/Updater.php' ;
68 require_once 'inc/rain.tpl.class.php' ;
70 // Ensure the PHP version is supported
72 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
73 } catch ( Exception
$exc ) {
74 header ( 'Content-Type: text/plain; charset=utf-8' );
75 echo $exc- > getMessage ();
79 // Force cookie path (but do not change lifetime)
80 $cookie = session_get_cookie_params ();
82 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
83 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
85 // Set default cookie expiration and path.
86 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
87 // Set session parameters on server side.
88 // If the user does not access any page within this time, his/her session is considered expired.
89 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
90 // Use cookies to store session.
91 ini_set ( 'session.use_cookies' , 1 );
92 // Force cookies for session (phpsessionID forbidden in URL).
93 ini_set ( 'session.use_only_cookies' , 1 );
94 // Prevent PHP form using sessionID in URL if cookies are disabled.
95 ini_set ( 'session.use_trans_sid' , false );
97 session_name ( 'shaarli' );
98 // Start session if needed (Some server auto-start sessions).
99 if ( session_id () == '' ) {
103 // Regenerate session ID if invalid or not defined in cookie.
104 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
105 session_regenerate_id ( true );
106 $_COOKIE [ 'shaarli' ] = session_id ();
109 $conf = new ConfigManager ();
110 $conf- > setEmpty ( 'general.timezone' , date_default_timezone_get ());
111 $conf- > setEmpty ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
112 RainTPL
:: $tpl_dir = $conf- > get ( 'resource.raintpl_tpl' ); // template directory
113 RainTPL
:: $cache_dir = $conf- > get ( 'resource.raintpl_tmp' ); // cache directory
115 $pluginManager = new PluginManager ( $conf );
116 $pluginManager- > load ( $conf- > get ( 'general.enabled_plugins' ));
118 date_default_timezone_set ( $conf- > get ( 'general.timezone' , 'UTC' ));
120 ob_start (); // Output buffering for the page cache.
122 // In case stupid admin has left magic_quotes enabled in php.ini:
123 if ( get_magic_quotes_gpc ())
125 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
126 $_POST = array_map ( 'stripslashes_deep' , $_POST );
127 $_GET = array_map ( 'stripslashes_deep' , $_GET );
128 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
131 // Prevent caching on client side or proxy: (yes, it's ugly)
132 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
133 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
134 header ( "Cache-Control: post-check=0, pre-check=0" , false );
135 header ( "Pragma: no-cache" );
137 if (! is_file ( $conf- > getConfigFileExt ())) {
138 // Ensure Shaarli has proper access to its resources
139 $errors = ApplicationUtils
:: checkResourcePermissions ( $conf );
141 if ( $errors != array ()) {
142 $message = '<p>Insufficient permissions:</p><ul>' ;
144 foreach ( $errors as $error ) {
145 $message .= '<li>' . $error . '</li>' ;
149 header ( 'Content-Type: text/html; charset=utf-8' );
154 // Display the installation form if no existing config is found
158 // a token depending of deployment salt, user password, and the current ip
159 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $conf- > get ( 'credentials.hash' ) . $_SERVER [ 'REMOTE_ADDR' ] . $conf- > get ( 'credentials.salt' )));
161 // Sniff browser language and set date format accordingly.
162 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
163 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
165 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
168 * Checking session state (i.e. is the user still logged in)
170 * @param ConfigManager $conf The configuration manager.
172 * @return bool: true if the user is logged in, false otherwise.
174 function setup_login_state ( $conf )
176 if ( $conf- > get ( 'security.open_shaarli' )) {
179 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
180 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
181 if (! $conf- > exists ( 'credentials.login' )) {
182 $userIsLoggedIn = false ; // Shaarli is not configured yet.
183 $loginFailure = true ;
185 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
186 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
189 fillSessionInfo ( $conf );
190 $userIsLoggedIn = true ;
192 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
193 if ( empty ( $_SESSION [ 'uid' ])
194 || ( $conf- > get ( 'security.session_protection_disabled' ) == false && $_SESSION [ 'ip' ] != allIPs ())
195 || time () >= $_SESSION [ 'expires_on' ])
198 $userIsLoggedIn = false ;
199 $loginFailure = true ;
201 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
202 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
205 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
207 if (! $loginFailure ) {
208 $userIsLoggedIn = true ;
211 return $userIsLoggedIn ;
213 $userIsLoggedIn = setup_login_state ( $conf );
216 * PubSubHubbub protocol support (if enabled) [UNTESTED]
217 * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
219 * @param ConfigManager $conf Configuration Manager instance.
221 function pubsubhub ( $conf )
223 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
226 include_once './publisher.php' ;
227 $p = new Publisher ( $pshUrl );
229 index_url ( $_SERVER ). '?do=atom' ,
230 index_url ( $_SERVER ). '?do=rss'
232 $p- > publish_update ( $topic_url );
236 // ------------------------------------------------------------------------------------------
237 // Session management
239 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
242 $ip = $_SERVER [ 'REMOTE_ADDR' ];
243 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
244 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
245 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
252 * @param ConfigManager $conf Configuration Manager instance.
254 function fillSessionInfo ( $conf )
256 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
257 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
258 $_SESSION [ 'username' ]= $conf- > get ( 'credentials.login' );
259 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
263 * Check that user/password is correct.
265 * @param string $login Username
266 * @param string $password User password
267 * @param ConfigManager $conf Configuration Manager instance.
269 * @return bool: authentication successful or not.
271 function check_auth ( $login , $password , $conf )
273 $hash = sha1 ( $password . $login . $conf- > get ( 'credentials.salt' ));
274 if ( $login == $conf- > get ( 'credentials.login' ) && $hash == $conf- > get ( 'credentials.hash' ))
275 { // Login/password is correct.
276 fillSessionInfo ( $conf );
277 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
280 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
284 // Returns true if the user is logged in.
285 function isLoggedIn ()
287 global $userIsLoggedIn ;
288 return $userIsLoggedIn ;
293 if ( isset ( $_SESSION )) {
294 unset ( $_SESSION [ 'uid' ]);
295 unset ( $_SESSION [ 'ip' ]);
296 unset ( $_SESSION [ 'username' ]);
297 unset ( $_SESSION [ 'privateonly' ]);
299 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
303 // ------------------------------------------------------------------------------------------
304 // Brute force protection system
305 // Several consecutive failed logins will ban the IP address for 30 minutes.
306 if (! is_file ( $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ))) {
309 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
310 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>"
313 include $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' );
315 * Signal a failed login. Will ban the IP if too many failures:
317 * @param ConfigManager $conf Configuration Manager instance.
319 function ban_loginFailed ( $conf )
321 $ip = $_SERVER [ 'REMOTE_ADDR' ];
322 $gb = $GLOBALS [ 'IPBANS' ];
323 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
324 $gb [ 'FAILURES' ][ $ip ] ++
;
325 if ( $gb [ 'FAILURES' ][ $ip ] > ( $conf- > get ( 'security.ban_after' ) - 1 ))
327 $gb [ 'BANS' ][ $ip ] = time () +
$conf- > get ( 'security.ban_after' , 1800 );
328 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
330 $GLOBALS [ 'IPBANS' ] = $gb ;
332 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
333 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
338 * Signals a successful login. Resets failed login counter.
340 * @param ConfigManager $conf Configuration Manager instance.
342 function ban_loginOk ( $conf )
344 $ip = $_SERVER [ 'REMOTE_ADDR' ];
345 $gb = $GLOBALS [ 'IPBANS' ];
346 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
347 $GLOBALS [ 'IPBANS' ] = $gb ;
349 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
350 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
355 * Checks if the user CAN login. If 'true', the user can try to login.
357 * @param ConfigManager $conf Configuration Manager instance.
359 * @return bool: true if the user is allowed to login.
361 function ban_canLogin ( $conf )
363 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
364 if ( isset ( $gb [ 'BANS' ][ $ip ]))
366 // User is banned. Check if the ban has expired:
367 if ( $gb [ 'BANS' ][ $ip ]<= time ())
368 { // Ban expired, user can try to login again.
369 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
370 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
372 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
373 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
375 return true ; // Ban has expired, user can login.
377 return false ; // User is banned.
379 return true ; // User is not banned.
382 // ------------------------------------------------------------------------------------------
383 // Process login form: Check if login/password is correct.
384 if ( isset ( $_POST [ 'login' ]))
386 if (! ban_canLogin ( $conf )) die ( 'I said: NO. You are banned for the moment. Go away.' );
387 if ( isset ( $_POST [ 'password' ])
388 && tokenOk ( $_POST [ 'token' ])
389 && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ], $conf ))
390 ) { // Login/password is OK.
392 // If user wants to keep the session cookie even after the browser closes:
393 if (! empty ( $_POST [ 'longlastingsession' ]))
395 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
396 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
397 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
399 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
400 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
401 // Note: Never forget the trailing slash on the cookie path!
402 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
404 else // Standard session expiration (=when browser closes)
406 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
407 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
408 session_regenerate_id ( true );
411 // Optional redirect after login:
412 if ( isset ( $_GET [ 'post' ])) {
413 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
414 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
415 if (! empty ( $_GET [ $param ])) {
416 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
419 header ( 'Location: ' . $uri );
423 if ( isset ( $_GET [ 'edit_link' ])) {
424 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
428 if ( isset ( $_POST [ 'returnurl' ])) {
429 // Prevent loops over login screen.
430 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
431 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
435 header ( 'Location: ?' ); exit ;
439 ban_loginFailed ( $conf );
440 $redir = '&username=' . $_POST [ 'login' ];
441 if ( isset ( $_GET [ 'post' ])) {
442 $redir .= '&post=' . urlencode ( $_GET [ 'post' ]);
443 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
444 if (! empty ( $_GET [ $param ])) {
445 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
449 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
454 // ------------------------------------------------------------------------------------------
455 // Misc utility functions:
457 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
458 function return_bytes ( $val )
460 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
463 case 'g' : $val *= 1024 ;
464 case 'm' : $val *= 1024 ;
465 case 'k' : $val *= 1024 ;
470 // Try to determine max file size for uploads (POST).
471 // Returns an integer (in bytes)
472 function getMaxFileSize ()
474 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
475 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
476 // Return the smaller of two:
477 $maxsize = min ( $size1 , $size2 );
478 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
482 // ------------------------------------------------------------------------------------------
483 // Token management for XSRF protection
484 // Token should be used in any form which acts on data (create,update,delete,import...).
485 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
490 * @param ConfigManager $conf Configuration Manager instance.
492 * @return string token.
494 function getToken ( $conf )
496 $rnd = sha1 ( uniqid ( '' , true ) . '_' . mt_rand () . $conf- > get ( 'credentials.salt' )); // We generate a random string.
497 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
501 // Tells if a token is OK. Using this function will destroy the token.
503 function tokenOk ( $token )
505 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
507 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
508 return true ; // Token is OK.
510 return false ; // Wrong token, or already used.
514 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
515 * Gives the last 7 days (which have links).
516 * This RSS feed cannot be filtered.
518 * @param ConfigManager $conf Configuration Manager instance.
520 function showDailyRSS ( $conf ) {
522 $query = $_SERVER [ 'QUERY_STRING' ];
523 $cache = new CachedPage (
524 $conf- > get ( 'config.PAGE_CACHE' ),
526 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
528 $cached = $cache- > cachedVersion ();
529 if (! empty ( $cached )) {
534 // If cached was not found (or not usable), then read the database and build the response:
535 // Read links from database (and filter private links if used it not logged in).
536 $LINKSDB = new LinkDB (
537 $conf- > get ( 'resource.datastore' ),
539 $conf- > get ( 'privacy.hide_public_links' ),
540 $conf- > get ( 'redirector.url' ),
541 $conf- > get ( 'redirector.encode_url' )
544 /* Some Shaarlies may have very few links, so we need to look
545 back in time (rsort()) until we have enough days ($nb_of_days).
547 $linkdates = array ();
548 foreach ( $LINKSDB as $linkdate => $value ) {
549 $linkdates [] = $linkdate ;
552 $nb_of_days = 7 ; // We take 7 days.
553 $today = date ( 'Ymd' );
556 foreach ( $linkdates as $linkdate ) {
557 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
558 if ( strcmp ( $day , $today ) < 0 ) {
559 if ( empty ( $days [ $day ])) {
560 $days [ $day ] = array ();
562 $days [ $day ][] = $linkdate ;
565 if ( count ( $days ) > $nb_of_days ) {
566 break ; // Have we collected enough days?
570 // Build the RSS feed.
571 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
572 $pageaddr = escape ( index_url ( $_SERVER ));
573 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
575 echo '<title>Daily - ' . $conf- > get ( 'general.title' ) . '</title>' ;
576 echo '<link>' . $pageaddr . '</link>' ;
577 echo '<description>Daily shared links</description>' ;
578 echo '<language>en-en</language>' ;
579 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
582 foreach ( $days as $day => $linkdates ) {
583 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
584 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
586 // Build the HTML body of this RSS entry.
591 // We pre-format some fields for proper output.
592 foreach ( $linkdates as $linkdate ) {
593 $l = $LINKSDB [ $linkdate ];
594 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $conf- > get ( 'redirector.url' ));
595 $l [ 'thumbnail' ] = thumbnail ( $conf , $l [ 'url' ]);
596 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
597 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
598 if ( startsWith ( $l [ 'url' ], '?' )) {
599 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
601 $links [ $linkdate ] = $l ;
604 // Then build the HTML for this day:
606 $tpl- > assign ( 'title' , $conf- > get ( 'general.title' ));
607 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
608 $tpl- > assign ( 'absurl' , $absurl );
609 $tpl- > assign ( 'links' , $links );
610 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
611 $tpl- > assign ( 'hide_timestamps' , $conf- > get ( 'privacy.hide_timestamps' , false ));
612 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
614 echo $html . PHP_EOL
;
616 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
618 $cache- > cache ( ob_get_contents ());
624 * Show the 'Daily' page.
626 * @param PageBuilder $pageBuilder Template engine wrapper.
627 * @param LinkDB $LINKSDB LinkDB instance.
628 * @param ConfigManager $conf Configuration Manager instance.
629 * @param PluginManager $pluginManager Plugin Manager instane.
631 function showDaily ( $pageBuilder , $LINKSDB , $conf , $pluginManager )
633 $day = date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
634 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
636 $days = $LINKSDB- > days ();
637 $i = array_search ( $day , $days );
638 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
643 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
644 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
648 $linksToDisplay = $LINKSDB- > filterDay ( $day );
649 } catch ( Exception
$exc ) {
651 $linksToDisplay = array ();
654 // We pre-format some fields for proper output.
655 foreach ( $linksToDisplay as $key => $link )
658 $taglist = explode ( ' ' , $link [ 'tags' ]);
659 uasort ( $taglist , 'strcasecmp' );
660 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
661 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
662 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $conf , $link [ 'url' ]);
663 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
664 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
667 /* We need to spread the articles on 3 columns.
668 I did not want to use a JavaScript lib like http://masonry.desandro.com/
669 so I manually spread entries with a simple method: I roughly evaluate the
670 height of a div according to title and description length.
672 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
673 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
674 foreach ( $linksToDisplay as $key => $link )
676 // Roughly estimate length of entry (by counting characters)
677 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
678 // Description: 836 characters gives roughly 342 pixel height.
679 // This is not perfect, but it's usually OK.
680 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
681 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
682 // Then put in column which is the less filled:
683 $smallest = min ( $fill ); // find smallest value in array.
684 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
685 array_push ( $columns [ $index ], $link ); // Put entry in this column.
686 $fill [ $index ] +
= $length ;
689 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
691 'linksToDisplay' => $linksToDisplay ,
693 'day' => $dayDate- > getTimestamp (),
694 'previousday' => $previousday ,
695 'nextday' => $nextday ,
698 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
700 foreach ( $data as $key => $value ) {
701 $pageBuilder- > assign ( $key , $value );
704 $pageBuilder- > renderPage ( 'daily' );
709 * Renders the linklist
711 * @param pageBuilder $PAGE pageBuilder instance.
712 * @param LinkDB $LINKSDB LinkDB instance.
713 * @param ConfigManager $conf Configuration Manager instance.
714 * @param PluginManager $pluginManager Plugin Manager instance.
716 function showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ) {
717 buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ); // Compute list of links to display
718 $PAGE- > renderPage ( 'linklist' );
722 * Render HTML page (according to URL parameters and user rights)
724 * @param ConfigManager $conf Configuration Manager instance.
725 * @param PluginManager $pluginManager Plugin Manager instance,
727 function renderPage ( $conf , $pluginManager )
729 $LINKSDB = new LinkDB (
730 $conf- > get ( 'resource.datastore' ),
732 $conf- > get ( 'privacy.hide_public_links' ),
733 $conf- > get ( 'redirector.url' ),
734 $conf- > get ( 'redirector.encode_url' )
737 $updater = new Updater (
738 read_updates_file ( $conf- > get ( 'resource.updates' )),
744 $newUpdates = $updater- > update ();
745 if (! empty ( $newUpdates )) {
747 $conf- > get ( 'resource.updates' ),
748 $updater- > getDoneUpdates ()
752 catch ( Exception
$e ) {
753 die ( $e- > getMessage ());
756 $PAGE = new PageBuilder ( $conf );
757 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
758 $PAGE- > assign ( 'privateLinkcount' , count_private ( $LINKSDB ));
760 // Determine which page will be rendered.
761 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
762 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
764 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
765 // Then assign generated data to RainTPL.
766 $common_hooks = array (
772 foreach ( $common_hooks as $name ) {
773 $plugin_data = array ();
774 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
776 'target' => $targetPage ,
777 'loggedin' => isLoggedIn ()
780 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
783 // -------- Display login form.
784 if ( $targetPage == Router
:: $PAGE_LOGIN )
786 if ( $conf- > get ( 'security.open_shaarli' )) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
787 if ( isset ( $_GET [ 'username' ])) {
788 $PAGE- > assign ( 'username' , escape ( $_GET [ 'username' ]));
790 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
791 $PAGE- > renderPage ( 'loginform' );
794 // -------- User wants to logout.
795 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=logout' ))
797 invalidateCaches ( $conf- > get ( 'resource.page_cache' ));
799 header ( 'Location: ?' );
803 // -------- Picture wall
804 if ( $targetPage == Router
:: $PAGE_PICWALL )
806 // Optionally filter the results:
807 $links = $LINKSDB- > filterSearch ( $_GET );
808 $linksToDisplay = array ();
810 // Get only links which have a thumbnail.
811 foreach ( $links as $link )
813 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
814 $thumb = lazyThumbnail ( $conf , $link [ 'url' ], $permalink );
815 if ( $thumb != '' ) // Only output links which have a thumbnail.
817 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
818 $linksToDisplay []= $link ; // Add to array.
823 'linksToDisplay' => $linksToDisplay ,
825 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
827 foreach ( $data as $key => $value ) {
828 $PAGE- > assign ( $key , $value );
831 $PAGE- > renderPage ( 'picwall' );
835 // -------- Tag cloud
836 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
838 $tags = $LINKSDB- > allTags ();
840 // We sort tags alphabetically, then choose a font size according to count.
841 // First, find max value.
843 foreach ( $tags as $value ) {
844 $maxcount = max ( $maxcount , $value );
847 // Sort tags alphabetically: case insensitive, support locale if avalaible.
848 uksort ( $tags , function ( $a , $b ) {
849 // Collator is part of PHP intl.
850 if ( class_exists ( 'Collator' )) {
851 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
852 if (! intl_is_failure ( intl_get_error_code ())) {
853 return $c- > compare ( $a , $b );
856 return strcasecmp ( $a , $b );
860 foreach ( $tags as $key => $value ) {
861 // Tag font size scaling:
862 // default 15 and 30 logarithm bases affect scaling,
863 // 22 and 6 are arbitrary font sizes for max and min sizes.
864 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
865 $tagList [ $key ] = array (
867 'size' => number_format ( $size , 2 , '.' , '' ),
874 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
876 foreach ( $data as $key => $value ) {
877 $PAGE- > assign ( $key , $value );
880 $PAGE- > renderPage ( 'tagcloud' );
885 if ( $targetPage == Router
:: $PAGE_DAILY ) {
886 showDaily ( $PAGE , $LINKSDB , $conf , $pluginManager );
889 // ATOM and RSS feed.
890 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
891 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
892 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
895 $query = $_SERVER [ 'QUERY_STRING' ];
896 $cache = new CachedPage (
897 $conf- > get ( 'resource.page_cache' ),
899 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
901 $cached = $cache- > cachedVersion ();
902 if (! empty ( $cached )) {
908 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
909 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
910 $feedGenerator- > setHideDates ( $conf- > get ( 'privacy.hide_timestamps' ) && ! isLoggedIn ());
911 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $conf- > get ( 'feed.rss_permalinks' ));
912 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
913 if (! empty ( $pshUrl )) {
914 $feedGenerator- > setPubsubhubUrl ( $pshUrl );
916 $data = $feedGenerator- > buildData ();
918 // Process plugin hook.
919 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
920 'loggedin' => isLoggedIn (),
921 'target' => $targetPage ,
924 // Render the template.
925 $PAGE- > assignAll ( $data );
926 $PAGE- > renderPage ( 'feed.' . $feedType );
927 $cache- > cache ( ob_get_contents ());
932 // Display openseach plugin (XML)
933 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
934 header ( 'Content-Type: application/xml; charset=utf-8' );
935 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
936 $PAGE- > renderPage ( 'opensearch' );
940 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
941 if ( isset ( $_GET [ 'addtag' ]))
943 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
944 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
945 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
947 // Prevent redirection loop
948 if ( isset ( $params [ 'addtag' ])) {
949 unset ( $params [ 'addtag' ]);
952 // Check if this tag is already in the search query and ignore it if it is.
953 // Each tag is always separated by a space
954 if ( isset ( $params [ 'searchtags' ])) {
955 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
957 $current_tags = array ();
960 foreach ( $current_tags as $value ) {
961 if ( $value === $_GET [ 'addtag' ]) {
966 // Append the tag if necessary
967 if ( empty ( $params [ 'searchtags' ])) {
968 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
971 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
974 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
975 header ( 'Location: ?' . http_build_query ( $params ));
979 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
980 if ( isset ( $_GET [ 'removetag' ])) {
981 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
982 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
983 header ( 'Location: ?' );
987 // In case browser does not send HTTP_REFERER
988 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
990 // Prevent redirection loop
991 if ( isset ( $params [ 'removetag' ])) {
992 unset ( $params [ 'removetag' ]);
995 if ( isset ( $params [ 'searchtags' ])) {
996 $tags = explode ( ' ' , $params [ 'searchtags' ]);
997 // Remove value from array $tags.
998 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
999 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1001 if ( empty ( $params [ 'searchtags' ])) {
1002 unset ( $params [ 'searchtags' ]);
1005 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1007 header ( 'Location: ?' . http_build_query ( $params ));
1011 // -------- User wants to change the number of links per page (linksperpage=...)
1012 if ( isset ( $_GET [ 'linksperpage' ])) {
1013 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1014 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1017 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1021 // -------- User wants to see only private links (toggle)
1022 if ( isset ( $_GET [ 'privateonly' ])) {
1023 if ( empty ( $_SESSION [ 'privateonly' ])) {
1024 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1026 unset ( $_SESSION [ 'privateonly' ]); // See all links
1029 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1033 // -------- Handle other actions allowed for non-logged in users:
1036 // User tries to post new link but is not logged in:
1037 // Show login screen, then redirect to ?post=...
1038 if ( isset ( $_GET [ 'post' ]))
1040 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.
1044 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1045 if ( isset ( $_GET [ 'edit_link' ])) {
1046 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1050 exit ; // Never remove this one! All operations below are reserved for logged in user.
1053 // -------- All other functions are reserved for the registered user:
1055 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1056 if ( $targetPage == Router
:: $PAGE_TOOLS )
1059 'pageabsaddr' => index_url ( $_SERVER ),
1061 $pluginManager- > executeHooks ( 'render_tools' , $data );
1063 foreach ( $data as $key => $value ) {
1064 $PAGE- > assign ( $key , $value );
1067 $PAGE- > renderPage ( 'tools' );
1071 // -------- User wants to change his/her password.
1072 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1074 if ( $conf- > get ( 'security.open_shaarli' )) {
1075 die ( 'You are not supposed to change a password on an Open Shaarli.' );
1078 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1080 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1082 // Make sure old password is correct.
1083 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $conf- > get ( 'credentials.login' ). $conf- > get ( 'credentials.salt' ));
1084 if ( $oldhash != $conf- > get ( 'credentials.hash' )) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1085 // Save new password
1086 // Salt renders rainbow-tables attacks useless.
1087 $conf- > set ( 'credentials.salt' , sha1 ( uniqid ( '' , true ) . '_' . mt_rand ()));
1088 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $conf- > get ( 'credentials.login' ) . $conf- > get ( 'credentials.salt' )));
1090 $conf- > write ( isLoggedIn ());
1092 catch ( Exception
$e ) {
1094 'ERROR while writing config file after changing password.' . PHP_EOL
.
1098 // TODO: do not handle exceptions/errors in JS.
1099 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1102 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1105 else // show the change password form.
1107 $PAGE- > renderPage ( 'changepassword' );
1112 // -------- User wants to change configuration
1113 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1115 if (! empty ( $_POST [ 'title' ]) )
1117 if (! tokenOk ( $_POST [ 'token' ])) {
1118 die ( 'Wrong token.' ); // Go away!
1121 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1122 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1124 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1126 $conf- > set ( 'general.timezone' , $tz );
1127 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
1128 $conf- > set ( 'general.header_link' , escape ( $_POST [ 'titleLink' ]));
1129 $conf- > set ( 'redirector.url' , escape ( $_POST [ 'redirector' ]));
1130 $conf- > set ( 'security.session_protection_disabled' , ! empty ( $_POST [ 'disablesessionprotection' ]));
1131 $conf- > set ( 'privacy.default_private_links' , ! empty ( $_POST [ 'privateLinkByDefault' ]));
1132 $conf- > set ( 'feed.rss_permalinks' , ! empty ( $_POST [ 'enableRssPermalinks' ]));
1133 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
1134 $conf- > set ( 'privacy.hide_public_links' , ! empty ( $_POST [ 'hidePublicLinks' ]));
1136 $conf- > write ( isLoggedIn ());
1138 catch ( Exception
$e ) {
1140 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1144 // TODO: do not handle exceptions/errors in JS.
1145 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=configure \' ;</script>' ;
1148 echo '<script>alert("Configuration was saved.");document.location= \' ?do=configure \' ;</script>' ;
1151 else // Show the configuration form.
1153 $PAGE- > assign ( 'title' , $conf- > get ( 'general.title' ));
1154 $PAGE- > assign ( 'redirector' , $conf- > get ( 'redirector.url' ));
1155 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $conf- > get ( 'general.timezone' ));
1156 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1157 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1158 $PAGE- > assign ( 'private_links_default' , $conf- > get ( 'privacy.default_private_links' , false ));
1159 $PAGE- > assign ( 'session_protection_disabled' , $conf- > get ( 'security.session_protection_disabled' , false ));
1160 $PAGE- > assign ( 'enable_rss_permalinks' , $conf- > get ( 'feed.rss_permalinks' , false ));
1161 $PAGE- > assign ( 'enable_update_check' , $conf- > get ( 'updates.check_updates' , true ));
1162 $PAGE- > assign ( 'hide_public_links' , $conf- > get ( 'privacy.hide_public_links' , false ));
1163 $PAGE- > renderPage ( 'configure' );
1168 // -------- User wants to rename a tag or delete it
1169 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1171 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1172 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1173 $PAGE- > renderPage ( 'changetag' );
1177 if (! tokenOk ( $_POST [ 'token' ])) {
1178 die ( 'Wrong token.' );
1182 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1183 $needle = trim ( $_POST [ 'fromtag' ]);
1184 // True for case-sensitive tag search.
1185 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1186 foreach ( $linksToAlter as $key => $value )
1188 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1189 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1190 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1191 $LINKSDB [ $key ]= $value ;
1193 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1194 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1199 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1200 $needle = trim ( $_POST [ 'fromtag' ]);
1201 // True for case-sensitive tag search.
1202 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1203 foreach ( $linksToAlter as $key => $value )
1205 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1206 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1207 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1208 $LINKSDB [ $key ]= $value ;
1210 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' )); // Save to disk.
1211 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1216 // -------- User wants to add a link without using the bookmarklet: Show form.
1217 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1219 $PAGE- > renderPage ( 'addlink' );
1223 // -------- User clicked the "Save" button when editing a link: Save link to database.
1224 if ( isset ( $_POST [ 'save_edit' ]))
1227 if (! tokenOk ( $_POST [ 'token' ])) {
1228 die ( 'Wrong token.' );
1230 // Remove multiple spaces.
1231 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1232 // Remove first '-' char in tags.
1233 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1234 // Remove duplicates.
1235 $tags = implode(' ', array_unique(explode(' ', $tags )));
1236 $linkdate = $_POST [' lf_linkdate
'];
1237 $url = trim( $_POST [' lf_url
']);
1238 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1239 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1240 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1242 $url = ' http
: //' . $url;
1246 'title' => trim ( $_POST [ 'lf_title' ]),
1248 'description' => $_POST [ 'lf_description' ],
1249 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1250 'linkdate' => $linkdate ,
1251 'tags' => str_replace ( ',' , ' ' , $tags )
1253 // If title is empty, use the URL as title.
1254 if ( $link [ 'title' ] == '' ) {
1255 $link [ 'title' ] = $link [ 'url' ];
1258 $pluginManager- > executeHooks ( 'save_link' , $link );
1260 $LINKSDB [ $linkdate ] = $link ;
1261 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1264 // If we are called from the bookmarklet, we must close the popup:
1265 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1266 echo '<script>self.close();</script>' ;
1270 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1271 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1272 // Scroll to the link which has been edited.
1273 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1274 // After saving the link, redirect to the page the user was on.
1275 header ( 'Location: ' . $location );
1279 // -------- User clicked the "Cancel" button when editing a link.
1280 if ( isset ( $_POST [ 'cancel_edit' ]))
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 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1285 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1286 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1287 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1291 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1292 if ( isset ( $_POST [ 'delete_link' ]))
1294 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1295 // We do not need to ask for confirmation:
1296 // - confirmation is handled by JavaScript
1297 // - we are protected from XSRF by the token.
1298 $linkdate = $_POST [ 'lf_linkdate' ];
1300 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1302 unset ( $LINKSDB [ $linkdate ]);
1303 $LINKSDB- > savedb ( 'resource.page_cache' ); // save to disk
1305 // If we are called from the bookmarklet, we must close the popup:
1306 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1307 // Pick where we're going to redirect
1308 // =============================================================
1309 // Basically, we can't redirect to where we were previously if it was a permalink
1310 // or an edit_link, because it would 404.
1312 // - / : nothing in $_GET, redirect to self
1313 // - /?page : redirect to self
1314 // - /?searchterm : redirect to self (there might be other links)
1315 // - /?searchtags : redirect to self
1316 // - /permalink : redirect to / (the link does not exist anymore)
1317 // - /?edit_link : redirect to / (the link does not exist anymore)
1318 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1319 // redirect is not satisfied, and only then redirect to /
1322 if ( count ( $_GET ) == 0
1323 || isset ( $_GET [ 'page' ])
1324 || isset ( $_GET [ 'searchterm' ])
1325 || isset ( $_GET [ 'searchtags' ])
1327 if ( isset ( $_POST [ 'returnurl' ])) {
1328 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1330 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1334 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1338 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1339 if ( isset ( $_GET [ 'edit_link' ]))
1341 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1342 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1345 'link_is_new' => false ,
1346 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1347 'tags' => $LINKSDB- > allTags (),
1349 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1351 foreach ( $data as $key => $value ) {
1352 $PAGE- > assign ( $key , $value );
1355 $PAGE- > renderPage ( 'editlink' );
1359 // -------- User want to post a new link: Display link edit form.
1360 if ( isset ( $_GET [ 'post' ])) {
1361 $url = cleanup_url ( $_GET [ 'post' ]);
1363 $link_is_new = false ;
1364 // Check if URL is not already in database (in this case, we will edit the existing link)
1365 $link = $LINKSDB- > getLinkFromUrl ( $url );
1368 $link_is_new = true ;
1369 $linkdate = strval ( date ( 'Ymd_His' ));
1370 // Get title if it was provided in URL (by the bookmarklet).
1371 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1372 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1373 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1374 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1375 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1376 // 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.)
1377 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1378 // Short timeout to keep the application responsive
1379 list ( $headers , $content ) = get_http_response ( $url , 4 );
1380 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1381 // Retrieve charset.
1382 $charset = get_charset ( $headers , $content );
1384 $title = html_extract_title ( $content );
1385 // Re-encode title in utf-8 if necessary.
1386 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1387 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1393 $url = '?' . smallHash ( $linkdate );
1396 $url = escape ( $url );
1397 $title = escape ( $title );
1400 'linkdate' => $linkdate ,
1403 'description' => $description ,
1405 'private' => $private
1411 'link_is_new' => $link_is_new ,
1412 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1413 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1414 'tags' => $LINKSDB- > allTags (),
1415 'default_private_links' => $conf- > get ( 'default_private_links' , false ),
1417 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1419 foreach ( $data as $key => $value ) {
1420 $PAGE- > assign ( $key , $value );
1423 $PAGE- > renderPage ( 'editlink' );
1427 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1428 // Export links as a Netscape Bookmarks file
1430 if ( empty ( $_GET [ 'selection' ])) {
1431 $PAGE- > renderPage ( 'export' );
1435 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1436 $selection = $_GET [ 'selection' ];
1437 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1438 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1440 $prependNoteUrl = false ;
1446 NetscapeBookmarkUtils
:: filterAndFormat (
1453 } catch ( Exception
$exc ) {
1454 header ( 'Content-Type: text/plain; charset=utf-8' );
1455 echo $exc- > getMessage ();
1458 $now = new DateTime ();
1459 header ( 'Content-Type: text/html; charset=utf-8' );
1461 'Content-disposition: attachment; filename=bookmarks_'
1462 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1464 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1465 $PAGE- > assign ( 'eol' , PHP_EOL
);
1466 $PAGE- > assign ( 'selection' , $selection );
1467 $PAGE- > renderPage ( 'export.bookmarks' );
1471 // -------- User is uploading a file for import
1472 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=upload' ))
1474 // If file is too big, some form field may be missing.
1475 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1477 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1478 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>' ;
1481 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1482 importFile ( $LINKSDB );
1486 // -------- Show upload/import dialog:
1487 if ( $targetPage == Router
:: $PAGE_IMPORT )
1489 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1490 $PAGE- > renderPage ( 'import' );
1494 // Plugin administration page
1495 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1496 $pluginMeta = $pluginManager- > getPluginsMeta ();
1498 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1499 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1501 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $conf- > get ( 'plugins' , array ()));
1504 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1506 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1508 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1509 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1510 $PAGE- > renderPage ( 'pluginsadmin' );
1514 // Plugin administration form action
1515 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1517 if ( isset ( $_POST [ 'parameters_form' ])) {
1518 unset ( $_POST [ 'parameters_form' ]);
1519 foreach ( $_POST as $param => $value ) {
1520 $conf- > set ( 'plugins.' . $param , escape ( $value ));
1524 $conf- > set ( 'general.enabled_plugins' , save_plugin_config ( $_POST ));
1526 $conf- > write ( isLoggedIn ());
1528 catch ( Exception
$e ) {
1530 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1534 // TODO: do not handle exceptions/errors in JS.
1535 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1538 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1542 // -------- Otherwise, simply display search form and links:
1543 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1548 * Process the import file form.
1550 * @param LinkDB $LINKSDB Loaded LinkDB instance.
1551 * @param ConfigManager $conf Configuration Manager instance.
1553 function importFile ( $LINKSDB , $conf )
1555 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1557 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1558 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1559 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1560 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1561 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1566 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1568 // Then import the bookmarks.
1569 if ( $type == 'netscape' )
1571 // This is a standard Netscape-style bookmark file.
1572 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1573 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1575 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1576 $d = explode ( '<DD>' , $html );
1577 if ( startsWith ( $d [ 0 ], '<A ' ))
1579 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1580 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1581 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1582 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1584 foreach ( $matches as $m )
1586 $attr = $m [ 1 ]; $value = $m [ 2 ];
1587 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1588 elseif ( $attr == 'ADD_DATE' )
1590 $raw_add_date = intval ( $value );
1591 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1593 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1594 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1596 if ( $link [ 'url' ]!= '' )
1598 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1599 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1601 { // Link not in database, let's import it...
1602 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1604 // Make sure date/time is not already used by another link.
1605 // (Some bookmark files have several different links with the same ADD_DATE)
1606 // We increment date by 1 second until we find a date which is not used in DB.
1607 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1608 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1609 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1610 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1613 else // Link already present in database.
1616 { // If overwrite is required, we import link data, except date/time.
1617 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1618 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1626 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1628 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1632 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1637 * Template for the list of links (<div id="linklist">)
1638 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1640 * @param pageBuilder $PAGE pageBuilder instance.
1641 * @param LinkDB $LINKSDB LinkDB instance.
1642 * @param ConfigManager $conf Configuration Manager instance.
1643 * @param PluginManager $pluginManager Plugin Manager instance.
1645 function buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager )
1647 // Used in templates
1648 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1649 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1652 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1653 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1655 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1656 } catch ( LinkNotFoundException
$e ) {
1657 $PAGE- > render404 ( $e- > getMessage ());
1661 // Filter links according search parameters.
1662 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1663 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1666 // ---- Handle paging.
1668 foreach ( $linksToDisplay as $key => $value ) {
1674 // Select articles according to paging.
1675 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1676 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1677 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1678 $page = $page < 1 ? 1 : $page ;
1679 $page = $page > $pagecount ? $pagecount : $page ;
1681 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1682 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1683 $linkDisp = array ();
1684 while ( $i < $end && $i < count ( $keys ))
1686 $link = $linksToDisplay [ $keys [ $i ]];
1687 $link [ 'description' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
1688 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1689 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1690 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1691 $link [ 'timestamp' ] = $date- > getTimestamp ();
1692 $taglist = explode ( ' ' , $link [ 'tags' ]);
1693 uasort ( $taglist , 'strcasecmp' );
1694 $link [ 'taglist' ] = $taglist ;
1695 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1696 // Check for both signs of a note: starting with ? and 7 chars long.
1697 if ( $link [ 'url' ][ 0 ] === '?' &&
1698 strlen ( $link [ 'url' ]) === 7 ) {
1699 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1702 $linkDisp [ $keys [ $i ]] = $link ;
1706 // Compute paging navigation
1707 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1708 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1709 $previous_page_url = '' ;
1710 if ( $i != count ( $keys )) {
1711 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1715 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1718 $token = isLoggedIn () ? getToken ( $conf ) : '' ;
1720 // Fill all template fields.
1722 'previous_page_url' => $previous_page_url ,
1723 'next_page_url' => $next_page_url ,
1724 'page_current' => $page ,
1725 'page_max' => $pagecount ,
1726 'result_count' => count ( $linksToDisplay ),
1727 'search_term' => $searchterm ,
1728 'search_tags' => $searchtags ,
1729 'redirector' => $conf- > get ( 'redirector.url' ), // Optional redirector URL.
1730 'links' => $linkDisp ,
1731 'tags' => $LINKSDB- > allTags (),
1734 // If there is only a single link, we change on-the-fly the title of the page.
1735 if ( count ( $linksToDisplay ) == 1 ) {
1736 $data [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ] . ' - ' . $conf- > get ( 'general.title' );
1739 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1741 foreach ( $data as $key => $value ) {
1742 $PAGE- > assign ( $key , $value );
1749 * Compute the thumbnail for a link.
1751 * With a link to the original URL.
1752 * Understands various services (youtube.com...)
1753 * Input: $url = URL for which the thumbnail must be found.
1754 * $href = if provided, this URL will be followed instead of $url
1755 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1756 * Some of them may be missing.
1757 * Return an empty array if no thumbnail available.
1759 * @param ConfigManager $conf Configuration Manager instance.
1760 * @param string $url
1761 * @param string|bool $href
1765 function computeThumbnail ( $conf , $url , $href = false )
1767 if (! $conf- > get ( 'thumbnail.enable_thumbnails' )) return array ();
1768 if ( $href == false ) $href = $url ;
1770 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1771 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1772 // ^^^^^^^^^^^ ^^^^^^^^^^^
1773 $domain = parse_url ( $url , PHP_URL_HOST
);
1774 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1776 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1777 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1778 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1780 if ( $domain == 'youtu.be' ) // Youtube short links
1782 $path = parse_url ( $url , PHP_URL_PATH
);
1783 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1784 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1786 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1788 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1789 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1790 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1793 if ( $domain == 'imgur.com' )
1795 $path = parse_url ( $url , PHP_URL_PATH
);
1796 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1797 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1798 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1799 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1800 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1802 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1803 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1805 if ( $domain == 'i.imgur.com' )
1807 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1808 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1809 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1811 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1813 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1815 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1816 return array ( 'src' => $thumburl ,
1817 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1820 if ( endsWith ( $domain , '.imageshack.us' ))
1822 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1823 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1825 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1826 return array ( 'src' => $thumburl ,
1827 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1831 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1832 // So we deport the thumbnail generation in order not to slow down page generation
1833 // (and we also cache the thumbnail)
1835 if (! $conf- > get ( 'thumbnail.enable_localcache' )) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1837 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1838 || $domain == 'vimeo.com'
1839 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1840 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1843 if ( $domain == 'vimeo.com' )
1844 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1845 $path = parse_url ( $url , PHP_URL_PATH
);
1846 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1848 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1849 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1850 $path = parse_url ( $url , PHP_URL_PATH
);
1851 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1853 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1854 { // Make sure this TED URL points to a video (/talks/...)
1855 $path = parse_url ( $url , PHP_URL_PATH
);
1856 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1858 $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)
1859 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1860 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1863 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1864 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1865 // But using the extension will do.
1866 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1867 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1869 $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)
1870 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1871 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1873 return array (); // No thumbnail.
1878 // Returns the HTML code to display a thumbnail for a link
1879 // with a link to the original URL.
1880 // Understands various services (youtube.com...)
1881 // Input: $url = URL for which the thumbnail must be found.
1882 // $href = if provided, this URL will be followed instead of $url
1883 // Returns '' if no thumbnail available.
1884 function thumbnail ( $url , $href = false )
1888 $t = computeThumbnail ( $conf , $url , $href );
1889 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1891 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
1892 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1893 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1894 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1895 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1900 // Returns the HTML code to display a thumbnail for a link
1901 // for the picture wall (using lazy image loading)
1902 // Understands various services (youtube.com...)
1903 // Input: $url = URL for which the thumbnail must be found.
1904 // $href = if provided, this URL will be followed instead of $url
1905 // Returns '' if no thumbnail available.
1906 function lazyThumbnail ( $conf , $url , $href = false )
1910 $t = computeThumbnail ( $conf , $url , $href );
1911 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1913 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
1916 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
1918 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1919 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1920 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1921 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1924 // No-JavaScript fallback.
1925 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
1926 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1927 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1928 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1929 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1930 $html .= '></noscript></a>' ;
1938 * This function should NEVER be called if the file data/config.php exists.
1940 * @param ConfigManager $conf Configuration Manager instance.
1942 function install ( $conf )
1944 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1945 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1948 // This part makes sure sessions works correctly.
1949 // (Because on some hosts, session.save_path may not be set correctly,
1950 // or we may not have write access to it.)
1951 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
1952 { // Step 2: Check if data in session is correct.
1953 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
1954 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
1955 echo 'It currently points to ' . session_save_path (). '<br>' ;
1956 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>' ;
1957 echo '<br><a href="?">Click to try again.</a></pre>' ;
1960 if (! isset ( $_SESSION [ 'session_tested' ]))
1961 { // Step 1 : Try to store data in session and reload page.
1962 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
1963 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
1965 if ( isset ( $_GET [ 'test_session' ]))
1966 { // Step 3: Sessions are OK. Remove test parameter from URL.
1967 header ( 'Location: ' . index_url ( $_SERVER ));
1971 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1974 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1975 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1977 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1979 $conf- > set ( 'general.timezone' , $tz );
1980 $login = $_POST [ 'setlogin' ];
1981 $conf- > set ( 'credentials.login' , $login );
1982 $salt = sha1 ( uniqid ( '' , true ) . '_' . mt_rand ());
1983 $conf- > set ( 'credentials.salt' , $salt );
1984 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $login . $salt ));
1985 if (! empty ( $_POST [ 'title' ])) {
1986 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
1988 $conf- > set ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
1990 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
1992 // Everything is ok, let's create config file.
1993 $conf- > write ( isLoggedIn ());
1995 catch ( Exception
$e ) {
1997 'ERROR while writing config file after installation.' . PHP_EOL
.
2001 // TODO: do not handle exceptions/errors in JS.
2002 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2005 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2009 // Display config form:
2010 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2011 $timezone_html = '' ;
2012 if ( $timezone_form != '' ) {
2013 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2016 $PAGE = new PageBuilder ( $conf );
2017 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2018 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2019 $PAGE- > renderPage ( 'install' );
2024 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2025 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2026 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2027 * This function is called by passing the URL:
2028 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2029 * [URL] is the URL of the link (e.g. a flickr page)
2030 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2031 * The function below will fetch the image from the webservice and store it in the cache.
2033 * @param ConfigManager $conf Configuration Manager instance,
2035 function genThumbnail ( $conf )
2037 // Make sure the parameters in the URL were generated by us.
2038 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $conf- > get ( 'credentials.salt' ));
2039 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2041 $cacheDir = $conf- > get ( 'resource.thumbnails_cache' , 'cache' );
2042 // Let's see if we don't already have the image for this URL in the cache.
2043 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2044 if ( is_file ( $cacheDir . '/' . $thumbname ))
2045 { // We have the thumbnail, just serve it:
2046 header ( 'Content-Type: image/jpeg' );
2047 echo file_get_contents ( $cacheDir . '/' . $thumbname );
2050 // We may also serve a blank image (if service did not respond)
2051 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2052 if ( is_file ( $cacheDir . '/' . $blankname ))
2054 header ( 'Content-Type: image/gif' );
2055 echo file_get_contents ( $cacheDir . '/' . $blankname );
2059 // Otherwise, generate the thumbnail.
2060 $url = $_GET [ 'url' ];
2061 $domain = parse_url ( $url , PHP_URL_HOST
);
2063 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2065 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2066 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2068 // Is this a link to an image, or to a flickr page ?
2070 if ( endsWith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2071 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2072 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2073 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2075 else // This is a flickr page (html)
2077 // Get the flickr html page.
2078 list ( $headers , $content ) = get_http_response ( $url , 20 );
2079 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2081 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2082 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2083 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2085 // In albums (and some other pages), the link rel="image_src" is not provided,
2086 // but flickr provides:
2087 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2090 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2091 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2097 { // Let's download the image.
2098 // Image is 240x120, so 10 seconds to download should be enough.
2099 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2100 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2101 // Save image to cache.
2102 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2103 header ( 'Content-Type: image/jpeg' );
2110 elseif ( $domain == 'vimeo.com' )
2112 // This is more complex: we have to perform a HTTP request, then parse the result.
2113 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2114 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2115 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2116 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2117 $t = unserialize ( $content );
2118 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2119 // Then we download the image and serve it to our client.
2120 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2121 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2122 // Save image to cache.
2123 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2124 header ( 'Content-Type: image/jpeg' );
2131 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2133 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2134 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2135 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2136 list ( $headers , $content ) = get_http_response ( $url , 5 );
2137 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2138 // Extract the link to the thumbnail
2139 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2140 if (! empty ( $matches [ 1 ]))
2141 { // Let's download the image.
2142 $imageurl = $matches [ 1 ];
2143 // No control on image size, so wait long enough
2144 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2145 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2146 $filepath = $cacheDir . '/' . $thumbname ;
2147 file_put_contents ( $filepath , $content ); // Save image to cache.
2148 if ( resizeImage ( $filepath ))
2150 header ( 'Content-Type: image/jpeg' );
2151 echo file_get_contents ( $filepath );
2159 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2161 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2162 // http://xkcd.com/327/
2163 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2164 list ( $headers , $content ) = get_http_response ( $url , 5 );
2165 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2166 // Extract the link to the thumbnail
2167 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2168 if (! empty ( $matches [ 1 ]))
2169 { // Let's download the image.
2170 $imageurl = $matches [ 1 ];
2171 // No control on image size, so wait long enough
2172 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2173 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2174 $filepath = $cacheDir . '/' . $thumbname ;
2175 // Save image to cache.
2176 file_put_contents ( $filepath , $content );
2177 if ( resizeImage ( $filepath ))
2179 header ( 'Content-Type: image/jpeg' );
2180 echo file_get_contents ( $filepath );
2190 // For all other domains, we try to download the image and make a thumbnail.
2191 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2192 list ( $headers , $content ) = get_http_response ( $url , 30 );
2193 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2194 $filepath = $cacheDir . '/' . $thumbname ;
2195 // Save image to cache.
2196 file_put_contents ( $filepath , $content );
2197 if ( resizeImage ( $filepath ))
2199 header ( 'Content-Type: image/jpeg' );
2200 echo file_get_contents ( $filepath );
2207 // Otherwise, return an empty image (8x8 transparent gif)
2208 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2209 // Also put something in cache so that this URL is not requested twice.
2210 file_put_contents ( $cacheDir . '/' . $blankname , $blankgif );
2211 header ( 'Content-Type: image/gif' );
2215 // Make a thumbnail of the image (to width: 120 pixels)
2216 // Returns true if success, false otherwise.
2217 function resizeImage ( $filepath )
2219 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2221 // Trick: some stupid people rename GIF as JPEG... or else.
2222 // So we really try to open each image type whatever the extension is.
2223 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2225 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2226 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2227 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2228 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2231 $ystart = 0 ; $yheight = $h ;
2232 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2233 $nw = 120 ; // Desired width
2234 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2236 $im2 = imagecreatetruecolor ( $nw , $nh );
2237 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2238 imageinterlace ( $im2 , true ); // For progressive JPEG.
2239 $tempname = $filepath . '_TEMP.jpg' ;
2240 imagejpeg ( $im2 , $tempname , 90 );
2244 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2248 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=genthumbnail' )) { genThumbnail ( $conf
); exit ; } // Thumbnail generation/cache does not need the link database.
2249 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=dailyrss' )) { showDailyRSS ( $conf
); exit ; }
2250 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) {
2251 $_SESSION [ 'LINKS_PER_PAGE' ] = $conf- > get ( 'general.links_per_page' , 20 );
2253 renderPage ( $conf , $pluginManager );