aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.net>2019-02-23 16:27:33 +0100
committerVirtualTam <virtualtam@flibidi.net>2019-02-23 16:27:33 +0100
commit43c77f658a905e2def6aeca4c092683977cd0c55 (patch)
treecb0dc273a315a777847d251f856625b2fc779c04 /index.php
parent630ebca2b6359e942e5b6c057cca2b6069c1093a (diff)
parent1826e383ecf501302974132fd443cf1ca06e10f6 (diff)
downloadShaarli-43c77f658a905e2def6aeca4c092683977cd0c55.tar.gz
Shaarli-43c77f658a905e2def6aeca4c092683977cd0c55.tar.zst
Shaarli-43c77f658a905e2def6aeca4c092683977cd0c55.zip
Merge commit '1826e383ecf501302974132fd443cf1ca06e10f6' into v0.10
Diffstat (limited to 'index.php')
-rw-r--r--index.php312
1 files changed, 183 insertions, 129 deletions
diff --git a/index.php b/index.php
index 4b86a3e2..acfcc660 100644
--- a/index.php
+++ b/index.php
@@ -28,7 +28,7 @@ if (date_default_timezone_get() == '') {
28define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0))); 28define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
29 29
30// High execution time in case of problematic imports/exports. 30// High execution time in case of problematic imports/exports.
31ini_set('max_input_time','60'); 31ini_set('max_input_time', '60');
32 32
33// Try to set max upload file size and read 33// Try to set max upload file size and read
34ini_set('memory_limit', '128M'); 34ini_set('memory_limit', '128M');
@@ -85,7 +85,7 @@ use \Shaarli\Thumbnailer;
85// Ensure the PHP version is supported 85// Ensure the PHP version is supported
86try { 86try {
87 ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION); 87 ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION);
88} catch(Exception $exc) { 88} catch (Exception $exc) {
89 header('Content-Type: text/plain; charset=utf-8'); 89 header('Content-Type: text/plain; charset=utf-8');
90 echo $exc->getMessage(); 90 echo $exc->getMessage();
91 exit; 91 exit;
@@ -111,7 +111,7 @@ ini_set('session.use_trans_sid', false);
111 111
112session_name('shaarli'); 112session_name('shaarli');
113// Start session if needed (Some server auto-start sessions). 113// Start session if needed (Some server auto-start sessions).
114if (session_id() == '') { 114if (session_status() == PHP_SESSION_NONE) {
115 session_start(); 115 session_start();
116} 116}
117 117
@@ -223,7 +223,6 @@ if (isset($_POST['login'])) {
223 $expirationTime, 223 $expirationTime,
224 WEB_PATH 224 WEB_PATH
225 ); 225 );
226
227 } else { 226 } else {
228 // Standard session expiration (=when browser closes) 227 // Standard session expiration (=when browser closes)
229 $expirationTime = 0; 228 $expirationTime = 0;
@@ -257,7 +256,8 @@ if (isset($_POST['login'])) {
257 exit; 256 exit;
258 } 257 }
259 } 258 }
260 header('Location: ?'); exit; 259 header('Location: ?');
260 exit;
261 } else { 261 } else {
262 $loginManager->handleFailedLogin($_SERVER); 262 $loginManager->handleFailedLogin($_SERVER);
263 $redir = '&username='. urlencode($_POST['login']); 263 $redir = '&username='. urlencode($_POST['login']);
@@ -278,7 +278,9 @@ if (isset($_POST['login'])) {
278// ------------------------------------------------------------------------------------------ 278// ------------------------------------------------------------------------------------------
279// Token management for XSRF protection 279// Token management for XSRF protection
280// Token should be used in any form which acts on data (create,update,delete,import...). 280// Token should be used in any form which acts on data (create,update,delete,import...).
281if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session. 281if (!isset($_SESSION['tokens'])) {
282 $_SESSION['tokens']=array(); // Token are attached to the session.
283}
282 284
283/** 285/**
284 * Daily RSS feed: 1 RSS entry per day giving all the links on that day. 286 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
@@ -288,13 +290,14 @@ if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are atta
288 * @param ConfigManager $conf Configuration Manager instance 290 * @param ConfigManager $conf Configuration Manager instance
289 * @param LoginManager $loginManager LoginManager instance 291 * @param LoginManager $loginManager LoginManager instance
290 */ 292 */
291function showDailyRSS($conf, $loginManager) { 293function showDailyRSS($conf, $loginManager)
294{
292 // Cache system 295 // Cache system
293 $query = $_SERVER['QUERY_STRING']; 296 $query = $_SERVER['QUERY_STRING'];
294 $cache = new CachedPage( 297 $cache = new CachedPage(
295 $conf->get('config.PAGE_CACHE'), 298 $conf->get('config.PAGE_CACHE'),
296 page_url($_SERVER), 299 page_url($_SERVER),
297 startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn() 300 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
298 ); 301 );
299 $cached = $cache->cachedVersion(); 302 $cached = $cache->cachedVersion();
300 if (!empty($cached)) { 303 if (!empty($cached)) {
@@ -395,7 +398,7 @@ function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
395{ 398{
396 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD. 399 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
397 if (isset($_GET['day'])) { 400 if (isset($_GET['day'])) {
398 $day = $_GET['day']; 401 $day = $_GET['day'];
399 } 402 }
400 403
401 $days = $LINKSDB->days(); 404 $days = $LINKSDB->days();
@@ -413,7 +416,7 @@ function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
413 $previousday=$days[$i - 1]; 416 $previousday=$days[$i - 1];
414 } 417 }
415 if ($i < count($days) - 1) { 418 if ($i < count($days) - 1) {
416 $nextday = $days[$i + 1]; 419 $nextday = $days[$i + 1];
417 } 420 }
418 } 421 }
419 try { 422 try {
@@ -424,8 +427,8 @@ function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
424 } 427 }
425 428
426 // We pre-format some fields for proper output. 429 // We pre-format some fields for proper output.
427 foreach($linksToDisplay as $key => $link) { 430 foreach ($linksToDisplay as $key => $link) {
428 $taglist = explode(' ',$link['tags']); 431 $taglist = explode(' ', $link['tags']);
429 uasort($taglist, 'strcasecmp'); 432 uasort($taglist, 'strcasecmp');
430 $linksToDisplay[$key]['taglist']=$taglist; 433 $linksToDisplay[$key]['taglist']=$taglist;
431 $linksToDisplay[$key]['formatedDescription'] = format_description( 434 $linksToDisplay[$key]['formatedDescription'] = format_description(
@@ -457,14 +460,14 @@ function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
457 */ 460 */
458 $columns = array(array(), array(), array()); // Entries to display, for each column. 461 $columns = array(array(), array(), array()); // Entries to display, for each column.
459 $fill = array(0, 0, 0); // Rough estimate of columns fill. 462 $fill = array(0, 0, 0); // Rough estimate of columns fill.
460 foreach($data['linksToDisplay'] as $key => $link) { 463 foreach ($data['linksToDisplay'] as $key => $link) {
461 // Roughly estimate length of entry (by counting characters) 464 // Roughly estimate length of entry (by counting characters)
462 // Title: 30 chars = 1 line. 1 line is 30 pixels height. 465 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
463 // Description: 836 characters gives roughly 342 pixel height. 466 // Description: 836 characters gives roughly 342 pixel height.
464 // This is not perfect, but it's usually OK. 467 // This is not perfect, but it's usually OK.
465 $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836; 468 $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836;
466 if ($link['thumbnail']) { 469 if ($link['thumbnail']) {
467 $length += 100; // 1 thumbnails roughly takes 100 pixels height. 470 $length += 100; // 1 thumbnails roughly takes 100 pixels height.
468 } 471 }
469 // Then put in column which is the less filled: 472 // Then put in column which is the less filled:
470 $smallest = min($fill); // find smallest value in array. 473 $smallest = min($fill); // find smallest value in array.
@@ -492,8 +495,9 @@ function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
492 * @param ConfigManager $conf Configuration Manager instance. 495 * @param ConfigManager $conf Configuration Manager instance.
493 * @param PluginManager $pluginManager Plugin Manager instance. 496 * @param PluginManager $pluginManager Plugin Manager instance.
494 */ 497 */
495function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) { 498function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
496 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager); 499{
500 buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
497 $PAGE->renderPage('linklist'); 501 $PAGE->renderPage('linklist');
498} 502}
499 503
@@ -524,8 +528,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
524 $updater->getDoneUpdates() 528 $updater->getDoneUpdates()
525 ); 529 );
526 } 530 }
527 } 531 } catch (Exception $e) {
528 catch(Exception $e) {
529 die($e->getMessage()); 532 die($e->getMessage());
530 } 533 }
531 534
@@ -538,8 +541,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
538 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : ''; 541 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
539 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn()); 542 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
540 543
541 if ( 544 if (// if the user isn't logged in
542 // if the user isn't logged in
543 !$loginManager->isLoggedIn() && 545 !$loginManager->isLoggedIn() &&
544 // and Shaarli doesn't have public content... 546 // and Shaarli doesn't have public content...
545 $conf->get('privacy.hide_public_links') && 547 $conf->get('privacy.hide_public_links') &&
@@ -563,9 +565,11 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
563 'footer', 565 'footer',
564 ); 566 );
565 567
566 foreach($common_hooks as $name) { 568 foreach ($common_hooks as $name) {
567 $plugin_data = array(); 569 $plugin_data = array();
568 $pluginManager->executeHooks('render_' . $name, $plugin_data, 570 $pluginManager->executeHooks(
571 'render_' . $name,
572 $plugin_data,
569 array( 573 array(
570 'target' => $targetPage, 574 'target' => $targetPage,
571 'loggedin' => $loginManager->isLoggedIn() 575 'loggedin' => $loginManager->isLoggedIn()
@@ -575,13 +579,15 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
575 } 579 }
576 580
577 // -------- Display login form. 581 // -------- Display login form.
578 if ($targetPage == Router::$PAGE_LOGIN) 582 if ($targetPage == Router::$PAGE_LOGIN) {
579 { 583 if ($conf->get('security.open_shaarli')) {
580 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli 584 header('Location: ?');
585 exit;
586 } // No need to login for open Shaarli
581 if (isset($_GET['username'])) { 587 if (isset($_GET['username'])) {
582 $PAGE->assign('username', escape($_GET['username'])); 588 $PAGE->assign('username', escape($_GET['username']));
583 } 589 }
584 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):'')); 590 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
585 // add default state of the 'remember me' checkbox 591 // add default state of the 'remember me' checkbox
586 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default')); 592 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
587 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER)); 593 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
@@ -590,8 +596,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
590 exit; 596 exit;
591 } 597 }
592 // -------- User wants to logout. 598 // -------- User wants to logout.
593 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) 599 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
594 {
595 invalidateCaches($conf->get('resource.page_cache')); 600 invalidateCaches($conf->get('resource.page_cache'));
596 $sessionManager->logout(); 601 $sessionManager->logout();
597 setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH); 602 setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH);
@@ -600,8 +605,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
600 } 605 }
601 606
602 // -------- Picture wall 607 // -------- Picture wall
603 if ($targetPage == Router::$PAGE_PICWALL) 608 if ($targetPage == Router::$PAGE_PICWALL) {
604 {
605 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli')); 609 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
606 if (! $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) === Thumbnailer::MODE_NONE) { 610 if (! $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) === Thumbnailer::MODE_NONE) {
607 $PAGE->assign('linksToDisplay', []); 611 $PAGE->assign('linksToDisplay', []);
@@ -615,8 +619,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
615 619
616 // Get only links which have a thumbnail. 620 // Get only links which have a thumbnail.
617 // Note: we do not retrieve thumbnails here, the request is too heavy. 621 // Note: we do not retrieve thumbnails here, the request is too heavy.
618 foreach($links as $key => $link) 622 foreach ($links as $key => $link) {
619 {
620 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) { 623 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
621 $linksToDisplay[] = $link; // Add to array. 624 $linksToDisplay[] = $link; // Add to array.
622 } 625 }
@@ -637,8 +640,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
637 } 640 }
638 641
639 // -------- Tag cloud 642 // -------- Tag cloud
640 if ($targetPage == Router::$PAGE_TAGCLOUD) 643 if ($targetPage == Router::$PAGE_TAGCLOUD) {
641 {
642 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : ''; 644 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
643 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : []; 645 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
644 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility); 646 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
@@ -653,7 +655,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
653 alphabetical_sort($tags, false, true); 655 alphabetical_sort($tags, false, true);
654 656
655 $tagList = array(); 657 $tagList = array();
656 foreach($tags as $key => $value) { 658 foreach ($tags as $key => $value) {
657 if (in_array($key, $filteringTags)) { 659 if (in_array($key, $filteringTags)) {
658 continue; 660 continue;
659 } 661 }
@@ -685,8 +687,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
685 } 687 }
686 688
687 // -------- Tag list 689 // -------- Tag list
688 if ($targetPage == Router::$PAGE_TAGLIST) 690 if ($targetPage == Router::$PAGE_TAGLIST) {
689 {
690 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : ''; 691 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
691 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : []; 692 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
692 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility); 693 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
@@ -732,7 +733,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
732 $cache = new CachedPage( 733 $cache = new CachedPage(
733 $conf->get('resource.page_cache'), 734 $conf->get('resource.page_cache'),
734 page_url($_SERVER), 735 page_url($_SERVER),
735 startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn() 736 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
736 ); 737 );
737 $cached = $cache->cachedVersion(); 738 $cached = $cache->cachedVersion();
738 if (!empty($cached)) { 739 if (!empty($cached)) {
@@ -770,11 +771,14 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
770 } 771 }
771 772
772 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...) 773 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
773 if (isset($_GET['addtag'])) 774 if (isset($_GET['addtag'])) {
774 {
775 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query. 775 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
776 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER 776 if (empty($_SERVER['HTTP_REFERER'])) {
777 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params); 777 // In case browser does not send HTTP_REFERER
778 header('Location: ?searchtags='.urlencode($_GET['addtag']));
779 exit;
780 }
781 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
778 782
779 // Prevent redirection loop 783 // Prevent redirection loop
780 if (isset($params['addtag'])) { 784 if (isset($params['addtag'])) {
@@ -798,12 +802,14 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
798 // Append the tag if necessary 802 // Append the tag if necessary
799 if (empty($params['searchtags'])) { 803 if (empty($params['searchtags'])) {
800 $params['searchtags'] = trim($_GET['addtag']); 804 $params['searchtags'] = trim($_GET['addtag']);
801 } 805 } elseif ($addtag) {
802 elseif ($addtag) {
803 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']); 806 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
804 } 807 }
805 808
806 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different) 809 // We also remove page (keeping the same page has no sense, since the
810 // results are different)
811 unset($params['page']);
812
807 header('Location: ?'.http_build_query($params)); 813 header('Location: ?'.http_build_query($params));
808 exit; 814 exit;
809 } 815 }
@@ -828,13 +834,15 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
828 $tags = explode(' ', $params['searchtags']); 834 $tags = explode(' ', $params['searchtags']);
829 // Remove value from array $tags. 835 // Remove value from array $tags.
830 $tags = array_diff($tags, array($_GET['removetag'])); 836 $tags = array_diff($tags, array($_GET['removetag']));
831 $params['searchtags'] = implode(' ',$tags); 837 $params['searchtags'] = implode(' ', $tags);
832 838
833 if (empty($params['searchtags'])) { 839 if (empty($params['searchtags'])) {
834 unset($params['searchtags']); 840 unset($params['searchtags']);
835 } 841 }
836 842
837 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different) 843 // We also remove page (keeping the same page has no sense, since
844 // the results are different)
845 unset($params['page']);
838 } 846 }
839 header('Location: ?'.http_build_query($params)); 847 header('Location: ?'.http_build_query($params));
840 exit; 848 exit;
@@ -897,12 +905,10 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
897 } 905 }
898 906
899 // -------- Handle other actions allowed for non-logged in users: 907 // -------- Handle other actions allowed for non-logged in users:
900 if (!$loginManager->isLoggedIn()) 908 if (!$loginManager->isLoggedIn()) {
901 {
902 // User tries to post new link but is not logged in: 909 // User tries to post new link but is not logged in:
903 // Show login screen, then redirect to ?post=... 910 // Show login screen, then redirect to ?post=...
904 if (isset($_GET['post'])) 911 if (isset($_GET['post'])) {
905 {
906 header( // Redirect to login page, then back to post link. 912 header( // Redirect to login page, then back to post link.
907 'Location: ?do=login&post='.urlencode($_GET['post']). 913 'Location: ?do=login&post='.urlencode($_GET['post']).
908 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):''). 914 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
@@ -925,8 +931,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
925 // -------- All other functions are reserved for the registered user: 931 // -------- All other functions are reserved for the registered user:
926 932
927 // -------- Display the Tools menu if requested (import/export/bookmarklet...) 933 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
928 if ($targetPage == Router::$PAGE_TOOLS) 934 if ($targetPage == Router::$PAGE_TOOLS) {
929 {
930 $data = [ 935 $data = [
931 'pageabsaddr' => index_url($_SERVER), 936 'pageabsaddr' => index_url($_SERVER),
932 'sslenabled' => is_https($_SERVER), 937 'sslenabled' => is_https($_SERVER),
@@ -943,30 +948,40 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
943 } 948 }
944 949
945 // -------- User wants to change his/her password. 950 // -------- User wants to change his/her password.
946 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) 951 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) {
947 {
948 if ($conf->get('security.open_shaarli')) { 952 if ($conf->get('security.open_shaarli')) {
949 die(t('You are not supposed to change a password on an Open Shaarli.')); 953 die(t('You are not supposed to change a password on an Open Shaarli.'));
950 } 954 }
951 955
952 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) 956 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
953 { 957 if (!$sessionManager->checkToken($_POST['token'])) {
954 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away! 958 die(t('Wrong token.')); // Go away!
959 }
955 960
956 // Make sure old password is correct. 961 // Make sure old password is correct.
957 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')); 962 $oldhash = sha1(
958 if ($oldhash!= $conf->get('credentials.hash')) { 963 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
959 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>'; 964 );
965 if ($oldhash != $conf->get('credentials.hash')) {
966 echo '<script>alert("'
967 . t('The old password is not correct.')
968 .'");document.location=\'?do=changepasswd\';</script>';
960 exit; 969 exit;
961 } 970 }
962 // Save new password 971 // Save new password
963 // Salt renders rainbow-tables attacks useless. 972 // Salt renders rainbow-tables attacks useless.
964 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand())); 973 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
965 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt'))); 974 $conf->set(
975 'credentials.hash',
976 sha1(
977 $_POST['setpassword']
978 . $conf->get('credentials.login')
979 . $conf->get('credentials.salt')
980 )
981 );
966 try { 982 try {
967 $conf->write($loginManager->isLoggedIn()); 983 $conf->write($loginManager->isLoggedIn());
968 } 984 } catch (Exception $e) {
969 catch(Exception $e) {
970 error_log( 985 error_log(
971 'ERROR while writing config file after changing password.' . PHP_EOL . 986 'ERROR while writing config file after changing password.' . PHP_EOL .
972 $e->getMessage() 987 $e->getMessage()
@@ -978,9 +993,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
978 } 993 }
979 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>'; 994 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
980 exit; 995 exit;
981 } 996 } else {
982 else // show the change password form. 997 // show the change password form.
983 {
984 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli')); 998 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
985 $PAGE->renderPage('changepassword'); 999 $PAGE->renderPage('changepassword');
986 exit; 1000 exit;
@@ -988,10 +1002,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
988 } 1002 }
989 1003
990 // -------- User wants to change configuration 1004 // -------- User wants to change configuration
991 if ($targetPage == Router::$PAGE_CONFIGURE) 1005 if ($targetPage == Router::$PAGE_CONFIGURE) {
992 { 1006 if (!empty($_POST['title'])) {
993 if (!empty($_POST['title']) )
994 {
995 if (!$sessionManager->checkToken($_POST['token'])) { 1007 if (!$sessionManager->checkToken($_POST['token'])) {
996 die(t('Wrong token.')); // Go away! 1008 die(t('Wrong token.')); // Go away!
997 } 1009 }
@@ -1019,7 +1031,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1019 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) 1031 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE)
1020 ) { 1032 ) {
1021 $_SESSION['warnings'][] = t( 1033 $_SESSION['warnings'][] = t(
1022 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.' 1034 'You have enabled or changed thumbnails mode. '
1035 .'<a href="?do=thumbs_update">Please synchronize them</a>.'
1023 ); 1036 );
1024 } 1037 }
1025 $conf->set('thumbnails.mode', $thumbnailsMode); 1038 $conf->set('thumbnails.mode', $thumbnailsMode);
@@ -1028,8 +1041,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1028 $conf->write($loginManager->isLoggedIn()); 1041 $conf->write($loginManager->isLoggedIn());
1029 $history->updateSettings(); 1042 $history->updateSettings();
1030 invalidateCaches($conf->get('resource.page_cache')); 1043 invalidateCaches($conf->get('resource.page_cache'));
1031 } 1044 } catch (Exception $e) {
1032 catch(Exception $e) {
1033 error_log( 1045 error_log(
1034 'ERROR while writing config file after configuration update.' . PHP_EOL . 1046 'ERROR while writing config file after configuration update.' . PHP_EOL .
1035 $e->getMessage() 1047 $e->getMessage()
@@ -1041,9 +1053,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1041 } 1053 }
1042 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>'; 1054 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1043 exit; 1055 exit;
1044 } 1056 } else {
1045 else // Show the configuration form. 1057 // Show the configuration form.
1046 {
1047 $PAGE->assign('title', $conf->get('general.title')); 1058 $PAGE->assign('title', $conf->get('general.title'));
1048 $PAGE->assign('theme', $conf->get('resource.theme')); 1059 $PAGE->assign('theme', $conf->get('resource.theme'));
1049 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl'))); 1060 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
@@ -1071,8 +1082,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1071 } 1082 }
1072 1083
1073 // -------- User wants to rename a tag or delete it 1084 // -------- User wants to rename a tag or delete it
1074 if ($targetPage == Router::$PAGE_CHANGETAG) 1085 if ($targetPage == Router::$PAGE_CHANGETAG) {
1075 {
1076 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) { 1086 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1077 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : ''); 1087 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1078 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli')); 1088 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
@@ -1084,7 +1094,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1084 die(t('Wrong token.')); 1094 die(t('Wrong token.'));
1085 } 1095 }
1086 1096
1087 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag'])); 1097 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
1098 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), $toTag);
1088 $LINKSDB->save($conf->get('resource.page_cache')); 1099 $LINKSDB->save($conf->get('resource.page_cache'));
1089 foreach ($alteredLinks as $link) { 1100 foreach ($alteredLinks as $link) {
1090 $history->updateLink($link); 1101 $history->updateLink($link);
@@ -1100,16 +1111,14 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1100 } 1111 }
1101 1112
1102 // -------- User wants to add a link without using the bookmarklet: Show form. 1113 // -------- User wants to add a link without using the bookmarklet: Show form.
1103 if ($targetPage == Router::$PAGE_ADDLINK) 1114 if ($targetPage == Router::$PAGE_ADDLINK) {
1104 {
1105 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli')); 1115 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1106 $PAGE->renderPage('addlink'); 1116 $PAGE->renderPage('addlink');
1107 exit; 1117 exit;
1108 } 1118 }
1109 1119
1110 // -------- User clicked the "Save" button when editing a link: Save link to database. 1120 // -------- User clicked the "Save" button when editing a link: Save link to database.
1111 if (isset($_POST['save_edit'])) 1121 if (isset($_POST['save_edit'])) {
1112 {
1113 // Go away! 1122 // Go away!
1114 if (! $sessionManager->checkToken($_POST['token'])) { 1123 if (! $sessionManager->checkToken($_POST['token'])) {
1115 die(t('Wrong token.')); 1124 die(t('Wrong token.'));
@@ -1196,14 +1205,16 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1196 } 1205 }
1197 1206
1198 // -------- User clicked the "Cancel" button when editing a link. 1207 // -------- User clicked the "Cancel" button when editing a link.
1199 if (isset($_POST['cancel_edit'])) 1208 if (isset($_POST['cancel_edit'])) {
1200 {
1201 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false; 1209 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1202 if (! isset($LINKSDB[$id])) { 1210 if (! isset($LINKSDB[$id])) {
1203 header('Location: ?'); 1211 header('Location: ?');
1204 } 1212 }
1205 // If we are called from the bookmarklet, we must close the popup: 1213 // If we are called from the bookmarklet, we must close the popup:
1206 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } 1214 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1215 echo '<script>self.close();</script>';
1216 exit;
1217 }
1207 $link = $LINKSDB[$id]; 1218 $link = $LINKSDB[$id];
1208 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); 1219 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1209 // Scroll to the link which has been edited. 1220 // Scroll to the link which has been edited.
@@ -1214,8 +1225,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1214 } 1225 }
1215 1226
1216 // -------- User clicked the "Delete" button when editing a link: Delete link from database. 1227 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1217 if ($targetPage == Router::$PAGE_DELETELINK) 1228 if ($targetPage == Router::$PAGE_DELETELINK) {
1218 {
1219 if (! $sessionManager->checkToken($_GET['token'])) { 1229 if (! $sessionManager->checkToken($_GET['token'])) {
1220 die(t('Wrong token.')); 1230 die(t('Wrong token.'));
1221 } 1231 }
@@ -1229,28 +1239,31 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1229 $ids = [$ids]; 1239 $ids = [$ids];
1230 } 1240 }
1231 // assert at least one id is given 1241 // assert at least one id is given
1232 if(!count($ids)){ 1242 if (!count($ids)) {
1233 die('no id provided'); 1243 die('no id provided');
1234 } 1244 }
1235 foreach ($ids as $id) { 1245 foreach ($ids as $id) {
1236 $id = (int) escape($id); 1246 $id = (int) escape($id);
1237 $link = $LINKSDB[$id]; 1247 $link = $LINKSDB[$id];
1238 $pluginManager->executeHooks('delete_link', $link); 1248 $pluginManager->executeHooks('delete_link', $link);
1249 $history->deleteLink($link);
1239 unset($LINKSDB[$id]); 1250 unset($LINKSDB[$id]);
1240 } 1251 }
1241 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk 1252 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1242 $history->deleteLink($link);
1243 1253
1244 // If we are called from the bookmarklet, we must close the popup: 1254 // If we are called from the bookmarklet, we must close the popup:
1245 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } 1255 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1256 echo '<script>self.close();</script>';
1257 exit;
1258 }
1246 1259
1247 $location = '?'; 1260 $location = '?';
1248 if (isset($_SERVER['HTTP_REFERER'])) { 1261 if (isset($_SERVER['HTTP_REFERER'])) {
1249 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404. 1262 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1250 $location = generateLocation( 1263 $location = generateLocation(
1251 $_SERVER['HTTP_REFERER'], 1264 $_SERVER['HTTP_REFERER'],
1252 $_SERVER['HTTP_HOST'], 1265 $_SERVER['HTTP_HOST'],
1253 ['delete_link', 'edit_link', $link['shorturl']] 1266 ['delete_link', 'edit_link', $link['shorturl']]
1254 ); 1267 );
1255 } 1268 }
1256 1269
@@ -1259,11 +1272,13 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1259 } 1272 }
1260 1273
1261 // -------- User clicked the "EDIT" button on a link: Display link edit form. 1274 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1262 if (isset($_GET['edit_link'])) 1275 if (isset($_GET['edit_link'])) {
1263 {
1264 $id = (int) escape($_GET['edit_link']); 1276 $id = (int) escape($_GET['edit_link']);
1265 $link = $LINKSDB[$id]; // Read database 1277 $link = $LINKSDB[$id]; // Read database
1266 if (!$link) { header('Location: ?'); exit; } // Link not found in database. 1278 if (!$link) {
1279 header('Location: ?');
1280 exit;
1281 } // Link not found in database.
1267 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT); 1282 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1268 $data = array( 1283 $data = array(
1269 'link' => $link, 1284 'link' => $link,
@@ -1289,8 +1304,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1289 $link_is_new = false; 1304 $link_is_new = false;
1290 // Check if URL is not already in database (in this case, we will edit the existing link) 1305 // Check if URL is not already in database (in this case, we will edit the existing link)
1291 $link = $LINKSDB->getLinkFromUrl($url); 1306 $link = $LINKSDB->getLinkFromUrl($url);
1292 if (! $link) 1307 if (! $link) {
1293 {
1294 $link_is_new = true; 1308 $link_is_new = true;
1295 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT)); 1309 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
1296 // Get title if it was provided in URL (by the bookmarklet). 1310 // Get title if it was provided in URL (by the bookmarklet).
@@ -1299,7 +1313,9 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1299 $description = empty($_GET['description']) ? '' : escape($_GET['description']); 1313 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1300 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']); 1314 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1301 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0; 1315 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1302 // 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.) 1316
1317 // If this is an HTTP(S) link, we try go get the page to extract
1318 // the title (otherwise we will to straight to the edit form.)
1303 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) { 1319 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1304 // Short timeout to keep the application responsive 1320 // Short timeout to keep the application responsive
1305 // The callback will fill $charset and $title with data from the downloaded page. 1321 // The callback will fill $charset and $title with data from the downloaded page.
@@ -1352,6 +1368,25 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1352 exit; 1368 exit;
1353 } 1369 }
1354 1370
1371 if ($targetPage == Router::$PAGE_PINLINK) {
1372 if (! isset($_GET['id']) || empty($LINKSDB[$_GET['id']])) {
1373 // FIXME! Use a proper error system.
1374 $msg = t('Invalid link ID provided');
1375 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1376 exit;
1377 }
1378 if (! $sessionManager->checkToken($_GET['token'])) {
1379 die('Wrong token.');
1380 }
1381
1382 $link = $LINKSDB[$_GET['id']];
1383 $link['sticky'] = ! $link['sticky'];
1384 $LINKSDB[(int) $_GET['id']] = $link;
1385 $LINKSDB->save($conf->get('resource.page_cache'));
1386 header('Location: '.index_url($_SERVER));
1387 exit;
1388 }
1389
1355 if ($targetPage == Router::$PAGE_EXPORT) { 1390 if ($targetPage == Router::$PAGE_EXPORT) {
1356 // Export links as a Netscape Bookmarks file 1391 // Export links as a Netscape Bookmarks file
1357 1392
@@ -1388,7 +1423,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1388 header('Content-Type: text/html; charset=utf-8'); 1423 header('Content-Type: text/html; charset=utf-8');
1389 header( 1424 header(
1390 'Content-disposition: attachment; filename=bookmarks_' 1425 'Content-disposition: attachment; filename=bookmarks_'
1391 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html' 1426 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1392 ); 1427 );
1393 $PAGE->assign('date', $now->format(DateTime::RFC822)); 1428 $PAGE->assign('date', $now->format(DateTime::RFC822));
1394 $PAGE->assign('eol', PHP_EOL); 1429 $PAGE->assign('eol', PHP_EOL);
@@ -1456,14 +1491,20 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1456 $pluginMeta = $pluginManager->getPluginsMeta(); 1491 $pluginMeta = $pluginManager->getPluginsMeta();
1457 1492
1458 // Split plugins into 2 arrays: ordered enabled plugins and disabled. 1493 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1459 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; }); 1494 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1495 return $v['order'] !== false;
1496 });
1460 // Load parameters. 1497 // Load parameters.
1461 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array())); 1498 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1462 uasort( 1499 uasort(
1463 $enabledPlugins, 1500 $enabledPlugins,
1464 function($a, $b) { return $a['order'] - $b['order']; } 1501 function ($a, $b) {
1502 return $a['order'] - $b['order'];
1503 }
1465 ); 1504 );
1466 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; }); 1505 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1506 return $v['order'] === false;
1507 });
1467 1508
1468 $PAGE->assign('enabledPlugins', $enabledPlugins); 1509 $PAGE->assign('enabledPlugins', $enabledPlugins);
1469 $PAGE->assign('disabledPlugins', $disabledPlugins); 1510 $PAGE->assign('disabledPlugins', $disabledPlugins);
@@ -1480,21 +1521,23 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1480 foreach ($_POST as $param => $value) { 1521 foreach ($_POST as $param => $value) {
1481 $conf->set('plugins.'. $param, escape($value)); 1522 $conf->set('plugins.'. $param, escape($value));
1482 } 1523 }
1483 } 1524 } else {
1484 else {
1485 $conf->set('general.enabled_plugins', save_plugin_config($_POST)); 1525 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1486 } 1526 }
1487 $conf->write($loginManager->isLoggedIn()); 1527 $conf->write($loginManager->isLoggedIn());
1488 $history->updateSettings(); 1528 $history->updateSettings();
1489 } 1529 } catch (Exception $e) {
1490 catch (Exception $e) {
1491 error_log( 1530 error_log(
1492 'ERROR while saving plugin configuration:.' . PHP_EOL . 1531 'ERROR while saving plugin configuration:.' . PHP_EOL .
1493 $e->getMessage() 1532 $e->getMessage()
1494 ); 1533 );
1495 1534
1496 // TODO: do not handle exceptions/errors in JS. 1535 // TODO: do not handle exceptions/errors in JS.
1497 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>'; 1536 echo '<script>alert("'
1537 . $e->getMessage()
1538 .'");document.location=\'?do='
1539 . Router::$PAGE_PLUGINSADMIN
1540 .'\';</script>';
1498 exit; 1541 exit;
1499 } 1542 }
1500 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN); 1543 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
@@ -1615,8 +1658,7 @@ function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1615 } 1658 }
1616 1659
1617 $linkDisp = array(); 1660 $linkDisp = array();
1618 while ($i<$end && $i<count($keys)) 1661 while ($i<$end && $i<count($keys)) {
1619 {
1620 $link = $linksToDisplay[$keys[$i]]; 1662 $link = $linksToDisplay[$keys[$i]];
1621 $link['description'] = format_description( 1663 $link['description'] = format_description(
1622 $link['description'], 1664 $link['description'],
@@ -1719,16 +1761,19 @@ function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1719 * @param SessionManager $sessionManager SessionManager instance 1761 * @param SessionManager $sessionManager SessionManager instance
1720 * @param LoginManager $loginManager LoginManager instance 1762 * @param LoginManager $loginManager LoginManager instance
1721 */ 1763 */
1722function install($conf, $sessionManager, $loginManager) { 1764function install($conf, $sessionManager, $loginManager)
1765{
1723 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. 1766 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1724 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); 1767 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1768 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1769 }
1725 1770
1726 1771
1727 // This part makes sure sessions works correctly. 1772 // This part makes sure sessions works correctly.
1728 // (Because on some hosts, session.save_path may not be set correctly, 1773 // (Because on some hosts, session.save_path may not be set correctly,
1729 // or we may not have write access to it.) 1774 // or we may not have write access to it.)
1730 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) 1775 if (isset($_GET['test_session'])
1731 { 1776 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1732 // Step 2: Check if data in session is correct. 1777 // Step 2: Check if data in session is correct.
1733 $msg = t( 1778 $msg = t(
1734 '<pre>Sessions do not seem to work correctly on your server.<br>'. 1779 '<pre>Sessions do not seem to work correctly on your server.<br>'.
@@ -1744,19 +1789,18 @@ function install($conf, $sessionManager, $loginManager) {
1744 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>'; 1789 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1745 die; 1790 die;
1746 } 1791 }
1747 if (!isset($_SESSION['session_tested'])) 1792 if (!isset($_SESSION['session_tested'])) {
1748 { // Step 1 : Try to store data in session and reload page. 1793 // Step 1 : Try to store data in session and reload page.
1749 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session. 1794 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1750 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data. 1795 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1751 } 1796 }
1752 if (isset($_GET['test_session'])) 1797 if (isset($_GET['test_session'])) {
1753 { // Step 3: Sessions are OK. Remove test parameter from URL. 1798 // Step 3: Sessions are OK. Remove test parameter from URL.
1754 header('Location: '.index_url($_SERVER)); 1799 header('Location: '.index_url($_SERVER));
1755 } 1800 }
1756 1801
1757 1802
1758 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) 1803 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1759 {
1760 $tz = 'UTC'; 1804 $tz = 'UTC';
1761 if (!empty($_POST['continent']) && !empty($_POST['city']) 1805 if (!empty($_POST['continent']) && !empty($_POST['city'])
1762 && isTimeZoneValid($_POST['continent'], $_POST['city']) 1806 && isTimeZoneValid($_POST['continent'], $_POST['city'])
@@ -1787,18 +1831,20 @@ function install($conf, $sessionManager, $loginManager) {
1787 try { 1831 try {
1788 // Everything is ok, let's create config file. 1832 // Everything is ok, let's create config file.
1789 $conf->write($loginManager->isLoggedIn()); 1833 $conf->write($loginManager->isLoggedIn());
1790 } 1834 } catch (Exception $e) {
1791 catch(Exception $e) {
1792 error_log( 1835 error_log(
1793 'ERROR while writing config file after installation.' . PHP_EOL . 1836 'ERROR while writing config file after installation.' . PHP_EOL .
1794 $e->getMessage() 1837 $e->getMessage()
1795 ); 1838 );
1796 1839
1797 // TODO: do not handle exceptions/errors in JS. 1840 // TODO: do not handle exceptions/errors in JS.
1798 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>'; 1841 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1799 exit; 1842 exit;
1800 } 1843 }
1801 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>'; 1844 echo '<script>alert('
1845 .'"Shaarli is now configured. '
1846 .'Please enter your login/password and start shaaring your links!"'
1847 .');document.location=\'?do=login\';</script>';
1802 exit; 1848 exit;
1803 } 1849 }
1804 1850
@@ -1822,7 +1868,7 @@ if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1822 1868
1823try { 1869try {
1824 $history = new History($conf->get('resource.history')); 1870 $history = new History($conf->get('resource.history'));
1825} catch(Exception $e) { 1871} catch (Exception $e) {
1826 die($e->getMessage()); 1872 die($e->getMessage());
1827} 1873}
1828 1874
@@ -1841,7 +1887,7 @@ $container['history'] = $history;
1841$app = new \Slim\App($container); 1887$app = new \Slim\App($container);
1842 1888
1843// REST API routes 1889// REST API routes
1844$app->group('/api/v1', function() { 1890$app->group('/api/v1', function () {
1845 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo'); 1891 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1846 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks'); 1892 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1847 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink'); 1893 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
@@ -1858,6 +1904,7 @@ $app->group('/api/v1', function() {
1858})->add('\Shaarli\Api\ApiMiddleware'); 1904})->add('\Shaarli\Api\ApiMiddleware');
1859 1905
1860$response = $app->run(true); 1906$response = $app->run(true);
1907
1861// Hack to make Slim and Shaarli router work together: 1908// Hack to make Slim and Shaarli router work together:
1862// If a Slim route isn't found and NOT API call, we call renderPage(). 1909// If a Slim route isn't found and NOT API call, we call renderPage().
1863if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) { 1910if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
@@ -1865,5 +1912,12 @@ if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v
1865 header('Content-Type: text/html; charset=utf-8'); 1912 header('Content-Type: text/html; charset=utf-8');
1866 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager); 1913 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1867} else { 1914} else {
1915 $response = $response
1916 ->withHeader('Access-Control-Allow-Origin', '*')
1917 ->withHeader(
1918 'Access-Control-Allow-Headers',
1919 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1920 )
1921 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1868 $app->respond($response); 1922 $app->respond($response);
1869} 1923}