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