]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
2737c22cdfea7a2f8a4bc802daae77c4a2e0f171
[github/shaarli/Shaarli.git] / index.php
1 <?php
2 /**
3 * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
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 */
14
15 // Set 'UTC' as the default timezone if it is not defined in php.ini
16 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
17 if (date_default_timezone_get() == '') {
18 date_default_timezone_set('UTC');
19 }
20
21 /*
22 * PHP configuration
23 */
24
25 // http://server.com/x/shaarli --> /shaarli/
26 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
27
28 // High execution time in case of problematic imports/exports.
29 ini_set('max_input_time', '60');
30
31 // Try to set max upload file size and read
32 ini_set('memory_limit', '128M');
33 ini_set('post_max_size', '16M');
34 ini_set('upload_max_filesize', '16M');
35
36 // See all error except warnings
37 error_reporting(E_ALL^E_WARNING);
38
39 // 3rd-party libraries
40 if (! file_exists(__DIR__ . '/vendor/autoload.php')) {
41 header('Content-Type: text/plain; charset=utf-8');
42 echo "Error: missing Composer configuration\n\n"
43 ."If you installed Shaarli through Git or using the development branch,\n"
44 ."please refer to the installation documentation to install PHP"
45 ." dependencies using Composer:\n"
46 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
47 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
48 exit;
49 }
50 require_once 'inc/rain.tpl.class.php';
51 require_once __DIR__ . '/vendor/autoload.php';
52
53 // Shaarli library
54 require_once 'application/bookmark/LinkUtils.php';
55 require_once 'application/config/ConfigPlugin.php';
56 require_once 'application/http/HttpUtils.php';
57 require_once 'application/http/UrlUtils.php';
58 require_once 'application/updater/UpdaterUtils.php';
59 require_once 'application/FileUtils.php';
60 require_once 'application/TimeZone.php';
61 require_once 'application/Utils.php';
62
63 use Shaarli\ApplicationUtils;
64 use Shaarli\Bookmark\BookmarkFileService;
65 use Shaarli\Config\ConfigManager;
66 use Shaarli\Container\ContainerBuilder;
67 use Shaarli\History;
68 use Shaarli\Languages;
69 use Shaarli\Plugin\PluginManager;
70 use Shaarli\Render\PageBuilder;
71 use Shaarli\Security\LoginManager;
72 use Shaarli\Security\SessionManager;
73 use Slim\App;
74
75 // Ensure the PHP version is supported
76 try {
77 ApplicationUtils::checkPHPVersion('7.1', PHP_VERSION);
78 } catch (Exception $exc) {
79 header('Content-Type: text/plain; charset=utf-8');
80 echo $exc->getMessage();
81 exit;
82 }
83
84 define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
85
86 // Force cookie path (but do not change lifetime)
87 $cookie = session_get_cookie_params();
88 $cookiedir = '';
89 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
90 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
91 }
92 // Set default cookie expiration and path.
93 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
94 // Set session parameters on server side.
95 // Use cookies to store session.
96 ini_set('session.use_cookies', 1);
97 // Force cookies for session (phpsessionID forbidden in URL).
98 ini_set('session.use_only_cookies', 1);
99 // Prevent PHP form using sessionID in URL if cookies are disabled.
100 ini_set('session.use_trans_sid', false);
101
102 session_name('shaarli');
103 // Start session if needed (Some server auto-start sessions).
104 if (session_status() == PHP_SESSION_NONE) {
105 session_start();
106 }
107
108 // Regenerate session ID if invalid or not defined in cookie.
109 if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
110 session_regenerate_id(true);
111 $_COOKIE['shaarli'] = session_id();
112 }
113
114 $conf = new ConfigManager();
115
116 // In dev mode, throw exception on any warning
117 if ($conf->get('dev.debug', false)) {
118 // See all errors (for debugging only)
119 error_reporting(-1);
120
121 set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
122 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
123 });
124 }
125
126 $sessionManager = new SessionManager($_SESSION, $conf);
127 $loginManager = new LoginManager($conf, $sessionManager);
128 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
129 $clientIpId = client_ip_id($_SERVER);
130
131 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
132 if (! defined('LC_MESSAGES')) {
133 define('LC_MESSAGES', LC_COLLATE);
134 }
135
136 // Sniff browser language and set date format accordingly.
137 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
138 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
139 }
140
141 new Languages(setlocale(LC_MESSAGES, 0), $conf);
142
143 $conf->setEmpty('general.timezone', date_default_timezone_get());
144 $conf->setEmpty('general.title', t('Shared bookmarks on '). escape(index_url($_SERVER)));
145 RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
146 RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
147
148 $pluginManager = new PluginManager($conf);
149 $pluginManager->load($conf->get('general.enabled_plugins'));
150
151 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
152
153 ob_start(); // Output buffering for the page cache.
154
155 // Prevent caching on client side or proxy: (yes, it's ugly)
156 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
157 header("Cache-Control: no-store, no-cache, must-revalidate");
158 header("Cache-Control: post-check=0, pre-check=0", false);
159 header("Pragma: no-cache");
160
161 if (! is_file($conf->getConfigFileExt())) {
162 // Ensure Shaarli has proper access to its resources
163 $errors = ApplicationUtils::checkResourcePermissions($conf);
164
165 if ($errors != array()) {
166 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
167
168 foreach ($errors as $error) {
169 $message .= '<li>'.$error.'</li>';
170 }
171 $message .= '</ul>';
172
173 header('Content-Type: text/html; charset=utf-8');
174 echo $message;
175 exit;
176 }
177
178 // Display the installation form if no existing config is found
179 install($conf, $sessionManager, $loginManager);
180 }
181
182 $loginManager->checkLoginState($_COOKIE, $clientIpId);
183
184 // ------------------------------------------------------------------------------------------
185 // Process login form: Check if login/password is correct.
186 if (isset($_POST['login'])) {
187 if (! $loginManager->canLogin($_SERVER)) {
188 die(t('I said: NO. You are banned for the moment. Go away.'));
189 }
190 if (isset($_POST['password'])
191 && $sessionManager->checkToken($_POST['token'])
192 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
193 ) {
194 $loginManager->handleSuccessfulLogin($_SERVER);
195
196 $cookiedir = '';
197 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
198 // Note: Never forget the trailing slash on the cookie path!
199 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
200 }
201
202 if (!empty($_POST['longlastingsession'])) {
203 // Keep the session cookie even after the browser closes
204 $sessionManager->setStaySignedIn(true);
205 $expirationTime = $sessionManager->extendSession();
206
207 setcookie(
208 $loginManager::$STAY_SIGNED_IN_COOKIE,
209 $loginManager->getStaySignedInToken(),
210 $expirationTime,
211 WEB_PATH
212 );
213 } else {
214 // Standard session expiration (=when browser closes)
215 $expirationTime = 0;
216 }
217
218 // Send cookie with the new expiration date to the browser
219 session_destroy();
220 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
221 session_start();
222 session_regenerate_id(true);
223
224 // Optional redirect after login:
225 if (isset($_GET['post'])) {
226 $uri = './?post='. urlencode($_GET['post']);
227 foreach (array('description', 'source', 'title', 'tags') as $param) {
228 if (!empty($_GET[$param])) {
229 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
230 }
231 }
232 header('Location: '. $uri);
233 exit;
234 }
235
236 if (isset($_GET['edit_link'])) {
237 header('Location: ./?edit_link='. escape($_GET['edit_link']));
238 exit;
239 }
240
241 if (isset($_POST['returnurl'])) {
242 // Prevent loops over login screen.
243 if (strpos($_POST['returnurl'], '/login') === false) {
244 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
245 exit;
246 }
247 }
248 header('Location: ./?');
249 exit;
250 } else {
251 $loginManager->handleFailedLogin($_SERVER);
252 $redir = '?username='. urlencode($_POST['login']);
253 if (isset($_GET['post'])) {
254 $redir .= '&post=' . urlencode($_GET['post']);
255 foreach (array('description', 'source', 'title', 'tags') as $param) {
256 if (!empty($_GET[$param])) {
257 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
258 }
259 }
260 }
261 // Redirect to login screen.
262 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'./login'.$redir.'\';</script>';
263 exit;
264 }
265 }
266
267 // ------------------------------------------------------------------------------------------
268 // Token management for XSRF protection
269 // Token should be used in any form which acts on data (create,update,delete,import...).
270 if (!isset($_SESSION['tokens'])) {
271 $_SESSION['tokens']=array(); // Token are attached to the session.
272 }
273
274 /**
275 * Installation
276 * This function should NEVER be called if the file data/config.php exists.
277 *
278 * @param ConfigManager $conf Configuration Manager instance.
279 * @param SessionManager $sessionManager SessionManager instance
280 * @param LoginManager $loginManager LoginManager instance
281 */
282 function install($conf, $sessionManager, $loginManager)
283 {
284 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
285 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
286 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
287 }
288
289
290 // This part makes sure sessions works correctly.
291 // (Because on some hosts, session.save_path may not be set correctly,
292 // or we may not have write access to it.)
293 if (isset($_GET['test_session'])
294 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
295 // Step 2: Check if data in session is correct.
296 $msg = t(
297 '<pre>Sessions do not seem to work correctly on your server.<br>'.
298 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
299 'and that you have write access to it.<br>'.
300 'It currently points to %s.<br>'.
301 'On some browsers, accessing your server via a hostname like \'localhost\' '.
302 'or any custom hostname without a dot causes cookie storage to fail. '.
303 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
304 );
305 $msg = sprintf($msg, session_save_path());
306 echo $msg;
307 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
308 die;
309 }
310 if (!isset($_SESSION['session_tested'])) {
311 // Step 1 : Try to store data in session and reload page.
312 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
313 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
314 }
315 if (isset($_GET['test_session'])) {
316 // Step 3: Sessions are OK. Remove test parameter from URL.
317 header('Location: '.index_url($_SERVER));
318 }
319
320
321 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
322 $tz = 'UTC';
323 if (!empty($_POST['continent']) && !empty($_POST['city'])
324 && isTimeZoneValid($_POST['continent'], $_POST['city'])
325 ) {
326 $tz = $_POST['continent'].'/'.$_POST['city'];
327 }
328 $conf->set('general.timezone', $tz);
329 $login = $_POST['setlogin'];
330 $conf->set('credentials.login', $login);
331 $salt = sha1(uniqid('', true) .'_'. mt_rand());
332 $conf->set('credentials.salt', $salt);
333 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
334 if (!empty($_POST['title'])) {
335 $conf->set('general.title', escape($_POST['title']));
336 } else {
337 $conf->set('general.title', 'Shared bookmarks on '.escape(index_url($_SERVER)));
338 }
339 $conf->set('translation.language', escape($_POST['language']));
340 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
341 $conf->set('api.enabled', !empty($_POST['enableApi']));
342 $conf->set(
343 'api.secret',
344 generate_api_secret(
345 $conf->get('credentials.login'),
346 $conf->get('credentials.salt')
347 )
348 );
349 try {
350 // Everything is ok, let's create config file.
351 $conf->write($loginManager->isLoggedIn());
352 } catch (Exception $e) {
353 error_log(
354 'ERROR while writing config file after installation.' . PHP_EOL .
355 $e->getMessage()
356 );
357
358 // TODO: do not handle exceptions/errors in JS.
359 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
360 exit;
361 }
362
363 $history = new History($conf->get('resource.history'));
364 $bookmarkService = new BookmarkFileService($conf, $history, true);
365 if ($bookmarkService->count() === 0) {
366 $bookmarkService->initialize();
367 }
368
369 echo '<script>alert('
370 .'"Shaarli is now configured. '
371 .'Please enter your login/password and start shaaring your bookmarks!"'
372 .');document.location=\'./login\';</script>';
373 exit;
374 }
375
376 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
377 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
378 $PAGE->assign('continents', $continents);
379 $PAGE->assign('cities', $cities);
380 $PAGE->assign('languages', Languages::getAvailableLanguages());
381 $PAGE->renderPage('install');
382 exit;
383 }
384
385 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
386 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
387 }
388
389 $containerBuilder = new ContainerBuilder($conf, $sessionManager, $loginManager);
390 $container = $containerBuilder->build();
391 $app = new App($container);
392
393 // REST API routes
394 $app->group('/api/v1', function () {
395 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
396 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
397 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
398 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
399 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
400 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
401
402 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
403 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
404 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
405 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
406
407 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
408 })->add('\Shaarli\Api\ApiMiddleware');
409
410 $app->group('', function () {
411 /* -- PUBLIC --*/
412 $this->get('/', '\Shaarli\Front\Controller\Visitor\BookmarkListController:index');
413 $this->get('/shaare/{hash}', '\Shaarli\Front\Controller\Visitor\BookmarkListController:permalink');
414 $this->get('/login', '\Shaarli\Front\Controller\Visitor\LoginController:index')->setName('login');
415 $this->get('/picture-wall', '\Shaarli\Front\Controller\Visitor\PictureWallController:index');
416 $this->get('/tags/cloud', '\Shaarli\Front\Controller\Visitor\TagCloudController:cloud');
417 $this->get('/tags/list', '\Shaarli\Front\Controller\Visitor\TagCloudController:list');
418 $this->get('/daily', '\Shaarli\Front\Controller\Visitor\DailyController:index');
419 $this->get('/daily-rss', '\Shaarli\Front\Controller\Visitor\DailyController:rss')->setName('rss');
420 $this->get('/feed/atom', '\Shaarli\Front\Controller\Visitor\FeedController:atom')->setName('atom');
421 $this->get('/feed/rss', '\Shaarli\Front\Controller\Visitor\FeedController:rss');
422 $this->get('/open-search', '\Shaarli\Front\Controller\Visitor\OpenSearchController:index');
423
424 $this->get('/add-tag/{newTag}', '\Shaarli\Front\Controller\Visitor\TagController:addTag');
425 $this->get('/remove-tag/{tag}', '\Shaarli\Front\Controller\Visitor\TagController:removeTag');
426
427 /* -- LOGGED IN -- */
428 $this->get('/logout', '\Shaarli\Front\Controller\Admin\LogoutController:index');
429 $this->get('/admin/tools', '\Shaarli\Front\Controller\Admin\ToolsController:index');
430 $this->get('/admin/password', '\Shaarli\Front\Controller\Admin\PasswordController:index');
431 $this->post('/admin/password', '\Shaarli\Front\Controller\Admin\PasswordController:change');
432 $this->get('/admin/configure', '\Shaarli\Front\Controller\Admin\ConfigureController:index');
433 $this->post('/admin/configure', '\Shaarli\Front\Controller\Admin\ConfigureController:save');
434 $this->get('/admin/tags', '\Shaarli\Front\Controller\Admin\ManageTagController:index');
435 $this->post('/admin/tags', '\Shaarli\Front\Controller\Admin\ManageTagController:save');
436 $this->get('/admin/add-shaare', '\Shaarli\Front\Controller\Admin\ManageShaareController:addShaare');
437 $this->get('/admin/shaare', '\Shaarli\Front\Controller\Admin\ManageShaareController:displayCreateForm');
438 $this->get('/admin/shaare/{id:[0-9]+}', '\Shaarli\Front\Controller\Admin\ManageShaareController:displayEditForm');
439 $this->post('/admin/shaare', '\Shaarli\Front\Controller\Admin\ManageShaareController:save');
440 $this->get('/admin/shaare/delete', '\Shaarli\Front\Controller\Admin\ManageShaareController:deleteBookmark');
441 $this->get('/admin/shaare/visibility', '\Shaarli\Front\Controller\Admin\ManageShaareController:changeVisibility');
442 $this->get('/admin/shaare/{id:[0-9]+}/pin', '\Shaarli\Front\Controller\Admin\ManageShaareController:pinBookmark');
443 $this->patch(
444 '/admin/shaare/{id:[0-9]+}/update-thumbnail',
445 '\Shaarli\Front\Controller\Admin\ThumbnailsController:ajaxUpdate'
446 );
447 $this->get('/admin/export', '\Shaarli\Front\Controller\Admin\ExportController:index');
448 $this->post('/admin/export', '\Shaarli\Front\Controller\Admin\ExportController:export');
449 $this->get('/admin/import', '\Shaarli\Front\Controller\Admin\ImportController:index');
450 $this->post('/admin/import', '\Shaarli\Front\Controller\Admin\ImportController:import');
451 $this->get('/admin/plugins', '\Shaarli\Front\Controller\Admin\PluginsController:index');
452 $this->post('/admin/plugins', '\Shaarli\Front\Controller\Admin\PluginsController:save');
453 $this->get('/admin/token', '\Shaarli\Front\Controller\Admin\TokenController:getToken');
454 $this->get('/admin/thumbnails', '\Shaarli\Front\Controller\Admin\ThumbnailsController:index');
455
456 $this->get('/links-per-page', '\Shaarli\Front\Controller\Admin\SessionFilterController:linksPerPage');
457 $this->get('/visibility/{visibility}', '\Shaarli\Front\Controller\Admin\SessionFilterController:visibility');
458 $this->get('/untagged-only', '\Shaarli\Front\Controller\Admin\SessionFilterController:untaggedOnly');
459 })->add('\Shaarli\Front\ShaarliMiddleware');
460
461 $response = $app->run(true);
462
463 $app->respond($response);