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