]>
Commit | Line | Data |
---|---|---|
45034273 | 1 | <?php |
49e2b35b | 2 | /** |
fdf88d19 | 3 | * Shaarli v0.8.0 - Shaare your links... |
49e2b35b | 4 | * |
2d97aa77 | 5 | * The personal, minimalist, super-fast, database free, bookmarking service. |
49e2b35b V |
6 | * |
7 | * Friendly fork by the Shaarli community: | |
8 | * - https://github.com/shaarli/Shaarli | |
9 | * | |
10 | * Original project by sebsauvage.net: | |
11 | * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli | |
12 | * - https://github.com/sebsauvage/Shaarli | |
13 | * | |
14 | * Licence: http://www.opensource.org/licenses/zlib-license.php | |
15 | * | |
16 | * Requires: PHP 5.3.x | |
17 | */ | |
afd7b77b V |
18 | |
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'); | |
23 | } | |
cb49ab94 | 24 | |
28bb2b74 V |
25 | /* |
26 | * PHP configuration | |
27 | */ | |
fdf88d19 | 28 | define('shaarli_version', '0.8.0'); |
28bb2b74 | 29 | |
ae00595b | 30 | // http://server.com/x/shaarli --> /shaarli/ |
684e662a | 31 | define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0))); |
45034273 | 32 | |
28bb2b74 V |
33 | // High execution time in case of problematic imports/exports. |
34 | ini_set('max_input_time','60'); | |
35 | ||
36 | // Try to set max upload file size and read | |
37 | ini_set('memory_limit', '128M'); | |
45034273 SS |
38 | ini_set('post_max_size', '16M'); |
39 | ini_set('upload_max_filesize', '16M'); | |
45034273 | 40 | |
28bb2b74 V |
41 | // See all error except warnings |
42 | error_reporting(E_ALL^E_WARNING); | |
43 | // See all errors (for debugging only) | |
44 | //error_reporting(-1); | |
45 | ||
50c9a12e | 46 | |
a973afea | 47 | // 3rd-party libraries |
52831753 V |
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"; | |
56 | exit; | |
57 | } | |
a973afea V |
58 | require_once 'inc/rain.tpl.class.php'; |
59 | require_once __DIR__ . '/vendor/autoload.php'; | |
60 | ||
ca74886f | 61 | // Shaarli library |
2e28269b | 62 | require_once 'application/ApplicationUtils.php'; |
01e48f26 V |
63 | require_once 'application/Cache.php'; |
64 | require_once 'application/CachedPage.php'; | |
278d9ee2 A |
65 | require_once 'application/config/ConfigManager.php'; |
66 | require_once 'application/config/ConfigPlugin.php'; | |
82e36802 | 67 | require_once 'application/FeedBuilder.php'; |
2e28269b | 68 | require_once 'application/FileUtils.php'; |
451314eb | 69 | require_once 'application/HttpUtils.php'; |
edf3ff5a | 70 | require_once 'application/Languages.php'; |
ca74886f | 71 | require_once 'application/LinkDB.php'; |
822bffce | 72 | require_once 'application/LinkFilter.php'; |
1557cefb | 73 | require_once 'application/LinkUtils.php'; |
cd5327be | 74 | require_once 'application/NetscapeBookmarkUtils.php'; |
03eb19ac | 75 | require_once 'application/PageBuilder.php'; |
d1e2f8e5 | 76 | require_once 'application/TimeZone.php'; |
d9d776af | 77 | require_once 'application/Url.php'; |
ca74886f | 78 | require_once 'application/Utils.php'; |
6fc14d53 A |
79 | require_once 'application/PluginManager.php'; |
80 | require_once 'application/Router.php'; | |
510377d2 | 81 | require_once 'application/Updater.php'; |
ca74886f | 82 | |
d1e2f8e5 V |
83 | // Ensure the PHP version is supported |
84 | try { | |
c9cf2715 | 85 | ApplicationUtils::checkPHPVersion('5.3', PHP_VERSION); |
2e28269b | 86 | } catch(Exception $exc) { |
d1e2f8e5 | 87 | header('Content-Type: text/plain; charset=utf-8'); |
2e28269b | 88 | echo $exc->getMessage(); |
d1e2f8e5 V |
89 | exit; |
90 | } | |
91 | ||
06b6660a A |
92 | // Force cookie path (but do not change lifetime) |
93 | $cookie = session_get_cookie_params(); | |
94 | $cookiedir = ''; | |
95 | if (dirname($_SERVER['SCRIPT_NAME']) != '/') { | |
96 | $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/'; | |
97 | } | |
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); | |
109 | ||
06b6660a A |
110 | session_name('shaarli'); |
111 | // Start session if needed (Some server auto-start sessions). | |
112 | if (session_id() == '') { | |
113 | session_start(); | |
114 | } | |
115 | ||
68bc2135 V |
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(); | |
120 | } | |
121 | ||
278d9ee2 | 122 | $conf = new ConfigManager(); |
7f179985 A |
123 | $conf->setEmpty('general.timezone', date_default_timezone_get()); |
124 | $conf->setEmpty('general.title', 'Shared links on '. escape(index_url($_SERVER))); | |
894a3c4b A |
125 | RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl'); // template directory |
126 | RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory | |
45034273 | 127 | |
278d9ee2 | 128 | $pluginManager = new PluginManager($conf); |
da10377b | 129 | $pluginManager->load($conf->get('general.enabled_plugins')); |
6fc14d53 | 130 | |
da10377b | 131 | date_default_timezone_set($conf->get('general.timezone', 'UTC')); |
d93d51b2 | 132 | |
45034273 SS |
133 | ob_start(); // Output buffering for the page cache. |
134 | ||
45034273 SS |
135 | // In case stupid admin has left magic_quotes enabled in php.ini: |
136 | if (get_magic_quotes_gpc()) | |
137 | { | |
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); | |
142 | } | |
143 | ||
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"); | |
149 | ||
278d9ee2 | 150 | if (! is_file($conf->getConfigFileExt())) { |
2e28269b | 151 | // Ensure Shaarli has proper access to its resources |
278d9ee2 | 152 | $errors = ApplicationUtils::checkResourcePermissions($conf); |
2e28269b V |
153 | |
154 | if ($errors != array()) { | |
155 | $message = '<p>Insufficient permissions:</p><ul>'; | |
156 | ||
157 | foreach ($errors as $error) { | |
158 | $message .= '<li>'.$error.'</li>'; | |
159 | } | |
160 | $message .= '</ul>'; | |
161 | ||
162 | header('Content-Type: text/html; charset=utf-8'); | |
163 | echo $message; | |
164 | exit; | |
165 | } | |
166 | ||
167 | // Display the installation form if no existing config is found | |
278d9ee2 | 168 | install($conf); |
50c9a12e | 169 | } |
8a80e4fe | 170 | |
ae00595b | 171 | // a token depending of deployment salt, user password, and the current ip |
da10377b | 172 | define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('credentials.hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('credentials.salt'))); |
8a80e4fe | 173 | |
408def1a A |
174 | // Sniff browser language and set date format accordingly. |
175 | if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { | |
176 | autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']); | |
177 | } | |
45034273 SS |
178 | header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling. |
179 | ||
278d9ee2 A |
180 | /** |
181 | * Checking session state (i.e. is the user still logged in) | |
182 | * | |
183 | * @param ConfigManager $conf The configuration manager. | |
184 | * | |
185 | * @return bool: true if the user is logged in, false otherwise. | |
186 | */ | |
187 | function setup_login_state($conf) | |
188 | { | |
894a3c4b | 189 | if ($conf->get('security.open_shaarli')) { |
02ad8fb6 | 190 | return true; |
ff69d87e | 191 | } |
02ad8fb6 JP |
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. | |
da10377b | 194 | if (! $conf->exists('credentials.login')) { |
ff69d87e FE |
195 | $userIsLoggedIn = false; // Shaarli is not configured yet. |
196 | $loginFailure = true; | |
197 | } | |
198 | if (isset($_COOKIE['shaarli_staySignedIn']) && | |
199 | $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN && | |
200 | !$loginFailure) | |
201 | { | |
278d9ee2 | 202 | fillSessionInfo($conf); |
ff69d87e FE |
203 | $userIsLoggedIn = true; |
204 | } | |
205 | // If session does not exist on server side, or IP address has changed, or session has expired, logout. | |
684e662a | 206 | if (empty($_SESSION['uid']) |
da10377b | 207 | || ($conf->get('security.session_protection_disabled') == false && $_SESSION['ip'] != allIPs()) |
684e662a | 208 | || time() >= $_SESSION['expires_on']) |
ff69d87e FE |
209 | { |
210 | logout(); | |
211 | $userIsLoggedIn = false; | |
212 | $loginFailure = true; | |
213 | } | |
214 | if (!empty($_SESSION['longlastingsession'])) { | |
215 | $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked. | |
216 | } | |
217 | else { | |
218 | $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date. | |
219 | } | |
220 | if (!$loginFailure) { | |
221 | $userIsLoggedIn = true; | |
222 | } | |
223 | ||
224 | return $userIsLoggedIn; | |
225 | } | |
278d9ee2 | 226 | $userIsLoggedIn = setup_login_state($conf); |
45034273 | 227 | |
278d9ee2 A |
228 | /** |
229 | * PubSubHubbub protocol support (if enabled) [UNTESTED] | |
230 | * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ ) | |
231 | * | |
232 | * @param ConfigManager $conf Configuration Manager instance. | |
233 | */ | |
234 | function pubsubhub($conf) | |
45034273 | 235 | { |
684e662a A |
236 | $pshUrl = $conf->get('config.PUBSUBHUB_URL'); |
237 | if (!empty($pshUrl)) | |
45034273 | 238 | { |
684e662a A |
239 | include_once './publisher.php'; |
240 | $p = new Publisher($pshUrl); | |
241 | $topic_url = array ( | |
242 | index_url($_SERVER).'?do=atom', | |
243 | index_url($_SERVER).'?do=rss' | |
244 | ); | |
245 | $p->publish_update($topic_url); | |
45034273 SS |
246 | } |
247 | } | |
248 | ||
249 | // ------------------------------------------------------------------------------------------ | |
250 | // Session management | |
45034273 SS |
251 | |
252 | // Returns the IP address of the client (Used to prevent session cookie hijacking.) | |
253 | function allIPs() | |
254 | { | |
684e662a | 255 | $ip = $_SERVER['REMOTE_ADDR']; |
45034273 SS |
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']; } | |
259 | return $ip; | |
260 | } | |
261 | ||
278d9ee2 A |
262 | /** |
263 | * Load user session. | |
264 | * | |
265 | * @param ConfigManager $conf Configuration Manager instance. | |
266 | */ | |
267 | function fillSessionInfo($conf) | |
268 | { | |
ad6c27b7 | 269 | $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid) |
ae00595b | 270 | $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked. |
da10377b | 271 | $_SESSION['username']= $conf->get('credentials.login'); |
ae00595b CH |
272 | $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration. |
273 | } | |
274 | ||
278d9ee2 A |
275 | /** |
276 | * Check that user/password is correct. | |
277 | * | |
278 | * @param string $login Username | |
279 | * @param string $password User password | |
280 | * @param ConfigManager $conf Configuration Manager instance. | |
281 | * | |
282 | * @return bool: authentication successful or not. | |
283 | */ | |
284 | function check_auth($login, $password, $conf) | |
45034273 | 285 | { |
da10377b A |
286 | $hash = sha1($password . $login . $conf->get('credentials.salt')); |
287 | if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) | |
45034273 | 288 | { // Login/password is correct. |
278d9ee2 | 289 | fillSessionInfo($conf); |
894a3c4b | 290 | logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful'); |
278d9ee2 | 291 | return true; |
45034273 | 292 | } |
894a3c4b | 293 | logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login); |
278d9ee2 | 294 | return false; |
45034273 SS |
295 | } |
296 | ||
297 | // Returns true if the user is logged in. | |
298 | function isLoggedIn() | |
299 | { | |
ff69d87e FE |
300 | global $userIsLoggedIn; |
301 | return $userIsLoggedIn; | |
45034273 SS |
302 | } |
303 | ||
304 | // Force logout. | |
ff69d87e FE |
305 | function logout() { |
306 | if (isset($_SESSION)) { | |
307 | unset($_SESSION['uid']); | |
308 | unset($_SESSION['ip']); | |
309 | unset($_SESSION['username']); | |
310 | unset($_SESSION['privateonly']); | |
311 | } | |
312 | setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH); | |
ae00595b | 313 | } |
45034273 SS |
314 | |
315 | ||
316 | // ------------------------------------------------------------------------------------------ | |
317 | // Brute force protection system | |
318 | // Several consecutive failed logins will ban the IP address for 30 minutes. | |
894a3c4b | 319 | if (!is_file($conf->get('resource.ban_file', 'data/ipbans.php'))) { |
684e662a A |
320 | // FIXME! globals |
321 | file_put_contents( | |
894a3c4b | 322 | $conf->get('resource.ban_file', 'data/ipbans.php'), |
684e662a A |
323 | "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>" |
324 | ); | |
325 | } | |
894a3c4b | 326 | include $conf->get('resource.ban_file', 'data/ipbans.php'); |
278d9ee2 A |
327 | /** |
328 | * Signal a failed login. Will ban the IP if too many failures: | |
329 | * | |
330 | * @param ConfigManager $conf Configuration Manager instance. | |
331 | */ | |
332 | function ban_loginFailed($conf) | |
45034273 | 333 | { |
684e662a | 334 | $ip = $_SERVER['REMOTE_ADDR']; |
50d17918 A |
335 | $trusted = $conf->get('security.trusted_proxies', array()); |
336 | if (in_array($ip, $trusted)) { | |
337 | $ip = getIpAddressFromProxy($_SERVER, $trusted); | |
338 | if (!$ip) { | |
339 | return; | |
340 | } | |
341 | } | |
684e662a | 342 | $gb = $GLOBALS['IPBANS']; |
50d17918 A |
343 | if (! isset($gb['FAILURES'][$ip])) { |
344 | $gb['FAILURES'][$ip]=0; | |
345 | } | |
45034273 | 346 | $gb['FAILURES'][$ip]++; |
da10377b | 347 | if ($gb['FAILURES'][$ip] > ($conf->get('security.ban_after') - 1)) |
45034273 | 348 | { |
da10377b | 349 | $gb['BANS'][$ip] = time() + $conf->get('security.ban_after', 1800); |
894a3c4b | 350 | logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'IP address banned from login'); |
45034273 SS |
351 | } |
352 | $GLOBALS['IPBANS'] = $gb; | |
684e662a | 353 | file_put_contents( |
894a3c4b | 354 | $conf->get('resource.ban_file', 'data/ipbans.php'), |
684e662a A |
355 | "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>" |
356 | ); | |
45034273 SS |
357 | } |
358 | ||
278d9ee2 A |
359 | /** |
360 | * Signals a successful login. Resets failed login counter. | |
361 | * | |
362 | * @param ConfigManager $conf Configuration Manager instance. | |
363 | */ | |
364 | function ban_loginOk($conf) | |
45034273 | 365 | { |
684e662a A |
366 | $ip = $_SERVER['REMOTE_ADDR']; |
367 | $gb = $GLOBALS['IPBANS']; | |
45034273 SS |
368 | unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); |
369 | $GLOBALS['IPBANS'] = $gb; | |
684e662a | 370 | file_put_contents( |
894a3c4b | 371 | $conf->get('resource.ban_file', 'data/ipbans.php'), |
684e662a A |
372 | "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>" |
373 | ); | |
45034273 SS |
374 | } |
375 | ||
278d9ee2 A |
376 | /** |
377 | * Checks if the user CAN login. If 'true', the user can try to login. | |
378 | * | |
379 | * @param ConfigManager $conf Configuration Manager instance. | |
380 | * | |
381 | * @return bool: true if the user is allowed to login. | |
382 | */ | |
383 | function ban_canLogin($conf) | |
45034273 SS |
384 | { |
385 | $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS']; | |
386 | if (isset($gb['BANS'][$ip])) | |
387 | { | |
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. | |
894a3c4b | 391 | logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Ban lifted.'); |
45034273 | 392 | unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); |
684e662a | 393 | file_put_contents( |
894a3c4b | 394 | $conf->get('resource.ban_file', 'data/ipbans.php'), |
684e662a A |
395 | "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>" |
396 | ); | |
45034273 SS |
397 | return true; // Ban has expired, user can login. |
398 | } | |
399 | return false; // User is banned. | |
400 | } | |
401 | return true; // User is not banned. | |
402 | } | |
403 | ||
404 | // ------------------------------------------------------------------------------------------ | |
405 | // Process login form: Check if login/password is correct. | |
406 | if (isset($_POST['login'])) | |
407 | { | |
278d9ee2 A |
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. | |
413 | ban_loginOk($conf); | |
45034273 SS |
414 | // If user wants to keep the session cookie even after the browser closes: |
415 | if (!empty($_POST['longlastingsession'])) | |
416 | { | |
ae00595b | 417 | setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN, time()+31536000, WEB_PATH); |
45034273 SS |
418 | $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year) |
419 | $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side. | |
2d9fab88 SS |
420 | |
421 | $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/'; | |
2f32d074 | 422 | session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side |
ad6c27b7 | 423 | // Note: Never forget the trailing slash on the cookie path! |
45034273 SS |
424 | session_regenerate_id(true); // Send cookie with new expiration date to browser. |
425 | } | |
426 | else // Standard session expiration (=when browser closes) | |
427 | { | |
2d9fab88 | 428 | $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/'; |
2f32d074 | 429 | session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes" |
45034273 SS |
430 | session_regenerate_id(true); |
431 | } | |
f4c84ad7 | 432 | |
45034273 | 433 | // Optional redirect after login: |
5fbabbb9 A |
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]); | |
439 | } | |
440 | } | |
441 | header('Location: '. $uri); | |
442 | exit; | |
443 | } | |
444 | ||
445 | if (isset($_GET['edit_link'])) { | |
446 | header('Location: ?edit_link='. escape($_GET['edit_link'])); | |
447 | exit; | |
448 | } | |
449 | ||
450 | if (isset($_POST['returnurl'])) { | |
451 | // Prevent loops over login screen. | |
452 | if (strpos($_POST['returnurl'], 'do=login') === false) { | |
e15f08d7 | 453 | header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST'])); |
5fbabbb9 A |
454 | exit; |
455 | } | |
45034273 SS |
456 | } |
457 | header('Location: ?'); exit; | |
458 | } | |
459 | else | |
460 | { | |
278d9ee2 | 461 | ban_loginFailed($conf); |
85c4bdc2 | 462 | $redir = '&username='. $_POST['login']; |
5fbabbb9 | 463 | if (isset($_GET['post'])) { |
85c4bdc2 | 464 | $redir .= '&post=' . urlencode($_GET['post']); |
5fbabbb9 A |
465 | foreach (array('description', 'source', 'title') as $param) { |
466 | if (!empty($_GET[$param])) { | |
467 | $redir .= '&' . $param . '=' . urlencode($_GET[$param]); | |
468 | } | |
469 | } | |
470 | } | |
fe16b01e | 471 | echo '<script>alert("Wrong login/password.");document.location=\'?do=login'.$redir.'\';</script>'; // Redirect to login screen. |
45034273 SS |
472 | exit; |
473 | } | |
474 | } | |
475 | ||
476 | // ------------------------------------------------------------------------------------------ | |
477 | // Misc utility functions: | |
478 | ||
ad6c27b7 | 479 | // Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes. |
45034273 SS |
480 | function return_bytes($val) |
481 | { | |
482 | $val = trim($val); $last=strtolower($val[strlen($val)-1]); | |
483 | switch($last) | |
484 | { | |
485 | case 'g': $val *= 1024; | |
486 | case 'm': $val *= 1024; | |
487 | case 'k': $val *= 1024; | |
488 | } | |
489 | return $val; | |
490 | } | |
491 | ||
492 | // Try to determine max file size for uploads (POST). | |
493 | // Returns an integer (in bytes) | |
494 | function getMaxFileSize() | |
495 | { | |
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); | |
ad6c27b7 | 500 | // FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000) |
45034273 SS |
501 | return $maxsize; |
502 | } | |
503 | ||
45034273 SS |
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. | |
508 | ||
278d9ee2 A |
509 | /** |
510 | * Returns a token. | |
511 | * | |
512 | * @param ConfigManager $conf Configuration Manager instance. | |
513 | * | |
514 | * @return string token. | |
515 | */ | |
516 | function getToken($conf) | |
45034273 | 517 | { |
da10377b | 518 | $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string. |
45034273 SS |
519 | $_SESSION['tokens'][$rnd]=1; // Store it on the server side. |
520 | return $rnd; | |
521 | } | |
522 | ||
ad6c27b7 | 523 | // Tells if a token is OK. Using this function will destroy the token. |
524 | // true=token is OK. | |
45034273 SS |
525 | function tokenOk($token) |
526 | { | |
527 | if (isset($_SESSION['tokens'][$token])) | |
528 | { | |
529 | unset($_SESSION['tokens'][$token]); // Token is used: destroy it. | |
ad6c27b7 | 530 | return true; // Token is OK. |
45034273 SS |
531 | } |
532 | return false; // Wrong token, or already used. | |
533 | } | |
534 | ||
278d9ee2 A |
535 | /** |
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. | |
539 | * | |
540 | * @param ConfigManager $conf Configuration Manager instance. | |
541 | */ | |
542 | function showDailyRSS($conf) { | |
45034273 | 543 | // Cache system |
5046bcb6 | 544 | $query = $_SERVER['QUERY_STRING']; |
01e48f26 | 545 | $cache = new CachedPage( |
684e662a | 546 | $conf->get('config.PAGE_CACHE'), |
482d67bd | 547 | page_url($_SERVER), |
01e48f26 V |
548 | startsWith($query,'do=dailyrss') && !isLoggedIn() |
549 | ); | |
f3b8f9f0 A |
550 | $cached = $cache->cachedVersion(); |
551 | if (!empty($cached)) { | |
552 | echo $cached; | |
553 | exit; | |
554 | } | |
9f15ca9e | 555 | |
f3b8f9f0 A |
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). | |
9f15ca9e | 558 | $LINKSDB = new LinkDB( |
894a3c4b | 559 | $conf->get('resource.datastore'), |
02ad8fb6 | 560 | isLoggedIn(), |
894a3c4b A |
561 | $conf->get('privacy.hide_public_links'), |
562 | $conf->get('redirector.url'), | |
563 | $conf->get('redirector.encode_url') | |
9f15ca9e | 564 | ); |
bb8f712d | 565 | |
45034273 SS |
566 | /* Some Shaarlies may have very few links, so we need to look |
567 | back in time (rsort()) until we have enough days ($nb_of_days). | |
568 | */ | |
f3b8f9f0 A |
569 | $linkdates = array(); |
570 | foreach ($LINKSDB as $linkdate => $value) { | |
571 | $linkdates[] = $linkdate; | |
572 | } | |
45034273 | 573 | rsort($linkdates); |
f3b8f9f0 | 574 | $nb_of_days = 7; // We take 7 days. |
684e662a | 575 | $today = date('Ymd'); |
f3b8f9f0 A |
576 | $days = array(); |
577 | ||
578 | foreach ($linkdates as $linkdate) { | |
579 | $day = substr($linkdate, 0, 8); // Extract day (without time) | |
580 | if (strcmp($day,$today) < 0) { | |
581 | if (empty($days[$day])) { | |
582 | $days[$day] = array(); | |
583 | } | |
584 | $days[$day][] = $linkdate; | |
585 | } | |
586 | ||
587 | if (count($days) > $nb_of_days) { | |
588 | break; // Have we collected enough days? | |
45034273 | 589 | } |
45034273 | 590 | } |
bb8f712d | 591 | |
45034273 SS |
592 | // Build the RSS feed. |
593 | header('Content-Type: application/rss+xml; charset=utf-8'); | |
482d67bd | 594 | $pageaddr = escape(index_url($_SERVER)); |
45034273 | 595 | echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">'; |
f3b8f9f0 | 596 | echo '<channel>'; |
da10377b | 597 | echo '<title>Daily - '. $conf->get('general.title') . '</title>'; |
f3b8f9f0 A |
598 | echo '<link>'. $pageaddr .'</link>'; |
599 | echo '<description>Daily shared links</description>'; | |
600 | echo '<language>en-en</language>'; | |
601 | echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL; | |
602 | ||
603 | // For each day. | |
604 | foreach ($days as $day => $linkdates) { | |
205a4277 | 605 | $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000'); |
482d67bd | 606 | $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page. |
bb8f712d | 607 | |
45034273 | 608 | // Build the HTML body of this RSS entry. |
f3b8f9f0 A |
609 | $html = ''; |
610 | $href = ''; | |
611 | $links = array(); | |
612 | ||
45034273 | 613 | // We pre-format some fields for proper output. |
f3b8f9f0 | 614 | foreach ($linkdates as $linkdate) { |
45034273 | 615 | $l = $LINKSDB[$linkdate]; |
894a3c4b | 616 | $l['formatedDescription'] = format_description($l['description'], $conf->get('redirector.url')); |
278d9ee2 | 617 | $l['thumbnail'] = thumbnail($conf, $l['url']); |
205a4277 V |
618 | $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']); |
619 | $l['timestamp'] = $l_date->getTimestamp(); | |
f3b8f9f0 | 620 | if (startsWith($l['url'], '?')) { |
482d67bd | 621 | $l['url'] = index_url($_SERVER) . $l['url']; // make permalink URL absolute |
f3b8f9f0 A |
622 | } |
623 | $links[$linkdate] = $l; | |
45034273 | 624 | } |
f3b8f9f0 | 625 | |
45034273 | 626 | // Then build the HTML for this day: |
bb8f712d | 627 | $tpl = new RainTPL; |
da10377b | 628 | $tpl->assign('title', $conf->get('general.title')); |
205a4277 | 629 | $tpl->assign('daydate', $dayDate->getTimestamp()); |
f3b8f9f0 A |
630 | $tpl->assign('absurl', $absurl); |
631 | $tpl->assign('links', $links); | |
205a4277 | 632 | $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS))); |
894a3c4b | 633 | $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false)); |
f3b8f9f0 | 634 | $html = $tpl->draw('dailyrss', $return_string=true); |
45034273 | 635 | |
f3b8f9f0 | 636 | echo $html . PHP_EOL; |
bb8f712d | 637 | } |
482d67bd | 638 | echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->'; |
bb8f712d | 639 | |
45034273 SS |
640 | $cache->cache(ob_get_contents()); |
641 | ob_end_flush(); | |
642 | exit; | |
643 | } | |
644 | ||
38603b24 A |
645 | /** |
646 | * Show the 'Daily' page. | |
647 | * | |
278d9ee2 A |
648 | * @param PageBuilder $pageBuilder Template engine wrapper. |
649 | * @param LinkDB $LINKSDB LinkDB instance. | |
650 | * @param ConfigManager $conf Configuration Manager instance. | |
651 | * @param PluginManager $pluginManager Plugin Manager instane. | |
38603b24 | 652 | */ |
278d9ee2 | 653 | function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager) |
45034273 | 654 | { |
684e662a | 655 | $day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD. |
45034273 | 656 | if (isset($_GET['day'])) $day=$_GET['day']; |
bb8f712d | 657 | |
45034273 SS |
658 | $days = $LINKSDB->days(); |
659 | $i = array_search($day,$days); | |
f3db3774 | 660 | if ($i===false) { $i=count($days)-1; $day=$days[$i]; } |
bb8f712d KT |
661 | $previousday=''; |
662 | $nextday=''; | |
45034273 SS |
663 | if ($i!==false) |
664 | { | |
f3db3774 | 665 | if ($i>=1) $previousday=$days[$i-1]; |
45034273 SS |
666 | if ($i<count($days)-1) $nextday=$days[$i+1]; |
667 | } | |
668 | ||
9186ab95 | 669 | try { |
528a6f8a | 670 | $linksToDisplay = $LINKSDB->filterDay($day); |
9186ab95 V |
671 | } catch (Exception $exc) { |
672 | error_log($exc); | |
d1e2f8e5 | 673 | $linksToDisplay = array(); |
9186ab95 V |
674 | } |
675 | ||
45034273 SS |
676 | // We pre-format some fields for proper output. |
677 | foreach($linksToDisplay as $key=>$link) | |
678 | { | |
5f85fcd8 | 679 | |
dd62b9ba SS |
680 | $taglist = explode(' ',$link['tags']); |
681 | uasort($taglist, 'strcasecmp'); | |
682 | $linksToDisplay[$key]['taglist']=$taglist; | |
894a3c4b | 683 | $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('redirector.url')); |
278d9ee2 | 684 | $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']); |
205a4277 V |
685 | $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']); |
686 | $linksToDisplay[$key]['timestamp'] = $date->getTimestamp(); | |
45034273 | 687 | } |
bb8f712d | 688 | |
45034273 | 689 | /* We need to spread the articles on 3 columns. |
ad6c27b7 | 690 | I did not want to use a JavaScript lib like http://masonry.desandro.com/ |
bb8f712d | 691 | so I manually spread entries with a simple method: I roughly evaluate the |
45034273 SS |
692 | height of a div according to title and description length. |
693 | */ | |
694 | $columns=array(array(),array(),array()); // Entries to display, for each column. | |
695 | $fill=array(0,0,0); // Rough estimate of columns fill. | |
696 | foreach($linksToDisplay as $key=>$link) | |
697 | { | |
698 | // Roughly estimate length of entry (by counting characters) | |
699 | // Title: 30 chars = 1 line. 1 line is 30 pixels height. | |
700 | // Description: 836 characters gives roughly 342 pixel height. | |
ad6c27b7 | 701 | // This is not perfect, but it's usually OK. |
45034273 SS |
702 | $length=strlen($link['title'])+(342*strlen($link['description']))/836; |
703 | if ($link['thumbnail']) $length +=100; // 1 thumbnails roughly takes 100 pixels height. | |
704 | // Then put in column which is the less filled: | |
705 | $smallest=min($fill); // find smallest value in array. | |
706 | $index=array_search($smallest,$fill); // find index of this smallest value. | |
707 | array_push($columns[$index],$link); // Put entry in this column. | |
708 | $fill[$index]+=$length; | |
709 | } | |
38603b24 | 710 | |
205a4277 | 711 | $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000'); |
6fc14d53 A |
712 | $data = array( |
713 | 'linksToDisplay' => $linksToDisplay, | |
6fc14d53 | 714 | 'cols' => $columns, |
205a4277 | 715 | 'day' => $dayDate->getTimestamp(), |
6fc14d53 A |
716 | 'previousday' => $previousday, |
717 | 'nextday' => $nextday, | |
718 | ); | |
278d9ee2 | 719 | |
6fc14d53 A |
720 | $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn())); |
721 | ||
722 | foreach ($data as $key => $value) { | |
38603b24 | 723 | $pageBuilder->assign($key, $value); |
6fc14d53 A |
724 | } |
725 | ||
38603b24 | 726 | $pageBuilder->renderPage('daily'); |
45034273 SS |
727 | exit; |
728 | } | |
729 | ||
278d9ee2 A |
730 | /** |
731 | * Renders the linklist | |
732 | * | |
733 | * @param pageBuilder $PAGE pageBuilder instance. | |
734 | * @param LinkDB $LINKSDB LinkDB instance. | |
735 | * @param ConfigManager $conf Configuration Manager instance. | |
736 | * @param PluginManager $pluginManager Plugin Manager instance. | |
737 | */ | |
738 | function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) { | |
739 | buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display | |
6fc14d53 A |
740 | $PAGE->renderPage('linklist'); |
741 | } | |
742 | ||
278d9ee2 A |
743 | /** |
744 | * Render HTML page (according to URL parameters and user rights) | |
745 | * | |
746 | * @param ConfigManager $conf Configuration Manager instance. | |
747 | * @param PluginManager $pluginManager Plugin Manager instance, | |
748 | */ | |
749 | function renderPage($conf, $pluginManager) | |
45034273 | 750 | { |
9f15ca9e | 751 | $LINKSDB = new LinkDB( |
894a3c4b | 752 | $conf->get('resource.datastore'), |
02ad8fb6 | 753 | isLoggedIn(), |
894a3c4b A |
754 | $conf->get('privacy.hide_public_links'), |
755 | $conf->get('redirector.url'), | |
756 | $conf->get('redirector.encode_url') | |
9f15ca9e | 757 | ); |
45034273 | 758 | |
510377d2 | 759 | $updater = new Updater( |
894a3c4b | 760 | read_updates_file($conf->get('resource.updates')), |
510377d2 | 761 | $LINKSDB, |
278d9ee2 | 762 | $conf, |
510377d2 A |
763 | isLoggedIn() |
764 | ); | |
765 | try { | |
766 | $newUpdates = $updater->update(); | |
767 | if (! empty($newUpdates)) { | |
768 | write_updates_file( | |
894a3c4b | 769 | $conf->get('resource.updates'), |
510377d2 A |
770 | $updater->getDoneUpdates() |
771 | ); | |
772 | } | |
773 | } | |
774 | catch(Exception $e) { | |
775 | die($e->getMessage()); | |
776 | } | |
777 | ||
278d9ee2 | 778 | $PAGE = new PageBuilder($conf); |
141a86c5 A |
779 | $PAGE->assign('linkcount', count($LINKSDB)); |
780 | $PAGE->assign('privateLinkcount', count_private($LINKSDB)); | |
7fde6de1 | 781 | $PAGE->assign('plugin_errors', $pluginManager->getErrors()); |
6fc14d53 A |
782 | |
783 | // Determine which page will be rendered. | |
784 | $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : ''; | |
785 | $targetPage = Router::findPage($query, $_GET, isLoggedIn()); | |
786 | ||
787 | // Call plugin hooks for header, footer and includes, specifying which page will be rendered. | |
788 | // Then assign generated data to RainTPL. | |
789 | $common_hooks = array( | |
fea5db7a | 790 | 'includes', |
6fc14d53 A |
791 | 'header', |
792 | 'footer', | |
6fc14d53 | 793 | ); |
278d9ee2 | 794 | |
6fc14d53 A |
795 | foreach($common_hooks as $name) { |
796 | $plugin_data = array(); | |
797 | $pluginManager->executeHooks('render_' . $name, $plugin_data, | |
798 | array( | |
799 | 'target' => $targetPage, | |
800 | 'loggedin' => isLoggedIn() | |
801 | ) | |
802 | ); | |
803 | $PAGE->assign('plugins_' . $name, $plugin_data); | |
804 | } | |
805 | ||
45034273 | 806 | // -------- Display login form. |
6fc14d53 | 807 | if ($targetPage == Router::$PAGE_LOGIN) |
45034273 | 808 | { |
894a3c4b | 809 | if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli |
85c4bdc2 A |
810 | if (isset($_GET['username'])) { |
811 | $PAGE->assign('username', escape($_GET['username'])); | |
812 | } | |
5f85fcd8 | 813 | $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):'')); |
45034273 SS |
814 | $PAGE->renderPage('loginform'); |
815 | exit; | |
816 | } | |
817 | // -------- User wants to logout. | |
5046bcb6 | 818 | if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) |
45034273 | 819 | { |
894a3c4b | 820 | invalidateCaches($conf->get('resource.page_cache')); |
45034273 SS |
821 | logout(); |
822 | header('Location: ?'); | |
823 | exit; | |
824 | } | |
825 | ||
826 | // -------- Picture wall | |
6fc14d53 | 827 | if ($targetPage == Router::$PAGE_PICWALL) |
45034273 | 828 | { |
ad6c27b7 | 829 | // Optionally filter the results: |
528a6f8a | 830 | $links = $LINKSDB->filterSearch($_GET); |
822bffce | 831 | $linksToDisplay = array(); |
45034273 SS |
832 | |
833 | // Get only links which have a thumbnail. | |
834 | foreach($links as $link) | |
835 | { | |
5f85fcd8 | 836 | $permalink='?'.escape(smallhash($link['linkdate'])); |
278d9ee2 | 837 | $thumb=lazyThumbnail($conf, $link['url'],$permalink); |
45034273 SS |
838 | if ($thumb!='') // Only output links which have a thumbnail. |
839 | { | |
840 | $link['thumbnail']=$thumb; // Thumbnail HTML code. | |
45034273 SS |
841 | $linksToDisplay[]=$link; // Add to array. |
842 | } | |
843 | } | |
f3db3774 | 844 | |
6fc14d53 | 845 | $data = array( |
6fc14d53 A |
846 | 'linksToDisplay' => $linksToDisplay, |
847 | ); | |
848 | $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn())); | |
849 | ||
850 | foreach ($data as $key => $value) { | |
851 | $PAGE->assign($key, $value); | |
852 | } | |
853 | ||
45034273 SS |
854 | $PAGE->renderPage('picwall'); |
855 | exit; | |
856 | } | |
857 | ||
858 | // -------- Tag cloud | |
6fc14d53 | 859 | if ($targetPage == Router::$PAGE_TAGCLOUD) |
45034273 SS |
860 | { |
861 | $tags= $LINKSDB->allTags(); | |
a037ac69 | 862 | |
45034273 SS |
863 | // We sort tags alphabetically, then choose a font size according to count. |
864 | // First, find max value. | |
f1e96a06 A |
865 | $maxcount = 0; |
866 | foreach ($tags as $value) { | |
867 | $maxcount = max($maxcount, $value); | |
868 | } | |
869 | ||
870 | // Sort tags alphabetically: case insensitive, support locale if avalaible. | |
871 | uksort($tags, function($a, $b) { | |
872 | // Collator is part of PHP intl. | |
873 | if (class_exists('Collator')) { | |
7eb0a832 A |
874 | $c = new Collator(setlocale(LC_COLLATE, 0)); |
875 | if (!intl_is_failure(intl_get_error_code())) { | |
876 | return $c->compare($a, $b); | |
877 | } | |
f1e96a06 | 878 | } |
7eb0a832 | 879 | return strcasecmp($a, $b); |
f1e96a06 A |
880 | }); |
881 | ||
b0128609 A |
882 | $tagList = array(); |
883 | foreach($tags as $key => $value) { | |
884 | // Tag font size scaling: | |
885 | // default 15 and 30 logarithm bases affect scaling, | |
886 | // 22 and 6 are arbitrary font sizes for max and min sizes. | |
887 | $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8; | |
888 | $tagList[$key] = array( | |
889 | 'count' => $value, | |
890 | 'size' => number_format($size, 2, '.', ''), | |
891 | ); | |
45034273 | 892 | } |
6fc14d53 A |
893 | |
894 | $data = array( | |
6fc14d53 A |
895 | 'tags' => $tagList, |
896 | ); | |
897 | $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn())); | |
898 | ||
899 | foreach ($data as $key => $value) { | |
900 | $PAGE->assign($key, $value); | |
901 | } | |
902 | ||
45034273 | 903 | $PAGE->renderPage('tagcloud'); |
bb8f712d | 904 | exit; |
45034273 SS |
905 | } |
906 | ||
38603b24 A |
907 | // Daily page. |
908 | if ($targetPage == Router::$PAGE_DAILY) { | |
278d9ee2 | 909 | showDaily($PAGE, $LINKSDB, $conf, $pluginManager); |
38603b24 A |
910 | } |
911 | ||
82e36802 A |
912 | // ATOM and RSS feed. |
913 | if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) { | |
914 | $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM; | |
915 | header('Content-Type: application/'. $feedType .'+xml; charset=utf-8'); | |
916 | ||
917 | // Cache system | |
918 | $query = $_SERVER['QUERY_STRING']; | |
919 | $cache = new CachedPage( | |
894a3c4b | 920 | $conf->get('resource.page_cache'), |
82e36802 A |
921 | page_url($_SERVER), |
922 | startsWith($query,'do='. $targetPage) && !isLoggedIn() | |
923 | ); | |
924 | $cached = $cache->cachedVersion(); | |
5f143b72 | 925 | if (!empty($cached)) { |
82e36802 A |
926 | echo $cached; |
927 | exit; | |
928 | } | |
69c474b9 | 929 | |
82e36802 A |
930 | // Generate data. |
931 | $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn()); | |
932 | $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0))); | |
894a3c4b A |
933 | $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !isLoggedIn()); |
934 | $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks')); | |
684e662a A |
935 | $pshUrl = $conf->get('config.PUBSUBHUB_URL'); |
936 | if (!empty($pshUrl)) { | |
937 | $feedGenerator->setPubsubhubUrl($pshUrl); | |
82e36802 A |
938 | } |
939 | $data = $feedGenerator->buildData(); | |
940 | ||
941 | // Process plugin hook. | |
82e36802 A |
942 | $pluginManager->executeHooks('render_feed', $data, array( |
943 | 'loggedin' => isLoggedIn(), | |
944 | 'target' => $targetPage, | |
945 | )); | |
946 | ||
947 | // Render the template. | |
948 | $PAGE->assignAll($data); | |
949 | $PAGE->renderPage('feed.'. $feedType); | |
950 | $cache->cache(ob_get_contents()); | |
951 | ob_end_flush(); | |
952 | exit; | |
e67712ba A |
953 | } |
954 | ||
8f8113b9 A |
955 | // Display openseach plugin (XML) |
956 | if ($targetPage == Router::$PAGE_OPENSEARCH) { | |
957 | header('Content-Type: application/xml; charset=utf-8'); | |
958 | $PAGE->assign('serverurl', index_url($_SERVER)); | |
959 | $PAGE->renderPage('opensearch'); | |
960 | exit; | |
961 | } | |
962 | ||
45034273 SS |
963 | // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...) |
964 | if (isset($_GET['addtag'])) | |
965 | { | |
966 | // Get previous URL (http_referer) and add the tag to the searchtags parameters in query. | |
967 | if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER | |
968 | parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params); | |
732e683b | 969 | |
775803a0 A |
970 | // Prevent redirection loop |
971 | if (isset($params['addtag'])) { | |
972 | unset($params['addtag']); | |
973 | } | |
974 | ||
732e683b FE |
975 | // Check if this tag is already in the search query and ignore it if it is. |
976 | // Each tag is always separated by a space | |
6ac95d9c A |
977 | if (isset($params['searchtags'])) { |
978 | $current_tags = explode(' ', $params['searchtags']); | |
979 | } else { | |
980 | $current_tags = array(); | |
981 | } | |
732e683b FE |
982 | $addtag = true; |
983 | foreach ($current_tags as $value) { | |
984 | if ($value === $_GET['addtag']) { | |
985 | $addtag = false; | |
986 | break; | |
987 | } | |
988 | } | |
989 | // Append the tag if necessary | |
990 | if (empty($params['searchtags'])) { | |
991 | $params['searchtags'] = trim($_GET['addtag']); | |
992 | } | |
993 | else if ($addtag) { | |
994 | $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']); | |
995 | } | |
996 | ||
45034273 SS |
997 | unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different) |
998 | header('Location: ?'.http_build_query($params)); | |
999 | exit; | |
1000 | } | |
1001 | ||
1002 | // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...) | |
775803a0 | 1003 | if (isset($_GET['removetag'])) { |
45034273 | 1004 | // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query. |
775803a0 A |
1005 | if (empty($_SERVER['HTTP_REFERER'])) { |
1006 | header('Location: ?'); | |
1007 | exit; | |
1008 | } | |
1009 | ||
1010 | // In case browser does not send HTTP_REFERER | |
1011 | parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params); | |
1012 | ||
1013 | // Prevent redirection loop | |
1014 | if (isset($params['removetag'])) { | |
1015 | unset($params['removetag']); | |
1016 | } | |
1017 | ||
1018 | if (isset($params['searchtags'])) { | |
822bffce | 1019 | $tags = explode(' ', $params['searchtags']); |
2c75f8e7 A |
1020 | // Remove value from array $tags. |
1021 | $tags = array_diff($tags, array($_GET['removetag'])); | |
1022 | $params['searchtags'] = implode(' ',$tags); | |
1023 | ||
1024 | if (empty($params['searchtags'])) { | |
775803a0 | 1025 | unset($params['searchtags']); |
775803a0 | 1026 | } |
2c75f8e7 | 1027 | |
45034273 SS |
1028 | unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different) |
1029 | } | |
1030 | header('Location: ?'.http_build_query($params)); | |
1031 | exit; | |
1032 | } | |
1033 | ||
1034 | // -------- User wants to change the number of links per page (linksperpage=...) | |
775803a0 A |
1035 | if (isset($_GET['linksperpage'])) { |
1036 | if (is_numeric($_GET['linksperpage'])) { | |
1037 | $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); | |
1038 | } | |
1039 | ||
1040 | header('Location: '. generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'))); | |
45034273 SS |
1041 | exit; |
1042 | } | |
bb8f712d | 1043 | |
45034273 | 1044 | // -------- User wants to see only private links (toggle) |
775803a0 A |
1045 | if (isset($_GET['privateonly'])) { |
1046 | if (empty($_SESSION['privateonly'])) { | |
1047 | $_SESSION['privateonly'] = 1; // See only private links | |
1048 | } else { | |
45034273 SS |
1049 | unset($_SESSION['privateonly']); // See all links |
1050 | } | |
775803a0 A |
1051 | |
1052 | header('Location: '. generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('privateonly'))); | |
45034273 SS |
1053 | exit; |
1054 | } | |
1055 | ||
1056 | // -------- Handle other actions allowed for non-logged in users: | |
1057 | if (!isLoggedIn()) | |
1058 | { | |
ad6c27b7 | 1059 | // User tries to post new link but is not logged in: |
45034273 SS |
1060 | // Show login screen, then redirect to ?post=... |
1061 | if (isset($_GET['post'])) | |
1062 | { | |
a1795ddc | 1063 | 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. |
45034273 SS |
1064 | exit; |
1065 | } | |
aedc912d | 1066 | |
278d9ee2 | 1067 | showLinkList($PAGE, $LINKSDB, $conf, $pluginManager); |
5fbabbb9 A |
1068 | if (isset($_GET['edit_link'])) { |
1069 | header('Location: ?do=login&edit_link='. escape($_GET['edit_link'])); | |
1070 | exit; | |
1071 | } | |
1072 | ||
ad6c27b7 | 1073 | exit; // Never remove this one! All operations below are reserved for logged in user. |
45034273 SS |
1074 | } |
1075 | ||
1076 | // -------- All other functions are reserved for the registered user: | |
1077 | ||
1078 | // -------- Display the Tools menu if requested (import/export/bookmarklet...) | |
6fc14d53 | 1079 | if ($targetPage == Router::$PAGE_TOOLS) |
45034273 | 1080 | { |
6fc14d53 | 1081 | $data = array( |
6fc14d53 A |
1082 | 'pageabsaddr' => index_url($_SERVER), |
1083 | ); | |
1084 | $pluginManager->executeHooks('render_tools', $data); | |
1085 | ||
1086 | foreach ($data as $key => $value) { | |
1087 | $PAGE->assign($key, $value); | |
1088 | } | |
1089 | ||
45034273 SS |
1090 | $PAGE->renderPage('tools'); |
1091 | exit; | |
1092 | } | |
1093 | ||
1094 | // -------- User wants to change his/her password. | |
6fc14d53 | 1095 | if ($targetPage == Router::$PAGE_CHANGEPASSWORD) |
45034273 | 1096 | { |
894a3c4b | 1097 | if ($conf->get('security.open_shaarli')) { |
684e662a A |
1098 | die('You are not supposed to change a password on an Open Shaarli.'); |
1099 | } | |
1100 | ||
45034273 SS |
1101 | if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) |
1102 | { | |
ad6c27b7 | 1103 | if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away! |
45034273 SS |
1104 | |
1105 | // Make sure old password is correct. | |
da10377b A |
1106 | $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')); |
1107 | if ($oldhash!= $conf->get('credentials.hash')) { echo '<script>alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; } | |
45034273 | 1108 | // Save new password |
684e662a | 1109 | // Salt renders rainbow-tables attacks useless. |
da10377b A |
1110 | $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand())); |
1111 | $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt'))); | |
dd484b90 | 1112 | try { |
684e662a | 1113 | $conf->write(isLoggedIn()); |
dd484b90 A |
1114 | } |
1115 | catch(Exception $e) { | |
1116 | error_log( | |
1117 | 'ERROR while writing config file after changing password.' . PHP_EOL . | |
1118 | $e->getMessage() | |
1119 | ); | |
1120 | ||
1121 | // TODO: do not handle exceptions/errors in JS. | |
1122 | echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>'; | |
1123 | exit; | |
1124 | } | |
fe16b01e | 1125 | echo '<script>alert("Your password has been changed.");document.location=\'?do=tools\';</script>'; |
45034273 SS |
1126 | exit; |
1127 | } | |
1128 | else // show the change password form. | |
1129 | { | |
45034273 SS |
1130 | $PAGE->renderPage('changepassword'); |
1131 | exit; | |
1132 | } | |
1133 | } | |
1134 | ||
1135 | // -------- User wants to change configuration | |
6fc14d53 | 1136 | if ($targetPage == Router::$PAGE_CONFIGURE) |
45034273 SS |
1137 | { |
1138 | if (!empty($_POST['title']) ) | |
1139 | { | |
12ff86c9 A |
1140 | if (!tokenOk($_POST['token'])) { |
1141 | die('Wrong token.'); // Go away! | |
1142 | } | |
45034273 | 1143 | $tz = 'UTC'; |
12ff86c9 A |
1144 | if (!empty($_POST['continent']) && !empty($_POST['city']) |
1145 | && isTimeZoneValid($_POST['continent'], $_POST['city']) | |
1146 | ) { | |
1147 | $tz = $_POST['continent'] . '/' . $_POST['city']; | |
1148 | } | |
da10377b | 1149 | $conf->set('general.timezone', $tz); |
7f179985 A |
1150 | $conf->set('general.title', escape($_POST['title'])); |
1151 | $conf->set('general.header_link', escape($_POST['titleLink'])); | |
894a3c4b | 1152 | $conf->set('redirector.url', escape($_POST['redirector'])); |
da10377b | 1153 | $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection'])); |
894a3c4b A |
1154 | $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault'])); |
1155 | $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks'])); | |
1156 | $conf->set('updates.check_updates', !empty($_POST['updateCheck'])); | |
1157 | $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks'])); | |
dd484b90 | 1158 | try { |
684e662a | 1159 | $conf->write(isLoggedIn()); |
dd484b90 A |
1160 | } |
1161 | catch(Exception $e) { | |
1162 | error_log( | |
1163 | 'ERROR while writing config file after configuration update.' . PHP_EOL . | |
1164 | $e->getMessage() | |
1165 | ); | |
1166 | ||
1167 | // TODO: do not handle exceptions/errors in JS. | |
684e662a | 1168 | echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>'; |
dd484b90 A |
1169 | exit; |
1170 | } | |
684e662a | 1171 | echo '<script>alert("Configuration was saved.");document.location=\'?do=configure\';</script>'; |
45034273 SS |
1172 | exit; |
1173 | } | |
1174 | else // Show the configuration form. | |
1175 | { | |
da10377b | 1176 | $PAGE->assign('title', $conf->get('general.title')); |
894a3c4b | 1177 | $PAGE->assign('redirector', $conf->get('redirector.url')); |
da10377b | 1178 | list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone')); |
d1e2f8e5 | 1179 | $PAGE->assign('timezone_form', $timezone_form); |
45034273 | 1180 | $PAGE->assign('timezone_js',$timezone_js); |
894a3c4b | 1181 | $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false)); |
2e193ad3 | 1182 | $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false)); |
894a3c4b A |
1183 | $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false)); |
1184 | $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true)); | |
1185 | $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false)); | |
45034273 SS |
1186 | $PAGE->renderPage('configure'); |
1187 | exit; | |
1188 | } | |
1189 | } | |
1190 | ||
1191 | // -------- User wants to rename a tag or delete it | |
6fc14d53 | 1192 | if ($targetPage == Router::$PAGE_CHANGETAG) |
45034273 | 1193 | { |
6a6aa2b9 | 1194 | if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) { |
bdd1715b | 1195 | $PAGE->assign('tags', $LINKSDB->allTags()); |
45034273 SS |
1196 | $PAGE->renderPage('changetag'); |
1197 | exit; | |
1198 | } | |
6a6aa2b9 A |
1199 | |
1200 | if (!tokenOk($_POST['token'])) { | |
1201 | die('Wrong token.'); | |
1202 | } | |
45034273 SS |
1203 | |
1204 | // Delete a tag: | |
6a6aa2b9 | 1205 | if (isset($_POST['deletetag']) && !empty($_POST['fromtag'])) { |
528a6f8a | 1206 | $needle = trim($_POST['fromtag']); |
822bffce | 1207 | // True for case-sensitive tag search. |
528a6f8a | 1208 | $linksToAlter = $LINKSDB->filterSearch(array('searchtags' => $needle), true); |
45034273 SS |
1209 | foreach($linksToAlter as $key=>$value) |
1210 | { | |
1211 | $tags = explode(' ',trim($value['tags'])); | |
1212 | unset($tags[array_search($needle,$tags)]); // Remove tag. | |
1213 | $value['tags']=trim(implode(' ',$tags)); | |
1214 | $LINKSDB[$key]=$value; | |
1215 | } | |
894a3c4b | 1216 | $LINKSDB->savedb($conf->get('resource.page_cache')); |
fe16b01e | 1217 | echo '<script>alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>'; |
45034273 SS |
1218 | exit; |
1219 | } | |
1220 | ||
1221 | // Rename a tag: | |
6a6aa2b9 | 1222 | if (isset($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag'])) { |
528a6f8a | 1223 | $needle = trim($_POST['fromtag']); |
822bffce | 1224 | // True for case-sensitive tag search. |
528a6f8a | 1225 | $linksToAlter = $LINKSDB->filterSearch(array('searchtags' => $needle), true); |
45034273 SS |
1226 | foreach($linksToAlter as $key=>$value) |
1227 | { | |
1228 | $tags = explode(' ',trim($value['tags'])); | |
ad6c27b7 | 1229 | $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Replace tags value. |
45034273 SS |
1230 | $value['tags']=trim(implode(' ',$tags)); |
1231 | $LINKSDB[$key]=$value; | |
1232 | } | |
894a3c4b | 1233 | $LINKSDB->savedb($conf->get('resource.page_cache')); // Save to disk. |
fe16b01e | 1234 | echo '<script>alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>'; |
45034273 SS |
1235 | exit; |
1236 | } | |
1237 | } | |
1238 | ||
ad6c27b7 | 1239 | // -------- User wants to add a link without using the bookmarklet: Show form. |
6fc14d53 | 1240 | if ($targetPage == Router::$PAGE_ADDLINK) |
45034273 | 1241 | { |
45034273 SS |
1242 | $PAGE->renderPage('addlink'); |
1243 | exit; | |
1244 | } | |
1245 | ||
1246 | // -------- User clicked the "Save" button when editing a link: Save link to database. | |
1247 | if (isset($_POST['save_edit'])) | |
1248 | { | |
9646b7da A |
1249 | $linkdate = $_POST['lf_linkdate']; |
1250 | $updated = isset($LINKSDB[$linkdate]) ? strval(date('Ymd_His')) : false; | |
1251 | ||
5a23950c A |
1252 | // Go away! |
1253 | if (! tokenOk($_POST['token'])) { | |
1254 | die('Wrong token.'); | |
1255 | } | |
1256 | // Remove multiple spaces. | |
1257 | $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags'])); | |
ce354bf1 A |
1258 | // Remove first '-' char in tags. |
1259 | $tags = preg_replace('/(^| )\-/', '$1', $tags); | |
5a23950c A |
1260 | // Remove duplicates. |
1261 | $tags = implode(' ', array_unique(explode(' ', $tags))); | |
9646b7da | 1262 | |
feebc6d4 | 1263 | $url = trim($_POST['lf_url']); |
5a23950c A |
1264 | if (! startsWith($url, 'http:') && ! startsWith($url, 'https:') |
1265 | && ! startsWith($url, 'ftp:') && ! startsWith($url, 'magnet:') | |
1266 | && ! startsWith($url, '?') && ! startsWith($url, 'javascript:') | |
1267 | ) { | |
1268 | $url = 'http://' . $url; | |
1269 | } | |
1270 | ||
1271 | $link = array( | |
1272 | 'title' => trim($_POST['lf_title']), | |
1273 | 'url' => $url, | |
ed853da7 | 1274 | 'description' => $_POST['lf_description'], |
5a23950c A |
1275 | 'private' => (isset($_POST['lf_private']) ? 1 : 0), |
1276 | 'linkdate' => $linkdate, | |
9646b7da | 1277 | 'updated' => $updated, |
5a23950c A |
1278 | 'tags' => str_replace(',', ' ', $tags) |
1279 | ); | |
1280 | // If title is empty, use the URL as title. | |
1281 | if ($link['title'] == '') { | |
1282 | $link['title'] = $link['url']; | |
1283 | } | |
6fc14d53 A |
1284 | |
1285 | $pluginManager->executeHooks('save_link', $link); | |
1286 | ||
45034273 | 1287 | $LINKSDB[$linkdate] = $link; |
894a3c4b | 1288 | $LINKSDB->savedb($conf->get('resource.page_cache')); |
278d9ee2 | 1289 | pubsubhub($conf); |
45034273 SS |
1290 | |
1291 | // If we are called from the bookmarklet, we must close the popup: | |
d01c2342 A |
1292 | if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { |
1293 | echo '<script>self.close();</script>'; | |
1294 | exit; | |
1295 | } | |
1296 | ||
fd50e14c | 1297 | $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?'; |
775803a0 | 1298 | $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link')); |
5a23950c A |
1299 | // Scroll to the link which has been edited. |
1300 | $location .= '#' . smallHash($_POST['lf_linkdate']); | |
1301 | // After saving the link, redirect to the page the user was on. | |
1302 | header('Location: '. $location); | |
45034273 SS |
1303 | exit; |
1304 | } | |
1305 | ||
1306 | // -------- User clicked the "Cancel" button when editing a link. | |
1307 | if (isset($_POST['cancel_edit'])) | |
1308 | { | |
ad6c27b7 | 1309 | // If we are called from the bookmarklet, we must close the popup: |
d33c5d4c | 1310 | if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } |
45034273 | 1311 | $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); |
b342b2a4 | 1312 | $returnurl .= '#'.smallHash($_POST['lf_linkdate']); // Scroll to the link which has been edited. |
775803a0 | 1313 | $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link')); |
45034273 SS |
1314 | header('Location: '.$returnurl); // After canceling, redirect to the page the user was on. |
1315 | exit; | |
1316 | } | |
1317 | ||
ad6c27b7 | 1318 | // -------- User clicked the "Delete" button when editing a link: Delete link from database. |
45034273 SS |
1319 | if (isset($_POST['delete_link'])) |
1320 | { | |
1321 | if (!tokenOk($_POST['token'])) die('Wrong token.'); | |
1322 | // We do not need to ask for confirmation: | |
ad6c27b7 | 1323 | // - confirmation is handled by JavaScript |
45034273 SS |
1324 | // - we are protected from XSRF by the token. |
1325 | $linkdate=$_POST['lf_linkdate']; | |
6fc14d53 A |
1326 | |
1327 | $pluginManager->executeHooks('delete_link', $LINKSDB[$linkdate]); | |
1328 | ||
45034273 | 1329 | unset($LINKSDB[$linkdate]); |
894a3c4b | 1330 | $LINKSDB->savedb('resource.page_cache'); // save to disk |
45034273 SS |
1331 | |
1332 | // If we are called from the bookmarklet, we must close the popup: | |
d33c5d4c | 1333 | if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } |
d528433d | 1334 | // Pick where we're going to redirect |
1335 | // ============================================================= | |
1336 | // Basically, we can't redirect to where we were previously if it was a permalink | |
1337 | // or an edit_link, because it would 404. | |
1338 | // Cases: | |
1339 | // - / : nothing in $_GET, redirect to self | |
1340 | // - /?page : redirect to self | |
d33c5d4c | 1341 | // - /?searchterm : redirect to self (there might be other links) |
d528433d | 1342 | // - /?searchtags : redirect to self |
1343 | // - /permalink : redirect to / (the link does not exist anymore) | |
1344 | // - /?edit_link : redirect to / (the link does not exist anymore) | |
1345 | // PHP treats the permalink as a $_GET variable, so we need to check if every condition for self | |
1346 | // redirect is not satisfied, and only then redirect to / | |
1347 | $location = "?"; | |
1348 | // Self redirection | |
775803a0 A |
1349 | if (count($_GET) == 0 |
1350 | || isset($_GET['page']) | |
1351 | || isset($_GET['searchterm']) | |
1352 | || isset($_GET['searchtags']) | |
1353 | ) { | |
d528433d | 1354 | if (isset($_POST['returnurl'])) { |
1355 | $location = $_POST['returnurl']; // Handle redirects given by the form | |
775803a0 A |
1356 | } else { |
1357 | $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('delete_link')); | |
d528433d | 1358 | } |
1359 | } | |
1360 | ||
1361 | header('Location: ' . $location); // After deleting the link, redirect to appropriate location | |
45034273 SS |
1362 | exit; |
1363 | } | |
1364 | ||
1365 | // -------- User clicked the "EDIT" button on a link: Display link edit form. | |
1366 | if (isset($_GET['edit_link'])) | |
1367 | { | |
1368 | $link = $LINKSDB[$_GET['edit_link']]; // Read database | |
1369 | if (!$link) { header('Location: ?'); exit; } // Link not found in database. | |
6fc14d53 | 1370 | $data = array( |
6fc14d53 A |
1371 | 'link' => $link, |
1372 | 'link_is_new' => false, | |
6fc14d53 A |
1373 | 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), |
1374 | 'tags' => $LINKSDB->allTags(), | |
1375 | ); | |
1376 | $pluginManager->executeHooks('render_editlink', $data); | |
1377 | ||
1378 | foreach ($data as $key => $value) { | |
1379 | $PAGE->assign($key, $value); | |
1380 | } | |
1381 | ||
45034273 SS |
1382 | $PAGE->renderPage('editlink'); |
1383 | exit; | |
1384 | } | |
1385 | ||
1386 | // -------- User want to post a new link: Display link edit form. | |
d9d776af | 1387 | if (isset($_GET['post'])) { |
ce7b0b64 | 1388 | $url = cleanup_url($_GET['post']); |
45034273 SS |
1389 | |
1390 | $link_is_new = false; | |
9e1724f1 | 1391 | // Check if URL is not already in database (in this case, we will edit the existing link) |
ef591e7e | 1392 | $link = $LINKSDB->getLinkFromUrl($url); |
45034273 SS |
1393 | if (!$link) |
1394 | { | |
9e1724f1 | 1395 | $link_is_new = true; |
45034273 | 1396 | $linkdate = strval(date('Ymd_His')); |
9e1724f1 | 1397 | // Get title if it was provided in URL (by the bookmarklet). |
739dc243 | 1398 | $title = empty($_GET['title']) ? '' : escape($_GET['title']); |
9e1724f1 | 1399 | // Get description if it was provided in URL (by the bookmarklet). [Bronco added that] |
739dc243 A |
1400 | $description = empty($_GET['description']) ? '' : escape($_GET['description']); |
1401 | $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']); | |
1402 | $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0; | |
26c50346 | 1403 | // 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.) |
ef591e7e | 1404 | if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) { |
451314eb | 1405 | // Short timeout to keep the application responsive |
1557cefb | 1406 | list($headers, $content) = get_http_response($url, 4); |
451314eb | 1407 | if (strpos($headers[0], '200 OK') !== false) { |
1557cefb A |
1408 | // Retrieve charset. |
1409 | $charset = get_charset($headers, $content); | |
1410 | // Extract title. | |
1411 | $title = html_extract_title($content); | |
1412 | // Re-encode title in utf-8 if necessary. | |
ce7b0b64 A |
1413 | if (! empty($title) && strtolower($charset) != 'utf-8') { |
1414 | $title = mb_convert_encoding($title, 'utf-8', $charset); | |
9e1724f1 A |
1415 | } |
1416 | } | |
45034273 | 1417 | } |
1557cefb | 1418 | |
9e1724f1 A |
1419 | if ($url == '') { |
1420 | $url = '?' . smallHash($linkdate); | |
1421 | $title = 'Note: '; | |
27646ca5 | 1422 | } |
ce7b0b64 A |
1423 | $url = escape($url); |
1424 | $title = escape($title); | |
1557cefb | 1425 | |
9e1724f1 A |
1426 | $link = array( |
1427 | 'linkdate' => $linkdate, | |
1428 | 'title' => $title, | |
ef591e7e | 1429 | 'url' => $url, |
9e1724f1 A |
1430 | 'description' => $description, |
1431 | 'tags' => $tags, | |
1432 | 'private' => $private | |
1433 | ); | |
45034273 SS |
1434 | } |
1435 | ||
6fc14d53 | 1436 | $data = array( |
6fc14d53 A |
1437 | 'link' => $link, |
1438 | 'link_is_new' => $link_is_new, | |
6fc14d53 A |
1439 | 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), |
1440 | 'source' => (isset($_GET['source']) ? $_GET['source'] : ''), | |
1441 | 'tags' => $LINKSDB->allTags(), | |
cdbc8180 | 1442 | 'default_private_links' => $conf->get('privacy.default_private_links', false), |
6fc14d53 A |
1443 | ); |
1444 | $pluginManager->executeHooks('render_editlink', $data); | |
1445 | ||
1446 | foreach ($data as $key => $value) { | |
1447 | $PAGE->assign($key, $value); | |
1448 | } | |
1449 | ||
45034273 SS |
1450 | $PAGE->renderPage('editlink'); |
1451 | exit; | |
1452 | } | |
1453 | ||
cd5327be | 1454 | if ($targetPage == Router::$PAGE_EXPORT) { |
bb4a23aa V |
1455 | // Export links as a Netscape Bookmarks file |
1456 | ||
cd5327be | 1457 | if (empty($_GET['selection'])) { |
45034273 SS |
1458 | $PAGE->renderPage('export'); |
1459 | exit; | |
1460 | } | |
45034273 | 1461 | |
cd5327be V |
1462 | // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html |
1463 | $selection = $_GET['selection']; | |
bb4a23aa V |
1464 | if (isset($_GET['prepend_note_url'])) { |
1465 | $prependNoteUrl = $_GET['prepend_note_url']; | |
1466 | } else { | |
1467 | $prependNoteUrl = false; | |
1468 | } | |
1469 | ||
cd5327be V |
1470 | try { |
1471 | $PAGE->assign( | |
1472 | 'links', | |
bb4a23aa V |
1473 | NetscapeBookmarkUtils::filterAndFormat( |
1474 | $LINKSDB, | |
1475 | $selection, | |
1476 | $prependNoteUrl, | |
1477 | index_url($_SERVER) | |
1478 | ) | |
cd5327be V |
1479 | ); |
1480 | } catch (Exception $exc) { | |
1481 | header('Content-Type: text/plain; charset=utf-8'); | |
1482 | echo $exc->getMessage(); | |
1483 | exit; | |
45034273 | 1484 | } |
cd5327be V |
1485 | $now = new DateTime(); |
1486 | header('Content-Type: text/html; charset=utf-8'); | |
1487 | header( | |
1488 | 'Content-disposition: attachment; filename=bookmarks_' | |
1489 | .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html' | |
1490 | ); | |
1491 | $PAGE->assign('date', $now->format(DateTime::RFC822)); | |
1492 | $PAGE->assign('eol', PHP_EOL); | |
1493 | $PAGE->assign('selection', $selection); | |
1494 | $PAGE->renderPage('export.bookmarks'); | |
1495 | exit; | |
45034273 SS |
1496 | } |
1497 | ||
a973afea V |
1498 | if ($targetPage == Router::$PAGE_IMPORT) { |
1499 | // Upload a Netscape bookmark dump to import its contents | |
1500 | ||
1501 | if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) { | |
1502 | // Show import dialog | |
1503 | $PAGE->assign('maxfilesize', getMaxFileSize()); | |
1504 | $PAGE->renderPage('import'); | |
45034273 SS |
1505 | exit; |
1506 | } | |
45034273 | 1507 | |
a973afea V |
1508 | // Import bookmarks from an uploaded file |
1509 | if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) { | |
1510 | // The file is too big or some form field may be missing. | |
1511 | echo '<script>alert("The file you are trying to upload is probably' | |
1512 | .' bigger than what this webserver can accept (' | |
1513 | .getMaxFileSize().' bytes).' | |
1514 | .' Please upload in smaller chunks.");document.location=\'?do=' | |
1515 | .Router::$PAGE_IMPORT .'\';</script>'; | |
1516 | exit; | |
1517 | } | |
1518 | if (! tokenOk($_POST['token'])) { | |
1519 | die('Wrong token.'); | |
1520 | } | |
1521 | $status = NetscapeBookmarkUtils::import( | |
1522 | $_POST, | |
1523 | $_FILES, | |
1524 | $LINKSDB, | |
1525 | $conf->get('resource.page_cache') | |
1526 | ); | |
1527 | echo '<script>alert("'.$status.'");document.location=\'?do=' | |
1528 | .Router::$PAGE_IMPORT .'\';</script>'; | |
45034273 SS |
1529 | exit; |
1530 | } | |
1531 | ||
dea0ba28 A |
1532 | // Plugin administration page |
1533 | if ($targetPage == Router::$PAGE_PLUGINSADMIN) { | |
1534 | $pluginMeta = $pluginManager->getPluginsMeta(); | |
1535 | ||
1536 | // Split plugins into 2 arrays: ordered enabled plugins and disabled. | |
1537 | $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; }); | |
1538 | // Load parameters. | |
684e662a | 1539 | $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array())); |
dea0ba28 A |
1540 | uasort( |
1541 | $enabledPlugins, | |
1542 | function($a, $b) { return $a['order'] - $b['order']; } | |
1543 | ); | |
1544 | $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; }); | |
1545 | ||
1546 | $PAGE->assign('enabledPlugins', $enabledPlugins); | |
1547 | $PAGE->assign('disabledPlugins', $disabledPlugins); | |
1548 | $PAGE->renderPage('pluginsadmin'); | |
1549 | exit; | |
1550 | } | |
1551 | ||
1552 | // Plugin administration form action | |
1553 | if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) { | |
1554 | try { | |
1555 | if (isset($_POST['parameters_form'])) { | |
1556 | unset($_POST['parameters_form']); | |
1557 | foreach ($_POST as $param => $value) { | |
684e662a | 1558 | $conf->set('plugins.'. $param, escape($value)); |
dea0ba28 A |
1559 | } |
1560 | } | |
1561 | else { | |
da10377b | 1562 | $conf->set('general.enabled_plugins', save_plugin_config($_POST)); |
dea0ba28 | 1563 | } |
684e662a | 1564 | $conf->write(isLoggedIn()); |
dea0ba28 A |
1565 | } |
1566 | catch (Exception $e) { | |
1567 | error_log( | |
1568 | 'ERROR while saving plugin configuration:.' . PHP_EOL . | |
1569 | $e->getMessage() | |
1570 | ); | |
1571 | ||
1572 | // TODO: do not handle exceptions/errors in JS. | |
59edea42 | 1573 | echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>'; |
dea0ba28 A |
1574 | exit; |
1575 | } | |
1576 | header('Location: ?do='. Router::$PAGE_PLUGINSADMIN); | |
1577 | exit; | |
1578 | } | |
1579 | ||
45034273 | 1580 | // -------- Otherwise, simply display search form and links: |
278d9ee2 | 1581 | showLinkList($PAGE, $LINKSDB, $conf, $pluginManager); |
45034273 SS |
1582 | exit; |
1583 | } | |
1584 | ||
528a6f8a A |
1585 | /** |
1586 | * Template for the list of links (<div id="linklist">) | |
1587 | * This function fills all the necessary fields in the $PAGE for the template 'linklist.html' | |
1588 | * | |
278d9ee2 A |
1589 | * @param pageBuilder $PAGE pageBuilder instance. |
1590 | * @param LinkDB $LINKSDB LinkDB instance. | |
1591 | * @param ConfigManager $conf Configuration Manager instance. | |
1592 | * @param PluginManager $pluginManager Plugin Manager instance. | |
528a6f8a | 1593 | */ |
278d9ee2 | 1594 | function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager) |
45034273 | 1595 | { |
528a6f8a | 1596 | // Used in templates |
c51fae92 | 1597 | $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : ''; |
528a6f8a | 1598 | $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : ''; |
822bffce | 1599 | |
528a6f8a A |
1600 | // Smallhash filter |
1601 | if (! empty($_SERVER['QUERY_STRING']) | |
1602 | && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) { | |
1603 | try { | |
1604 | $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']); | |
1605 | } catch (LinkNotFoundException $e) { | |
1606 | $PAGE->render404($e->getMessage()); | |
45034273 SS |
1607 | exit; |
1608 | } | |
528a6f8a A |
1609 | } else { |
1610 | // Filter links according search parameters. | |
1611 | $privateonly = !empty($_SESSION['privateonly']); | |
1612 | $linksToDisplay = $LINKSDB->filterSearch($_GET, false, $privateonly); | |
45034273 SS |
1613 | } |
1614 | ||
1615 | // ---- Handle paging. | |
822bffce A |
1616 | $keys = array(); |
1617 | foreach ($linksToDisplay as $key => $value) { | |
1618 | $keys[] = $key; | |
1619 | } | |
45034273 | 1620 | |
97ef33bb | 1621 | |
45034273 SS |
1622 | |
1623 | // Select articles according to paging. | |
822bffce A |
1624 | $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']); |
1625 | $pagecount = $pagecount == 0 ? 1 : $pagecount; | |
1626 | $page= empty($_GET['page']) ? 1 : intval($_GET['page']); | |
1627 | $page = $page < 1 ? 1 : $page; | |
1628 | $page = $page > $pagecount ? $pagecount : $page; | |
1629 | // Start index. | |
1630 | $i = ($page-1) * $_SESSION['LINKS_PER_PAGE']; | |
1631 | $end = $i + $_SESSION['LINKS_PER_PAGE']; | |
1632 | $linkDisp = array(); | |
45034273 SS |
1633 | while ($i<$end && $i<count($keys)) |
1634 | { | |
1635 | $link = $linksToDisplay[$keys[$i]]; | |
894a3c4b | 1636 | $link['description'] = format_description($link['description'], $conf->get('redirector.url')); |
822bffce A |
1637 | $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight'; |
1638 | $link['class'] = $link['private'] == 0 ? $classLi : 'private'; | |
205a4277 V |
1639 | $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']); |
1640 | $link['timestamp'] = $date->getTimestamp(); | |
9646b7da A |
1641 | if (! empty($link['updated'])) { |
1642 | $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['updated']); | |
1643 | $link['updated_timestamp'] = $date->getTimestamp(); | |
1644 | } else { | |
1645 | $link['updated_timestamp'] = ''; | |
1646 | } | |
822bffce | 1647 | $taglist = explode(' ', $link['tags']); |
a5752e77 | 1648 | uasort($taglist, 'strcasecmp'); |
822bffce | 1649 | $link['taglist'] = $taglist; |
6fc14d53 | 1650 | $link['shorturl'] = smallHash($link['linkdate']); |
822bffce A |
1651 | // Check for both signs of a note: starting with ? and 7 chars long. |
1652 | if ($link['url'][0] === '?' && | |
1653 | strlen($link['url']) === 7) { | |
1654 | $link['url'] = index_url($_SERVER) . $link['url']; | |
b47f515a | 1655 | } |
d33c5d4c | 1656 | |
45034273 SS |
1657 | $linkDisp[$keys[$i]] = $link; |
1658 | $i++; | |
1659 | } | |
bb8f712d | 1660 | |
45034273 | 1661 | // Compute paging navigation |
c51fae92 A |
1662 | $searchtagsUrl = empty($searchtags) ? '' : '&searchtags=' . urlencode($searchtags); |
1663 | $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm); | |
822bffce A |
1664 | $previous_page_url = ''; |
1665 | if ($i != count($keys)) { | |
c51fae92 | 1666 | $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl; |
822bffce A |
1667 | } |
1668 | $next_page_url=''; | |
1669 | if ($page>1) { | |
c51fae92 | 1670 | $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl; |
822bffce | 1671 | } |
45034273 | 1672 | |
278d9ee2 | 1673 | $token = isLoggedIn() ? getToken($conf) : ''; |
bb8f712d | 1674 | |
45034273 | 1675 | // Fill all template fields. |
6fc14d53 | 1676 | $data = array( |
6fc14d53 A |
1677 | 'previous_page_url' => $previous_page_url, |
1678 | 'next_page_url' => $next_page_url, | |
1679 | 'page_current' => $page, | |
1680 | 'page_max' => $pagecount, | |
1681 | 'result_count' => count($linksToDisplay), | |
c51fae92 A |
1682 | 'search_term' => $searchterm, |
1683 | 'search_tags' => $searchtags, | |
894a3c4b | 1684 | 'redirector' => $conf->get('redirector.url'), // Optional redirector URL. |
6fc14d53 A |
1685 | 'links' => $linkDisp, |
1686 | 'tags' => $LINKSDB->allTags(), | |
1687 | ); | |
97ef33bb A |
1688 | |
1689 | // If there is only a single link, we change on-the-fly the title of the page. | |
1690 | if (count($linksToDisplay) == 1) { | |
1691 | $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title'); | |
18cca483 | 1692 | } |
6fc14d53 | 1693 | |
6fc14d53 A |
1694 | $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn())); |
1695 | ||
1696 | foreach ($data as $key => $value) { | |
1697 | $PAGE->assign($key, $value); | |
1698 | } | |
1699 | ||
45034273 SS |
1700 | return; |
1701 | } | |
1702 | ||
278d9ee2 A |
1703 | /** |
1704 | * Compute the thumbnail for a link. | |
1705 | * | |
1706 | * With a link to the original URL. | |
1707 | * Understands various services (youtube.com...) | |
1708 | * Input: $url = URL for which the thumbnail must be found. | |
1709 | * $href = if provided, this URL will be followed instead of $url | |
1710 | * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt) | |
1711 | * Some of them may be missing. | |
1712 | * Return an empty array if no thumbnail available. | |
1713 | * | |
1714 | * @param ConfigManager $conf Configuration Manager instance. | |
1715 | * @param string $url | |
1716 | * @param string|bool $href | |
1717 | * | |
1718 | * @return array | |
1719 | */ | |
1720 | function computeThumbnail($conf, $url, $href = false) | |
45034273 | 1721 | { |
894a3c4b | 1722 | if (!$conf->get('thumbnail.enable_thumbnails')) return array(); |
45034273 SS |
1723 | if ($href==false) $href=$url; |
1724 | ||
1725 | // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link. | |
ad6c27b7 | 1726 | // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg ) |
45034273 SS |
1727 | // ^^^^^^^^^^^ ^^^^^^^^^^^ |
1728 | $domain = parse_url($url,PHP_URL_HOST); | |
1729 | if ($domain=='youtube.com' || $domain=='www.youtube.com') | |
1730 | { | |
1731 | parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail | |
1a663a0f | 1732 | if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg', |
45034273 SS |
1733 | 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail'); |
1734 | } | |
1735 | if ($domain=='youtu.be') // Youtube short links | |
1736 | { | |
1737 | $path = parse_url($url,PHP_URL_PATH); | |
1a663a0f | 1738 | return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg', |
bb8f712d | 1739 | 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail'); |
45034273 SS |
1740 | } |
1741 | if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting | |
1742 | { | |
1743 | parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract image filename. | |
1744 | if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']), | |
bb8f712d KT |
1745 | 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail'); |
1746 | } | |
1747 | ||
45034273 SS |
1748 | if ($domain=='imgur.com') |
1749 | { | |
1750 | $path = parse_url($url,PHP_URL_PATH); | |
1751 | if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available. | |
1a663a0f | 1752 | if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg', |
45034273 | 1753 | 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail'); |
1a663a0f | 1754 | if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg', |
45034273 SS |
1755 | 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail'); |
1756 | ||
1a663a0f | 1757 | if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg', |
45034273 SS |
1758 | 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail'); |
1759 | } | |
1760 | if ($domain=='i.imgur.com') | |
1761 | { | |
1762 | $pi = pathinfo(parse_url($url,PHP_URL_PATH)); | |
1a663a0f | 1763 | if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg', |
45034273 SS |
1764 | 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail'); |
1765 | } | |
1766 | if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com') | |
1767 | { | |
1768 | if (strpos($url,'dailymotion.com/video/')!==false) | |
1769 | { | |
1770 | $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url); | |
1771 | return array('src'=>$thumburl, | |
1772 | 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail'); | |
1773 | } | |
1774 | } | |
1775 | if (endsWith($domain,'.imageshack.us')) | |
1776 | { | |
1777 | $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION)); | |
1778 | if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif') | |
1779 | { | |
1780 | $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext; | |
1781 | return array('src'=>$thumburl, | |
1782 | 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail'); | |
1783 | } | |
1784 | } | |
1785 | ||
1786 | // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL. | |
1787 | // So we deport the thumbnail generation in order not to slow down page generation | |
1788 | // (and we also cache the thumbnail) | |
1789 | ||
894a3c4b | 1790 | if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache. |
45034273 SS |
1791 | |
1792 | if ($domain=='flickr.com' || endsWith($domain,'.flickr.com') | |
1793 | || $domain=='vimeo.com' | |
1794 | || $domain=='ted.com' || endsWith($domain,'.ted.com') | |
1795 | || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com') | |
1796 | ) | |
1797 | { | |
1798 | if ($domain=='vimeo.com') | |
ad6c27b7 | 1799 | { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric) |
45034273 SS |
1800 | $path = parse_url($url,PHP_URL_PATH); |
1801 | if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL. | |
1802 | } | |
1803 | if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com')) | |
ad6c27b7 | 1804 | { // Make sure this URL points to a single comic (/xxx... where xxx is numeric) |
45034273 SS |
1805 | $path = parse_url($url,PHP_URL_PATH); |
1806 | if (!preg_match('!/\d+.+?!',$path)) return array(); | |
1807 | } | |
1808 | if ($domain=='ted.com' || endsWith($domain,'.ted.com')) | |
ad6c27b7 | 1809 | { // Make sure this TED URL points to a video (/talks/...) |
45034273 SS |
1810 | $path = parse_url($url,PHP_URL_PATH); |
1811 | if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL. | |
1812 | } | |
da10377b | 1813 | $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) |
482d67bd | 1814 | return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url), |
45034273 SS |
1815 | 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail'); |
1816 | } | |
1817 | ||
1818 | // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif | |
1819 | // Technically speaking, we should download ALL links and check their Content-Type to see if they are images. | |
1820 | // But using the extension will do. | |
1821 | $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION)); | |
1822 | if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif') | |
1823 | { | |
da10377b | 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) |
482d67bd | 1825 | return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url), |
bb8f712d | 1826 | 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail'); |
45034273 SS |
1827 | } |
1828 | return array(); // No thumbnail. | |
1829 | ||
1830 | } | |
1831 | ||
1832 | ||
1833 | // Returns the HTML code to display a thumbnail for a link | |
1834 | // with a link to the original URL. | |
1835 | // Understands various services (youtube.com...) | |
ad6c27b7 | 1836 | // Input: $url = URL for which the thumbnail must be found. |
45034273 SS |
1837 | // $href = if provided, this URL will be followed instead of $url |
1838 | // Returns '' if no thumbnail available. | |
1839 | function thumbnail($url,$href=false) | |
1840 | { | |
278d9ee2 A |
1841 | // FIXME! |
1842 | global $conf; | |
1843 | $t = computeThumbnail($conf, $url,$href); | |
45034273 | 1844 | if (count($t)==0) return ''; // Empty array = no thumbnail for this URL. |
bb8f712d | 1845 | |
5f85fcd8 A |
1846 | $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"'; |
1847 | if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"'; | |
1848 | if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"'; | |
1849 | if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"'; | |
1850 | if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"'; | |
45034273 SS |
1851 | $html.='></a>'; |
1852 | return $html; | |
1853 | } | |
1854 | ||
45034273 SS |
1855 | // Returns the HTML code to display a thumbnail for a link |
1856 | // for the picture wall (using lazy image loading) | |
1857 | // Understands various services (youtube.com...) | |
ad6c27b7 | 1858 | // Input: $url = URL for which the thumbnail must be found. |
45034273 SS |
1859 | // $href = if provided, this URL will be followed instead of $url |
1860 | // Returns '' if no thumbnail available. | |
278d9ee2 | 1861 | function lazyThumbnail($conf, $url,$href=false) |
45034273 | 1862 | { |
278d9ee2 A |
1863 | // FIXME! |
1864 | global $conf; | |
1865 | $t = computeThumbnail($conf, $url,$href); | |
45034273 SS |
1866 | if (count($t)==0) return ''; // Empty array = no thumbnail for this URL. |
1867 | ||
5f85fcd8 | 1868 | $html='<a href="'.escape($t['href']).'">'; |
bb8f712d | 1869 | |
34047d23 | 1870 | // Lazy image |
5f85fcd8 | 1871 | $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"'; |
858c5c2b | 1872 | |
5f85fcd8 A |
1873 | if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"'; |
1874 | if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"'; | |
1875 | if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"'; | |
1876 | if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"'; | |
45034273 | 1877 | $html.='>'; |
bb8f712d | 1878 | |
ad6c27b7 | 1879 | // No-JavaScript fallback. |
5f85fcd8 A |
1880 | $html.='<noscript><img src="'.escape($t['src']).'"'; |
1881 | if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"'; | |
1882 | if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"'; | |
1883 | if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"'; | |
1884 | if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"'; | |
45034273 | 1885 | $html.='></noscript></a>'; |
bb8f712d | 1886 | |
45034273 SS |
1887 | return $html; |
1888 | } | |
1889 | ||
1890 | ||
278d9ee2 A |
1891 | /** |
1892 | * Installation | |
1893 | * This function should NEVER be called if the file data/config.php exists. | |
1894 | * | |
1895 | * @param ConfigManager $conf Configuration Manager instance. | |
1896 | */ | |
1897 | function install($conf) | |
45034273 SS |
1898 | { |
1899 | // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. | |
f6a6ca0a | 1900 | if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); |
45034273 | 1901 | |
f37664a2 SS |
1902 | |
1903 | // This part makes sure sessions works correctly. | |
1904 | // (Because on some hosts, session.save_path may not be set correctly, | |
1905 | // or we may not have write access to it.) | |
1906 | if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) | |
1907 | { // Step 2: Check if data in session is correct. | |
1908 | echo '<pre>Sessions do not seem to work correctly on your server.<br>'; | |
1909 | echo 'Make sure the variable session.save_path is set correctly in your php config, and that you have write access to it.<br>'; | |
01ec1791 | 1910 | echo 'It currently points to '.session_save_path().'<br>'; |
1911 | 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>'; | |
1912 | echo '<br><a href="?">Click to try again.</a></pre>'; | |
f37664a2 SS |
1913 | die; |
1914 | } | |
1915 | if (!isset($_SESSION['session_tested'])) | |
1916 | { // Step 1 : Try to store data in session and reload page. | |
1917 | $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session. | |
482d67bd | 1918 | header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data. |
f37664a2 SS |
1919 | } |
1920 | if (isset($_GET['test_session'])) | |
ad6c27b7 | 1921 | { // Step 3: Sessions are OK. Remove test parameter from URL. |
482d67bd | 1922 | header('Location: '.index_url($_SERVER)); |
f37664a2 SS |
1923 | } |
1924 | ||
1925 | ||
45034273 SS |
1926 | if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) |
1927 | { | |
1928 | $tz = 'UTC'; | |
12ff86c9 A |
1929 | if (!empty($_POST['continent']) && !empty($_POST['city']) |
1930 | && isTimeZoneValid($_POST['continent'], $_POST['city']) | |
1931 | ) { | |
1932 | $tz = $_POST['continent'].'/'.$_POST['city']; | |
d1e2f8e5 | 1933 | } |
da10377b | 1934 | $conf->set('general.timezone', $tz); |
684e662a | 1935 | $login = $_POST['setlogin']; |
da10377b | 1936 | $conf->set('credentials.login', $login); |
684e662a | 1937 | $salt = sha1(uniqid('', true) .'_'. mt_rand()); |
da10377b A |
1938 | $conf->set('credentials.salt', $salt); |
1939 | $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt)); | |
684e662a | 1940 | if (!empty($_POST['title'])) { |
7f179985 | 1941 | $conf->set('general.title', escape($_POST['title'])); |
684e662a | 1942 | } else { |
da10377b | 1943 | $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER))); |
684e662a | 1944 | } |
894a3c4b | 1945 | $conf->set('updates.check_updates', !empty($_POST['updateCheck'])); |
dd484b90 | 1946 | try { |
684e662a A |
1947 | // Everything is ok, let's create config file. |
1948 | $conf->write(isLoggedIn()); | |
dd484b90 A |
1949 | } |
1950 | catch(Exception $e) { | |
1951 | error_log( | |
1952 | 'ERROR while writing config file after installation.' . PHP_EOL . | |
1953 | $e->getMessage() | |
1954 | ); | |
1955 | ||
1956 | // TODO: do not handle exceptions/errors in JS. | |
1957 | echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>'; | |
1958 | exit; | |
1959 | } | |
fe16b01e | 1960 | echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>'; |
45034273 SS |
1961 | exit; |
1962 | } | |
1963 | ||
1964 | // Display config form: | |
d1e2f8e5 V |
1965 | list($timezone_form, $timezone_js) = generateTimeZoneForm(); |
1966 | $timezone_html = ''; | |
1967 | if ($timezone_form != '') { | |
1968 | $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>'; | |
1969 | } | |
bb8f712d | 1970 | |
278d9ee2 | 1971 | $PAGE = new PageBuilder($conf); |
45034273 SS |
1972 | $PAGE->assign('timezone_html',$timezone_html); |
1973 | $PAGE->assign('timezone_js',$timezone_js); | |
1974 | $PAGE->renderPage('install'); | |
1975 | exit; | |
1976 | } | |
1977 | ||
278d9ee2 A |
1978 | /** |
1979 | * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL, | |
1980 | * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation. | |
1981 | * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail. | |
1982 | * This function is called by passing the URL: | |
1983 | * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL] | |
1984 | * [URL] is the URL of the link (e.g. a flickr page) | |
1985 | * [HMAC] is the signature for the [URL] (so that these URL cannot be forged). | |
1986 | * The function below will fetch the image from the webservice and store it in the cache. | |
1987 | * | |
1988 | * @param ConfigManager $conf Configuration Manager instance, | |
1989 | */ | |
1990 | function genThumbnail($conf) | |
45034273 SS |
1991 | { |
1992 | // Make sure the parameters in the URL were generated by us. | |
da10377b | 1993 | $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt')); |
ad6c27b7 | 1994 | if ($sign!=$_GET['hmac']) die('Naughty boy!'); |
45034273 | 1995 | |
894a3c4b | 1996 | $cacheDir = $conf->get('resource.thumbnails_cache', 'cache'); |
45034273 SS |
1997 | // Let's see if we don't already have the image for this URL in the cache. |
1998 | $thumbname=hash('sha1',$_GET['url']).'.jpg'; | |
684e662a | 1999 | if (is_file($cacheDir .'/'. $thumbname)) |
45034273 SS |
2000 | { // We have the thumbnail, just serve it: |
2001 | header('Content-Type: image/jpeg'); | |
684e662a | 2002 | echo file_get_contents($cacheDir .'/'. $thumbname); |
45034273 SS |
2003 | return; |
2004 | } | |
2005 | // We may also serve a blank image (if service did not respond) | |
2006 | $blankname=hash('sha1',$_GET['url']).'.gif'; | |
684e662a | 2007 | if (is_file($cacheDir .'/'. $blankname)) |
45034273 SS |
2008 | { |
2009 | header('Content-Type: image/gif'); | |
684e662a | 2010 | echo file_get_contents($cacheDir .'/'. $blankname); |
45034273 SS |
2011 | return; |
2012 | } | |
2013 | ||
2014 | // Otherwise, generate the thumbnail. | |
2015 | $url = $_GET['url']; | |
2016 | $domain = parse_url($url,PHP_URL_HOST); | |
2017 | ||
2018 | if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')) | |
2019 | { | |
ad6c27b7 | 2020 | // Crude replacement to handle new flickr domain policy (They prefer www. now) |
45034273 SS |
2021 | $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url); |
2022 | ||
2023 | // Is this a link to an image, or to a flickr page ? | |
2024 | $imageurl=''; | |
5046bcb6 | 2025 | if (endsWith(parse_url($url, PHP_URL_PATH), '.jpg')) |
ad6c27b7 | 2026 | { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg |
45034273 SS |
2027 | preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches); |
2028 | if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg'; | |
2029 | } | |
ad6c27b7 | 2030 | else // This is a flickr page (html) |
45034273 | 2031 | { |
451314eb | 2032 | // Get the flickr html page. |
1557cefb | 2033 | list($headers, $content) = get_http_response($url, 20); |
451314eb | 2034 | if (strpos($headers[0], '200 OK') !== false) |
45034273 | 2035 | { |
ad6c27b7 | 2036 | // flickr now nicely provides the URL of the thumbnail in each flickr page. |
1557cefb | 2037 | preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches); |
45034273 SS |
2038 | if (!empty($matches[1])) $imageurl=$matches[1]; |
2039 | ||
2040 | // In albums (and some other pages), the link rel="image_src" is not provided, | |
2041 | // but flickr provides: | |
2042 | // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" /> | |
2043 | if ($imageurl=='') | |
2044 | { | |
1557cefb | 2045 | preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches); |
45034273 SS |
2046 | if (!empty($matches[1])) $imageurl=$matches[1]; |
2047 | } | |
2048 | } | |
2049 | } | |
2050 | ||
2051 | if ($imageurl!='') | |
2052 | { // Let's download the image. | |
451314eb | 2053 | // Image is 240x120, so 10 seconds to download should be enough. |
1557cefb | 2054 | list($headers, $content) = get_http_response($imageurl, 10); |
451314eb | 2055 | if (strpos($headers[0], '200 OK') !== false) { |
1557cefb | 2056 | // Save image to cache. |
684e662a | 2057 | file_put_contents($cacheDir .'/'. $thumbname, $content); |
45034273 | 2058 | header('Content-Type: image/jpeg'); |
1557cefb | 2059 | echo $content; |
45034273 SS |
2060 | return; |
2061 | } | |
2062 | } | |
2063 | } | |
2064 | ||
2065 | elseif ($domain=='vimeo.com' ) | |
2066 | { | |
2067 | // This is more complex: we have to perform a HTTP request, then parse the result. | |
ad6c27b7 | 2068 | // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098 |
45034273 | 2069 | $vid = substr(parse_url($url,PHP_URL_PATH),1); |
1557cefb | 2070 | list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5); |
451314eb | 2071 | if (strpos($headers[0], '200 OK') !== false) { |
1557cefb | 2072 | $t = unserialize($content); |
45034273 SS |
2073 | $imageurl = $t[0]['thumbnail_medium']; |
2074 | // Then we download the image and serve it to our client. | |
1557cefb | 2075 | list($headers, $content) = get_http_response($imageurl, 10); |
451314eb | 2076 | if (strpos($headers[0], '200 OK') !== false) { |
1557cefb | 2077 | // Save image to cache. |
684e662a | 2078 | file_put_contents($cacheDir .'/'. $thumbname, $content); |
45034273 | 2079 | header('Content-Type: image/jpeg'); |
1557cefb | 2080 | echo $content; |
45034273 SS |
2081 | return; |
2082 | } | |
2083 | } | |
2084 | } | |
2085 | ||
2086 | elseif ($domain=='ted.com' || endsWith($domain,'.ted.com')) | |
2087 | { | |
2088 | // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page | |
2089 | // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html | |
2090 | // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" /> | |
1557cefb | 2091 | list($headers, $content) = get_http_response($url, 5); |
451314eb | 2092 | if (strpos($headers[0], '200 OK') !== false) { |
45034273 | 2093 | // Extract the link to the thumbnail |
1557cefb | 2094 | preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches); |
45034273 SS |
2095 | if (!empty($matches[1])) |
2096 | { // Let's download the image. | |
2097 | $imageurl=$matches[1]; | |
451314eb | 2098 | // No control on image size, so wait long enough |
1557cefb | 2099 | list($headers, $content) = get_http_response($imageurl, 20); |
451314eb | 2100 | if (strpos($headers[0], '200 OK') !== false) { |
684e662a | 2101 | $filepath = $cacheDir .'/'. $thumbname; |
1557cefb | 2102 | file_put_contents($filepath, $content); // Save image to cache. |
45034273 SS |
2103 | if (resizeImage($filepath)) |
2104 | { | |
2105 | header('Content-Type: image/jpeg'); | |
2106 | echo file_get_contents($filepath); | |
2107 | return; | |
2108 | } | |
2109 | } | |
2110 | } | |
2111 | } | |
2112 | } | |
bb8f712d | 2113 | |
45034273 SS |
2114 | elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com')) |
2115 | { | |
2116 | // There is no thumbnail available for xkcd comics, so download the whole image and resize it. | |
2117 | // http://xkcd.com/327/ | |
2118 | // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" /> | |
1557cefb | 2119 | list($headers, $content) = get_http_response($url, 5); |
451314eb | 2120 | if (strpos($headers[0], '200 OK') !== false) { |
45034273 | 2121 | // Extract the link to the thumbnail |
1557cefb | 2122 | preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches); |
45034273 SS |
2123 | if (!empty($matches[1])) |
2124 | { // Let's download the image. | |
2125 | $imageurl=$matches[1]; | |
451314eb | 2126 | // No control on image size, so wait long enough |
1557cefb | 2127 | list($headers, $content) = get_http_response($imageurl, 20); |
451314eb | 2128 | if (strpos($headers[0], '200 OK') !== false) { |
684e662a | 2129 | $filepath = $cacheDir.'/'.$thumbname; |
1557cefb A |
2130 | // Save image to cache. |
2131 | file_put_contents($filepath, $content); | |
45034273 SS |
2132 | if (resizeImage($filepath)) |
2133 | { | |
2134 | header('Content-Type: image/jpeg'); | |
2135 | echo file_get_contents($filepath); | |
2136 | return; | |
2137 | } | |
2138 | } | |
2139 | } | |
2140 | } | |
bb8f712d | 2141 | } |
45034273 SS |
2142 | |
2143 | else | |
2144 | { | |
2145 | // For all other domains, we try to download the image and make a thumbnail. | |
451314eb | 2146 | // We allow 30 seconds max to download (and downloads are limited to 4 Mb) |
1557cefb | 2147 | list($headers, $content) = get_http_response($url, 30); |
451314eb | 2148 | if (strpos($headers[0], '200 OK') !== false) { |
684e662a | 2149 | $filepath = $cacheDir .'/'.$thumbname; |
1557cefb A |
2150 | // Save image to cache. |
2151 | file_put_contents($filepath, $content); | |
45034273 SS |
2152 | if (resizeImage($filepath)) |
2153 | { | |
2154 | header('Content-Type: image/jpeg'); | |
2155 | echo file_get_contents($filepath); | |
2156 | return; | |
2157 | } | |
2158 | } | |
2159 | } | |
2160 | ||
2161 | ||
2162 | // Otherwise, return an empty image (8x8 transparent gif) | |
2163 | $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7'); | |
684e662a A |
2164 | // Also put something in cache so that this URL is not requested twice. |
2165 | file_put_contents($cacheDir .'/'. $blankname, $blankgif); | |
45034273 SS |
2166 | header('Content-Type: image/gif'); |
2167 | echo $blankgif; | |
2168 | } | |
2169 | ||
2170 | // Make a thumbnail of the image (to width: 120 pixels) | |
2171 | // Returns true if success, false otherwise. | |
2172 | function resizeImage($filepath) | |
2173 | { | |
2174 | if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible. | |
2175 | ||
2176 | // Trick: some stupid people rename GIF as JPEG... or else. | |
2177 | // So we really try to open each image type whatever the extension is. | |
2178 | $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type. | |
2179 | $im=false; | |
2180 | $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough. | |
2181 | $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath); | |
2182 | $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath); | |
2183 | if (!$im) return false; // Unable to open image (corrupted or not an image) | |
2184 | $w = imagesx($im); | |
2185 | $h = imagesy($im); | |
2186 | $ystart = 0; $yheight=$h; | |
2187 | if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; } | |
2188 | $nw = 120; // Desired width | |
2189 | $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height. | |
2190 | // Resize image: | |
2191 | $im2 = imagecreatetruecolor($nw,$nh); | |
2192 | imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight); | |
2193 | imageinterlace($im2,true); // For progressive JPEG. | |
2194 | $tempname=$filepath.'_TEMP.jpg'; | |
2195 | imagejpeg($im2, $tempname, 90); | |
2196 | imagedestroy($im); | |
2197 | imagedestroy($im2); | |
9e820906 | 2198 | unlink($filepath); |
45034273 SS |
2199 | rename($tempname,$filepath); // Overwrite original picture with thumbnail. |
2200 | return true; | |
2201 | } | |
2202 | ||
278d9ee2 A |
2203 | if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database. |
2204 | if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; } | |
684e662a | 2205 | if (!isset($_SESSION['LINKS_PER_PAGE'])) { |
da10377b | 2206 | $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20); |
684e662a | 2207 | } |
278d9ee2 | 2208 | renderPage($conf, $pluginManager); |