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