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