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