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