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