From 55f9dba230780a2826a36a7d1db1ebdd4557d87f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 16:18:08 +0200 Subject: [PATCH 1/9] Prepare App for further usage --- src/App.php | 231 ++++++++++++++++++++++++++-------------------------- 1 file changed, 114 insertions(+), 117 deletions(-) diff --git a/src/App.php b/src/App.php index 505f502e5..2b229bdf4 100644 --- a/src/App.php +++ b/src/App.php @@ -16,7 +16,6 @@ use Friendica\Core\L10n\L10n; use Friendica\Core\System; use Friendica\Core\Theme; use Friendica\Database\Database; -use Friendica\Database\DBA; use Friendica\Model\Profile; use Friendica\Module\Login; use Friendica\Module\Special\HTTPException as ModuleHTTPException; @@ -45,7 +44,7 @@ class App { /** @deprecated 2019.09 - use App\Arguments->getQueryString() */ public $query_string = ''; - public $page = []; + public $page = []; public $profile; public $profile_uid; public $user; @@ -54,7 +53,7 @@ class App public $contacts; public $page_contact; public $content; - public $data = []; + public $data = []; /** @deprecated 2019.09 - use App\Arguments->getCommand() */ public $cmd = ''; /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */ @@ -66,20 +65,20 @@ class App public $timezone; public $interactive = true; public $identities; - public $is_mobile = false; - public $is_tablet = false; - public $theme_info = []; + public $is_mobile = false; + public $is_tablet = false; + public $theme_info = []; public $category; // Allow themes to control internal parameters // by changing App values in theme.php - public $sourcename = ''; - public $videowidth = 425; - public $videoheight = 350; - public $force_max_items = 0; + public $sourcename = ''; + public $videowidth = 425; + public $videoheight = 350; + public $force_max_items = 0; public $theme_events_in_profile = true; - public $stylesheets = []; + public $stylesheets = []; public $footerScripts = []; /** @@ -218,9 +217,10 @@ class App * Inclusion is done in App->initHead(). * The path can be absolute or relative to the Friendica installation base folder. * + * @param string $path + * * @see initHead() * - * @param string $path */ public function registerStylesheet($path) { @@ -236,9 +236,10 @@ class App * Inclusion is done in App->initFooter(). * The path can be absolute or relative to the Friendica installation base folder. * + * @param string $path + * * @see initFooter() * - * @param string $path */ public function registerFooterScript($path) { @@ -250,35 +251,48 @@ class App public $queue; /** - * @brief App constructor. - * - * @param Database $database The Friendica Database - * @param Configuration $config The Configuration - * @param App\Mode $mode The mode of this Friendica app - * @param App\Router $router The router of this Friendica app - * @param BaseURL $baseURL The full base URL of this Friendica app - * @param LoggerInterface $logger The current app logger - * @param Profiler $profiler The profiler of this application - * @param L10n $l10n The translator instance - * - * @throws Exception if the Basepath is not usable + * @param Database $database The Friendica Database + * @param Configuration $config The Configuration + * @param App\Mode $mode The mode of this Friendica app + * @param App\Router $router The router of this Friendica app + * @param BaseURL $baseURL The full base URL of this Friendica app + * @param LoggerInterface $logger The current app logger + * @param Profiler $profiler The profiler of this application + * @param L10n $l10n The translator instance + * @param App\Arguments $args The Friendica Arguments of the call + * @param MobileDetect $mobileDetect A mobile detection class */ - public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args) + public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, MobileDetect $mobileDetect) { - $this->database = $database; - $this->config = $config; - $this->mode = $mode; - $this->router = $router; - $this->baseURL = $baseURL; - $this->profiler = $profiler; - $this->logger = $logger; - $this->l10n = $l10n; - $this->args = $args; + $this->database = $database; + $this->config = $config; + $this->mode = $mode; + $this->router = $router; + $this->baseURL = $baseURL; + $this->profiler = $profiler; + $this->logger = $logger; + $this->l10n = $l10n; + $this->args = $args; + $this->mobileDetect = $mobileDetect; - $this->profiler->reset(); + $this->cmd = $args->getCommand(); + $this->argv = $args->getArgv(); + $this->argc = $args->getArgc(); + $this->query_string = $args->getQueryString(); - $this->reload(); + $this->is_mobile = $mobileDetect->isMobile(); + $this->is_tablet = $mobileDetect->isTablet(); + $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest'; + + $this->load(); + } + + /** + * Load the whole app instance + */ + public function load() + { set_time_limit(0); // This has to be quite large to deal with embedded private photos @@ -290,31 +304,9 @@ class App . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR . $this->getBasePath()); - $this->cmd = $args->getCommand(); - $this->argv = $args->getArgv(); - $this->argc = $args->getArgc(); - $this->query_string = $args->getQueryString(); + $this->profiler->reset(); - // Detect mobile devices - $mobile_detect = new MobileDetect(); - - $this->mobileDetect = $mobile_detect; - - $this->is_mobile = $mobile_detect->isMobile(); - $this->is_tablet = $mobile_detect->isTablet(); - - $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest'; - - // Register template engines - Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine'); - } - - /** - * Reloads the whole app instance - */ - public function reload() - { - if ($this->getMode()->has(App\Mode::DBAVAILABLE)) { + if ($this->mode->has(App\Mode::DBAVAILABLE)) { $this->profiler->update($this->config); Core\Hook::loadHooks(); @@ -323,6 +315,8 @@ class App } $this->loadDefaultTimezone(); + // Register template engines + Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine'); } /** @@ -348,6 +342,7 @@ class App /** * Returns the scheme of the current call + * * @return string * * @deprecated 2019.06 - use BaseURL->getScheme() instead @@ -372,7 +367,7 @@ class App } /** - * @brief Initializes the baseurl components + * @brief Initializes the baseurl components * * Clears the baseurl cache to prevent inconsistencies * @@ -466,15 +461,15 @@ class App * being first */ $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [ - '$local_user' => local_user(), - '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION, - '$delitem' => $this->l10n->t('Delete this item?'), - '$update_interval' => $interval, - '$shortcut_icon' => $shortcut_icon, - '$touch_icon' => $touch_icon, - '$block_public' => intval($this->config->get('system', 'block_public')), - '$stylesheets' => $this->stylesheets, - ]) . $this->page['htmlhead']; + '$local_user' => local_user(), + '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION, + '$delitem' => $this->l10n->t('Delete this item?'), + '$update_interval' => $interval, + '$shortcut_icon' => $shortcut_icon, + '$touch_icon' => $touch_icon, + '$block_public' => intval($this->config->get('system', 'block_public')), + '$stylesheets' => $this->stylesheets, + ]) . $this->page['htmlhead']; } /** @@ -516,10 +511,10 @@ class App Core\Hook::callAll('footer', $this->page['footer']); - $tpl = Core\Renderer::getMarkupTemplate('footer.tpl'); + $tpl = Core\Renderer::getMarkupTemplate('footer.tpl'); $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [ - '$footerScripts' => $this->footerScripts, - ]) . $this->page['footer']; + '$footerScripts' => $this->footerScripts, + ]) . $this->page['footer']; } /** @@ -535,7 +530,7 @@ class App // Remove the hostname from the url if it is an internal link $nurl = Util\Strings::normaliseLink($origURL); $base = Util\Strings::normaliseLink($this->getBaseURL()); - $url = str_replace($base . '/', '', $nurl); + $url = str_replace($base . '/', '', $nurl); // if it is an external link return the orignal value if ($url == Util\Strings::normaliseLink($origURL)) { @@ -641,8 +636,8 @@ class App continue; } list($key, $val) = $data; - $meminfo[$key] = (int) trim(str_replace('kB', '', $val)); - $meminfo[$key] = (int) ($meminfo[$key] / 1024); + $meminfo[$key] = (int)trim(str_replace('kB', '', $val)); + $meminfo[$key] = (int)($meminfo[$key] / 1024); } if (!isset($meminfo['MemFree'])) { @@ -668,14 +663,14 @@ class App */ public function isMaxLoadReached() { - if ($this->isBackend()) { - $process = 'backend'; + if ($this->mode->isBackend()) { + $process = 'backend'; $maxsysload = intval($this->config->get('system', 'maxloadavg')); if ($maxsysload < 1) { $maxsysload = 50; } } else { - $process = 'frontend'; + $process = 'frontend'; $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend')); if ($maxsysload < 1) { $maxsysload = 50; @@ -685,7 +680,7 @@ class App $load = Core\System::currentLoad(); if ($load) { if (intval($load) > $maxsysload) { - Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.'); + $this->logger->info('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]); return true; } } @@ -697,6 +692,7 @@ class App * * @param string $command The command to execute * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ] + * * @throws HTTPException\InternalServerErrorException */ public function proc_run($command, $args) @@ -728,7 +724,7 @@ class App $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath()); } if (!is_resource($resource)) { - Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG); + $this->logger->debug('We got no resource for command.', ['cmd' => $cmdline]); return; } proc_close($resource); @@ -763,7 +759,7 @@ class App */ public function getCurrentTheme() { - if ($this->getMode()->isInstall()) { + if ($this->mode->isInstall()) { return ''; } @@ -799,8 +795,8 @@ class App if ($this->profile_uid && ($this->profile_uid != local_user())) { // Allow folks to override user themes and always use their own on their own site. // This works only if the user is on the same server - $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]); - if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) { + $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]); + if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) { $page_theme = $user['theme']; } } @@ -810,7 +806,7 @@ class App // Specific mobile theme override if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) { $system_mobile_theme = $this->config->get('system', 'mobile-theme'); - $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme); + $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme); // --- means same mobile theme as desktop if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') { @@ -826,9 +822,9 @@ class App $theme_name = Strings::sanitizeFilePathItem($theme_name); if ($theme_name - && in_array($theme_name, Theme::getAllowedList()) - && (file_exists('view/theme/' . $theme_name . '/style.css') - || file_exists('view/theme/' . $theme_name . '/style.php')) + && in_array($theme_name, Theme::getAllowedList()) + && (file_exists('view/theme/' . $theme_name . '/style.css') + || file_exists('view/theme/' . $theme_name . '/style.php')) ) { $this->currentTheme = $theme_name; } @@ -860,7 +856,7 @@ class App /** * @deprecated use Arguments->get() instead * - * @see App\Arguments + * @see App\Arguments */ public function getArgumentValue($position, $default = '') { @@ -902,7 +898,7 @@ class App try { // Missing DB connection: ERROR - if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) { + if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) { throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.'); } @@ -914,7 +910,7 @@ class App throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.'); } - if (!$this->getMode()->isInstall()) { + if (!$this->mode->isInstall()) { // Force SSL redirection if ($this->baseURL->checkRedirectHttps()) { System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString()); @@ -925,7 +921,7 @@ class App } // Exclude the backend processes from the session management - if (!$this->isBackend()) { + if (!$this->mode->isBackend()) { $stamp1 = microtime(true); session_start(); $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack()); @@ -936,7 +932,7 @@ class App Core\Worker::executeIfIdle(); } - if ($this->getMode()->isNormal()) { + if ($this->mode->isNormal()) { $requester = HTTPSignature::getSigner('', $_SERVER); if (!empty($requester)) { Profile::addVisitorCookieForHandle($requester); @@ -944,12 +940,12 @@ class App } // ZRL - if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) { + if (!empty($_GET['zrl']) && $this->mode->isNormal()) { if (!local_user()) { // Only continue when the given profile link seems valid // Valid profile links contain a path with "/profile/" and no query parameters if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") && - strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) { + strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) { if (Core\Session::get('visitor_home') != $_GET["zrl"]) { Core\Session::set('my_url', $_GET['zrl']); Core\Session::set('authenticated', 0); @@ -959,13 +955,13 @@ class App } else { // Someone came with an invalid parameter, maybe as a DDoS attempt // We simply stop processing here - Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG); + $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]); throw new HTTPException\ForbiddenException(); } } } - if (!empty($_GET['owt']) && $this->getMode()->isNormal()) { + if (!empty($_GET['owt']) && $this->mode->isNormal()) { $token = $_GET['owt']; Model\Profile::openWebAuthInit($token); } @@ -988,28 +984,28 @@ class App // in install mode, any url loads install module // but we need "view" module for stylesheet - if ($this->getMode()->isInstall() && $moduleName !== 'install') { + if ($this->mode->isInstall() && $moduleName !== 'install') { $this->internalRedirect('install'); - } elseif (!$this->getMode()->isInstall() && !$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') { + } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') { $this->internalRedirect('maintenance'); } else { $this->checkURL(); - Core\Update::check($this->getBasePath(), false, $this->getMode()); + Core\Update::check($this->getBasePath(), false, $this->mode); Core\Addon::loadAddons(); Core\Hook::loadHooks(); } $this->page = [ - 'aside' => '', - 'bottom' => '', - 'content' => '', - 'footer' => '', - 'htmlhead' => '', - 'nav' => '', - 'page_title' => '', + 'aside' => '', + 'bottom' => '', + 'content' => '', + 'footer' => '', + 'htmlhead' => '', + 'nav' => '', + 'page_title' => '', 'right_aside' => '', - 'template' => '', - 'title' => '' + 'template' => '', + 'title' => '' ]; // Compatibility with the Android Diaspora client @@ -1055,7 +1051,7 @@ class App // Let the module run it's internal process (init, get, post, ...) $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST); - } catch(HTTPException $e) { + } catch (HTTPException $e) { ModuleHTTPException::rawContent($e); } @@ -1067,15 +1063,15 @@ class App $arr = ['content' => $content]; Core\Hook::callAll($moduleClass . '_mod_content', $arr); $content = $arr['content']; - $arr = ['content' => call_user_func([$moduleClass, 'content'])]; + $arr = ['content' => call_user_func([$moduleClass, 'content'])]; Core\Hook::callAll($moduleClass . '_mod_aftercontent', $arr); $content .= $arr['content']; - } catch(HTTPException $e) { + } catch (HTTPException $e) { $content = ModuleHTTPException::content($e); } // initialise content region - if ($this->getMode()->isNormal()) { + if ($this->mode->isNormal()) { Core\Hook::callAll('page_content_top', $this->page['content']); } @@ -1102,7 +1098,7 @@ class App // Add the navigation (menu) template if ($moduleName != 'install' && $moduleName != 'maintenance') { $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []); - $this->page['nav'] = Content\Nav::build($this); + $this->page['nav'] = Content\Nav::build($this); } // Build the page - now that we have all the components @@ -1184,7 +1180,7 @@ class App * If you want to redirect to a external URL, use System::externalRedirectTo() * * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node) - * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths) + * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths) * * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node */ @@ -1194,7 +1190,7 @@ class App throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo"); } - $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/'); + $redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/'); Core\System::externalRedirect($redirectTo); } @@ -1203,6 +1199,7 @@ class App * Should only be used if it isn't clear if the URL is either internal or external * * @param string $toUrl The target URL + * * @throws HTTPException\InternalServerErrorException */ public function redirect($toUrl) From 4f0ee4df2790574c7af4c1e98f717b2ed4e59b91 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:04:36 +0200 Subject: [PATCH 2/9] Move $page initialization into constructor --- src/App.php | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/App.php b/src/App.php index 2b229bdf4..e9c43b21b 100644 --- a/src/App.php +++ b/src/App.php @@ -43,8 +43,8 @@ use Psr\Log\LoggerInterface; class App { /** @deprecated 2019.09 - use App\Arguments->getQueryString() */ - public $query_string = ''; - public $page = []; + public $query_string; + public $page; public $profile; public $profile_uid; public $user; @@ -285,6 +285,19 @@ class App $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest'; + $this->page = [ + 'aside' => '', + 'bottom' => '', + 'content' => '', + 'footer' => '', + 'htmlhead' => '', + 'nav' => '', + 'page_title' => '', + 'right_aside' => '', + 'template' => '', + 'title' => '' + ]; + $this->load(); } @@ -995,19 +1008,6 @@ class App Core\Hook::loadHooks(); } - $this->page = [ - 'aside' => '', - 'bottom' => '', - 'content' => '', - 'footer' => '', - 'htmlhead' => '', - 'nav' => '', - 'page_title' => '', - 'right_aside' => '', - 'template' => '', - 'title' => '' - ]; - // Compatibility with the Android Diaspora client if ($moduleName == 'stream') { $this->internalRedirect('network?order=post'); From fa1b783052a28d677b1da4ff8ff18021d5204452 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:10:14 +0200 Subject: [PATCH 3/9] removed static Logger usage --- src/App.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/App.php b/src/App.php index e9c43b21b..c9a66c523 100644 --- a/src/App.php +++ b/src/App.php @@ -612,10 +612,10 @@ class App $processlist = DBA::processlist(); if ($processlist['list'] != '') { - Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG); + $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']); if ($processlist['amount'] > $max_processes) { - Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG); + $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.'); return true; } } @@ -662,7 +662,7 @@ class App $reached = ($free < $min_memory); if ($reached) { - Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG); + $this->logger->debug('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]); } return $reached; From 08be92a86226fdad7f53e2b330fa0b5bd1388f0a Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:23:00 +0200 Subject: [PATCH 4/9] Moved BaseURL to App namespace (because similar type as Arguments/Modules/Modes) --- src/App.php | 18 ++--- src/{Util => App}/BaseURL.php | 65 ++++++++++++++----- src/Core/Session.php | 4 +- src/Core/System.php | 2 +- src/Model/Contact.php | 2 +- src/Module/Admin/Site.php | 11 ++-- src/Module/Install.php | 7 +- src/Protocol/DFRN.php | 2 +- static/dependencies.config.php | 6 +- .../AutomaticInstallationConsoleTest.php | 3 +- tests/src/Content/Text/BBCodeTest.php | 2 +- tests/src/Util/BaseURLTest.php | 2 +- 12 files changed, 73 insertions(+), 51 deletions(-) rename src/{Util => App}/BaseURL.php (82%) diff --git a/src/App.php b/src/App.php index c9a66c523..0a7bab0e1 100644 --- a/src/App.php +++ b/src/App.php @@ -9,6 +9,7 @@ use DOMDocument; use DOMXPath; use Exception; use Friendica\App\Arguments; +use Friendica\App\BaseURL; use Friendica\Core\Config\Cache\ConfigCache; use Friendica\Core\Config\Configuration; use Friendica\Core\Config\PConfiguration; @@ -20,7 +21,6 @@ use Friendica\Model\Profile; use Friendica\Module\Login; use Friendica\Module\Special\HTTPException as ModuleHTTPException; use Friendica\Network\HTTPException; -use Friendica\Util\BaseURL; use Friendica\Util\ConfigFileLoader; use Friendica\Util\HTTPSignature; use Friendica\Util\Profiler; @@ -536,21 +536,13 @@ class App * @param string $origURL * * @return string The cleaned url - * @throws HTTPException\InternalServerErrorException + * + * @deprecated 2019.09 - Use BaseURL->remove() instead + * @see BaseURL::remove() */ public function removeBaseURL($origURL) { - // Remove the hostname from the url if it is an internal link - $nurl = Util\Strings::normaliseLink($origURL); - $base = Util\Strings::normaliseLink($this->getBaseURL()); - $url = str_replace($base . '/', '', $nurl); - - // if it is an external link return the orignal value - if ($url == Util\Strings::normaliseLink($origURL)) { - return $origURL; - } else { - return $url; - } + return $this->baseURL->remove($origURL); } /** diff --git a/src/Util/BaseURL.php b/src/App/BaseURL.php similarity index 82% rename from src/Util/BaseURL.php rename to src/App/BaseURL.php index be34de30e..ad5fd0d4e 100644 --- a/src/Util/BaseURL.php +++ b/src/App/BaseURL.php @@ -1,8 +1,10 @@ hostname) { if ($this->config->set('config', 'hostname', $hostname)) { - $this->hostname = $hostname; + $this->hostname = $hostname; } else { return false; } @@ -153,7 +166,7 @@ class BaseURL if ($this->config->set('system', 'ssl_policy', $sslPolicy)) { $this->sslPolicy = $sslPolicy; } else { - $this->hostname = $currHostname; + $this->hostname = $currHostname; $this->config->set('config', 'hostname', $this->hostname); return false; } @@ -229,12 +242,12 @@ class BaseURL */ public function checkRedirectHttps() { - return $this->config->get('system', 'force_ssl') - && ($this->getScheme() == "http") - && intval($this->getSSLPolicy()) == BaseURL::SSL_POLICY_FULL - && strpos($this->get(), 'https://') === 0 - && !empty($this->server['REQUEST_METHOD']) - && $this->server['REQUEST_METHOD'] === 'GET'; + return $this->config->get('system', 'force_ssl') && + ($this->getScheme() == "http") && + intval($this->getSSLPolicy()) == BaseURL::SSL_POLICY_FULL && + strpos($this->get(), 'https://') === 0 && + !empty($this->server['REQUEST_METHOD']) && + $this->server['REQUEST_METHOD'] === 'GET'; } /** @@ -359,7 +372,7 @@ class BaseURL $scheme = 'https'; } - $this->url = $scheme . '://' . $this->hostname . (!empty($this->urlPath) ? '/' . $this->urlPath : '' ); + $this->url = $scheme . '://' . $this->hostname . (!empty($this->urlPath) ? '/' . $this->urlPath : ''); } /** @@ -370,13 +383,35 @@ class BaseURL $this->scheme = 'http'; if (!empty($this->server['HTTPS']) || - !empty($this->server['HTTP_FORWARDED']) && preg_match('/proto=https/', $this->server['HTTP_FORWARDED']) || - !empty($this->server['HTTP_X_FORWARDED_PROTO']) && $this->server['HTTP_X_FORWARDED_PROTO'] == 'https' || - !empty($this->server['HTTP_X_FORWARDED_SSL']) && $this->server['HTTP_X_FORWARDED_SSL'] == 'on' || - !empty($this->server['FRONT_END_HTTPS']) && $this->server['FRONT_END_HTTPS'] == 'on' || - !empty($this->server['SERVER_PORT']) && (intval($this->server['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much? + !empty($this->server['HTTP_FORWARDED']) && preg_match('/proto=https/', $this->server['HTTP_FORWARDED']) || + !empty($this->server['HTTP_X_FORWARDED_PROTO']) && $this->server['HTTP_X_FORWARDED_PROTO'] == 'https' || + !empty($this->server['HTTP_X_FORWARDED_SSL']) && $this->server['HTTP_X_FORWARDED_SSL'] == 'on' || + !empty($this->server['FRONT_END_HTTPS']) && $this->server['FRONT_END_HTTPS'] == 'on' || + !empty($this->server['SERVER_PORT']) && (intval($this->server['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much? ) { $this->scheme = 'https'; } } + + /** + * Removes the base url from an url. This avoids some mixed content problems. + * + * @param string $origURL + * + * @return string The cleaned url + */ + public function remove(string $origURL) + { + // Remove the hostname from the url if it is an internal link + $nurl = Strings::normaliseLink($origURL); + $base = Strings::normaliseLink($this->get()); + $url = str_replace($base . '/', '', $nurl); + + // if it is an external link return the orignal value + if ($url == Strings::normaliseLink($origURL)) { + return $origURL; + } else { + return $url; + } + } } diff --git a/src/Core/Session.php b/src/Core/Session.php index e54c0e49b..22909a6e6 100644 --- a/src/Core/Session.php +++ b/src/Core/Session.php @@ -9,9 +9,7 @@ use Friendica\App; use Friendica\Core\Session\CacheSessionHandler; use Friendica\Core\Session\DatabaseSessionHandler; use Friendica\Database\DBA; -use Friendica\Model\Contact; use Friendica\Model\User; -use Friendica\Util\BaseURL; use Friendica\Util\DateTimeFormat; /** @@ -30,7 +28,7 @@ class Session ini_set('session.use_only_cookies', 1); ini_set('session.cookie_httponly', 1); - if (Config::get('system', 'ssl_policy') == BaseURL::SSL_POLICY_FULL) { + if (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) { ini_set('session.cookie_secure', 1); } diff --git a/src/Core/System.php b/src/Core/System.php index 89526bdb4..0888f390a 100644 --- a/src/Core/System.php +++ b/src/Core/System.php @@ -4,9 +4,9 @@ */ namespace Friendica\Core; +use Friendica\App\BaseURL; use Friendica\BaseObject; use Friendica\Network\HTTPException\InternalServerErrorException; -use Friendica\Util\BaseURL; use Friendica\Util\XML; /** diff --git a/src/Model/Contact.php b/src/Model/Contact.php index f01cb7360..df3efa0c5 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -4,6 +4,7 @@ */ namespace Friendica\Model; +use Friendica\App\BaseURL; use Friendica\BaseObject; use Friendica\Content\Pager; use Friendica\Core\Config; @@ -22,7 +23,6 @@ use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; use Friendica\Protocol\PortableContact; use Friendica\Protocol\Salmon; -use Friendica\Util\BaseURL; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Strings; diff --git a/src/Module/Admin/Site.php b/src/Module/Admin/Site.php index c899729f8..dff869df2 100644 --- a/src/Module/Admin/Site.php +++ b/src/Module/Admin/Site.php @@ -14,7 +14,6 @@ use Friendica\Module\BaseAdminModule; use Friendica\Module\Register; use Friendica\Protocol\PortableContact; use Friendica\Util\BasePath; -use Friendica\Util\BaseURL; use Friendica\Util\Strings; use Friendica\Worker\Delivery; @@ -246,7 +245,7 @@ class Site extends BaseAdminModule $diaspora_enabled = false; } if ($ssl_policy != intval(Config::get('system', 'ssl_policy'))) { - if ($ssl_policy == BaseURL::SSL_POLICY_FULL) { + if ($ssl_policy == App\BaseURL::SSL_POLICY_FULL) { DBA::e("UPDATE `contact` SET `url` = REPLACE(`url` , 'http:' , 'https:'), `photo` = REPLACE(`photo` , 'http:' , 'https:'), @@ -264,7 +263,7 @@ class Site extends BaseAdminModule `thumb` = REPLACE(`thumb` , 'http:' , 'https:') WHERE 1 " ); - } elseif ($ssl_policy == BaseURL::SSL_POLICY_SELFSIGN) { + } elseif ($ssl_policy == App\BaseURL::SSL_POLICY_SELFSIGN) { DBA::e("UPDATE `contact` SET `url` = REPLACE(`url` , 'https:' , 'http:'), `photo` = REPLACE(`photo` , 'https:' , 'http:'), @@ -512,9 +511,9 @@ class Site extends BaseAdminModule ]; $ssl_choices = [ - BaseURL::SSL_POLICY_NONE => L10n::t('No SSL policy, links will track page SSL state'), - BaseURL::SSL_POLICY_FULL => L10n::t('Force all links to use SSL'), - BaseURL::SSL_POLICY_SELFSIGN => L10n::t('Self-signed certificate, use SSL for local links only (discouraged)') + App\BaseURL::SSL_POLICY_NONE => L10n::t('No SSL policy, links will track page SSL state'), + App\BaseURL::SSL_POLICY_FULL => L10n::t('Force all links to use SSL'), + App\BaseURL::SSL_POLICY_SELFSIGN => L10n::t('Self-signed certificate, use SSL for local links only (discouraged)') ]; $check_git_version_choices = [ diff --git a/src/Module/Install.php b/src/Module/Install.php index 3b8ebb471..7ba403966 100644 --- a/src/Module/Install.php +++ b/src/Module/Install.php @@ -10,7 +10,6 @@ use Friendica\Core\L10n; use Friendica\Core\Renderer; use Friendica\Network\HTTPException; use Friendica\Util\BasePath; -use Friendica\Util\BaseURL; use Friendica\Util\Strings; use Friendica\Util\Temporal; @@ -180,9 +179,9 @@ class Install extends BaseModule case self::BASE_CONFIG: $ssl_choices = [ - BaseURL::SSL_POLICY_NONE => L10n::t("No SSL policy, links will track page SSL state"), - BaseURL::SSL_POLICY_FULL => L10n::t("Force all links to use SSL"), - BaseURL::SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29") + App\BaseURL::SSL_POLICY_NONE => L10n::t("No SSL policy, links will track page SSL state"), + App\BaseURL::SSL_POLICY_FULL => L10n::t("Force all links to use SSL"), + App\BaseURL::SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29") ]; $tpl = Renderer::getMarkupTemplate('install_base.tpl'); diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 2abdfe148..273a7c248 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -11,6 +11,7 @@ namespace Friendica\Protocol; use DOMDocument; use DOMXPath; use Friendica\App; +use Friendica\App\BaseURL; use Friendica\Content\OEmbed; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; @@ -31,7 +32,6 @@ use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; -use Friendica\Util\BaseURL; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; diff --git a/static/dependencies.config.php b/static/dependencies.config.php index 7a4adb5ea..e32f99a60 100644 --- a/static/dependencies.config.php +++ b/static/dependencies.config.php @@ -85,12 +85,12 @@ return [ ], ], /** - * Creates the Util\BaseURL + * Creates the App\BaseURL * * Same as: - * $baseURL = new Util\BaseURL($configuration, $_SERVER); + * $baseURL = new App\BaseURL($configuration, $_SERVER); */ - Util\BaseURL::class => [ + App\BaseURL::class => [ 'constructParams' => [ $_SERVER, ], diff --git a/tests/src/Console/AutomaticInstallationConsoleTest.php b/tests/src/Console/AutomaticInstallationConsoleTest.php index a8c4894b9..774db3174 100644 --- a/tests/src/Console/AutomaticInstallationConsoleTest.php +++ b/tests/src/Console/AutomaticInstallationConsoleTest.php @@ -15,7 +15,6 @@ use Friendica\Test\Util\DBAMockTrait; use Friendica\Test\Util\DBStructureMockTrait; use Friendica\Test\Util\RendererMockTrait; use Friendica\Test\Util\VFSTrait; -use Friendica\Util\BaseURL; use Friendica\Util\Logger\VoidLogger; use Mockery\MockInterface; use org\bovigo\vfs\vfsStream; @@ -353,7 +352,7 @@ FIN; $this->assertConfigEntry('system', 'language', $assertion, ($default) ? Installer::DEFAULT_LANG : null); $this->assertConfigEntry('system', 'url', $assertion); $this->assertConfigEntry('system', 'urlpath', $assertion); - $this->assertConfigEntry('system', 'ssl_policy', $assertion, ($default) ? BaseURL::DEFAULT_SSL_SCHEME : null); + $this->assertConfigEntry('system', 'ssl_policy', $assertion, ($default) ? App\BaseURL::DEFAULT_SSL_SCHEME : null); $this->assertConfigEntry('system', 'basepath', ($realBasepath) ? $this->root->url() : $assertion); } diff --git a/tests/src/Content/Text/BBCodeTest.php b/tests/src/Content/Text/BBCodeTest.php index 6938f8ed5..899f32764 100644 --- a/tests/src/Content/Text/BBCodeTest.php +++ b/tests/src/Content/Text/BBCodeTest.php @@ -2,12 +2,12 @@ namespace Friendica\Test\src\Content\Text; +use Friendica\App\BaseURL; use Friendica\Content\Text\BBCode; use Friendica\Core\L10n\L10n; use Friendica\Test\MockedTest; use Friendica\Test\Util\AppMockTrait; use Friendica\Test\Util\VFSTrait; -use Friendica\Util\BaseURL; class BBCodeTest extends MockedTest { diff --git a/tests/src/Util/BaseURLTest.php b/tests/src/Util/BaseURLTest.php index 1e74af39f..7f63027fc 100644 --- a/tests/src/Util/BaseURLTest.php +++ b/tests/src/Util/BaseURLTest.php @@ -1,9 +1,9 @@ Date: Thu, 15 Aug 2019 17:23:35 +0200 Subject: [PATCH 5/9] Fixed wrong "BaseUrl" class (=> "BaseURL") --- src/App.php | 2 +- src/Core/Authentication.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index 0a7bab0e1..bb6d2a6e3 100644 --- a/src/App.php +++ b/src/App.php @@ -1131,7 +1131,7 @@ class App header("X-Friendica-Version: " . FRIENDICA_VERSION); header("Content-type: text/html; charset=utf-8"); - if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseUrl::SSL_POLICY_FULL)) { + if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) { header("Strict-Transport-Security: max-age=31536000"); } diff --git a/src/Core/Authentication.php b/src/Core/Authentication.php index e75cc93e7..d68a3e683 100644 --- a/src/Core/Authentication.php +++ b/src/Core/Authentication.php @@ -51,7 +51,7 @@ class Authentication extends BaseObject $value = ""; } - setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == BaseUrl::SSL_POLICY_FULL), true); + setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL), true); } /** From 956439a9f22c3a79f95e73b283ebd585f2c41301 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:25:03 +0200 Subject: [PATCH 6/9] reverted wrong indentation --- src/App.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/App.php b/src/App.php index bb6d2a6e3..d3b712509 100644 --- a/src/App.php +++ b/src/App.php @@ -53,7 +53,7 @@ class App public $contacts; public $page_contact; public $content; - public $data = []; + public $data = []; /** @deprecated 2019.09 - use App\Arguments->getCommand() */ public $cmd = ''; /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */ @@ -531,14 +531,14 @@ class App } /** - * @brief Removes the base url from an url. This avoids some mixed content problems. + * @brief Removes the base url from an url. This avoids some mixed content problems. * * @param string $origURL * * @return string The cleaned url * * @deprecated 2019.09 - Use BaseURL->remove() instead - * @see BaseURL::remove() + * @see BaseURL::remove() */ public function removeBaseURL($origURL) { @@ -567,7 +567,7 @@ class App * @return bool Is it a known backend? * * @deprecated 2019.09 - use App\Mode->isBackend() instead - * @see App\Mode::isBackend() + * @see App\Mode::isBackend() * Use BaseObject::getClass(App\Mode::class) to get the global instance of Mode */ public function isBackend() From ccbb0241bfc47e61c88c58a87110fd688234b3ae Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:27:05 +0200 Subject: [PATCH 7/9] Removed unnecessary auto-initializing --- src/App.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index d3b712509..8a2a20704 100644 --- a/src/App.php +++ b/src/App.php @@ -65,8 +65,8 @@ class App public $timezone; public $interactive = true; public $identities; - public $is_mobile = false; - public $is_tablet = false; + public $is_mobile; + public $is_tablet; public $theme_info = []; public $category; // Allow themes to control internal parameters From 290dd2ab39452b1e915c7511695a8077637a86fd Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:36:07 +0200 Subject: [PATCH 8/9] moved rest of BaseURL --- src/Console/AutomaticInstallation.php | 2 +- src/Core/Authentication.php | 1 - src/Factory/CacheFactory.php | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Console/AutomaticInstallation.php b/src/Console/AutomaticInstallation.php index 475e3e10c..0f1e7a742 100644 --- a/src/Console/AutomaticInstallation.php +++ b/src/Console/AutomaticInstallation.php @@ -4,12 +4,12 @@ namespace Friendica\Console; use Asika\SimpleConsole\Console; use Friendica\App; +use Friendica\App\BaseURL; use Friendica\Core\Config; use Friendica\Core\Installer; use Friendica\Core\Theme; use Friendica\Database\Database; use Friendica\Util\BasePath; -use Friendica\Util\BaseURL; use Friendica\Util\ConfigFileLoader; use RuntimeException; diff --git a/src/Core/Authentication.php b/src/Core/Authentication.php index d68a3e683..59061c04c 100644 --- a/src/Core/Authentication.php +++ b/src/Core/Authentication.php @@ -8,7 +8,6 @@ namespace Friendica\Core; use Friendica\App; use Friendica\BaseObject; use Friendica\Network\HTTPException\ForbiddenException; -use Friendica\Util\BaseURL; /** * Handle Authentification, Session and Cookies diff --git a/src/Factory/CacheFactory.php b/src/Factory/CacheFactory.php index 7b30c553e..39b0b94ff 100644 --- a/src/Factory/CacheFactory.php +++ b/src/Factory/CacheFactory.php @@ -2,11 +2,11 @@ namespace Friendica\Factory; +use Friendica\App\BaseURL; use Friendica\Core\Cache; use Friendica\Core\Cache\ICache; use Friendica\Core\Config\Configuration; use Friendica\Database\Database; -use Friendica\Util\BaseURL; use Friendica\Util\Profiler; use Psr\Log\LoggerInterface; From 822ba671055748f4d85658e96fbf383374022f74 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 15 Aug 2019 17:47:08 +0200 Subject: [PATCH 9/9] Fixing https://github.com/friendica/friendica/pull/7508#issuecomment-521679624 --- src/App.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/App.php b/src/App.php index 8a2a20704..749cbe9cc 100644 --- a/src/App.php +++ b/src/App.php @@ -262,7 +262,7 @@ class App * @param App\Arguments $args The Friendica Arguments of the call * @param MobileDetect $mobileDetect A mobile detection class */ - public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, MobileDetect $mobileDetect) + public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, MobileDetect $mobileDetect) { $this->database = $database; $this->config = $config; @@ -279,6 +279,7 @@ class App $this->argv = $args->getArgv(); $this->argc = $args->getArgc(); $this->query_string = $args->getQueryString(); + $this->module = $module->getName(); $this->is_mobile = $mobileDetect->isMobile(); $this->is_tablet = $mobileDetect->isTablet();