]>
git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
3 * Shaarli v0.8.1 - 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.8.1' );
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);
47 // 3rd-party libraries
48 if (! file_exists ( __DIR__
. '/vendor/autoload.php' )) {
49 header ( 'Content-Type: text/plain; charset=utf-8' );
50 echo "Error: missing Composer configuration \n\n "
51 . "If you installed Shaarli through Git or using the development branch, \n "
52 . "please refer to the installation documentation to install PHP"
53 . " dependencies using Composer: \n "
54 . "- https://github.com/shaarli/Shaarli/wiki/Server-requirements \n "
55 . "- https://github.com/shaarli/Shaarli/wiki/Download-and-Installation" ;
58 require_once 'inc/rain.tpl.class.php' ;
59 require_once __DIR__
. '/vendor/autoload.php' ;
62 require_once 'application/ApplicationUtils.php' ;
63 require_once 'application/Cache.php' ;
64 require_once 'application/CachedPage.php' ;
65 require_once 'application/config/ConfigManager.php' ;
66 require_once 'application/config/ConfigPlugin.php' ;
67 require_once 'application/FeedBuilder.php' ;
68 require_once 'application/FileUtils.php' ;
69 require_once 'application/HttpUtils.php' ;
70 require_once 'application/Languages.php' ;
71 require_once 'application/LinkDB.php' ;
72 require_once 'application/LinkFilter.php' ;
73 require_once 'application/LinkUtils.php' ;
74 require_once 'application/NetscapeBookmarkUtils.php' ;
75 require_once 'application/PageBuilder.php' ;
76 require_once 'application/TimeZone.php' ;
77 require_once 'application/Url.php' ;
78 require_once 'application/Utils.php' ;
79 require_once 'application/PluginManager.php' ;
80 require_once 'application/Router.php' ;
81 require_once 'application/Updater.php' ;
83 // Ensure the PHP version is supported
85 ApplicationUtils
:: checkPHPVersion ( '5.3' , PHP_VERSION
);
86 } catch ( Exception
$exc ) {
87 header ( 'Content-Type: text/plain; charset=utf-8' );
88 echo $exc- > getMessage ();
92 // Force cookie path (but do not change lifetime)
93 $cookie = session_get_cookie_params ();
95 if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ]) != '/' ) {
96 $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
98 // Set default cookie expiration and path.
99 session_set_cookie_params ( $cookie [ 'lifetime' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]);
100 // Set session parameters on server side.
101 // If the user does not access any page within this time, his/her session is considered expired.
102 define ( 'INACTIVITY_TIMEOUT' , 3600 ); // in seconds.
103 // Use cookies to store session.
104 ini_set ( 'session.use_cookies' , 1 );
105 // Force cookies for session (phpsessionID forbidden in URL).
106 ini_set ( 'session.use_only_cookies' , 1 );
107 // Prevent PHP form using sessionID in URL if cookies are disabled.
108 ini_set ( 'session.use_trans_sid' , false );
110 session_name ( 'shaarli' );
111 // Start session if needed (Some server auto-start sessions).
112 if ( session_id () == '' ) {
116 // Regenerate session ID if invalid or not defined in cookie.
117 if ( isset ( $_COOKIE [ 'shaarli' ]) && ! is_session_id_valid ( $_COOKIE [ 'shaarli' ])) {
118 session_regenerate_id ( true );
119 $_COOKIE [ 'shaarli' ] = session_id ();
122 $conf = new ConfigManager ();
123 $conf- > setEmpty ( 'general.timezone' , date_default_timezone_get ());
124 $conf- > setEmpty ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
125 RainTPL
:: $tpl_dir = $conf- > get ( 'resource.raintpl_tpl' ); // template directory
126 RainTPL
:: $cache_dir = $conf- > get ( 'resource.raintpl_tmp' ); // cache directory
128 $pluginManager = new PluginManager ( $conf );
129 $pluginManager- > load ( $conf- > get ( 'general.enabled_plugins' ));
131 date_default_timezone_set ( $conf- > get ( 'general.timezone' , 'UTC' ));
133 ob_start (); // Output buffering for the page cache.
135 // In case stupid admin has left magic_quotes enabled in php.ini:
136 if ( get_magic_quotes_gpc ())
138 function stripslashes_deep ( $value ) { $value
= is_array ( $value
) ? array_map ( 'stripslashes_deep' , $value
) : stripslashes ( $value
); return $value
; }
139 $_POST = array_map ( 'stripslashes_deep' , $_POST );
140 $_GET = array_map ( 'stripslashes_deep' , $_GET );
141 $_COOKIE = array_map ( 'stripslashes_deep' , $_COOKIE );
144 // Prevent caching on client side or proxy: (yes, it's ugly)
145 header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
146 header ( "Cache-Control: no-store, no-cache, must-revalidate" );
147 header ( "Cache-Control: post-check=0, pre-check=0" , false );
148 header ( "Pragma: no-cache" );
150 if (! is_file ( $conf- > getConfigFileExt ())) {
151 // Ensure Shaarli has proper access to its resources
152 $errors = ApplicationUtils
:: checkResourcePermissions ( $conf );
154 if ( $errors != array ()) {
155 $message = '<p>Insufficient permissions:</p><ul>' ;
157 foreach ( $errors as $error ) {
158 $message .= '<li>' . $error . '</li>' ;
162 header ( 'Content-Type: text/html; charset=utf-8' );
167 // Display the installation form if no existing config is found
171 // a token depending of deployment salt, user password, and the current ip
172 define ( 'STAY_SIGNED_IN_TOKEN' , sha1 ( $conf- > get ( 'credentials.hash' ) . $_SERVER [ 'REMOTE_ADDR' ] . $conf- > get ( 'credentials.salt' )));
174 // Sniff browser language and set date format accordingly.
175 if ( isset ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ])) {
176 autoLocale ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ]);
178 header ( 'Content-Type: text/html; charset=utf-8' ); // We use UTF-8 for proper international characters handling.
181 * Checking session state (i.e. is the user still logged in)
183 * @param ConfigManager $conf The configuration manager.
185 * @return bool: true if the user is logged in, false otherwise.
187 function setup_login_state ( $conf )
189 if ( $conf- > get ( 'security.open_shaarli' )) {
192 $userIsLoggedIn = false ; // By default, we do not consider the user as logged in;
193 $loginFailure = false ; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
194 if (! $conf- > exists ( 'credentials.login' )) {
195 $userIsLoggedIn = false ; // Shaarli is not configured yet.
196 $loginFailure = true ;
198 if ( isset ( $_COOKIE [ 'shaarli_staySignedIn' ]) &&
199 $_COOKIE [ 'shaarli_staySignedIn' ]=== STAY_SIGNED_IN_TOKEN
&&
202 fillSessionInfo ( $conf );
203 $userIsLoggedIn = true ;
205 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
206 if ( empty ( $_SESSION [ 'uid' ])
207 || ( $conf- > get ( 'security.session_protection_disabled' ) == false && $_SESSION [ 'ip' ] != allIPs ())
208 || time () >= $_SESSION [ 'expires_on' ])
211 $userIsLoggedIn = false ;
212 $loginFailure = true ;
214 if (! empty ( $_SESSION [ 'longlastingsession' ])) {
215 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // In case of "Stay signed in" checked.
218 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Standard session expiration date.
220 if (! $loginFailure ) {
221 $userIsLoggedIn = true ;
224 return $userIsLoggedIn ;
226 $userIsLoggedIn = setup_login_state ( $conf );
229 * PubSubHubbub protocol support (if enabled) [UNTESTED]
230 * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
232 * @param ConfigManager $conf Configuration Manager instance.
234 function pubsubhub ( $conf )
236 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
239 include_once './publisher.php' ;
240 $p = new Publisher ( $pshUrl );
242 index_url ( $_SERVER ). '?do=atom' ,
243 index_url ( $_SERVER ). '?do=rss'
245 $p- > publish_update ( $topic_url );
249 // ------------------------------------------------------------------------------------------
250 // Session management
252 // Returns the IP address of the client (Used to prevent session cookie hijacking.)
255 $ip = $_SERVER [ 'REMOTE_ADDR' ];
256 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
257 if ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_X_FORWARDED_FOR' ]; }
258 if ( isset ( $_SERVER [ 'HTTP_CLIENT_IP' ])) { $ip
= $ip
. '_' . $_SERVER
[ 'HTTP_CLIENT_IP' ]; }
265 * @param ConfigManager $conf Configuration Manager instance.
267 function fillSessionInfo ( $conf )
269 $_SESSION [ 'uid' ] = sha1 ( uniqid ( '' , true ). '_' . mt_rand ()); // Generate unique random number (different than phpsessionid)
270 $_SESSION [ 'ip' ]= allIPs (); // We store IP address(es) of the client to make sure session is not hijacked.
271 $_SESSION [ 'username' ]= $conf- > get ( 'credentials.login' );
272 $_SESSION [ 'expires_on' ]= time () +INACTIVITY_TIMEOUT
; // Set session expiration.
276 * Check that user/password is correct.
278 * @param string $login Username
279 * @param string $password User password
280 * @param ConfigManager $conf Configuration Manager instance.
282 * @return bool: authentication successful or not.
284 function check_auth ( $login , $password , $conf )
286 $hash = sha1 ( $password . $login . $conf- > get ( 'credentials.salt' ));
287 if ( $login == $conf- > get ( 'credentials.login' ) && $hash == $conf- > get ( 'credentials.hash' ))
288 { // Login/password is correct.
289 fillSessionInfo ( $conf );
290 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login successful' );
293 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Login failed for user ' . $login );
297 // Returns true if the user is logged in.
298 function isLoggedIn ()
300 global $userIsLoggedIn ;
301 return $userIsLoggedIn ;
306 if ( isset ( $_SESSION )) {
307 unset ( $_SESSION [ 'uid' ]);
308 unset ( $_SESSION [ 'ip' ]);
309 unset ( $_SESSION [ 'username' ]);
310 unset ( $_SESSION [ 'privateonly' ]);
312 setcookie ( 'shaarli_staySignedIn' , FALSE , 0 , WEB_PATH
);
316 // ------------------------------------------------------------------------------------------
317 // Brute force protection system
318 // Several consecutive failed logins will ban the IP address for 30 minutes.
319 if (! is_file ( $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ))) {
322 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
323 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( array ( 'FAILURES' => array (), 'BANS' => array ()), true ). "; \n ?>"
326 include $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' );
328 * Signal a failed login. Will ban the IP if too many failures:
330 * @param ConfigManager $conf Configuration Manager instance.
332 function ban_loginFailed ( $conf )
334 $ip = $_SERVER [ 'REMOTE_ADDR' ];
335 $trusted = $conf- > get ( 'security.trusted_proxies' , array ());
336 if ( in_array ( $ip , $trusted )) {
337 $ip = getIpAddressFromProxy ( $_SERVER , $trusted );
342 $gb = $GLOBALS [ 'IPBANS' ];
343 if (! isset ( $gb [ 'FAILURES' ][ $ip ])) {
344 $gb [ 'FAILURES' ][ $ip ]= 0 ;
346 $gb [ 'FAILURES' ][ $ip ] ++
;
347 if ( $gb [ 'FAILURES' ][ $ip ] > ( $conf- > get ( 'security.ban_after' ) - 1 ))
349 $gb [ 'BANS' ][ $ip ] = time () +
$conf- > get ( 'security.ban_after' , 1800 );
350 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'IP address banned from login' );
352 $GLOBALS [ 'IPBANS' ] = $gb ;
354 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
355 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
360 * Signals a successful login. Resets failed login counter.
362 * @param ConfigManager $conf Configuration Manager instance.
364 function ban_loginOk ( $conf )
366 $ip = $_SERVER [ 'REMOTE_ADDR' ];
367 $gb = $GLOBALS [ 'IPBANS' ];
368 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
369 $GLOBALS [ 'IPBANS' ] = $gb ;
371 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
372 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
377 * Checks if the user CAN login. If 'true', the user can try to login.
379 * @param ConfigManager $conf Configuration Manager instance.
381 * @return bool: true if the user is allowed to login.
383 function ban_canLogin ( $conf )
385 $ip = $_SERVER [ "REMOTE_ADDR" ]; $gb = $GLOBALS [ 'IPBANS' ];
386 if ( isset ( $gb [ 'BANS' ][ $ip ]))
388 // User is banned. Check if the ban has expired:
389 if ( $gb [ 'BANS' ][ $ip ]<= time ())
390 { // Ban expired, user can try to login again.
391 logm ( $conf- > get ( 'resource.log' ), $_SERVER [ 'REMOTE_ADDR' ], 'Ban lifted.' );
392 unset ( $gb [ 'FAILURES' ][ $ip ]); unset ( $gb [ 'BANS' ][ $ip ]);
394 $conf- > get ( 'resource.ban_file' , 'data/ipbans.php' ),
395 "<?php \n\$ GLOBALS['IPBANS']=" . var_export ( $gb , true ). "; \n ?>"
397 return true ; // Ban has expired, user can login.
399 return false ; // User is banned.
401 return true ; // User is not banned.
404 // ------------------------------------------------------------------------------------------
405 // Process login form: Check if login/password is correct.
406 if ( isset ( $_POST [ 'login' ]))
408 if (! ban_canLogin ( $conf )) die ( 'I said: NO. You are banned for the moment. Go away.' );
409 if ( isset ( $_POST [ 'password' ])
410 && tokenOk ( $_POST [ 'token' ])
411 && ( check_auth ( $_POST [ 'login' ], $_POST [ 'password' ], $conf ))
412 ) { // Login/password is OK.
414 // If user wants to keep the session cookie even after the browser closes:
415 if (! empty ( $_POST [ 'longlastingsession' ]))
417 setcookie ( 'shaarli_staySignedIn' , STAY_SIGNED_IN_TOKEN
, time () +
31536000 , WEB_PATH
);
418 $_SESSION [ 'longlastingsession' ]= 31536000 ; // (31536000 seconds = 1 year)
419 $_SESSION [ 'expires_on' ]= time () +
$_SESSION [ 'longlastingsession' ]; // Set session expiration on server-side.
421 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
422 session_set_cookie_params ( $_SESSION [ 'longlastingsession' ], $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // Set session cookie expiration on client side
423 // Note: Never forget the trailing slash on the cookie path!
424 session_regenerate_id ( true ); // Send cookie with new expiration date to browser.
426 else // Standard session expiration (=when browser closes)
428 $cookiedir = '' ; if ( dirname ( $_SERVER [ 'SCRIPT_NAME' ])!= '/' ) $cookiedir = dirname ( $_SERVER [ "SCRIPT_NAME" ]). '/' ;
429 session_set_cookie_params ( 0 , $cookiedir , $_SERVER [ 'SERVER_NAME' ]); // 0 means "When browser closes"
430 session_regenerate_id ( true );
433 // Optional redirect after login:
434 if ( isset ( $_GET [ 'post' ])) {
435 $uri = '?post=' . urlencode ( $_GET [ 'post' ]);
436 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
437 if (! empty ( $_GET [ $param ])) {
438 $uri .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
441 header ( 'Location: ' . $uri );
445 if ( isset ( $_GET [ 'edit_link' ])) {
446 header ( 'Location: ?edit_link=' . escape ( $_GET [ 'edit_link' ]));
450 if ( isset ( $_POST [ 'returnurl' ])) {
451 // Prevent loops over login screen.
452 if ( strpos ( $_POST [ 'returnurl' ], 'do=login' ) === false ) {
453 header ( 'Location: ' . generateLocation ( $_POST [ 'returnurl' ], $_SERVER [ 'HTTP_HOST' ]));
457 header ( 'Location: ?' ); exit ;
461 ban_loginFailed ( $conf );
462 $redir = '&username=' . $_POST [ 'login' ];
463 if ( isset ( $_GET [ 'post' ])) {
464 $redir .= '&post=' . urlencode ( $_GET [ 'post' ]);
465 foreach ( array ( 'description' , 'source' , 'title' ) as $param ) {
466 if (! empty ( $_GET [ $param ])) {
467 $redir .= '&' . $param . '=' . urlencode ( $_GET [ $param ]);
471 echo '<script>alert("Wrong login/password.");document.location= \' ?do=login' . $redir . ' \' ;</script>' ; // Redirect to login screen.
476 // ------------------------------------------------------------------------------------------
477 // Misc utility functions:
479 // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
480 function return_bytes ( $val )
482 $val = trim ( $val ); $last = strtolower ( $val [ strlen ( $val )- 1 ]);
485 case 'g' : $val *= 1024 ;
486 case 'm' : $val *= 1024 ;
487 case 'k' : $val *= 1024 ;
492 // Try to determine max file size for uploads (POST).
493 // Returns an integer (in bytes)
494 function getMaxFileSize ()
496 $size1 = return_bytes ( ini_get ( 'post_max_size' ));
497 $size2 = return_bytes ( ini_get ( 'upload_max_filesize' ));
498 // Return the smaller of two:
499 $maxsize = min ( $size1 , $size2 );
500 // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
504 // ------------------------------------------------------------------------------------------
505 // Token management for XSRF protection
506 // Token should be used in any form which acts on data (create,update,delete,import...).
507 if (! isset ( $_SESSION [ 'tokens' ])) $_SESSION [ 'tokens' ]= array (); // Token are attached to the session.
512 * @param ConfigManager $conf Configuration Manager instance.
514 * @return string token.
516 function getToken ( $conf )
518 $rnd = sha1 ( uniqid ( '' , true ) . '_' . mt_rand () . $conf- > get ( 'credentials.salt' )); // We generate a random string.
519 $_SESSION [ 'tokens' ][ $rnd ]= 1 ; // Store it on the server side.
523 // Tells if a token is OK. Using this function will destroy the token.
525 function tokenOk ( $token )
527 if ( isset ( $_SESSION [ 'tokens' ][ $token ]))
529 unset ( $_SESSION [ 'tokens' ][ $token ]); // Token is used: destroy it.
530 return true ; // Token is OK.
532 return false ; // Wrong token, or already used.
536 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
537 * Gives the last 7 days (which have links).
538 * This RSS feed cannot be filtered.
540 * @param ConfigManager $conf Configuration Manager instance.
542 function showDailyRSS ( $conf ) {
544 $query = $_SERVER [ 'QUERY_STRING' ];
545 $cache = new CachedPage (
546 $conf- > get ( 'config.PAGE_CACHE' ),
548 startsWith ( $query , 'do=dailyrss' ) && ! isLoggedIn ()
550 $cached = $cache- > cachedVersion ();
551 if (! empty ( $cached )) {
556 // If cached was not found (or not usable), then read the database and build the response:
557 // Read links from database (and filter private links if used it not logged in).
558 $LINKSDB = new LinkDB (
559 $conf- > get ( 'resource.datastore' ),
561 $conf- > get ( 'privacy.hide_public_links' ),
562 $conf- > get ( 'redirector.url' ),
563 $conf- > get ( 'redirector.encode_url' )
566 /* Some Shaarlies may have very few links, so we need to look
567 back in time until we have enough days ($nb_of_days).
569 $nb_of_days = 7 ; // We take 7 days.
570 $today = date ( 'Ymd' );
573 foreach ( $LINKSDB as $link ) {
574 $day = $link [ 'created' ]-> format ( 'Ymd' ); // Extract day (without time)
575 if ( strcmp ( $day , $today ) < 0 ) {
576 if ( empty ( $days [ $day ])) {
577 $days [ $day ] = array ();
579 $days [ $day ][] = $link ;
582 if ( count ( $days ) > $nb_of_days ) {
583 break ; // Have we collected enough days?
587 // Build the RSS feed.
588 header ( 'Content-Type: application/rss+xml; charset=utf-8' );
589 $pageaddr = escape ( index_url ( $_SERVER ));
590 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">' ;
592 echo '<title>Daily - ' . $conf- > get ( 'general.title' ) . '</title>' ;
593 echo '<link>' . $pageaddr . '</link>' ;
594 echo '<description>Daily shared links</description>' ;
595 echo '<language>en-en</language>' ;
596 echo '<copyright>' . $pageaddr . '</copyright>' . PHP_EOL
;
599 foreach ( $days as $day => $links ) {
600 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
601 $absurl = escape ( index_url ( $_SERVER ). '?do=daily&day=' . $day ); // Absolute URL of the corresponding "Daily" page.
603 // We pre-format some fields for proper output.
604 foreach ( $links as & $link ) {
605 $link [ 'formatedDescription' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
606 $link [ 'thumbnail' ] = thumbnail ( $conf , $link [ 'url' ]);
607 $link [ 'timestamp' ] = $link [ 'created' ]-> getTimestamp ();
608 if ( startsWith ( $link [ 'url' ], '?' )) {
609 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ]; // make permalink URL absolute
613 // Then build the HTML for this day:
615 $tpl- > assign ( 'title' , $conf- > get ( 'general.title' ));
616 $tpl- > assign ( 'daydate' , $dayDate- > getTimestamp ());
617 $tpl- > assign ( 'absurl' , $absurl );
618 $tpl- > assign ( 'links' , $links );
619 $tpl- > assign ( 'rssdate' , escape ( $dayDate- > format ( DateTime
:: RSS
)));
620 $tpl- > assign ( 'hide_timestamps' , $conf- > get ( 'privacy.hide_timestamps' , false ));
621 $html = $tpl- > draw ( 'dailyrss' , $return_string = true );
623 echo $html . PHP_EOL
;
625 echo '</channel></rss><!-- Cached version of ' . escape ( page_url ( $_SERVER )) . ' -->' ;
627 $cache- > cache ( ob_get_contents ());
633 * Show the 'Daily' page.
635 * @param PageBuilder $pageBuilder Template engine wrapper.
636 * @param LinkDB $LINKSDB LinkDB instance.
637 * @param ConfigManager $conf Configuration Manager instance.
638 * @param PluginManager $pluginManager Plugin Manager instane.
640 function showDaily ( $pageBuilder , $LINKSDB , $conf , $pluginManager )
642 $day = date ( 'Ymd' , strtotime ( '-1 day' )); // Yesterday, in format YYYYMMDD.
643 if ( isset ( $_GET [ 'day' ])) $day = $_GET [ 'day' ];
645 $days = $LINKSDB- > days ();
646 $i = array_search ( $day , $days );
647 if ( $i === false ) { $i
= count ( $days
)- 1 ; $day
= $days
[ $i
]; }
652 if ( $i >= 1 ) $previousday = $days [ $i-1 ];
653 if ( $i < count ( $days )- 1 ) $nextday = $days [ $i +
1 ];
657 $linksToDisplay = $LINKSDB- > filterDay ( $day );
658 } catch ( Exception
$exc ) {
660 $linksToDisplay = array ();
663 // We pre-format some fields for proper output.
664 foreach ( $linksToDisplay as $key => $link )
667 $taglist = explode ( ' ' , $link [ 'tags' ]);
668 uasort ( $taglist , 'strcasecmp' );
669 $linksToDisplay [ $key ][ 'taglist' ]= $taglist ;
670 $linksToDisplay [ $key ][ 'formatedDescription' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
671 $linksToDisplay [ $key ][ 'thumbnail' ] = thumbnail ( $conf , $link [ 'url' ]);
672 $linksToDisplay [ $key ][ 'timestamp' ] = $link [ 'created' ]-> getTimestamp ();
675 /* We need to spread the articles on 3 columns.
676 I did not want to use a JavaScript lib like http://masonry.desandro.com/
677 so I manually spread entries with a simple method: I roughly evaluate the
678 height of a div according to title and description length.
680 $columns = array ( array (), array (), array ()); // Entries to display, for each column.
681 $fill = array ( 0 , 0 , 0 ); // Rough estimate of columns fill.
682 foreach ( $linksToDisplay as $key => $link )
684 // Roughly estimate length of entry (by counting characters)
685 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
686 // Description: 836 characters gives roughly 342 pixel height.
687 // This is not perfect, but it's usually OK.
688 $length = strlen ( $link [ 'title' ]) +
( 342 * strlen ( $link [ 'description' ]))/ 836 ;
689 if ( $link [ 'thumbnail' ]) $length +
= 100 ; // 1 thumbnails roughly takes 100 pixels height.
690 // Then put in column which is the less filled:
691 $smallest = min ( $fill ); // find smallest value in array.
692 $index = array_search ( $smallest , $fill ); // find index of this smallest value.
693 array_push ( $columns [ $index ], $link ); // Put entry in this column.
694 $fill [ $index ] +
= $length ;
697 $dayDate = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $day . '_000000' );
699 'linksToDisplay' => $linksToDisplay ,
701 'day' => $dayDate- > getTimestamp (),
702 'previousday' => $previousday ,
703 'nextday' => $nextday ,
706 $pluginManager- > executeHooks ( 'render_daily' , $data , array ( 'loggedin' => isLoggedIn ()));
708 foreach ( $data as $key => $value ) {
709 $pageBuilder- > assign ( $key , $value );
712 $pageBuilder- > renderPage ( 'daily' );
717 * Renders the linklist
719 * @param pageBuilder $PAGE pageBuilder instance.
720 * @param LinkDB $LINKSDB LinkDB instance.
721 * @param ConfigManager $conf Configuration Manager instance.
722 * @param PluginManager $pluginManager Plugin Manager instance.
724 function showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ) {
725 buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager ); // Compute list of links to display
726 $PAGE- > renderPage ( 'linklist' );
730 * Render HTML page (according to URL parameters and user rights)
732 * @param ConfigManager $conf Configuration Manager instance.
733 * @param PluginManager $pluginManager Plugin Manager instance,
735 function renderPage ( $conf , $pluginManager )
737 $LINKSDB = new LinkDB (
738 $conf- > get ( 'resource.datastore' ),
740 $conf- > get ( 'privacy.hide_public_links' ),
741 $conf- > get ( 'redirector.url' ),
742 $conf- > get ( 'redirector.encode_url' )
745 $updater = new Updater (
746 read_updates_file ( $conf- > get ( 'resource.updates' )),
752 $newUpdates = $updater- > update ();
753 if (! empty ( $newUpdates )) {
755 $conf- > get ( 'resource.updates' ),
756 $updater- > getDoneUpdates ()
760 catch ( Exception
$e ) {
761 die ( $e- > getMessage ());
764 $PAGE = new PageBuilder ( $conf );
765 $PAGE- > assign ( 'linkcount' , count ( $LINKSDB ));
766 $PAGE- > assign ( 'privateLinkcount' , count_private ( $LINKSDB ));
767 $PAGE- > assign ( 'plugin_errors' , $pluginManager- > getErrors ());
769 // Determine which page will be rendered.
770 $query = ( isset ( $_SERVER [ 'QUERY_STRING' ])) ? $_SERVER [ 'QUERY_STRING' ] : '' ;
771 $targetPage = Router
:: findPage ( $query , $_GET , isLoggedIn ());
773 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
774 // Then assign generated data to RainTPL.
775 $common_hooks = array (
781 foreach ( $common_hooks as $name ) {
782 $plugin_data = array ();
783 $pluginManager- > executeHooks ( 'render_' . $name , $plugin_data ,
785 'target' => $targetPage ,
786 'loggedin' => isLoggedIn ()
789 $PAGE- > assign ( 'plugins_' . $name , $plugin_data );
792 // -------- Display login form.
793 if ( $targetPage == Router
:: $PAGE_LOGIN )
795 if ( $conf- > get ( 'security.open_shaarli' )) { header ( 'Location: ?' ); exit ; } // No need to login for open Shaarli
796 if ( isset ( $_GET [ 'username' ])) {
797 $PAGE- > assign ( 'username' , escape ( $_GET [ 'username' ]));
799 $PAGE- > assign ( 'returnurl' ,( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]): '' ));
800 $PAGE- > renderPage ( 'loginform' );
803 // -------- User wants to logout.
804 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=logout' ))
806 invalidateCaches ( $conf- > get ( 'resource.page_cache' ));
808 header ( 'Location: ?' );
812 // -------- Picture wall
813 if ( $targetPage == Router
:: $PAGE_PICWALL )
815 // Optionally filter the results:
816 $links = $LINKSDB- > filterSearch ( $_GET );
817 $linksToDisplay = array ();
819 // Get only links which have a thumbnail.
820 foreach ( $links as $link )
822 $permalink = '?' . $link [ 'shorturl' ];
823 $thumb = lazyThumbnail ( $conf , $link [ 'url' ], $permalink );
824 if ( $thumb != '' ) // Only output links which have a thumbnail.
826 $link [ 'thumbnail' ]= $thumb ; // Thumbnail HTML code.
827 $linksToDisplay []= $link ; // Add to array.
832 'linksToDisplay' => $linksToDisplay ,
834 $pluginManager- > executeHooks ( 'render_picwall' , $data , array ( 'loggedin' => isLoggedIn ()));
836 foreach ( $data as $key => $value ) {
837 $PAGE- > assign ( $key , $value );
840 $PAGE- > renderPage ( 'picwall' );
844 // -------- Tag cloud
845 if ( $targetPage == Router
:: $PAGE_TAGCLOUD )
847 $tags = $LINKSDB- > allTags ();
849 // We sort tags alphabetically, then choose a font size according to count.
850 // First, find max value.
852 foreach ( $tags as $value ) {
853 $maxcount = max ( $maxcount , $value );
856 // Sort tags alphabetically: case insensitive, support locale if available.
857 uksort ( $tags , function ( $a , $b ) {
858 // Collator is part of PHP intl.
859 if ( class_exists ( 'Collator' )) {
860 $c = new Collator ( setlocale ( LC_COLLATE
, 0 ));
861 if (! intl_is_failure ( intl_get_error_code ())) {
862 return $c- > compare ( $a , $b );
865 return strcasecmp ( $a , $b );
869 foreach ( $tags as $key => $value ) {
870 // Tag font size scaling:
871 // default 15 and 30 logarithm bases affect scaling,
872 // 22 and 6 are arbitrary font sizes for max and min sizes.
873 $size = log ( $value , 15 ) / log ( $maxcount , 30 ) * 2.2 +
0.8 ;
874 $tagList [ $key ] = array (
876 'size' => number_format ( $size , 2 , '.' , '' ),
883 $pluginManager- > executeHooks ( 'render_tagcloud' , $data , array ( 'loggedin' => isLoggedIn ()));
885 foreach ( $data as $key => $value ) {
886 $PAGE- > assign ( $key , $value );
889 $PAGE- > renderPage ( 'tagcloud' );
894 if ( $targetPage == Router
:: $PAGE_DAILY ) {
895 showDaily ( $PAGE , $LINKSDB , $conf , $pluginManager );
898 // ATOM and RSS feed.
899 if ( $targetPage == Router
:: $PAGE_FEED_ATOM || $targetPage == Router
:: $PAGE_FEED_RSS ) {
900 $feedType = $targetPage == Router
:: $PAGE_FEED_RSS ? FeedBuilder
:: $FEED_RSS : FeedBuilder
:: $FEED_ATOM ;
901 header ( 'Content-Type: application/' . $feedType . '+xml; charset=utf-8' );
904 $query = $_SERVER [ 'QUERY_STRING' ];
905 $cache = new CachedPage (
906 $conf- > get ( 'resource.page_cache' ),
908 startsWith ( $query , 'do=' . $targetPage ) && ! isLoggedIn ()
910 $cached = $cache- > cachedVersion ();
911 if (! empty ( $cached )) {
917 $feedGenerator = new FeedBuilder ( $LINKSDB , $feedType , $_SERVER , $_GET , isLoggedIn ());
918 $feedGenerator- > setLocale ( strtolower ( setlocale ( LC_COLLATE
, 0 )));
919 $feedGenerator- > setHideDates ( $conf- > get ( 'privacy.hide_timestamps' ) && ! isLoggedIn ());
920 $feedGenerator- > setUsePermalinks ( isset ( $_GET [ 'permalinks' ]) || ! $conf- > get ( 'feed.rss_permalinks' ));
921 $pshUrl = $conf- > get ( 'config.PUBSUBHUB_URL' );
922 if (! empty ( $pshUrl )) {
923 $feedGenerator- > setPubsubhubUrl ( $pshUrl );
925 $data = $feedGenerator- > buildData ();
927 // Process plugin hook.
928 $pluginManager- > executeHooks ( 'render_feed' , $data , array (
929 'loggedin' => isLoggedIn (),
930 'target' => $targetPage ,
933 // Render the template.
934 $PAGE- > assignAll ( $data );
935 $PAGE- > renderPage ( 'feed.' . $feedType );
936 $cache- > cache ( ob_get_contents ());
941 // Display openseach plugin (XML)
942 if ( $targetPage == Router
:: $PAGE_OPENSEARCH ) {
943 header ( 'Content-Type: application/xml; charset=utf-8' );
944 $PAGE- > assign ( 'serverurl' , index_url ( $_SERVER ));
945 $PAGE- > renderPage ( 'opensearch' );
949 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
950 if ( isset ( $_GET [ 'addtag' ]))
952 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
953 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) { header ( 'Location: ?searchtags=' . urlencode ( $_GET
[ 'addtag' ])); exit ; } // In case browser does not send HTTP_REFERER
954 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
956 // Prevent redirection loop
957 if ( isset ( $params [ 'addtag' ])) {
958 unset ( $params [ 'addtag' ]);
961 // Check if this tag is already in the search query and ignore it if it is.
962 // Each tag is always separated by a space
963 if ( isset ( $params [ 'searchtags' ])) {
964 $current_tags = explode ( ' ' , $params [ 'searchtags' ]);
966 $current_tags = array ();
969 foreach ( $current_tags as $value ) {
970 if ( $value === $_GET [ 'addtag' ]) {
975 // Append the tag if necessary
976 if ( empty ( $params [ 'searchtags' ])) {
977 $params [ 'searchtags' ] = trim ( $_GET [ 'addtag' ]);
980 $params [ 'searchtags' ] = trim ( $params [ 'searchtags' ]). ' ' . trim ( $_GET [ 'addtag' ]);
983 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
984 header ( 'Location: ?' . http_build_query ( $params ));
988 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
989 if ( isset ( $_GET [ 'removetag' ])) {
990 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
991 if ( empty ( $_SERVER [ 'HTTP_REFERER' ])) {
992 header ( 'Location: ?' );
996 // In case browser does not send HTTP_REFERER
997 parse_str ( parse_url ( $_SERVER [ 'HTTP_REFERER' ], PHP_URL_QUERY
), $params );
999 // Prevent redirection loop
1000 if ( isset ( $params [ 'removetag' ])) {
1001 unset ( $params [ 'removetag' ]);
1004 if ( isset ( $params [ 'searchtags' ])) {
1005 $tags = explode ( ' ' , $params [ 'searchtags' ]);
1006 // Remove value from array $tags.
1007 $tags = array_diff ( $tags , array ( $_GET [ 'removetag' ]));
1008 $params [ 'searchtags' ] = implode ( ' ' , $tags );
1010 if ( empty ( $params [ 'searchtags' ])) {
1011 unset ( $params [ 'searchtags' ]);
1014 unset ( $params [ 'page' ]); // We also remove page (keeping the same page has no sense, since the results are different)
1016 header ( 'Location: ?' . http_build_query ( $params ));
1020 // -------- User wants to change the number of links per page (linksperpage=...)
1021 if ( isset ( $_GET [ 'linksperpage' ])) {
1022 if ( is_numeric ( $_GET [ 'linksperpage' ])) {
1023 $_SESSION [ 'LINKS_PER_PAGE' ]= abs ( intval ( $_GET [ 'linksperpage' ]));
1026 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'linksperpage' )));
1030 // -------- User wants to see only private links (toggle)
1031 if ( isset ( $_GET [ 'privateonly' ])) {
1032 if ( empty ( $_SESSION [ 'privateonly' ])) {
1033 $_SESSION [ 'privateonly' ] = 1 ; // See only private links
1035 unset ( $_SESSION [ 'privateonly' ]); // See all links
1038 header ( 'Location: ' . generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'privateonly' )));
1042 // -------- Handle other actions allowed for non-logged in users:
1045 // User tries to post new link but is not logged in:
1046 // Show login screen, then redirect to ?post=...
1047 if ( isset ( $_GET [ 'post' ]))
1049 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.
1053 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1054 if ( isset ( $_GET [ 'edit_link' ])) {
1055 header ( 'Location: ?do=login&edit_link=' . escape ( $_GET [ 'edit_link' ]));
1059 exit ; // Never remove this one! All operations below are reserved for logged in user.
1062 // -------- All other functions are reserved for the registered user:
1064 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1065 if ( $targetPage == Router
:: $PAGE_TOOLS )
1068 'pageabsaddr' => index_url ( $_SERVER ),
1069 'sslenabled' => ! empty ( $_SERVER [ 'HTTPS' ])
1071 $pluginManager- > executeHooks ( 'render_tools' , $data );
1073 foreach ( $data as $key => $value ) {
1074 $PAGE- > assign ( $key , $value );
1077 $PAGE- > renderPage ( 'tools' );
1081 // -------- User wants to change his/her password.
1082 if ( $targetPage == Router
:: $PAGE_CHANGEPASSWORD )
1084 if ( $conf- > get ( 'security.open_shaarli' )) {
1085 die ( 'You are not supposed to change a password on an Open Shaarli.' );
1088 if (! empty ( $_POST [ 'setpassword' ]) && ! empty ( $_POST [ 'oldpassword' ]))
1090 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' ); // Go away!
1092 // Make sure old password is correct.
1093 $oldhash = sha1 ( $_POST [ 'oldpassword' ]. $conf- > get ( 'credentials.login' ). $conf- > get ( 'credentials.salt' ));
1094 if ( $oldhash != $conf- > get ( 'credentials.hash' )) { echo '<script>alert("The old password is not correct.");document.location= \' ?do=changepasswd \' ;</script>' ; exit ; }
1095 // Save new password
1096 // Salt renders rainbow-tables attacks useless.
1097 $conf- > set ( 'credentials.salt' , sha1 ( uniqid ( '' , true ) . '_' . mt_rand ()));
1098 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $conf- > get ( 'credentials.login' ) . $conf- > get ( 'credentials.salt' )));
1100 $conf- > write ( isLoggedIn ());
1102 catch ( Exception
$e ) {
1104 'ERROR while writing config file after changing password.' . PHP_EOL
.
1108 // TODO: do not handle exceptions/errors in JS.
1109 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=tools \' ;</script>' ;
1112 echo '<script>alert("Your password has been changed.");document.location= \' ?do=tools \' ;</script>' ;
1115 else // show the change password form.
1117 $PAGE- > renderPage ( 'changepassword' );
1122 // -------- User wants to change configuration
1123 if ( $targetPage == Router
:: $PAGE_CONFIGURE )
1125 if (! empty ( $_POST [ 'title' ]) )
1127 if (! tokenOk ( $_POST [ 'token' ])) {
1128 die ( 'Wrong token.' ); // Go away!
1131 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1132 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1134 $tz = $_POST [ 'continent' ] . '/' . $_POST [ 'city' ];
1136 $conf- > set ( 'general.timezone' , $tz );
1137 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
1138 $conf- > set ( 'general.header_link' , escape ( $_POST [ 'titleLink' ]));
1139 $conf- > set ( 'redirector.url' , escape ( $_POST [ 'redirector' ]));
1140 $conf- > set ( 'security.session_protection_disabled' , ! empty ( $_POST [ 'disablesessionprotection' ]));
1141 $conf- > set ( 'privacy.default_private_links' , ! empty ( $_POST [ 'privateLinkByDefault' ]));
1142 $conf- > set ( 'feed.rss_permalinks' , ! empty ( $_POST [ 'enableRssPermalinks' ]));
1143 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
1144 $conf- > set ( 'privacy.hide_public_links' , ! empty ( $_POST [ 'hidePublicLinks' ]));
1146 $conf- > write ( isLoggedIn ());
1148 catch ( Exception
$e ) {
1150 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1154 // TODO: do not handle exceptions/errors in JS.
1155 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=configure \' ;</script>' ;
1158 echo '<script>alert("Configuration was saved.");document.location= \' ?do=configure \' ;</script>' ;
1161 else // Show the configuration form.
1163 $PAGE- > assign ( 'title' , $conf- > get ( 'general.title' ));
1164 $PAGE- > assign ( 'redirector' , $conf- > get ( 'redirector.url' ));
1165 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ( $conf- > get ( 'general.timezone' ));
1166 $PAGE- > assign ( 'timezone_form' , $timezone_form );
1167 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1168 $PAGE- > assign ( 'private_links_default' , $conf- > get ( 'privacy.default_private_links' , false ));
1169 $PAGE- > assign ( 'session_protection_disabled' , $conf- > get ( 'security.session_protection_disabled' , false ));
1170 $PAGE- > assign ( 'enable_rss_permalinks' , $conf- > get ( 'feed.rss_permalinks' , false ));
1171 $PAGE- > assign ( 'enable_update_check' , $conf- > get ( 'updates.check_updates' , true ));
1172 $PAGE- > assign ( 'hide_public_links' , $conf- > get ( 'privacy.hide_public_links' , false ));
1173 $PAGE- > renderPage ( 'configure' );
1178 // -------- User wants to rename a tag or delete it
1179 if ( $targetPage == Router
:: $PAGE_CHANGETAG )
1181 if ( empty ( $_POST [ 'fromtag' ]) || ( empty ( $_POST [ 'totag' ]) && isset ( $_POST [ 'renametag' ]))) {
1182 $PAGE- > assign ( 'tags' , $LINKSDB- > allTags ());
1183 $PAGE- > renderPage ( 'changetag' );
1187 if (! tokenOk ( $_POST [ 'token' ])) {
1188 die ( 'Wrong token.' );
1192 if ( isset ( $_POST [ 'deletetag' ]) && ! empty ( $_POST [ 'fromtag' ])) {
1193 $needle = trim ( $_POST [ 'fromtag' ]);
1194 // True for case-sensitive tag search.
1195 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1196 foreach ( $linksToAlter as $key => $value )
1198 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1199 unset ( $tags [ array_search ( $needle , $tags )]); // Remove tag.
1200 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1201 $LINKSDB [ $key ]= $value ;
1203 $LINKSDB- > save ( $conf- > get ( 'resource.page_cache' ));
1204 echo '<script>alert("Tag was removed from ' . count ( $linksToAlter ). ' links.");document.location= \' ? \' ;</script>' ;
1209 if ( isset ( $_POST [ 'renametag' ]) && ! empty ( $_POST [ 'fromtag' ]) && ! empty ( $_POST [ 'totag' ])) {
1210 $needle = trim ( $_POST [ 'fromtag' ]);
1211 // True for case-sensitive tag search.
1212 $linksToAlter = $LINKSDB- > filterSearch ( array ( 'searchtags' => $needle ), true );
1213 foreach ( $linksToAlter as $key => $value )
1215 $tags = explode ( ' ' , trim ( $value [ 'tags' ]));
1216 $tags [ array_search ( $needle , $tags )] = trim ( $_POST [ 'totag' ]); // Replace tags value.
1217 $value [ 'tags' ]= trim ( implode ( ' ' , $tags ));
1218 $LINKSDB [ $key ]= $value ;
1220 $LINKSDB- > save ( $conf- > get ( 'resource.page_cache' )); // Save to disk.
1221 echo '<script>alert("Tag was renamed in ' . count ( $linksToAlter ). ' links.");document.location= \' ?searchtags=' . urlencode ( $_POST [ 'totag' ]). ' \' ;</script>' ;
1226 // -------- User wants to add a link without using the bookmarklet: Show form.
1227 if ( $targetPage == Router
:: $PAGE_ADDLINK )
1229 $PAGE- > renderPage ( 'addlink' );
1233 // -------- User clicked the "Save" button when editing a link: Save link to database.
1234 if ( isset ( $_POST [ 'save_edit' ]))
1237 if (! tokenOk ( $_POST [ 'token' ])) {
1238 die ( 'Wrong token.' );
1241 // lf_id should only be present if the link exists.
1242 $id = ! empty ( $_POST [ 'lf_id' ]) ? intval ( escape ( $_POST [ 'lf_id' ])) : $LINKSDB- > getNextId ();
1243 // Linkdate is kept here to:
1244 // - use the same permalink for notes as they're displayed when creating them
1245 // - let users hack creation date of their posts
1246 // See: https://github.com/shaarli/Shaarli/wiki/Datastore-hacks#changing-the-timestamp-for-a-link
1247 $linkdate = escape ( $_POST [ 'lf_linkdate' ]);
1248 if ( isset ( $LINKSDB [ $id ])) {
1250 $created = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $linkdate );
1251 $updated = new DateTime ();
1252 $shortUrl = $LINKSDB [ $id ][ 'shorturl' ];
1255 $created = DateTime
:: createFromFormat ( LinkDB
:: LINK_DATE_FORMAT
, $linkdate );
1257 $shortUrl = link_small_hash ( $created , $id );
1260 // Remove multiple spaces.
1261 $tags = trim ( preg_replace ( '/\s\s+/' , ' ' , $_POST [ 'lf_tags' ]));
1262 // Remove first '-' char in tags.
1263 $tags = preg_replace ( '/(^| )\-/' , ' $1' , $tags );
1264 // Remove duplicates.
1265 $tags = implode(' ', array_unique(explode(' ', $tags )));
1267 $url = trim( $_POST [' lf_url
']);
1268 if (! startsWith( $url , ' http
: ') && ! startsWith( $url , ' https
: ')
1269 && ! startsWith( $url , ' ftp
: ') && ! startsWith( $url , ' magnet
: ')
1270 && ! startsWith( $url , ' ? ') && ! startsWith( $url , ' javascript
: ')
1272 $url = ' http
: //' . $url;
1277 'title' => trim ( $_POST [ 'lf_title' ]),
1279 'description' => $_POST [ 'lf_description' ],
1280 'private' => ( isset ( $_POST [ 'lf_private' ]) ? 1 : 0 ),
1281 'created' => $created ,
1282 'updated' => $updated ,
1283 'tags' => str_replace ( ',' , ' ' , $tags ),
1284 'shorturl' => $shortUrl ,
1287 // If title is empty, use the URL as title.
1288 if ( $link [ 'title' ] == '' ) {
1289 $link [ 'title' ] = $link [ 'url' ];
1292 $pluginManager- > executeHooks ( 'save_link' , $link );
1294 $LINKSDB [ $id ] = $link ;
1295 $LINKSDB- > save ( $conf- > get ( 'resource.page_cache' ));
1298 // If we are called from the bookmarklet, we must close the popup:
1299 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) {
1300 echo '<script>self.close();</script>' ;
1304 $returnurl = ! empty ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' ;
1305 $location = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1306 // Scroll to the link which has been edited.
1307 $location .= '#' . $link [ 'shorturl' ];
1308 // After saving the link, redirect to the page the user was on.
1309 header ( 'Location: ' . $location );
1313 // -------- User clicked the "Cancel" button when editing a link.
1314 if ( isset ( $_POST [ 'cancel_edit' ]))
1316 // If we are called from the bookmarklet, we must close the popup:
1317 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1318 $link = $LINKSDB [( int ) escape ( $_POST [ 'lf_id' ])];
1319 $returnurl = ( isset ( $_POST [ 'returnurl' ]) ? $_POST [ 'returnurl' ] : '?' );
1320 // Scroll to the link which has been edited.
1321 $returnurl .= '#' . $link [ 'shorturl' ];
1322 $returnurl = generateLocation ( $returnurl , $_SERVER [ 'HTTP_HOST' ], array ( 'addlink' , 'post' , 'edit_link' ));
1323 header ( 'Location: ' . $returnurl ); // After canceling, redirect to the page the user was on.
1327 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1328 if ( isset ( $_POST [ 'delete_link' ]))
1330 if (! tokenOk ( $_POST [ 'token' ])) die ( 'Wrong token.' );
1332 // We do not need to ask for confirmation:
1333 // - confirmation is handled by JavaScript
1334 // - we are protected from XSRF by the token.
1336 // FIXME! We keep `lf_linkdate` for consistency before a proper API. To be removed.
1337 $id = isset ( $_POST [ 'lf_id' ]) ? intval ( escape ( $_POST [ 'lf_id' ])) : intval ( escape ( $_POST [ 'lf_linkdate' ]));
1339 $pluginManager- > executeHooks ( 'delete_link' , $LINKSDB [ $id ]);
1341 unset ( $LINKSDB [ $id ]);
1342 $LINKSDB- > save ( 'resource.page_cache' ); // save to disk
1344 // If we are called from the bookmarklet, we must close the popup:
1345 if ( isset ( $_GET [ 'source' ]) && ( $_GET [ 'source' ]== 'bookmarklet' || $_GET [ 'source' ]== 'firefoxsocialapi' )) { echo '<script>self.close();</script>' ; exit ; }
1346 // Pick where we're going to redirect
1347 // =============================================================
1348 // Basically, we can't redirect to where we were previously if it was a permalink
1349 // or an edit_link, because it would 404.
1351 // - / : nothing in $_GET, redirect to self
1352 // - /?page : redirect to self
1353 // - /?searchterm : redirect to self (there might be other links)
1354 // - /?searchtags : redirect to self
1355 // - /permalink : redirect to / (the link does not exist anymore)
1356 // - /?edit_link : redirect to / (the link does not exist anymore)
1357 // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self
1358 // redirect is not satisfied, and only then redirect to /
1361 if ( count ( $_GET ) == 0
1362 || isset ( $_GET [ 'page' ])
1363 || isset ( $_GET [ 'searchterm' ])
1364 || isset ( $_GET [ 'searchtags' ])
1366 if ( isset ( $_POST [ 'returnurl' ])) {
1367 $location = $_POST [ 'returnurl' ]; // Handle redirects given by the form
1369 $location = generateLocation ( $_SERVER [ 'HTTP_REFERER' ], $_SERVER [ 'HTTP_HOST' ], array ( 'delete_link' ));
1373 header ( 'Location: ' . $location ); // After deleting the link, redirect to appropriate location
1377 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1378 if ( isset ( $_GET [ 'edit_link' ]))
1380 $id = ( int ) escape ( $_GET [ 'edit_link' ]);
1381 $link = $LINKSDB [ $id ]; // Read database
1382 if (! $link ) { header ( 'Location: ?' ); exit ; } // Link not found in database.
1383 $link [ 'linkdate' ] = $link [ 'created' ]-> format ( LinkDB
:: LINK_DATE_FORMAT
);
1386 'link_is_new' => false ,
1387 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1388 'tags' => $LINKSDB- > allTags (),
1390 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1392 foreach ( $data as $key => $value ) {
1393 $PAGE- > assign ( $key , $value );
1396 $PAGE- > renderPage ( 'editlink' );
1400 // -------- User want to post a new link: Display link edit form.
1401 if ( isset ( $_GET [ 'post' ])) {
1402 $url = cleanup_url ( $_GET [ 'post' ]);
1404 $link_is_new = false ;
1405 // Check if URL is not already in database (in this case, we will edit the existing link)
1406 $link = $LINKSDB- > getLinkFromUrl ( $url );
1409 $link_is_new = true ;
1410 $linkdate = strval ( date ( LinkDB
:: LINK_DATE_FORMAT
));
1411 // Get title if it was provided in URL (by the bookmarklet).
1412 $title = empty ( $_GET [ 'title' ]) ? '' : escape ( $_GET [ 'title' ]);
1413 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1414 $description = empty ( $_GET [ 'description' ]) ? '' : escape ( $_GET [ 'description' ]);
1415 $tags = empty ( $_GET [ 'tags' ]) ? '' : escape ( $_GET [ 'tags' ]);
1416 $private = ! empty ( $_GET [ 'private' ]) && $_GET [ 'private' ] === "1" ? 1 : 0 ;
1417 // 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.)
1418 if ( empty ( $title ) && strpos ( get_url_scheme ( $url ), 'http' ) !== false ) {
1419 // Short timeout to keep the application responsive
1420 list ( $headers , $content ) = get_http_response ( $url , 4 );
1421 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
1422 // Retrieve charset.
1423 $charset = get_charset ( $headers , $content );
1425 $title = html_extract_title ( $content );
1426 // Re-encode title in utf-8 if necessary.
1427 if (! empty ( $title ) && strtolower ( $charset ) != 'utf-8' ) {
1428 $title = mb_convert_encoding ( $title , 'utf-8' , $charset );
1434 $url = '?' . smallHash ( $linkdate . $LINKSDB- > getNextId ());
1437 $url = escape ( $url );
1438 $title = escape ( $title );
1441 'linkdate' => $linkdate ,
1444 'description' => $description ,
1446 'private' => $private
1449 $link [ 'linkdate' ] = $link [ 'created' ]-> format ( LinkDB
:: LINK_DATE_FORMAT
);
1454 'link_is_new' => $link_is_new ,
1455 'http_referer' => ( isset ( $_SERVER [ 'HTTP_REFERER' ]) ? escape ( $_SERVER [ 'HTTP_REFERER' ]) : '' ),
1456 'source' => ( isset ( $_GET [ 'source' ]) ? $_GET [ 'source' ] : '' ),
1457 'tags' => $LINKSDB- > allTags (),
1458 'default_private_links' => $conf- > get ( 'privacy.default_private_links' , false ),
1460 $pluginManager- > executeHooks ( 'render_editlink' , $data );
1462 foreach ( $data as $key => $value ) {
1463 $PAGE- > assign ( $key , $value );
1466 $PAGE- > renderPage ( 'editlink' );
1470 if ( $targetPage == Router
:: $PAGE_EXPORT ) {
1471 // Export links as a Netscape Bookmarks file
1473 if ( empty ( $_GET [ 'selection' ])) {
1474 $PAGE- > renderPage ( 'export' );
1478 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1479 $selection = $_GET [ 'selection' ];
1480 if ( isset ( $_GET [ 'prepend_note_url' ])) {
1481 $prependNoteUrl = $_GET [ 'prepend_note_url' ];
1483 $prependNoteUrl = false ;
1489 NetscapeBookmarkUtils
:: filterAndFormat (
1496 } catch ( Exception
$exc ) {
1497 header ( 'Content-Type: text/plain; charset=utf-8' );
1498 echo $exc- > getMessage ();
1501 $now = new DateTime ();
1502 header ( 'Content-Type: text/html; charset=utf-8' );
1504 'Content-disposition: attachment; filename=bookmarks_'
1505 . $selection . '_' . $now- > format ( LinkDB
:: LINK_DATE_FORMAT
). '.html'
1507 $PAGE- > assign ( 'date' , $now- > format ( DateTime
:: RFC822
));
1508 $PAGE- > assign ( 'eol' , PHP_EOL
);
1509 $PAGE- > assign ( 'selection' , $selection );
1510 $PAGE- > renderPage ( 'export.bookmarks' );
1514 if ( $targetPage == Router
:: $PAGE_IMPORT ) {
1515 // Upload a Netscape bookmark dump to import its contents
1517 if (! isset ( $_POST [ 'token' ]) || ! isset ( $_FILES [ 'filetoupload' ])) {
1518 // Show import dialog
1519 $PAGE- > assign ( 'maxfilesize' , getMaxFileSize ());
1520 $PAGE- > renderPage ( 'import' );
1524 // Import bookmarks from an uploaded file
1525 if ( isset ( $_FILES [ 'filetoupload' ][ 'size' ]) && $_FILES [ 'filetoupload' ][ 'size' ] == 0 ) {
1526 // The file is too big or some form field may be missing.
1527 echo '<script>alert("The file you are trying to upload is probably'
1528 . ' bigger than what this webserver can accept ('
1529 . getMaxFileSize (). ' bytes).'
1530 . ' Please upload in smaller chunks.");document.location= \' ?do='
1531 . Router
:: $PAGE_IMPORT . ' \' ;</script>' ;
1534 if (! tokenOk ( $_POST [ 'token' ])) {
1535 die ( 'Wrong token.' );
1537 $status = NetscapeBookmarkUtils
:: import (
1541 $conf- > get ( 'resource.page_cache' )
1543 echo '<script>alert("' . $status . '");document.location= \' ?do='
1544 . Router
:: $PAGE_IMPORT . ' \' ;</script>' ;
1548 // Plugin administration page
1549 if ( $targetPage == Router
:: $PAGE_PLUGINSADMIN ) {
1550 $pluginMeta = $pluginManager- > getPluginsMeta ();
1552 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1553 $enabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] !== false ; });
1555 $enabledPlugins = load_plugin_parameter_values ( $enabledPlugins , $conf- > get ( 'plugins' , array ()));
1558 function ( $a , $b ) { return $a
[ 'order' ] - $b
[ 'order' ]; }
1560 $disabledPlugins = array_filter ( $pluginMeta , function ( $v ) { return $v
[ 'order' ] === false ; });
1562 $PAGE- > assign ( 'enabledPlugins' , $enabledPlugins );
1563 $PAGE- > assign ( 'disabledPlugins' , $disabledPlugins );
1564 $PAGE- > renderPage ( 'pluginsadmin' );
1568 // Plugin administration form action
1569 if ( $targetPage == Router
:: $PAGE_SAVE_PLUGINSADMIN ) {
1571 if ( isset ( $_POST [ 'parameters_form' ])) {
1572 unset ( $_POST [ 'parameters_form' ]);
1573 foreach ( $_POST as $param => $value ) {
1574 $conf- > set ( 'plugins.' . $param , escape ( $value ));
1578 $conf- > set ( 'general.enabled_plugins' , save_plugin_config ( $_POST ));
1580 $conf- > write ( isLoggedIn ());
1582 catch ( Exception
$e ) {
1584 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1588 // TODO: do not handle exceptions/errors in JS.
1589 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ?do=' . Router
:: $PAGE_PLUGINSADMIN . ' \' ;</script>' ;
1592 header ( 'Location: ?do=' . Router
:: $PAGE_PLUGINSADMIN );
1596 // -------- Otherwise, simply display search form and links:
1597 showLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager );
1602 * Template for the list of links (<div id="linklist">)
1603 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1605 * @param pageBuilder $PAGE pageBuilder instance.
1606 * @param LinkDB $LINKSDB LinkDB instance.
1607 * @param ConfigManager $conf Configuration Manager instance.
1608 * @param PluginManager $pluginManager Plugin Manager instance.
1610 function buildLinkList ( $PAGE , $LINKSDB , $conf , $pluginManager )
1612 // Used in templates
1613 $searchtags = ! empty ( $_GET [ 'searchtags' ]) ? escape ( $_GET [ 'searchtags' ]) : '' ;
1614 $searchterm = ! empty ( $_GET [ 'searchterm' ]) ? escape ( $_GET [ 'searchterm' ]) : '' ;
1617 if (! empty ( $_SERVER [ 'QUERY_STRING' ])
1618 && preg_match ( '/^[a-zA-Z0-9-_@] {6} ( $| &|#)/' , $_SERVER [ 'QUERY_STRING' ])) {
1620 $linksToDisplay = $LINKSDB- > filterHash ( $_SERVER [ 'QUERY_STRING' ]);
1621 } catch ( LinkNotFoundException
$e ) {
1622 $PAGE- > render404 ( $e- > getMessage ());
1626 // Filter links according search parameters.
1627 $privateonly = ! empty ( $_SESSION [ 'privateonly' ]);
1628 $linksToDisplay = $LINKSDB- > filterSearch ( $_GET , false , $privateonly );
1631 // ---- Handle paging.
1633 foreach ( $linksToDisplay as $key => $value ) {
1639 // Select articles according to paging.
1640 $pagecount = ceil ( count ( $keys ) / $_SESSION [ 'LINKS_PER_PAGE' ]);
1641 $pagecount = $pagecount == 0 ? 1 : $pagecount ;
1642 $page = empty ( $_GET [ 'page' ]) ? 1 : intval ( $_GET [ 'page' ]);
1643 $page = $page < 1 ? 1 : $page ;
1644 $page = $page > $pagecount ? $pagecount : $page ;
1646 $i = ( $page-1 ) * $_SESSION [ 'LINKS_PER_PAGE' ];
1647 $end = $i +
$_SESSION [ 'LINKS_PER_PAGE' ];
1648 $linkDisp = array ();
1649 while ( $i < $end && $i < count ( $keys ))
1651 $link = $linksToDisplay [ $keys [ $i ]];
1652 $link [ 'description' ] = format_description ( $link [ 'description' ], $conf- > get ( 'redirector.url' ));
1653 $classLi = ( $i %
2 ) != 0 ? '' : 'publicLinkHightLight' ;
1654 $link [ 'class' ] = $link [ 'private' ] == 0 ? $classLi : 'private' ;
1655 $link [ 'timestamp' ] = $link [ 'created' ]-> getTimestamp ();
1656 if (! empty ( $link [ 'updated' ])) {
1657 $link [ 'updated_timestamp' ] = $link [ 'updated' ]-> getTimestamp ();
1659 $link [ 'updated_timestamp' ] = '' ;
1661 $taglist = explode ( ' ' , $link [ 'tags' ]);
1662 uasort ( $taglist , 'strcasecmp' );
1663 $link [ 'taglist' ] = $taglist ;
1664 // Check for both signs of a note: starting with ? and 7 chars long.
1665 if ( $link [ 'url' ][ 0 ] === '?' &&
1666 strlen ( $link [ 'url' ]) === 7 ) {
1667 $link [ 'url' ] = index_url ( $_SERVER ) . $link [ 'url' ];
1670 $linkDisp [ $keys [ $i ]] = $link ;
1674 // Compute paging navigation
1675 $searchtagsUrl = empty ( $searchtags ) ? '' : '&searchtags=' . urlencode ( $searchtags );
1676 $searchtermUrl = empty ( $searchterm ) ? '' : '&searchterm=' . urlencode ( $searchterm );
1677 $previous_page_url = '' ;
1678 if ( $i != count ( $keys )) {
1679 $previous_page_url = '?page=' . ( $page +
1 ) . $searchtermUrl . $searchtagsUrl ;
1683 $next_page_url = '?page=' . ( $page-1 ) . $searchtermUrl . $searchtagsUrl ;
1686 // Fill all template fields.
1688 'previous_page_url' => $previous_page_url ,
1689 'next_page_url' => $next_page_url ,
1690 'page_current' => $page ,
1691 'page_max' => $pagecount ,
1692 'result_count' => count ( $linksToDisplay ),
1693 'search_term' => $searchterm ,
1694 'search_tags' => $searchtags ,
1695 'redirector' => $conf- > get ( 'redirector.url' ), // Optional redirector URL.
1696 'links' => $linkDisp ,
1697 'tags' => $LINKSDB- > allTags (),
1700 // If there is only a single link, we change on-the-fly the title of the page.
1701 if ( count ( $linksToDisplay ) == 1 ) {
1702 $data [ 'pagetitle' ] = $linksToDisplay [ $keys [ 0 ]][ 'title' ] . ' - ' . $conf- > get ( 'general.title' );
1705 $pluginManager- > executeHooks ( 'render_linklist' , $data , array ( 'loggedin' => isLoggedIn ()));
1707 foreach ( $data as $key => $value ) {
1708 $PAGE- > assign ( $key , $value );
1715 * Compute the thumbnail for a link.
1717 * With a link to the original URL.
1718 * Understands various services (youtube.com...)
1719 * Input: $url = URL for which the thumbnail must be found.
1720 * $href = if provided, this URL will be followed instead of $url
1721 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1722 * Some of them may be missing.
1723 * Return an empty array if no thumbnail available.
1725 * @param ConfigManager $conf Configuration Manager instance.
1726 * @param string $url
1727 * @param string|bool $href
1731 function computeThumbnail ( $conf , $url , $href = false )
1733 if (! $conf- > get ( 'thumbnail.enable_thumbnails' )) return array ();
1734 if ( $href == false ) $href = $url ;
1736 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1737 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1738 // ^^^^^^^^^^^ ^^^^^^^^^^^
1739 $domain = parse_url ( $url , PHP_URL_HOST
);
1740 if ( $domain == 'youtube.com' || $domain == 'www.youtube.com' )
1742 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract video ID and get thumbnail
1743 if (! empty ( $params [ 'v' ])) return array ( 'src' => 'https://img.youtube.com/vi/' . $params [ 'v' ]. '/default.jpg' ,
1744 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1746 if ( $domain == 'youtu.be' ) // Youtube short links
1748 $path = parse_url ( $url , PHP_URL_PATH
);
1749 return array ( 'src' => 'https://img.youtube.com/vi' . $path . '/default.jpg' ,
1750 'href' => $href , 'width' => '120' , 'height' => '90' , 'alt' => 'YouTube thumbnail' );
1752 if ( $domain == 'pix.toile-libre.org' ) // pix.toile-libre.org image hosting
1754 parse_str ( parse_url ( $url , PHP_URL_QUERY
), $params ); // Extract image filename.
1755 if (! empty ( $params ) && ! empty ( $params [ 'img' ])) return array ( 'src' => 'http://pix.toile-libre.org/upload/thumb/' . urlencode ( $params [ 'img' ]),
1756 'href' => $href , 'style' => 'max-width:120px; max-height:150px' , 'alt' => 'pix.toile-libre.org thumbnail' );
1759 if ( $domain == 'imgur.com' )
1761 $path = parse_url ( $url , PHP_URL_PATH
);
1762 if ( startsWith ( $path , '/a/' )) return array (); // Thumbnails for albums are not available.
1763 if ( startsWith ( $path , '/r/' )) return array ( 'src' => 'https://i.imgur.com/' . basename ( $path ). 's.jpg' ,
1764 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1765 if ( startsWith ( $path , '/gallery/' )) return array ( 'src' => 'https://i.imgur.com' . substr ( $path , 8 ). 's.jpg' ,
1766 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1768 if ( substr_count ( $path , '/' )== 1 ) return array ( 'src' => 'https://i.imgur.com/' . substr ( $path , 1 ). 's.jpg' ,
1769 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1771 if ( $domain == 'i.imgur.com' )
1773 $pi = pathinfo ( parse_url ( $url , PHP_URL_PATH
));
1774 if (! empty ( $pi [ 'filename' ])) return array ( 'src' => 'https://i.imgur.com/' . $pi [ 'filename' ]. 's.jpg' ,
1775 'href' => $href , 'width' => '90' , 'height' => '90' , 'alt' => 'imgur.com thumbnail' );
1777 if ( $domain == 'dailymotion.com' || $domain == 'www.dailymotion.com' )
1779 if ( strpos ( $url , 'dailymotion.com/video/' )!== false )
1781 $thumburl = str_replace ( 'dailymotion.com/video/' , 'dailymotion.com/thumbnail/video/' , $url );
1782 return array ( 'src' => $thumburl ,
1783 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'DailyMotion thumbnail' );
1786 if ( endsWith ( $domain , '.imageshack.us' ))
1788 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1789 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1791 $thumburl = substr ( $url , 0 , strlen ( $url )- strlen ( $ext )). 'th.' . $ext ;
1792 return array ( 'src' => $thumburl ,
1793 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'imageshack.us thumbnail' );
1797 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1798 // So we deport the thumbnail generation in order not to slow down page generation
1799 // (and we also cache the thumbnail)
1801 if (! $conf- > get ( 'thumbnail.enable_localcache' )) return array (); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1803 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' )
1804 || $domain == 'vimeo.com'
1805 || $domain == 'ted.com' || endsWith ( $domain , '.ted.com' )
1806 || $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' )
1809 if ( $domain == 'vimeo.com' )
1810 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1811 $path = parse_url ( $url , PHP_URL_PATH
);
1812 if (! preg_match ( '!/\d+.+?!' , $path )) return array (); // This is not a single video URL.
1814 if ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
1815 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1816 $path = parse_url ( $url , PHP_URL_PATH
);
1817 if (! preg_match ( '!/\d+.+?!' , $path )) return array ();
1819 if ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
1820 { // Make sure this TED URL points to a video (/talks/...)
1821 $path = parse_url ( $url , PHP_URL_PATH
);
1822 if ( "/talks/" !== substr ( $path , 0 , 7 )) return array (); // This is not a single video URL.
1824 $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)
1825 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1826 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1829 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1830 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1831 // But using the extension will do.
1832 $ext = strtolower ( pathinfo ( $url , PATHINFO_EXTENSION
));
1833 if ( $ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif' )
1835 $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)
1836 return array ( 'src' => index_url ( $_SERVER ). '?do=genthumbnail&hmac=' . $sign . '&url=' . urlencode ( $url ),
1837 'href' => $href , 'width' => '120' , 'style' => 'height:auto;' , 'alt' => 'thumbnail' );
1839 return array (); // No thumbnail.
1844 // Returns the HTML code to display a thumbnail for a link
1845 // with a link to the original URL.
1846 // Understands various services (youtube.com...)
1847 // Input: $url = URL for which the thumbnail must be found.
1848 // $href = if provided, this URL will be followed instead of $url
1849 // Returns '' if no thumbnail available.
1850 function thumbnail ( $url , $href = false )
1854 $t = computeThumbnail ( $conf , $url , $href );
1855 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1857 $html = '<a href="' . escape ( $t [ 'href' ]). '"><img src="' . escape ( $t [ 'src' ]). '"' ;
1858 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1859 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1860 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1861 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1866 // Returns the HTML code to display a thumbnail for a link
1867 // for the picture wall (using lazy image loading)
1868 // Understands various services (youtube.com...)
1869 // Input: $url = URL for which the thumbnail must be found.
1870 // $href = if provided, this URL will be followed instead of $url
1871 // Returns '' if no thumbnail available.
1872 function lazyThumbnail ( $conf , $url , $href = false )
1876 $t = computeThumbnail ( $conf , $url , $href );
1877 if ( count ( $t )== 0 ) return '' ; // Empty array = no thumbnail for this URL.
1879 $html = '<a href="' . escape ( $t [ 'href' ]). '">' ;
1882 $html .= '<img class="b-lazy" src="#" data-src="' . escape ( $t [ 'src' ]). '"' ;
1884 if (! empty ( $t [ 'width' ])) $html .= ' width="' . escape ( $t [ 'width' ]). '"' ;
1885 if (! empty ( $t [ 'height' ])) $html .= ' height="' . escape ( $t [ 'height' ]). '"' ;
1886 if (! empty ( $t [ 'style' ])) $html .= ' style="' . escape ( $t [ 'style' ]). '"' ;
1887 if (! empty ( $t [ 'alt' ])) $html .= ' alt="' . escape ( $t [ 'alt' ]). '"' ;
1890 // No-JavaScript fallback.
1891 $html .= '<noscript><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' ]). '"' ;
1896 $html .= '></noscript></a>' ;
1904 * This function should NEVER be called if the file data/config.php exists.
1906 * @param ConfigManager $conf Configuration Manager instance.
1908 function install ( $conf )
1910 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1911 if ( endsWith ( $_SERVER [ 'HTTP_HOST' ], '.free.fr' ) && ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' )) mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ]. '/sessions' , 0705 );
1914 // This part makes sure sessions works correctly.
1915 // (Because on some hosts, session.save_path may not be set correctly,
1916 // or we may not have write access to it.)
1917 if ( isset ( $_GET [ 'test_session' ]) && ( ! isset ( $_SESSION ) || ! isset ( $_SESSION [ 'session_tested' ]) || $_SESSION [ 'session_tested' ]!= 'Working' ))
1918 { // Step 2: Check if data in session is correct.
1919 echo '<pre>Sessions do not seem to work correctly on your server.<br>' ;
1920 echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>' ;
1921 echo 'It currently points to ' . session_save_path (). '<br>' ;
1922 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>' ;
1923 echo '<br><a href="?">Click to try again.</a></pre>' ;
1926 if (! isset ( $_SESSION [ 'session_tested' ]))
1927 { // Step 1 : Try to store data in session and reload page.
1928 $_SESSION [ 'session_tested' ] = 'Working' ; // Try to set a variable in session.
1929 header ( 'Location: ' . index_url ( $_SERVER ). '?test_session' ); // Redirect to check stored data.
1931 if ( isset ( $_GET [ 'test_session' ]))
1932 { // Step 3: Sessions are OK. Remove test parameter from URL.
1933 header ( 'Location: ' . index_url ( $_SERVER ));
1937 if (! empty ( $_POST [ 'setlogin' ]) && ! empty ( $_POST [ 'setpassword' ]))
1940 if (! empty ( $_POST [ 'continent' ]) && ! empty ( $_POST [ 'city' ])
1941 && isTimeZoneValid ( $_POST [ 'continent' ], $_POST [ 'city' ])
1943 $tz = $_POST [ 'continent' ]. '/' . $_POST [ 'city' ];
1945 $conf- > set ( 'general.timezone' , $tz );
1946 $login = $_POST [ 'setlogin' ];
1947 $conf- > set ( 'credentials.login' , $login );
1948 $salt = sha1 ( uniqid ( '' , true ) . '_' . mt_rand ());
1949 $conf- > set ( 'credentials.salt' , $salt );
1950 $conf- > set ( 'credentials.hash' , sha1 ( $_POST [ 'setpassword' ] . $login . $salt ));
1951 if (! empty ( $_POST [ 'title' ])) {
1952 $conf- > set ( 'general.title' , escape ( $_POST [ 'title' ]));
1954 $conf- > set ( 'general.title' , 'Shared links on ' . escape ( index_url ( $_SERVER )));
1956 $conf- > set ( 'updates.check_updates' , ! empty ( $_POST [ 'updateCheck' ]));
1958 // Everything is ok, let's create config file.
1959 $conf- > write ( isLoggedIn ());
1961 catch ( Exception
$e ) {
1963 'ERROR while writing config file after installation.' . PHP_EOL
.
1967 // TODO: do not handle exceptions/errors in JS.
1968 echo '<script>alert("' . $e- > getMessage () . '");document.location= \' ? \' ;</script>' ;
1971 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location= \' ?do=login \' ;</script>' ;
1975 // Display config form:
1976 list ( $timezone_form , $timezone_js ) = generateTimeZoneForm ();
1977 $timezone_html = '' ;
1978 if ( $timezone_form != '' ) {
1979 $timezone_html = '<tr><td><b>Timezone:</b></td><td>' . $timezone_form . '</td></tr>' ;
1982 $PAGE = new PageBuilder ( $conf );
1983 $PAGE- > assign ( 'timezone_html' , $timezone_html );
1984 $PAGE- > assign ( 'timezone_js' , $timezone_js );
1985 $PAGE- > renderPage ( 'install' );
1990 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1991 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1992 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1993 * This function is called by passing the URL:
1994 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1995 * [URL] is the URL of the link (e.g. a flickr page)
1996 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1997 * The function below will fetch the image from the webservice and store it in the cache.
1999 * @param ConfigManager $conf Configuration Manager instance,
2001 function genThumbnail ( $conf )
2003 // Make sure the parameters in the URL were generated by us.
2004 $sign = hash_hmac ( 'sha256' , $_GET [ 'url' ], $conf- > get ( 'credentials.salt' ));
2005 if ( $sign != $_GET [ 'hmac' ]) die ( 'Naughty boy!' );
2007 $cacheDir = $conf- > get ( 'resource.thumbnails_cache' , 'cache' );
2008 // Let's see if we don't already have the image for this URL in the cache.
2009 $thumbname = hash ( 'sha1' , $_GET [ 'url' ]). '.jpg' ;
2010 if ( is_file ( $cacheDir . '/' . $thumbname ))
2011 { // We have the thumbnail, just serve it:
2012 header ( 'Content-Type: image/jpeg' );
2013 echo file_get_contents ( $cacheDir . '/' . $thumbname );
2016 // We may also serve a blank image (if service did not respond)
2017 $blankname = hash ( 'sha1' , $_GET [ 'url' ]). '.gif' ;
2018 if ( is_file ( $cacheDir . '/' . $blankname ))
2020 header ( 'Content-Type: image/gif' );
2021 echo file_get_contents ( $cacheDir . '/' . $blankname );
2025 // Otherwise, generate the thumbnail.
2026 $url = $_GET [ 'url' ];
2027 $domain = parse_url ( $url , PHP_URL_HOST
);
2029 if ( $domain == 'flickr.com' || endsWith ( $domain , '.flickr.com' ))
2031 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2032 $url = str_replace ( 'http://flickr.com/' , 'http://www.flickr.com/' , $url );
2034 // Is this a link to an image, or to a flickr page ?
2036 if ( endsWith ( parse_url ( $url , PHP_URL_PATH
), '.jpg' ))
2037 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2038 preg_match ( '!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!' , $url , $matches );
2039 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ]. 'm.jpg' ;
2041 else // This is a flickr page (html)
2043 // Get the flickr html page.
2044 list ( $headers , $content ) = get_http_response ( $url , 20 );
2045 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false )
2047 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2048 preg_match ( '!<link rel= \" image_src \" href= \" (.+?) \" !' , $content , $matches );
2049 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2051 // In albums (and some other pages), the link rel="image_src" is not provided,
2052 // but flickr provides:
2053 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2056 preg_match ( '!<meta property= \" og:image \" content= \" (.+?) \" !' , $content , $matches );
2057 if (! empty ( $matches [ 1 ])) $imageurl = $matches [ 1 ];
2063 { // Let's download the image.
2064 // Image is 240x120, so 10 seconds to download should be enough.
2065 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2066 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2067 // Save image to cache.
2068 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2069 header ( 'Content-Type: image/jpeg' );
2076 elseif ( $domain == 'vimeo.com' )
2078 // This is more complex: we have to perform a HTTP request, then parse the result.
2079 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2080 $vid = substr ( parse_url ( $url , PHP_URL_PATH
), 1 );
2081 list ( $headers , $content ) = get_http_response ( 'https://vimeo.com/api/v2/video/' . escape ( $vid ). '.php' , 5 );
2082 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2083 $t = unserialize ( $content );
2084 $imageurl = $t [ 0 ][ 'thumbnail_medium' ];
2085 // Then we download the image and serve it to our client.
2086 list ( $headers , $content ) = get_http_response ( $imageurl , 10 );
2087 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2088 // Save image to cache.
2089 file_put_contents ( $cacheDir . '/' . $thumbname , $content );
2090 header ( 'Content-Type: image/jpeg' );
2097 elseif ( $domain == 'ted.com' || endsWith ( $domain , '.ted.com' ))
2099 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2100 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2101 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2102 list ( $headers , $content ) = get_http_response ( $url , 5 );
2103 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2104 // Extract the link to the thumbnail
2105 preg_match ( '!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!' , $content , $matches );
2106 if (! empty ( $matches [ 1 ]))
2107 { // Let's download the image.
2108 $imageurl = $matches [ 1 ];
2109 // No control on image size, so wait long enough
2110 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2111 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2112 $filepath = $cacheDir . '/' . $thumbname ;
2113 file_put_contents ( $filepath , $content ); // Save image to cache.
2114 if ( resizeImage ( $filepath ))
2116 header ( 'Content-Type: image/jpeg' );
2117 echo file_get_contents ( $filepath );
2125 elseif ( $domain == 'xkcd.com' || endsWith ( $domain , '.xkcd.com' ))
2127 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2128 // http://xkcd.com/327/
2129 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2130 list ( $headers , $content ) = get_http_response ( $url , 5 );
2131 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2132 // Extract the link to the thumbnail
2133 preg_match ( '!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!' , $content , $matches );
2134 if (! empty ( $matches [ 1 ]))
2135 { // Let's download the image.
2136 $imageurl = $matches [ 1 ];
2137 // No control on image size, so wait long enough
2138 list ( $headers , $content ) = get_http_response ( $imageurl , 20 );
2139 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2140 $filepath = $cacheDir . '/' . $thumbname ;
2141 // Save image to cache.
2142 file_put_contents ( $filepath , $content );
2143 if ( resizeImage ( $filepath ))
2145 header ( 'Content-Type: image/jpeg' );
2146 echo file_get_contents ( $filepath );
2156 // For all other domains, we try to download the image and make a thumbnail.
2157 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2158 list ( $headers , $content ) = get_http_response ( $url , 30 );
2159 if ( strpos ( $headers [ 0 ], '200 OK' ) !== false ) {
2160 $filepath = $cacheDir . '/' . $thumbname ;
2161 // Save image to cache.
2162 file_put_contents ( $filepath , $content );
2163 if ( resizeImage ( $filepath ))
2165 header ( 'Content-Type: image/jpeg' );
2166 echo file_get_contents ( $filepath );
2173 // Otherwise, return an empty image (8x8 transparent gif)
2174 $blankgif = base64_decode ( 'R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7' );
2175 // Also put something in cache so that this URL is not requested twice.
2176 file_put_contents ( $cacheDir . '/' . $blankname , $blankgif );
2177 header ( 'Content-Type: image/gif' );
2181 // Make a thumbnail of the image (to width: 120 pixels)
2182 // Returns true if success, false otherwise.
2183 function resizeImage ( $filepath )
2185 if (! function_exists ( 'imagecreatefromjpeg' )) return false ; // GD not present: no thumbnail possible.
2187 // Trick: some stupid people rename GIF as JPEG... or else.
2188 // So we really try to open each image type whatever the extension is.
2189 $header = file_get_contents ( $filepath , false , NULL , 0 , 256 ); // Read first 256 bytes and try to sniff file type.
2191 $i = strpos ( $header , 'GIF8' ); if (( $i !== false ) && ( $i == 0 )) $im = imagecreatefromgif ( $filepath ); // Well this is crude, but it should be enough.
2192 $i = strpos ( $header , 'PNG' ); if (( $i !== false ) && ( $i == 1 )) $im = imagecreatefrompng ( $filepath );
2193 $i = strpos ( $header , 'JFIF' ); if ( $i !== false ) $im = imagecreatefromjpeg ( $filepath );
2194 if (! $im ) return false ; // Unable to open image (corrupted or not an image)
2197 $ystart = 0 ; $yheight = $h ;
2198 if ( $h > $w ) { $ystart
= ( $h
/ 2 )-( $w
/ 2 ); $yheight
= $w
/ 2 ; }
2199 $nw = 120 ; // Desired width
2200 $nh = min ( floor (( $h * $nw )/ $w ), 120 ); // Compute new width/height, but maximum 120 pixels height.
2202 $im2 = imagecreatetruecolor ( $nw , $nh );
2203 imagecopyresampled ( $im2 , $im , 0 , 0 , 0 , $ystart , $nw , $nh , $w , $yheight );
2204 imageinterlace ( $im2 , true ); // For progressive JPEG.
2205 $tempname = $filepath . '_TEMP.jpg' ;
2206 imagejpeg ( $im2 , $tempname , 90 );
2210 rename ( $tempname , $filepath ); // Overwrite original picture with thumbnail.
2214 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=genthumbnail' )) { genThumbnail ( $conf
); exit ; } // Thumbnail generation/cache does not need the link database.
2215 if ( isset ( $_SERVER [ 'QUERY_STRING' ]) && startsWith ( $_SERVER [ 'QUERY_STRING' ], 'do=dailyrss' )) { showDailyRSS ( $conf
); exit ; }
2216 if (! isset ( $_SESSION [ 'LINKS_PER_PAGE' ])) {
2217 $_SESSION [ 'LINKS_PER_PAGE' ] = $conf- > get ( 'general.links_per_page' , 20 );
2219 renderPage ( $conf , $pluginManager );