]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.7.0 - Shaare your links...
5 * The personal, minimalist, super-fast, database free, bookmarking service.
7 * Friendly fork by the Shaarli community:
8 * - https://github.com/shaarli/Shaarli
10 * Original project by sebsauvage.net:
11 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
12 * - https://github.com/sebsauvage/Shaarli
14 * Licence: http://www.opensource.org/licenses/zlib-license.php
19 // Set 'UTC' as the default timezone if it is not defined in php.ini
20 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
21 if ( date_default_timezone_get () == '' ) {
22 date_default_timezone_set ( 'UTC' );
28 define ( 'shaarli_version' , '0.7.0' );
30 // http://server.com/x/shaarli --> /shaarli/
31 define ( 'WEB_PATH' , substr ( $_SERVER [ 'REQUEST_URI' ], 0 , 1 +
strrpos ( $_SERVER [ 'REQUEST_URI' ], '/' , 0 )));
33 // High execution time in case of problematic imports/exports.
34 ini_set ( 'max_input_time' , '60' );
36 // Try to set max upload file size and read
37 ini_set ( 'memory_limit' , '128M' );
38 ini_set ( 'post_max_size' , '16M' );
39 ini_set ( 'upload_max_filesize' , '16M' );
41 // See all error except warnings
42 error_reporting ( E_ALL^E_WARNING
);
43 // See all errors (for debugging only)
44 //error_reporting(-1);
48 require_once 'application/ApplicationUtils.php' ;
49 require_once 'application/Cache.php' ;
50 require_once 'application/CachedPage.php' ;
51 require_once 'application/config/ConfigManager.php' ;
52 require_once 'application/config/ConfigPlugin.php' ;
53 require_once 'application/FeedBuilder.php' ;
54 require_once 'application/FileUtils.php' ;
55 require_once 'application/HttpUtils.php' ;
56 require_once 'application/LinkDB.php' ;
57 require_once 'application/LinkFilter.php' ;
58 require_once 'application/LinkUtils.php' ;
59 require_once 'application/NetscapeBookmarkUtils.php' ;
60 require_once 'application/PageBuilder.php' ;
61 require_once 'application/TimeZone.php' ;
62 require_once 'application/Url.php' ;
63 require_once 'application/Utils.php' ;
64 require_once 'application/PluginManager.php' ;
65 require_once 'application/Router.php' ;
66 require_once 'application/Updater.php' ;
67 require_once 'inc/rain.tpl.class.php' ;
69 // Ensure the PHP version is supported
71 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
72 } catch ( Exception
$exc ) {
73 header ( 'Content-Type: text/plain; charset=utf-8' );
74 echo $exc- > getMessage ();
78 // Force cookie path (but do not change lifetime)
79 $cookie = session_get_cookie_params ();
81 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
82 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
84 // Set default cookie expiration and path.
85 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
86 // Set session parameters on server side.
87 // If the user does not access any page within this time, his/her session is considered expired.
88 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
89 // Use cookies to store session.
90 ini_set ( 'session.use_cookies' , 1 );
91 // Force cookies for session (phpsessionID forbidden in URL).
92 ini_set ( 'session.use_only_cookies' , 1 );
93 // Prevent PHP form using sessionID in URL if cookies are disabled.
94 ini_set ( 'session.use_trans_sid' , false );
96 session_name ( 'shaarli' );
97 // Start session if needed (Some server auto-start sessions).
98 if ( session_id () == '' ) {
102 // Regenerate session ID if invalid or not defined in cookie.
103 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
104 session_regenerate_id ( true );
105 $_COOKIE [ 'shaarli' ] = session_id ();
108 $conf = new ConfigManager ();
109 $conf- > setEmpty ( 'general.timezone' , date_default_timezone_get ());
110 $conf- > setEmpty ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
111 RainTPL
:: $tpl_dir = $conf- > get ( 'resource.raintpl_tpl' ); // template directory
112 RainTPL
:: $cache_dir = $conf- > get ( 'resource.raintpl_tmp' ); // cache directory
114 $pluginManager = new PluginManager ( $conf );
115 $pluginManager- > load ( $conf- > get ( 'general.enabled_plugins' ));
117 date_default_timezone_set ( $conf- > get ( 'general.timezone' , 'UTC' ));
119 ob_start (); // Output buffering for the page cache.
121 // In case stupid admin has left magic_quotes enabled in php.ini:
122 if ( get_magic_quotes_gpc ())
124 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
125 $_POST = array_map ( 'stripslashes_deep' , $_POST );
126 $_GET = array_map ( 'stripslashes_deep' , $_GET );
127 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
130 // Prevent caching on client side or proxy: (yes, it's ugly)
131 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
132 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
133 header ( "Cache-Control: post-check=0, pre-check=0" , false );
134 header ( "Pragma: no-cache" );
136 if (! is_file ( $conf- > getConfigFileExt ())) {
137 // Ensure Shaarli has proper access to its resources
138 $errors = ApplicationUtils
:: checkResourcePermissions ( $conf );
140 if ( $errors != array ()) {
141 $message = '<p>Insufficient permissions:</p><ul>' ;
143 foreach ( $errors as $error ) {
144 $message .= '<li>' . $error . '</li>' ;
148 header ( 'Content-Type: text/html; charset=utf-8' );
153 // Display the installation form if no existing config is found
157 // a token depending of deployment salt, user password, and the current ip
158 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $conf- > get ( 'credentials.hash' ) . $_SERVER [ 'REMOTE_ADDR' ] . $conf- > get ( 'credentials.salt' )));
160 // Sniff browser language and set date format accordingly.
161 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
162 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
164 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
167 * Checking session state (i.e. is the user still logged in)
169 * @param ConfigManager $conf The configuration manager.
171 * @return bool: true if the user is logged in, false otherwise.
173 function setup_login_state ( $conf )
175 if ( $conf- > get ( 'security.open_shaarli' )) {
178 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
179 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
180 if (! $conf- > exists ( 'credentials.login' )) {
181 $userIsLoggedIn = false ; // Shaarli is not configured yet.
182 $loginFailure = true ;
184 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
185 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
188 fillSessionInfo ( $conf );
189 $userIsLoggedIn = true ;
191 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
192 if ( empty ( $_SESSION [ 'uid' ])
193 || ( $conf- > get ( 'security.session_protection_disabled' ) == false && $_SESSION [ 'ip' ] != allIPs ())
194 || time () >= $_SESSION [ 'expires_on' ])
197 $userIsLoggedIn = false ;
198 $loginFailure = true ;
200 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
201 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
204 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
206 if (! $loginFailure ) {
207 $userIsLoggedIn = true ;
210 return $userIsLoggedIn ;
212 $userIsLoggedIn = setup_login_state ( $conf );
215 * PubSubHubbub protocol support (if enabled) [UNTESTED]
216 * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
218 * @param ConfigManager $conf Configuration Manager instance.
220 function pubsubhub ( $conf )
222 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
225 include_once './publisher.php' ;
226 $p = new Publisher ( $pshUrl );
228 index_url ( $_SERVER ). '?do=atom' ,
229 index_url ( $_SERVER ). '?do=rss'
231 $p- > publish_update ( $topic_url );
235 // ------------------------------------------------------------------------------------------
236 // Session management
238 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
241 $ip = $_SERVER [ 'REMOTE_ADDR' ];
242 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
243 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
244 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
251 * @param ConfigManager $conf Configuration Manager instance.
253 function fillSessionInfo ( $conf )
255 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
256 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
257 $_SESSION [ 'username' ]= $conf- > get ( 'credentials.login' );
258 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
262 * Check that user/password is correct.
264 * @param string $login Username
265 * @param string $password User password
266 * @param ConfigManager $conf Configuration Manager instance.
268 * @return bool: authentication successful or not.
270 function check_auth ( $login , $password , $conf )
272 $hash = sha1 ( $password . $login . $conf- > get ( 'credentials.salt' ));
273 if ( $login == $conf- > get ( 'credentials.login' ) && $hash == $conf- > get ( 'credentials.hash' ))
274 { // Login/password is correct.
275 fillSessionInfo ( $conf );
276 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
279 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
283 // Returns true if the user is logged in.
284 function isLoggedIn ()
286 global $userIsLoggedIn ;
287 return $userIsLoggedIn ;
292 if ( isset ( $_SESSION )) {
293 unset ( $_SESSION [ 'uid' ]);
294 unset ( $_SESSION [ 'ip' ]);
295 unset ( $_SESSION [ 'username' ]);
296 unset ( $_SESSION [ 'privateonly' ]);
298 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
302 // ------------------------------------------------------------------------------------------
303 // Brute force protection system
304 // Several consecutive failed logins will ban the IP address for 30 minutes.
305 if (! is_file ( $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ))) {
308 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
309 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>"
312 include $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' );
314 * Signal a failed login. Will ban the IP if too many failures:
316 * @param ConfigManager $conf Configuration Manager instance.
318 function ban_loginFailed ( $conf )
320 $ip = $_SERVER [ 'REMOTE_ADDR' ];
321 $gb = $GLOBALS [ 'IPBANS' ];
322 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) $gb [ 'FAILURES' ][ $ip ]= 0 ;
323 $gb [ 'FAILURES' ][ $ip ] ++
;
324 if ( $gb [ 'FAILURES' ][ $ip ] > ( $conf- > get ( 'security.ban_after' ) - 1 ))
326 $gb [ 'BANS' ][ $ip ] = time () +
$conf- > get ( 'security.ban_after' , 1800 );
327 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
329 $GLOBALS [ 'IPBANS' ] = $gb ;
331 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
332 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
337 * Signals a successful login. Resets failed login counter.
339 * @param ConfigManager $conf Configuration Manager instance.
341 function ban_loginOk ( $conf )
343 $ip = $_SERVER [ 'REMOTE_ADDR' ];
344 $gb = $GLOBALS [ 'IPBANS' ];
345 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
346 $GLOBALS [ 'IPBANS' ] = $gb ;
348 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
349 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
354 * Checks if the user CAN login. If 'true', the user can try to login.
356 * @param ConfigManager $conf Configuration Manager instance.
358 * @return bool: true if the user is allowed to login.
360 function ban_canLogin ( $conf )
362 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
363 if ( isset ( $gb [ 'BANS' ][ $ip ]))
365 // User is banned. Check if the ban has expired:
366 if ( $gb [ 'BANS' ][ $ip ]<= time ())
367 { // Ban expired, user can try to login again.
368 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
369 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
371 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
372 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
374 return true ; // Ban has expired, user can login.
376 return false ; // User is banned.
378 return true ; // User is not banned.
381 // ------------------------------------------------------------------------------------------
382 // Process login form: Check if login/password is correct.
383 if ( isset ( $_POST [ 'login' ]))
385 if (! ban_canLogin ( $conf )) die ( 'I said: NO. You are banned for the moment. Go away.' );
386 if ( isset ( $_POST [ 'password' ])
387 && tokenOk ( $_POST [ 'token' ])
388 && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ], $conf ))
389 ) { // Login/password is OK.
391 // If user wants to keep the session cookie even after the browser closes:
392 if (! empty ( $_POST [ 'longlastingsession' ]))
394 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
395 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
396 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
398 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
399 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
400 // Note: Never forget the trailing slash on the cookie path!
401 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
403 else // Standard session expiration (=when browser closes)
405 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
406 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
407 session_regenerate_id ( true );
410 // Optional redirect after login:
411 if ( isset ( $_GET [ 'post' ])) {
412 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
413 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
414 if (! empty ( $_GET [ $param ])) {
415 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
418 header ( 'Location: ' . $uri );
422 if ( isset ( $_GET [ 'edit_link' ])) {
423 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
427 if ( isset ( $_POST [ 'returnurl' ])) {
428 // Prevent loops over login screen.
429 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
430 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
434 header ( 'Location: ?' ); exit ;
438 ban_loginFailed ( $conf );
439 $redir = '&username=' . $_POST [ 'login' ];
440 if ( isset ( $_GET [ 'post' ])) {
441 $redir .= '&post=' . urlencode ( $_GET [ 'post' ]);
442 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
443 if (! empty ( $_GET [ $param ])) {
444 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
448 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
453 // ------------------------------------------------------------------------------------------
454 // Misc utility functions:
456 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
457 function return_bytes ( $val )
459 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
462 case 'g' : $val *= 1024 ;
463 case 'm' : $val *= 1024 ;
464 case 'k' : $val *= 1024 ;
469 // Try to determine max file size for uploads (POST).
470 // Returns an integer (in bytes)
471 function getMaxFileSize ()
473 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
474 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
475 // Return the smaller of two:
476 $maxsize = min ( $size1 , $size2 );
477 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
481 // ------------------------------------------------------------------------------------------
482 // Token management for XSRF protection
483 // Token should be used in any form which acts on data (create,update,delete,import...).
484 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
489 * @param ConfigManager $conf Configuration Manager instance.
491 * @return string token.
493 function getToken ( $conf )
495 $rnd = sha1 ( uniqid ( '' , true ) . '_' . mt_rand () . $conf- > get ( 'credentials.salt' )); // We generate a random string.
496 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
500 // Tells if a token is OK. Using this function will destroy the token.
502 function tokenOk ( $token )
504 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
506 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
507 return true ; // Token is OK.
509 return false ; // Wrong token, or already used.
513 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
514 * Gives the last 7 days (which have links).
515 * This RSS feed cannot be filtered.
517 * @param ConfigManager $conf Configuration Manager instance.
519 function showDailyRSS ( $conf ) {
521 $query = $_SERVER [ 'QUERY_STRING' ];
522 $cache = new CachedPage (
523 $conf- > get ( 'config.PAGE_CACHE' ),
525 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
527 $cached = $cache- > cachedVersion ();
528 if (! empty ( $cached )) {
533 // If cached was not found (or not usable), then read the database and build the response:
534 // Read links from database (and filter private links if used it not logged in).
535 $LINKSDB = new LinkDB (
536 $conf- > get ( 'resource.datastore' ),
538 $conf- > get ( 'privacy.hide_public_links' ),
539 $conf- > get ( 'redirector.url' ),
540 $conf- > get ( 'redirector.encode_url' )
543 /* Some Shaarlies may have very few links, so we need to look
544 back in time (rsort()) until we have enough days ($nb_of_days).
546 $linkdates = array ();
547 foreach ( $LINKSDB as $linkdate => $value ) {
548 $linkdates [] = $linkdate ;
551 $nb_of_days = 7 ; // We take 7 days.
552 $today = date ( 'Ymd' );
555 foreach ( $linkdates as $linkdate ) {
556 $day = substr ( $linkdate , 0 , 8 ); // Extract day (without time)
557 if ( strcmp ( $day , $today ) < 0 ) {
558 if ( empty ( $days [ $day ])) {
559 $days [ $day ] = array ();
561 $days [ $day ][] = $linkdate ;
564 if ( count ( $days ) > $nb_of_days ) {
565 break ; // Have we collected enough days?
569 // Build the RSS feed.
570 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
571 $pageaddr = escape ( index_url ( $_SERVER ));
572 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
574 echo '<title>Daily - ' . $conf- > get ( 'general.title' ) . '</title>' ;
575 echo '<link>' . $pageaddr . '</link>' ;
576 echo '<description>Daily shared links</description>' ;
577 echo '<language>en-en</language>' ;
578 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
581 foreach ( $days as $day => $linkdates ) {
582 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
583 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
585 // Build the HTML body of this RSS entry.
590 // We pre-format some fields for proper output.
591 foreach ( $linkdates as $linkdate ) {
592 $l = $LINKSDB [ $linkdate ];
593 $l [ 'formatedDescription' ] = format_description ( $l [ 'description' ], $conf- > get ( 'redirector.url' ));
594 $l [ 'thumbnail' ] = thumbnail ( $conf , $l [ 'url' ]);
595 $l_date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $l [ 'linkdate' ]);
596 $l [ 'timestamp' ] = $l_date- > getTimestamp ();
597 if ( startsWith ( $l [ 'url' ], '?' )) {
598 $l [ 'url' ] = index_url ( $_SERVER ) . $l [ 'url' ]; // make permalink URL absolute
600 $links [ $linkdate ] = $l ;
603 // Then build the HTML for this day:
605 $tpl- > assign ( 'title' , $conf- > get ( 'general.title' ));
606 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
607 $tpl- > assign ( 'absurl' , $absurl );
608 $tpl- > assign ( 'links' , $links );
609 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
610 $tpl- > assign ( 'hide_timestamps' , $conf- > get ( 'privacy.hide_timestamps' , false ));
611 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
613 echo $html . PHP_EOL
;
615 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
617 $cache- > cache ( ob_get_contents ());
623 * Show the 'Daily' page.
625 * @param PageBuilder $pageBuilder Template engine wrapper.
626 * @param LinkDB $LINKSDB LinkDB instance.
627 * @param ConfigManager $conf Configuration Manager instance.
628 * @param PluginManager $pluginManager Plugin Manager instane.
630 function showDaily ( $pageBuilder , $LINKSDB , $conf , $pluginManager )
632 $day = date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
633 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
635 $days = $LINKSDB- > days ();
636 $i = array_search ( $day , $days );
637 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
642 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
643 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
647 $linksToDisplay = $LINKSDB- > filterDay ( $day );
648 } catch ( Exception
$exc ) {
650 $linksToDisplay = array ();
653 // We pre-format some fields for proper output.
654 foreach ( $linksToDisplay as $key => $link )
657 $taglist = explode ( ' ' , $link [ 'tags' ]);
658 uasort ( $taglist , 'strcasecmp' );
659 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
660 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
661 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $conf , $link [ 'url' ]);
662 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
663 $linksToDisplay [ $key ][ 'timestamp' ] = $date- > getTimestamp ();
666 /* We need to spread the articles on 3 columns.
667 I did not want to use a JavaScript lib like http://masonry.desandro.com/
668 so I manually spread entries with a simple method: I roughly evaluate the
669 height of a div according to title and description length.
671 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
672 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
673 foreach ( $linksToDisplay as $key => $link )
675 // Roughly estimate length of entry (by counting characters)
676 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
677 // Description: 836 characters gives roughly 342 pixel height.
678 // This is not perfect, but it's usually OK.
679 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
680 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
681 // Then put in column which is the less filled:
682 $smallest = min ( $fill ); // find smallest value in array.
683 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
684 array_push ( $columns [ $index ], $link ); // Put entry in this column.
685 $fill [ $index ] +
= $length ;
688 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
690 'linksToDisplay' => $linksToDisplay ,
692 'day' => $dayDate- > getTimestamp (),
693 'previousday' => $previousday ,
694 'nextday' => $nextday ,
697 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
699 foreach ( $data as $key => $value ) {
700 $pageBuilder- > assign ( $key , $value );
703 $pageBuilder- > renderPage ( 'daily' );
708 * Renders the linklist
710 * @param pageBuilder $PAGE pageBuilder instance.
711 * @param LinkDB $LINKSDB LinkDB instance.
712 * @param ConfigManager $conf Configuration Manager instance.
713 * @param PluginManager $pluginManager Plugin Manager instance.
715 function showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ) {
716 buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ); // Compute list of links to display
717 $PAGE- > renderPage ( 'linklist' );
721 * Render HTML page (according to URL parameters and user rights)
723 * @param ConfigManager $conf Configuration Manager instance.
724 * @param PluginManager $pluginManager Plugin Manager instance,
726 function renderPage ( $conf , $pluginManager )
728 $LINKSDB = new LinkDB (
729 $conf- > get ( 'resource.datastore' ),
731 $conf- > get ( 'privacy.hide_public_links' ),
732 $conf- > get ( 'redirector.url' ),
733 $conf- > get ( 'redirector.encode_url' )
736 $updater = new Updater (
737 read_updates_file ( $conf- > get ( 'resource.updates' )),
743 $newUpdates = $updater- > update ();
744 if (! empty ( $newUpdates )) {
746 $conf- > get ( 'resource.updates' ),
747 $updater- > getDoneUpdates ()
751 catch ( Exception
$e ) {
752 die ( $e- > getMessage ());
755 $PAGE = new PageBuilder ( $conf );
756 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
757 $PAGE- > assign ( 'privateLinkcount' , count_private ( $LINKSDB ));
759 // Determine which page will be rendered.
760 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
761 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
763 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
764 // Then assign generated data to RainTPL.
765 $common_hooks = array (
771 foreach ( $common_hooks as $name ) {
772 $plugin_data = array ();
773 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
775 'target' => $targetPage ,
776 'loggedin' => isLoggedIn ()
779 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
782 // -------- Display login form.
783 if ( $targetPage == Router
:: $PAGE_LOGIN )
785 if ( $conf- > get ( 'security.open_shaarli' )) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
786 $token = '' ; if ( ban_canLogin ( $conf )) $token = getToken ( $conf ); // Do not waste token generation if not useful.
787 $PAGE- > assign ( 'token' , $token );
788 if ( isset ( $_GET [ 'username' ])) {
789 $PAGE- > assign ( 'username' , escape ( $_GET [ 'username' ]));
791 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
792 $PAGE- > renderPage ( 'loginform' );
795 // -------- User wants to logout.
796 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=logout' ))
798 invalidateCaches ( $conf- > get ( 'resource.page_cache' ));
800 header ( 'Location: ?' );
804 // -------- Picture wall
805 if ( $targetPage == Router
:: $PAGE_PICWALL )
807 // Optionally filter the results:
808 $links = $LINKSDB- > filterSearch ( $_GET );
809 $linksToDisplay = array ();
811 // Get only links which have a thumbnail.
812 foreach ( $links as $link )
814 $permalink = '?' . escape ( smallhash ( $link [ 'linkdate' ]));
815 $thumb = lazyThumbnail ( $conf , $link [ 'url' ], $permalink );
816 if ( $thumb != '' ) // Only output links which have a thumbnail.
818 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
819 $linksToDisplay []= $link ; // Add to array.
824 'linksToDisplay' => $linksToDisplay ,
826 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
828 foreach ( $data as $key => $value ) {
829 $PAGE- > assign ( $key , $value );
832 $PAGE- > renderPage ( 'picwall' );
836 // -------- Tag cloud
837 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
839 $tags = $LINKSDB- > allTags ();
841 // We sort tags alphabetically, then choose a font size according to count.
842 // First, find max value.
844 foreach ( $tags as $value ) {
845 $maxcount = max ( $maxcount , $value );
848 // Sort tags alphabetically: case insensitive, support locale if avalaible.
849 uksort ( $tags , function ( $a , $b ) {
850 // Collator is part of PHP intl.
851 if ( class_exists ( 'Collator' )) {
852 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
853 if (! intl_is_failure ( intl_get_error_code ())) {
854 return $c- > compare ( $a , $b );
857 return strcasecmp ( $a , $b );
861 foreach ( $tags as $key => $value ) {
862 // Tag font size scaling:
863 // default 15 and 30 logarithm bases affect scaling,
864 // 22 and 6 are arbitrary font sizes for max and min sizes.
865 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
866 $tagList [ $key ] = array (
868 'size' => number_format ( $size , 2 , '.' , '' ),
875 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
877 foreach ( $data as $key => $value ) {
878 $PAGE- > assign ( $key , $value );
881 $PAGE- > renderPage ( 'tagcloud' );
886 if ( $targetPage == Router
:: $PAGE_DAILY ) {
887 showDaily ( $PAGE , $LINKSDB , $conf , $pluginManager );
890 // ATOM and RSS feed.
891 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
892 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
893 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
896 $query = $_SERVER [ 'QUERY_STRING' ];
897 $cache = new CachedPage (
898 $conf- > get ( 'resource.page_cache' ),
900 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
902 $cached = $cache- > cachedVersion ();
903 if (! empty ( $cached )) {
909 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
910 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
911 $feedGenerator- > setHideDates ( $conf- > get ( 'privacy.hide_timestamps' ) && ! isLoggedIn ());
912 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $conf- > get ( 'feed.rss_permalinks' ));
913 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
914 if (! empty ( $pshUrl )) {
915 $feedGenerator- > setPubsubhubUrl ( $pshUrl );
917 $data = $feedGenerator- > buildData ();
919 // Process plugin hook.
920 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
921 'loggedin' => isLoggedIn (),
922 'target' => $targetPage ,
925 // Render the template.
926 $PAGE- > assignAll ( $data );
927 $PAGE- > renderPage ( 'feed.' . $feedType );
928 $cache- > cache ( ob_get_contents ());
933 // Display openseach plugin (XML)
934 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
935 header ( 'Content-Type: application/xml; charset=utf-8' );
936 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
937 $PAGE- > renderPage ( 'opensearch' );
941 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
942 if ( isset ( $_GET [ 'addtag' ]))
944 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
945 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
946 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
948 // Prevent redirection loop
949 if ( isset ( $params [ 'addtag' ])) {
950 unset ( $params [ 'addtag' ]);
953 // Check if this tag is already in the search query and ignore it if it is.
954 // Each tag is always separated by a space
955 if ( isset ( $params [ 'searchtags' ])) {
956 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
958 $current_tags = array ();
961 foreach ( $current_tags as $value ) {
962 if ( $value === $_GET [ 'addtag' ]) {
967 // Append the tag if necessary
968 if ( empty ( $params [ 'searchtags' ])) {
969 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
972 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
975 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
976 header ( 'Location: ?' . http_build_query ( $params ));
980 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
981 if ( isset ( $_GET [ 'removetag' ])) {
982 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
983 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
984 header ( 'Location: ?' );
988 // In case browser does not send HTTP_REFERER
989 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
991 // Prevent redirection loop
992 if ( isset ( $params [ 'removetag' ])) {
993 unset ( $params [ 'removetag' ]);
996 if ( isset ( $params [ 'searchtags' ])) {
997 $tags = explode ( ' ' , $params [ 'searchtags' ]);
998 // Remove value from array $tags.
999 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1000 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1002 if ( empty ( $params [ 'searchtags' ])) {
1003 unset ( $params [ 'searchtags' ]);
1006 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1008 header ( 'Location: ?' . http_build_query ( $params ));
1012 // -------- User wants to change the number of links per page (linksperpage=...)
1013 if ( isset ( $_GET [ 'linksperpage' ])) {
1014 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1015 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1018 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1022 // -------- User wants to see only private links (toggle)
1023 if ( isset ( $_GET [ 'privateonly' ])) {
1024 if ( empty ( $_SESSION [ 'privateonly' ])) {
1025 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1027 unset ( $_SESSION [ 'privateonly' ]); // See all links
1030 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1034 // -------- Handle other actions allowed for non-logged in users:
1037 // User tries to post new link but is not logged in:
1038 // Show login screen, then redirect to ?post=...
1039 if ( isset ( $_GET [ 'post' ]))
1041 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.
1045 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1046 if ( isset ( $_GET [ 'edit_link' ])) {
1047 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1051 exit ; // Never remove this one! All operations below are reserved for logged in user.
1054 // -------- All other functions are reserved for the registered user:
1056 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1057 if ( $targetPage == Router
:: $PAGE_TOOLS )
1060 'pageabsaddr' => index_url ( $_SERVER ),
1062 $pluginManager- > executeHooks ( 'render_tools' , $data );
1064 foreach ( $data as $key => $value ) {
1065 $PAGE- > assign ( $key , $value );
1068 $PAGE- > renderPage ( 'tools' );
1072 // -------- User wants to change his/her password.
1073 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1075 if ( $conf- > get ( 'security.open_shaarli' )) {
1076 die ( 'You are not supposed to change a password on an Open Shaarli.' );
1079 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1081 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1083 // Make sure old password is correct.
1084 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $conf- > get ( 'credentials.login' ). $conf- > get ( 'credentials.salt' ));
1085 if ( $oldhash != $conf- > get ( 'credentials.hash' )) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1086 // Save new password
1087 // Salt renders rainbow-tables attacks useless.
1088 $conf- > set ( 'credentials.salt' , sha1 ( uniqid ( '' , true ) . '_' . mt_rand ()));
1089 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $conf- > get ( 'credentials.login' ) . $conf- > get ( 'credentials.salt' )));
1091 $conf- > write ( isLoggedIn ());
1093 catch ( Exception
$e ) {
1095 'ERROR while writing config file after changing password.' . PHP_EOL
.
1099 // TODO: do not handle exceptions/errors in JS.
1100 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1103 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1106 else // show the change password form.
1108 $PAGE- > assign ( 'token' , getToken ( $conf ));
1109 $PAGE- > renderPage ( 'changepassword' );
1114 // -------- User wants to change configuration
1115 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1117 if (! empty ( $_POST [ 'title' ]) )
1119 if (! tokenOk ( $_POST [ 'token' ])) {
1120 die ( 'Wrong token.' ); // Go away!
1123 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1124 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1126 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1128 $conf- > set ( 'general.timezone' , $tz );
1129 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
1130 $conf- > set ( 'general.header_link' , escape ( $_POST [ 'titleLink' ]));
1131 $conf- > set ( 'redirector.url' , escape ( $_POST [ 'redirector' ]));
1132 $conf- > set ( 'security.session_protection_disabled' , ! empty ( $_POST [ 'disablesessionprotection' ]));
1133 $conf- > set ( 'privacy.default_private_links' , ! empty ( $_POST [ 'privateLinkByDefault' ]));
1134 $conf- > set ( 'feed.rss_permalinks' , ! empty ( $_POST [ 'enableRssPermalinks' ]));
1135 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
1136 $conf- > set ( 'privacy.hide_public_links' , ! empty ( $_POST [ 'hidePublicLinks' ]));
1138 $conf- > write ( isLoggedIn ());
1140 catch ( Exception
$e ) {
1142 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1146 // TODO: do not handle exceptions/errors in JS.
1147 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=configure \' ;</script>' ;
1150 echo '<script>alert("Configuration was saved.");document.location= \' ?do=configure \' ;</script>' ;
1153 else // Show the configuration form.
1155 $PAGE- > assign ( 'token' , getToken ( $conf ));
1156 $PAGE- > assign ( 'title' , $conf- > get ( 'general.title' ));
1157 $PAGE- > assign ( 'redirector' , $conf- > get ( 'redirector.url' ));
1158 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $conf- > get ( 'general.timezone' ));
1159 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1160 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1161 $PAGE- > assign ( 'private_links_default' , $conf- > get ( 'privacy.default_private_links' , false ));
1162 $PAGE- > assign ( 'session_protection_disabled' , $conf- > get ( 'security.session_protection_disabled' , false ));
1163 $PAGE- > assign ( 'enable_rss_permalinks' , $conf- > get ( 'feed.rss_permalinks' , false ));
1164 $PAGE- > assign ( 'enable_update_check' , $conf- > get ( 'updates.check_updates' , true ));
1165 $PAGE- > assign ( 'hide_public_links' , $conf- > get ( 'privacy.hide_public_links' , false ));
1166 $PAGE- > renderPage ( 'configure' );
1171 // -------- User wants to rename a tag or delete it
1172 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1174 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1175 $PAGE- > assign ( 'token' , getToken ( $conf ));
1176 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1177 $PAGE- > renderPage ( 'changetag' );
1181 if (! tokenOk ( $_POST [ 'token' ])) {
1182 die ( 'Wrong token.' );
1186 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1187 $needle = trim ( $_POST [ 'fromtag' ]);
1188 // True for case-sensitive tag search.
1189 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1190 foreach ( $linksToAlter as $key => $value )
1192 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1193 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1194 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1195 $LINKSDB [ $key ]= $value ;
1197 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1198 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1203 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1204 $needle = trim ( $_POST [ 'fromtag' ]);
1205 // True for case-sensitive tag search.
1206 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1207 foreach ( $linksToAlter as $key => $value )
1209 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1210 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1211 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1212 $LINKSDB [ $key ]= $value ;
1214 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' )); // Save to disk.
1215 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1220 // -------- User wants to add a link without using the bookmarklet: Show form.
1221 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1223 $PAGE- > renderPage ( 'addlink' );
1227 // -------- User clicked the "Save" button when editing a link: Save link to database.
1228 if ( isset ( $_POST [ 'save_edit' ]))
1230 $linkdate = $_POST [ 'lf_linkdate' ];
1231 $updated = isset ( $LINKSDB [ $linkdate ]) ? strval ( date ( 'Ymd_His' )) : false ;
1234 if (! tokenOk ( $_POST [ 'token' ])) {
1235 die ( 'Wrong token.' );
1237 // Remove multiple spaces.
1238 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1239 // Remove first '-' char in tags.
1240 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1241 // Remove duplicates.
1242 $tags = implode(' ', array_unique(explode(' ', $tags )));
1244 $url = trim( $_POST [' lf_url
']);
1245 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1246 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1247 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1249 $url = ' http
: //' . $url;
1253 'title' => trim ( $_POST [ 'lf_title' ]),
1255 'description' => $_POST [ 'lf_description' ],
1256 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1257 'linkdate' => $linkdate ,
1258 'updated' => $updated ,
1259 'tags' => str_replace ( ',' , ' ' , $tags )
1261 // If title is empty, use the URL as title.
1262 if ( $link [ 'title' ] == '' ) {
1263 $link [ 'title' ] = $link [ 'url' ];
1266 $pluginManager- > executeHooks ( 'save_link' , $link );
1268 $LINKSDB [ $linkdate ] = $link ;
1269 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1272 // If we are called from the bookmarklet, we must close the popup:
1273 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1274 echo '<script>self.close();</script>' ;
1278 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1279 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1280 // Scroll to the link which has been edited.
1281 $location .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]);
1282 // After saving the link, redirect to the page the user was on.
1283 header ( 'Location: ' . $location );
1287 // -------- User clicked the "Cancel" button when editing a link.
1288 if ( isset ( $_POST [ 'cancel_edit' ]))
1290 // If we are called from the bookmarklet, we must close the popup:
1291 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1292 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1293 $returnurl .= '#' . smallHash ( $_POST [ 'lf_linkdate' ]); // Scroll to the link which has been edited.
1294 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1295 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1299 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1300 if ( isset ( $_POST [ 'delete_link' ]))
1302 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1303 // We do not need to ask for confirmation:
1304 // - confirmation is handled by JavaScript
1305 // - we are protected from XSRF by the token.
1306 $linkdate = $_POST [ 'lf_linkdate' ];
1308 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $linkdate ]);
1310 unset ( $LINKSDB [ $linkdate ]);
1311 $LINKSDB- > savedb ( 'resource.page_cache' ); // save to disk
1313 // If we are called from the bookmarklet, we must close the popup:
1314 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1315 // Pick where we're going to redirect
1316 // =============================================================
1317 // Basically, we can't redirect to where we were previously if it was a permalink
1318 // or an edit_link, because it would 404.
1320 // - / : nothing in $_GET, redirect to self
1321 // - /?page : redirect to self
1322 // - /?searchterm : redirect to self (there might be other links)
1323 // - /?searchtags : redirect to self
1324 // - /permalink : redirect to / (the link does not exist anymore)
1325 // - /?edit_link : redirect to / (the link does not exist anymore)
1326 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1327 // redirect is not satisfied, and only then redirect to /
1330 if ( count ( $_GET ) == 0
1331 || isset ( $_GET [ 'page' ])
1332 || isset ( $_GET [ 'searchterm' ])
1333 || isset ( $_GET [ 'searchtags' ])
1335 if ( isset ( $_POST [ 'returnurl' ])) {
1336 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1338 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1342 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1346 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1347 if ( isset ( $_GET [ 'edit_link' ]))
1349 $link = $LINKSDB [ $_GET [ 'edit_link' ]]; // Read database
1350 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1353 'link_is_new' => false ,
1354 'token' => getToken ( $conf ),
1355 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1356 'tags' => $LINKSDB- > allTags (),
1358 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1360 foreach ( $data as $key => $value ) {
1361 $PAGE- > assign ( $key , $value );
1364 $PAGE- > renderPage ( 'editlink' );
1368 // -------- User want to post a new link: Display link edit form.
1369 if ( isset ( $_GET [ 'post' ])) {
1370 $url = cleanup_url ( $_GET [ 'post' ]);
1372 $link_is_new = false ;
1373 // Check if URL is not already in database (in this case, we will edit the existing link)
1374 $link = $LINKSDB- > getLinkFromUrl ( $url );
1377 $link_is_new = true ;
1378 $linkdate = strval ( date ( 'Ymd_His' ));
1379 // Get title if it was provided in URL (by the bookmarklet).
1380 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1381 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1382 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1383 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1384 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1385 // 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.)
1386 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1387 // Short timeout to keep the application responsive
1388 list ( $headers , $content ) = get_http_response ( $url , 4 );
1389 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1390 // Retrieve charset.
1391 $charset = get_charset ( $headers , $content );
1393 $title = html_extract_title ( $content );
1394 // Re-encode title in utf-8 if necessary.
1395 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1396 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1402 $url = '?' . smallHash ( $linkdate );
1405 $url = escape ( $url );
1406 $title = escape ( $title );
1409 'linkdate' => $linkdate ,
1412 'description' => $description ,
1414 'private' => $private
1420 'link_is_new' => $link_is_new ,
1421 'token' => getToken ( $conf ), // XSRF protection.
1422 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1423 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1424 'tags' => $LINKSDB- > allTags (),
1425 'default_private_links' => $conf- > get ( 'default_private_links' , false ),
1427 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1429 foreach ( $data as $key => $value ) {
1430 $PAGE- > assign ( $key , $value );
1433 $PAGE- > renderPage ( 'editlink' );
1437 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1438 // Export links as a Netscape Bookmarks file
1440 if ( empty ( $_GET [ 'selection' ])) {
1441 $PAGE- > renderPage ( 'export' );
1445 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1446 $selection = $_GET [ 'selection' ];
1447 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1448 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1450 $prependNoteUrl = false ;
1456 NetscapeBookmarkUtils
:: filterAndFormat (
1463 } catch ( Exception
$exc ) {
1464 header ( 'Content-Type: text/plain; charset=utf-8' );
1465 echo $exc- > getMessage ();
1468 $now = new DateTime ();
1469 header ( 'Content-Type: text/html; charset=utf-8' );
1471 'Content-disposition: attachment; filename=bookmarks_'
1472 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1474 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1475 $PAGE- > assign ( 'eol' , PHP_EOL
);
1476 $PAGE- > assign ( 'selection' , $selection );
1477 $PAGE- > renderPage ( 'export.bookmarks' );
1481 // -------- User is uploading a file for import
1482 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=upload' ))
1484 // If file is too big, some form field may be missing.
1485 if (! isset ( $_POST [ 'token' ]) || (! isset ( $_FILES )) || ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ]== 0 ))
1487 $returnurl = ( empty ( $_SERVER [ 'HTTP_REFERER' ]) ? '?' : $_SERVER [ 'HTTP_REFERER' ] );
1488 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>' ;
1491 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1492 importFile ( $LINKSDB );
1496 // -------- Show upload/import dialog:
1497 if ( $targetPage == Router
:: $PAGE_IMPORT )
1499 $PAGE- > assign ( 'token' , getToken ( $conf ));
1500 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1501 $PAGE- > renderPage ( 'import' );
1505 // Plugin administration page
1506 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1507 $pluginMeta = $pluginManager- > getPluginsMeta ();
1509 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1510 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1512 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $conf- > get ( 'plugins' , array ()));
1515 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1517 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1519 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1520 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1521 $PAGE- > renderPage ( 'pluginsadmin' );
1525 // Plugin administration form action
1526 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1528 if ( isset ( $_POST [ 'parameters_form' ])) {
1529 unset ( $_POST [ 'parameters_form' ]);
1530 foreach ( $_POST as $param => $value ) {
1531 $conf- > set ( 'plugins.' . $param , escape ( $value ));
1535 $conf- > set ( 'general.enabled_plugins' , save_plugin_config ( $_POST ));
1537 $conf- > write ( isLoggedIn ());
1539 catch ( Exception
$e ) {
1541 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1545 // TODO: do not handle exceptions/errors in JS.
1546 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1549 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1553 // -------- Otherwise, simply display search form and links:
1554 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1559 * Process the import file form.
1561 * @param LinkDB $LINKSDB Loaded LinkDB instance.
1562 * @param ConfigManager $conf Configuration Manager instance.
1564 function importFile ( $LINKSDB , $conf )
1566 if (! isLoggedIn ()) { die ( 'Not allowed.' ); }
1568 $filename = $_FILES [ 'filetoupload' ][ 'name' ];
1569 $filesize = $_FILES [ 'filetoupload' ][ 'size' ];
1570 $data = file_get_contents ( $_FILES [ 'filetoupload' ][ 'tmp_name' ]);
1571 $private = ( empty ( $_POST [ 'private' ]) ? 0 : 1 ); // Should the links be imported as private?
1572 $overwrite = ! empty ( $_POST [ 'overwrite' ]) ; // Should the imported links overwrite existing ones?
1577 if ( startsWith ( $data , '<!DOCTYPE NETSCAPE-Bookmark-file-1>' )) $type = 'netscape' ; // Netscape bookmark file (aka Firefox).
1579 // Then import the bookmarks.
1580 if ( $type == 'netscape' )
1582 // This is a standard Netscape-style bookmark file.
1583 // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others.
1584 foreach ( explode ( '<DT>' , $data ) as $html ) // explode is very fast
1586 $link = array ( 'linkdate' => '' , 'title' => '' , 'url' => '' , 'description' => '' , 'tags' => '' , 'private' => 0 );
1587 $d = explode ( '<DD>' , $html );
1588 if ( startsWith ( $d [ 0 ], '<A ' ))
1590 $link [ 'description' ] = ( isset ( $d [ 1 ]) ? html_entity_decode ( trim ( $d [ 1 ]), ENT_QUOTES
, 'UTF-8' ) : '' ); // Get description (optional)
1591 preg_match ( '!<A .*?>(.*?)</A>!i' , $d [ 0 ], $matches ); $link [ 'title' ] = ( isset ( $matches [ 1 ]) ? trim ( $matches [ 1 ]) : '' ); // Get title
1592 $link [ 'title' ] = html_entity_decode ( $link [ 'title' ], ENT_QUOTES
, 'UTF-8' );
1593 preg_match_all ( '! ([A-Z_]+)= \" (.*?)"!i' , $html , $matches , PREG_SET_ORDER
); // Get all other attributes
1595 foreach ( $matches as $m )
1597 $attr = $m [ 1 ]; $value = $m [ 2 ];
1598 if ( $attr == 'HREF' ) $link [ 'url' ]= html_entity_decode ( $value , ENT_QUOTES
, 'UTF-8' );
1599 elseif ( $attr == 'ADD_DATE' )
1601 $raw_add_date = intval ( $value );
1602 if ( $raw_add_date > 30000000000 ) $raw_add_date /= 1000 ; //If larger than year 2920, then was likely stored in milliseconds instead of seconds
1604 elseif ( $attr == 'PRIVATE' ) $link [ 'private' ]=( $value == '0' ? 0 : 1 );
1605 elseif ( $attr == 'TAGS' ) $link [ 'tags' ]= html_entity_decode ( str_replace ( ',' , ' ' , $value ), ENT_QUOTES
, 'UTF-8' );
1607 if ( $link [ 'url' ]!= '' )
1609 if ( $private == 1 ) $link [ 'private' ]= 1 ;
1610 $dblink = $LINKSDB- > getLinkFromUrl ( $link [ 'url' ]); // See if the link is already in database.
1612 { // Link not in database, let's import it...
1613 if ( empty ( $raw_add_date )) $raw_add_date = time (); // In case of shitty bookmark file with no ADD_DATE
1615 // Make sure date/time is not already used by another link.
1616 // (Some bookmark files have several different links with the same ADD_DATE)
1617 // We increment date by 1 second until we find a date which is not used in DB.
1618 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1619 while (! empty ( $LINKSDB [ date ( 'Ymd_His' , $raw_add_date )])) { $raw_add_date++
; } // Yes, I know it's ugly.
1620 $link [ 'linkdate' ]= date ( 'Ymd_His' , $raw_add_date );
1621 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1624 else // Link already present in database.
1627 { // If overwrite is required, we import link data, except date/time.
1628 $link [ 'linkdate' ]= $dblink [ 'linkdate' ];
1629 $LINKSDB [ $link [ 'linkdate' ]] = $link ;
1637 $LINKSDB- > savedb ( $conf- > get ( 'resource.page_cache' ));
1639 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) was successfully processed: ' . $import_count . ' links imported.");document.location= \' ? \' ;</script>' ;
1643 echo '<script>alert("File ' . json_encode ( $filename ). ' (' . $filesize . ' bytes) has an unknown file format. Nothing was imported.");document.location= \' ? \' ;</script>' ;
1648 * Template for the list of links (<div id="linklist">)
1649 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1651 * @param pageBuilder $PAGE pageBuilder instance.
1652 * @param LinkDB $LINKSDB LinkDB instance.
1653 * @param ConfigManager $conf Configuration Manager instance.
1654 * @param PluginManager $pluginManager Plugin Manager instance.
1656 function buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager )
1658 // Used in templates
1659 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1660 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1663 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1664 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1666 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1667 } catch ( LinkNotFoundException
$e ) {
1668 $PAGE- > render404 ( $e- > getMessage ());
1672 // Filter links according search parameters.
1673 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1674 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1677 // ---- Handle paging.
1679 foreach ( $linksToDisplay as $key => $value ) {
1685 // Select articles according to paging.
1686 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1687 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1688 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1689 $page = $page < 1 ? 1 : $page ;
1690 $page = $page > $pagecount ? $pagecount : $page ;
1692 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1693 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1694 $linkDisp = array ();
1695 while ( $i < $end && $i < count ( $keys ))
1697 $link = $linksToDisplay [ $keys [ $i ]];
1698 $link [ 'description' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
1699 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1700 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1701 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'linkdate' ]);
1702 $link [ 'timestamp' ] = $date- > getTimestamp ();
1703 if (! empty ( $link [ 'updated' ])) {
1704 $date = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $link [ 'updated' ]);
1705 $link [ 'updated_timestamp' ] = $date- > getTimestamp ();
1707 $link [ 'updated_timestamp' ] = '' ;
1709 $taglist = explode ( ' ' , $link [ 'tags' ]);
1710 uasort ( $taglist , 'strcasecmp' );
1711 $link [ 'taglist' ] = $taglist ;
1712 $link [ 'shorturl' ] = smallHash ( $link [ 'linkdate' ]);
1713 // Check for both signs of a note: starting with ? and 7 chars long.
1714 if ( $link [ 'url' ][ 0 ] === '?' &&
1715 strlen ( $link [ 'url' ]) === 7 ) {
1716 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1719 $linkDisp [ $keys [ $i ]] = $link ;
1723 // Compute paging navigation
1724 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1725 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1726 $previous_page_url = '' ;
1727 if ( $i != count ( $keys )) {
1728 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1732 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1735 $token = isLoggedIn () ? getToken ( $conf ) : '' ;
1737 // Fill all template fields.
1739 'previous_page_url' => $previous_page_url ,
1740 'next_page_url' => $next_page_url ,
1741 'page_current' => $page ,
1742 'page_max' => $pagecount ,
1743 'result_count' => count ( $linksToDisplay ),
1744 'search_term' => $searchterm ,
1745 'search_tags' => $searchtags ,
1746 'redirector' => $conf- > get ( 'redirector.url' ), // Optional redirector URL.
1748 'links' => $linkDisp ,
1749 'tags' => $LINKSDB- > allTags (),
1752 // If there is only a single link, we change on-the-fly the title of the page.
1753 if ( count ( $linksToDisplay ) == 1 ) {
1754 $data [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ] . ' - ' . $conf- > get ( 'general.title' );
1757 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1759 foreach ( $data as $key => $value ) {
1760 $PAGE- > assign ( $key , $value );
1767 * Compute the thumbnail for a link.
1769 * With a link to the original URL.
1770 * Understands various services (youtube.com...)
1771 * Input: $url = URL for which the thumbnail must be found.
1772 * $href = if provided, this URL will be followed instead of $url
1773 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1774 * Some of them may be missing.
1775 * Return an empty array if no thumbnail available.
1777 * @param ConfigManager $conf Configuration Manager instance.
1778 * @param string $url
1779 * @param string|bool $href
1783 function computeThumbnail ( $conf , $url , $href = false )
1785 if (! $conf- > get ( 'thumbnail.enable_thumbnails' )) return array ();
1786 if ( $href == false ) $href = $url ;
1788 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1789 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1790 // ^^^^^^^^^^^ ^^^^^^^^^^^
1791 $domain = parse_url ( $url , PHP_URL_HOST
);
1792 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1794 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1795 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1796 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1798 if ( $domain == 'youtu.be' ) // Youtube short links
1800 $path = parse_url ( $url , PHP_URL_PATH
);
1801 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1802 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1804 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1806 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1807 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1808 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1811 if ( $domain == 'imgur.com' )
1813 $path = parse_url ( $url , PHP_URL_PATH
);
1814 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1815 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1816 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1817 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1818 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1820 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1821 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1823 if ( $domain == 'i.imgur.com' )
1825 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1826 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1827 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1829 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1831 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1833 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1834 return array ( 'src' => $thumburl ,
1835 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1838 if ( endsWith ( $domain , '.imageshack.us' ))
1840 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1841 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1843 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1844 return array ( 'src' => $thumburl ,
1845 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1849 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1850 // So we deport the thumbnail generation in order not to slow down page generation
1851 // (and we also cache the thumbnail)
1853 if (! $conf- > get ( 'thumbnail.enable_localcache' )) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1855 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1856 || $domain == 'vimeo.com'
1857 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1858 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1861 if ( $domain == 'vimeo.com' )
1862 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1863 $path = parse_url ( $url , PHP_URL_PATH
);
1864 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1866 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1867 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1868 $path = parse_url ( $url , PHP_URL_PATH
);
1869 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1871 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1872 { // Make sure this TED URL points to a video (/talks/...)
1873 $path = parse_url ( $url , PHP_URL_PATH
);
1874 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1876 $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)
1877 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1878 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1881 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1882 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1883 // But using the extension will do.
1884 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1885 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1887 $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)
1888 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1889 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1891 return array (); // No thumbnail.
1896 // Returns the HTML code to display a thumbnail for a link
1897 // with a link to the original URL.
1898 // Understands various services (youtube.com...)
1899 // Input: $url = URL for which the thumbnail must be found.
1900 // $href = if provided, this URL will be followed instead of $url
1901 // Returns '' if no thumbnail available.
1902 function thumbnail ( $url , $href = false )
1906 $t = computeThumbnail ( $conf , $url , $href );
1907 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1909 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
1910 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1911 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1912 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1913 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1918 // Returns the HTML code to display a thumbnail for a link
1919 // for the picture wall (using lazy image loading)
1920 // Understands various services (youtube.com...)
1921 // Input: $url = URL for which the thumbnail must be found.
1922 // $href = if provided, this URL will be followed instead of $url
1923 // Returns '' if no thumbnail available.
1924 function lazyThumbnail ( $conf , $url , $href = false )
1928 $t = computeThumbnail ( $conf , $url , $href );
1929 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1931 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
1934 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
1936 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1937 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1938 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1939 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1942 // No-JavaScript fallback.
1943 $html .= '<noscript><img src="' . escape ( $t [ 'src' ]). '"' ;
1944 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1945 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1946 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1947 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1948 $html .= '></noscript></a>' ;
1956 * This function should NEVER be called if the file data/config.php exists.
1958 * @param ConfigManager $conf Configuration Manager instance.
1960 function install ( $conf )
1962 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1963 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1966 // This part makes sure sessions works correctly.
1967 // (Because on some hosts, session.save_path may not be set correctly,
1968 // or we may not have write access to it.)
1969 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
1970 { // Step 2: Check if data in session is correct.
1971 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
1972 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
1973 echo 'It currently points to ' . session_save_path (). '<br>' ;
1974 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>' ;
1975 echo '<br><a href="?">Click to try again.</a></pre>' ;
1978 if (! isset ( $_SESSION [ 'session_tested' ]))
1979 { // Step 1 : Try to store data in session and reload page.
1980 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
1981 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
1983 if ( isset ( $_GET [ 'test_session' ]))
1984 { // Step 3: Sessions are OK. Remove test parameter from URL.
1985 header ( 'Location: ' . index_url ( $_SERVER ));
1989 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1992 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1993 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1995 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1997 $conf- > set ( 'general.timezone' , $tz );
1998 $login = $_POST [ 'setlogin' ];
1999 $conf- > set ( 'credentials.login' , $login );
2000 $salt = sha1 ( uniqid ( '' , true ) . '_' . mt_rand ());
2001 $conf- > set ( 'credentials.salt' , $salt );
2002 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $login . $salt ));
2003 if (! empty ( $_POST [ 'title' ])) {
2004 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
2006 $conf- > set ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
2008 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
2010 // Everything is ok, let's create config file.
2011 $conf- > write ( isLoggedIn ());
2013 catch ( Exception
$e ) {
2015 'ERROR while writing config file after installation.' . PHP_EOL
.
2019 // TODO: do not handle exceptions/errors in JS.
2020 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
2023 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
2027 // Display config form:
2028 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
2029 $timezone_html = '' ;
2030 if ( $timezone_form != '' ) {
2031 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
2034 $PAGE = new PageBuilder ( $conf );
2035 $PAGE- > assign ( 'timezone_html' , $timezone_html );
2036 $PAGE- > assign ( 'timezone_js' , $timezone_js );
2037 $PAGE- > renderPage ( 'install' );
2042 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2043 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2044 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2045 * This function is called by passing the URL:
2046 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2047 * [URL] is the URL of the link (e.g. a flickr page)
2048 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2049 * The function below will fetch the image from the webservice and store it in the cache.
2051 * @param ConfigManager $conf Configuration Manager instance,
2053 function genThumbnail ( $conf )
2055 // Make sure the parameters in the URL were generated by us.
2056 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $conf- > get ( 'credentials.salt' ));
2057 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2059 $cacheDir = $conf- > get ( 'resource.thumbnails_cache' , 'cache' );
2060 // Let's see if we don't already have the image for this URL in the cache.
2061 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2062 if ( is_file ( $cacheDir . '/' . $thumbname ))
2063 { // We have the thumbnail, just serve it:
2064 header ( 'Content-Type: image/jpeg' );
2065 echo file_get_contents ( $cacheDir . '/' . $thumbname );
2068 // We may also serve a blank image (if service did not respond)
2069 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2070 if ( is_file ( $cacheDir . '/' . $blankname ))
2072 header ( 'Content-Type: image/gif' );
2073 echo file_get_contents ( $cacheDir . '/' . $blankname );
2077 // Otherwise, generate the thumbnail.
2078 $url = $_GET [ 'url' ];
2079 $domain = parse_url ( $url , PHP_URL_HOST
);
2081 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2083 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2084 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2086 // Is this a link to an image, or to a flickr page ?
2088 if ( endsWith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2089 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2090 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2091 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2093 else // This is a flickr page (html)
2095 // Get the flickr html page.
2096 list ( $headers , $content ) = get_http_response ( $url , 20 );
2097 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2099 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2100 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2101 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2103 // In albums (and some other pages), the link rel="image_src" is not provided,
2104 // but flickr provides:
2105 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2108 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2109 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2115 { // Let's download the image.
2116 // Image is 240x120, so 10 seconds to download should be enough.
2117 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2118 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2119 // Save image to cache.
2120 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2121 header ( 'Content-Type: image/jpeg' );
2128 elseif ( $domain == 'vimeo.com' )
2130 // This is more complex: we have to perform a HTTP request, then parse the result.
2131 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2132 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2133 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2134 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2135 $t = unserialize ( $content );
2136 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2137 // Then we download the image and serve it to our client.
2138 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2139 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2140 // Save image to cache.
2141 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2142 header ( 'Content-Type: image/jpeg' );
2149 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2151 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2152 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2153 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2154 list ( $headers , $content ) = get_http_response ( $url , 5 );
2155 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2156 // Extract the link to the thumbnail
2157 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2158 if (! empty ( $matches [ 1 ]))
2159 { // Let's download the image.
2160 $imageurl = $matches [ 1 ];
2161 // No control on image size, so wait long enough
2162 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2163 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2164 $filepath = $cacheDir . '/' . $thumbname ;
2165 file_put_contents ( $filepath , $content ); // Save image to cache.
2166 if ( resizeImage ( $filepath ))
2168 header ( 'Content-Type: image/jpeg' );
2169 echo file_get_contents ( $filepath );
2177 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2179 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2180 // http://xkcd.com/327/
2181 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2182 list ( $headers , $content ) = get_http_response ( $url , 5 );
2183 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2184 // Extract the link to the thumbnail
2185 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2186 if (! empty ( $matches [ 1 ]))
2187 { // Let's download the image.
2188 $imageurl = $matches [ 1 ];
2189 // No control on image size, so wait long enough
2190 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2191 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2192 $filepath = $cacheDir . '/' . $thumbname ;
2193 // Save image to cache.
2194 file_put_contents ( $filepath , $content );
2195 if ( resizeImage ( $filepath ))
2197 header ( 'Content-Type: image/jpeg' );
2198 echo file_get_contents ( $filepath );
2208 // For all other domains, we try to download the image and make a thumbnail.
2209 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2210 list ( $headers , $content ) = get_http_response ( $url , 30 );
2211 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2212 $filepath = $cacheDir . '/' . $thumbname ;
2213 // Save image to cache.
2214 file_put_contents ( $filepath , $content );
2215 if ( resizeImage ( $filepath ))
2217 header ( 'Content-Type: image/jpeg' );
2218 echo file_get_contents ( $filepath );
2225 // Otherwise, return an empty image (8x8 transparent gif)
2226 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2227 // Also put something in cache so that this URL is not requested twice.
2228 file_put_contents ( $cacheDir . '/' . $blankname , $blankgif );
2229 header ( 'Content-Type: image/gif' );
2233 // Make a thumbnail of the image (to width: 120 pixels)
2234 // Returns true if success, false otherwise.
2235 function resizeImage ( $filepath )
2237 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2239 // Trick: some stupid people rename GIF as JPEG... or else.
2240 // So we really try to open each image type whatever the extension is.
2241 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2243 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2244 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2245 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2246 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2249 $ystart = 0 ; $yheight = $h ;
2250 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2251 $nw = 120 ; // Desired width
2252 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2254 $im2 = imagecreatetruecolor ( $nw , $nh );
2255 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2256 imageinterlace ( $im2 , true ); // For progressive JPEG.
2257 $tempname = $filepath . '_TEMP.jpg' ;
2258 imagejpeg ( $im2 , $tempname , 90 );
2262 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2266 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=genthumbnail' )) { genThumbnail ( $conf
); exit ; } // Thumbnail generation/cache does not need the link database.
2267 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=dailyrss' )) { showDailyRSS ( $conf
); exit ; }
2268 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) {
2269 $_SESSION [ 'LINKS_PER_PAGE' ] = $conf- > get ( 'general.links_per_page' , 20 );
2271 renderPage ( $conf , $pluginManager );