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