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