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