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