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