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