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