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