aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.net>2018-10-13 00:31:11 +0200
committerVirtualTam <virtualtam@flibidi.net>2018-12-02 22:39:16 +0100
commit93bf0918fa7bb1efb39d1540d7e46e52767270df (patch)
treec96682e2e4e6a5af61b12ca84351abb532aacd6e
parenta0ab3c3f68ed3bca7d218e6e5847820b82b086ca (diff)
downloadShaarli-93bf0918fa7bb1efb39d1540d7e46e52767270df.tar.gz
Shaarli-93bf0918fa7bb1efb39d1540d7e46e52767270df.tar.zst
Shaarli-93bf0918fa7bb1efb39d1540d7e46e52767270df.zip
lint: apply phpcbf to index.php
Signed-off-by: VirtualTam <virtualtam@flibidi.net>
-rw-r--r--index.php231
1 files changed, 115 insertions, 116 deletions
diff --git a/index.php b/index.php
index 82285dd9..2e350fcf 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;
@@ -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,8 +802,7 @@ 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
@@ -828,7 +831,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
828 $tags = explode(' ', $params['searchtags']); 831 $tags = explode(' ', $params['searchtags']);
829 // Remove value from array $tags. 832 // Remove value from array $tags.
830 $tags = array_diff($tags, array($_GET['removetag'])); 833 $tags = array_diff($tags, array($_GET['removetag']));
831 $params['searchtags'] = implode(' ',$tags); 834 $params['searchtags'] = implode(' ', $tags);
832 835
833 if (empty($params['searchtags'])) { 836 if (empty($params['searchtags'])) {
834 unset($params['searchtags']); 837 unset($params['searchtags']);
@@ -897,12 +900,10 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
897 } 900 }
898 901
899 // -------- Handle other actions allowed for non-logged in users: 902 // -------- Handle other actions allowed for non-logged in users:
900 if (!$loginManager->isLoggedIn()) 903 if (!$loginManager->isLoggedIn()) {
901 {
902 // User tries to post new link but is not logged in: 904 // User tries to post new link but is not logged in:
903 // Show login screen, then redirect to ?post=... 905 // Show login screen, then redirect to ?post=...
904 if (isset($_GET['post'])) 906 if (isset($_GET['post'])) {
905 {
906 header( // Redirect to login page, then back to post link. 907 header( // Redirect to login page, then back to post link.
907 'Location: ?do=login&post='.urlencode($_GET['post']). 908 'Location: ?do=login&post='.urlencode($_GET['post']).
908 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):''). 909 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
@@ -925,8 +926,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
925 // -------- All other functions are reserved for the registered user: 926 // -------- All other functions are reserved for the registered user:
926 927
927 // -------- Display the Tools menu if requested (import/export/bookmarklet...) 928 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
928 if ($targetPage == Router::$PAGE_TOOLS) 929 if ($targetPage == Router::$PAGE_TOOLS) {
929 {
930 $data = [ 930 $data = [
931 'pageabsaddr' => index_url($_SERVER), 931 'pageabsaddr' => index_url($_SERVER),
932 'sslenabled' => is_https($_SERVER), 932 'sslenabled' => is_https($_SERVER),
@@ -943,15 +943,15 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
943 } 943 }
944 944
945 // -------- User wants to change his/her password. 945 // -------- User wants to change his/her password.
946 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) 946 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) {
947 {
948 if ($conf->get('security.open_shaarli')) { 947 if ($conf->get('security.open_shaarli')) {
949 die(t('You are not supposed to change a password on an Open Shaarli.')); 948 die(t('You are not supposed to change a password on an Open Shaarli.'));
950 } 949 }
951 950
952 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) 951 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
953 { 952 if (!$sessionManager->checkToken($_POST['token'])) {
954 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away! 953 die(t('Wrong token.')); // Go away!
954 }
955 955
956 // Make sure old password is correct. 956 // Make sure old password is correct.
957 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')); 957 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
@@ -965,8 +965,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
965 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt'))); 965 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
966 try { 966 try {
967 $conf->write($loginManager->isLoggedIn()); 967 $conf->write($loginManager->isLoggedIn());
968 } 968 } catch (Exception $e) {
969 catch(Exception $e) {
970 error_log( 969 error_log(
971 'ERROR while writing config file after changing password.' . PHP_EOL . 970 'ERROR while writing config file after changing password.' . PHP_EOL .
972 $e->getMessage() 971 $e->getMessage()
@@ -978,9 +977,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
978 } 977 }
979 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>'; 978 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
980 exit; 979 exit;
981 } 980 } else {
982 else // show the change password form. 981 // show the change password form.
983 {
984 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli')); 982 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
985 $PAGE->renderPage('changepassword'); 983 $PAGE->renderPage('changepassword');
986 exit; 984 exit;
@@ -988,10 +986,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
988 } 986 }
989 987
990 // -------- User wants to change configuration 988 // -------- User wants to change configuration
991 if ($targetPage == Router::$PAGE_CONFIGURE) 989 if ($targetPage == Router::$PAGE_CONFIGURE) {
992 { 990 if (!empty($_POST['title'])) {
993 if (!empty($_POST['title']) )
994 {
995 if (!$sessionManager->checkToken($_POST['token'])) { 991 if (!$sessionManager->checkToken($_POST['token'])) {
996 die(t('Wrong token.')); // Go away! 992 die(t('Wrong token.')); // Go away!
997 } 993 }
@@ -1028,8 +1024,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1028 $conf->write($loginManager->isLoggedIn()); 1024 $conf->write($loginManager->isLoggedIn());
1029 $history->updateSettings(); 1025 $history->updateSettings();
1030 invalidateCaches($conf->get('resource.page_cache')); 1026 invalidateCaches($conf->get('resource.page_cache'));
1031 } 1027 } catch (Exception $e) {
1032 catch(Exception $e) {
1033 error_log( 1028 error_log(
1034 'ERROR while writing config file after configuration update.' . PHP_EOL . 1029 'ERROR while writing config file after configuration update.' . PHP_EOL .
1035 $e->getMessage() 1030 $e->getMessage()
@@ -1041,9 +1036,8 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1041 } 1036 }
1042 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>'; 1037 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1043 exit; 1038 exit;
1044 } 1039 } else {
1045 else // Show the configuration form. 1040 // Show the configuration form.
1046 {
1047 $PAGE->assign('title', $conf->get('general.title')); 1041 $PAGE->assign('title', $conf->get('general.title'));
1048 $PAGE->assign('theme', $conf->get('resource.theme')); 1042 $PAGE->assign('theme', $conf->get('resource.theme'));
1049 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl'))); 1043 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
@@ -1071,8 +1065,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1071 } 1065 }
1072 1066
1073 // -------- User wants to rename a tag or delete it 1067 // -------- User wants to rename a tag or delete it
1074 if ($targetPage == Router::$PAGE_CHANGETAG) 1068 if ($targetPage == Router::$PAGE_CHANGETAG) {
1075 {
1076 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) { 1069 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1077 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : ''); 1070 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1078 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli')); 1071 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
@@ -1101,16 +1094,14 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1101 } 1094 }
1102 1095
1103 // -------- User wants to add a link without using the bookmarklet: Show form. 1096 // -------- User wants to add a link without using the bookmarklet: Show form.
1104 if ($targetPage == Router::$PAGE_ADDLINK) 1097 if ($targetPage == Router::$PAGE_ADDLINK) {
1105 {
1106 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli')); 1098 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1107 $PAGE->renderPage('addlink'); 1099 $PAGE->renderPage('addlink');
1108 exit; 1100 exit;
1109 } 1101 }
1110 1102
1111 // -------- User clicked the "Save" button when editing a link: Save link to database. 1103 // -------- User clicked the "Save" button when editing a link: Save link to database.
1112 if (isset($_POST['save_edit'])) 1104 if (isset($_POST['save_edit'])) {
1113 {
1114 // Go away! 1105 // Go away!
1115 if (! $sessionManager->checkToken($_POST['token'])) { 1106 if (! $sessionManager->checkToken($_POST['token'])) {
1116 die(t('Wrong token.')); 1107 die(t('Wrong token.'));
@@ -1197,14 +1188,16 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1197 } 1188 }
1198 1189
1199 // -------- User clicked the "Cancel" button when editing a link. 1190 // -------- User clicked the "Cancel" button when editing a link.
1200 if (isset($_POST['cancel_edit'])) 1191 if (isset($_POST['cancel_edit'])) {
1201 {
1202 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false; 1192 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1203 if (! isset($LINKSDB[$id])) { 1193 if (! isset($LINKSDB[$id])) {
1204 header('Location: ?'); 1194 header('Location: ?');
1205 } 1195 }
1206 // If we are called from the bookmarklet, we must close the popup: 1196 // If we are called from the bookmarklet, we must close the popup:
1207 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } 1197 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1198 echo '<script>self.close();</script>';
1199 exit;
1200 }
1208 $link = $LINKSDB[$id]; 1201 $link = $LINKSDB[$id];
1209 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); 1202 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1210 // Scroll to the link which has been edited. 1203 // Scroll to the link which has been edited.
@@ -1215,8 +1208,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1215 } 1208 }
1216 1209
1217 // -------- User clicked the "Delete" button when editing a link: Delete link from database. 1210 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1218 if ($targetPage == Router::$PAGE_DELETELINK) 1211 if ($targetPage == Router::$PAGE_DELETELINK) {
1219 {
1220 if (! $sessionManager->checkToken($_GET['token'])) { 1212 if (! $sessionManager->checkToken($_GET['token'])) {
1221 die(t('Wrong token.')); 1213 die(t('Wrong token.'));
1222 } 1214 }
@@ -1230,7 +1222,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1230 $ids = [$ids]; 1222 $ids = [$ids];
1231 } 1223 }
1232 // assert at least one id is given 1224 // assert at least one id is given
1233 if(!count($ids)){ 1225 if (!count($ids)) {
1234 die('no id provided'); 1226 die('no id provided');
1235 } 1227 }
1236 foreach ($ids as $id) { 1228 foreach ($ids as $id) {
@@ -1243,15 +1235,18 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1243 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk 1235 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1244 1236
1245 // If we are called from the bookmarklet, we must close the popup: 1237 // If we are called from the bookmarklet, we must close the popup:
1246 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; } 1238 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1239 echo '<script>self.close();</script>';
1240 exit;
1241 }
1247 1242
1248 $location = '?'; 1243 $location = '?';
1249 if (isset($_SERVER['HTTP_REFERER'])) { 1244 if (isset($_SERVER['HTTP_REFERER'])) {
1250 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404. 1245 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1251 $location = generateLocation( 1246 $location = generateLocation(
1252 $_SERVER['HTTP_REFERER'], 1247 $_SERVER['HTTP_REFERER'],
1253 $_SERVER['HTTP_HOST'], 1248 $_SERVER['HTTP_HOST'],
1254 ['delete_link', 'edit_link', $link['shorturl']] 1249 ['delete_link', 'edit_link', $link['shorturl']]
1255 ); 1250 );
1256 } 1251 }
1257 1252
@@ -1260,11 +1255,13 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1260 } 1255 }
1261 1256
1262 // -------- User clicked the "EDIT" button on a link: Display link edit form. 1257 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1263 if (isset($_GET['edit_link'])) 1258 if (isset($_GET['edit_link'])) {
1264 {
1265 $id = (int) escape($_GET['edit_link']); 1259 $id = (int) escape($_GET['edit_link']);
1266 $link = $LINKSDB[$id]; // Read database 1260 $link = $LINKSDB[$id]; // Read database
1267 if (!$link) { header('Location: ?'); exit; } // Link not found in database. 1261 if (!$link) {
1262 header('Location: ?');
1263 exit;
1264 } // Link not found in database.
1268 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT); 1265 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1269 $data = array( 1266 $data = array(
1270 'link' => $link, 1267 'link' => $link,
@@ -1290,8 +1287,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1290 $link_is_new = false; 1287 $link_is_new = false;
1291 // Check if URL is not already in database (in this case, we will edit the existing link) 1288 // Check if URL is not already in database (in this case, we will edit the existing link)
1292 $link = $LINKSDB->getLinkFromUrl($url); 1289 $link = $LINKSDB->getLinkFromUrl($url);
1293 if (! $link) 1290 if (! $link) {
1294 {
1295 $link_is_new = true; 1291 $link_is_new = true;
1296 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT)); 1292 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
1297 // Get title if it was provided in URL (by the bookmarklet). 1293 // Get title if it was provided in URL (by the bookmarklet).
@@ -1408,7 +1404,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1408 header('Content-Type: text/html; charset=utf-8'); 1404 header('Content-Type: text/html; charset=utf-8');
1409 header( 1405 header(
1410 'Content-disposition: attachment; filename=bookmarks_' 1406 'Content-disposition: attachment; filename=bookmarks_'
1411 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html' 1407 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1412 ); 1408 );
1413 $PAGE->assign('date', $now->format(DateTime::RFC822)); 1409 $PAGE->assign('date', $now->format(DateTime::RFC822));
1414 $PAGE->assign('eol', PHP_EOL); 1410 $PAGE->assign('eol', PHP_EOL);
@@ -1476,14 +1472,20 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1476 $pluginMeta = $pluginManager->getPluginsMeta(); 1472 $pluginMeta = $pluginManager->getPluginsMeta();
1477 1473
1478 // Split plugins into 2 arrays: ordered enabled plugins and disabled. 1474 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1479 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; }); 1475 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1476 return $v['order'] !== false;
1477 });
1480 // Load parameters. 1478 // Load parameters.
1481 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array())); 1479 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1482 uasort( 1480 uasort(
1483 $enabledPlugins, 1481 $enabledPlugins,
1484 function($a, $b) { return $a['order'] - $b['order']; } 1482 function ($a, $b) {
1483 return $a['order'] - $b['order'];
1484 }
1485 ); 1485 );
1486 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; }); 1486 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1487 return $v['order'] === false;
1488 });
1487 1489
1488 $PAGE->assign('enabledPlugins', $enabledPlugins); 1490 $PAGE->assign('enabledPlugins', $enabledPlugins);
1489 $PAGE->assign('disabledPlugins', $disabledPlugins); 1491 $PAGE->assign('disabledPlugins', $disabledPlugins);
@@ -1500,14 +1502,12 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
1500 foreach ($_POST as $param => $value) { 1502 foreach ($_POST as $param => $value) {
1501 $conf->set('plugins.'. $param, escape($value)); 1503 $conf->set('plugins.'. $param, escape($value));
1502 } 1504 }
1503 } 1505 } else {
1504 else {
1505 $conf->set('general.enabled_plugins', save_plugin_config($_POST)); 1506 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1506 } 1507 }
1507 $conf->write($loginManager->isLoggedIn()); 1508 $conf->write($loginManager->isLoggedIn());
1508 $history->updateSettings(); 1509 $history->updateSettings();
1509 } 1510 } catch (Exception $e) {
1510 catch (Exception $e) {
1511 error_log( 1511 error_log(
1512 'ERROR while saving plugin configuration:.' . PHP_EOL . 1512 'ERROR while saving plugin configuration:.' . PHP_EOL .
1513 $e->getMessage() 1513 $e->getMessage()
@@ -1635,8 +1635,7 @@ function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1635 } 1635 }
1636 1636
1637 $linkDisp = array(); 1637 $linkDisp = array();
1638 while ($i<$end && $i<count($keys)) 1638 while ($i<$end && $i<count($keys)) {
1639 {
1640 $link = $linksToDisplay[$keys[$i]]; 1639 $link = $linksToDisplay[$keys[$i]];
1641 $link['description'] = format_description( 1640 $link['description'] = format_description(
1642 $link['description'], 1641 $link['description'],
@@ -1739,16 +1738,18 @@ function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1739 * @param SessionManager $sessionManager SessionManager instance 1738 * @param SessionManager $sessionManager SessionManager instance
1740 * @param LoginManager $loginManager LoginManager instance 1739 * @param LoginManager $loginManager LoginManager instance
1741 */ 1740 */
1742function install($conf, $sessionManager, $loginManager) { 1741function install($conf, $sessionManager, $loginManager)
1742{
1743 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. 1743 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1744 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); 1744 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1745 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1746 }
1745 1747
1746 1748
1747 // This part makes sure sessions works correctly. 1749 // This part makes sure sessions works correctly.
1748 // (Because on some hosts, session.save_path may not be set correctly, 1750 // (Because on some hosts, session.save_path may not be set correctly,
1749 // or we may not have write access to it.) 1751 // or we may not have write access to it.)
1750 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) 1752 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1751 {
1752 // Step 2: Check if data in session is correct. 1753 // Step 2: Check if data in session is correct.
1753 $msg = t( 1754 $msg = t(
1754 '<pre>Sessions do not seem to work correctly on your server.<br>'. 1755 '<pre>Sessions do not seem to work correctly on your server.<br>'.
@@ -1764,19 +1765,18 @@ function install($conf, $sessionManager, $loginManager) {
1764 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>'; 1765 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1765 die; 1766 die;
1766 } 1767 }
1767 if (!isset($_SESSION['session_tested'])) 1768 if (!isset($_SESSION['session_tested'])) {
1768 { // Step 1 : Try to store data in session and reload page. 1769 // Step 1 : Try to store data in session and reload page.
1769 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session. 1770 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1770 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data. 1771 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1771 } 1772 }
1772 if (isset($_GET['test_session'])) 1773 if (isset($_GET['test_session'])) {
1773 { // Step 3: Sessions are OK. Remove test parameter from URL. 1774 // Step 3: Sessions are OK. Remove test parameter from URL.
1774 header('Location: '.index_url($_SERVER)); 1775 header('Location: '.index_url($_SERVER));
1775 } 1776 }
1776 1777
1777 1778
1778 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) 1779 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1779 {
1780 $tz = 'UTC'; 1780 $tz = 'UTC';
1781 if (!empty($_POST['continent']) && !empty($_POST['city']) 1781 if (!empty($_POST['continent']) && !empty($_POST['city'])
1782 && isTimeZoneValid($_POST['continent'], $_POST['city']) 1782 && isTimeZoneValid($_POST['continent'], $_POST['city'])
@@ -1807,12 +1807,11 @@ function install($conf, $sessionManager, $loginManager) {
1807 try { 1807 try {
1808 // Everything is ok, let's create config file. 1808 // Everything is ok, let's create config file.
1809 $conf->write($loginManager->isLoggedIn()); 1809 $conf->write($loginManager->isLoggedIn());
1810 } 1810 } catch (Exception $e) {
1811 catch(Exception $e) {
1812 error_log( 1811 error_log(
1813 'ERROR while writing config file after installation.' . PHP_EOL . 1812 'ERROR while writing config file after installation.' . PHP_EOL .
1814 $e->getMessage() 1813 $e->getMessage()
1815 ); 1814 );
1816 1815
1817 // TODO: do not handle exceptions/errors in JS. 1816 // TODO: do not handle exceptions/errors in JS.
1818 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>'; 1817 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
@@ -1842,7 +1841,7 @@ if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1842 1841
1843try { 1842try {
1844 $history = new History($conf->get('resource.history')); 1843 $history = new History($conf->get('resource.history'));
1845} catch(Exception $e) { 1844} catch (Exception $e) {
1846 die($e->getMessage()); 1845 die($e->getMessage());
1847} 1846}
1848 1847
@@ -1861,7 +1860,7 @@ $container['history'] = $history;
1861$app = new \Slim\App($container); 1860$app = new \Slim\App($container);
1862 1861
1863// REST API routes 1862// REST API routes
1864$app->group('/api/v1', function() { 1863$app->group('/api/v1', function () {
1865 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo'); 1864 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1866 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks'); 1865 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1867 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink'); 1866 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');