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