3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\App;
24 use Friendica\Core\Config\Capability\IManageConfigValues;
25 use Friendica\Core\System;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Network\HTTPException;
31 * A class which checks and contains the basic
32 * environment for the BaseURL (url, urlpath, ssl_policy, hostname, scheme)
39 const SSL_POLICY_NONE = 0;
44 const SSL_POLICY_FULL = 1;
47 * SSL is optional, but preferred
49 const SSL_POLICY_SELFSIGN = 2;
52 * Define the Default SSL scheme
54 const DEFAULT_SSL_SCHEME = self::SSL_POLICY_SELFSIGN;
57 * The Friendica Config
59 * @var IManageConfigValues
64 * The server side variables
71 * The hostname of the Base URL
78 * The SSL_POLICY of the Base URL
85 * The URL sub-path of the Base URL
99 * The current scheme of this call
106 * Returns the hostname of this node
110 public function getHostname(): string
112 return $this->hostname;
116 * Returns the current scheme of this call
120 public function getScheme(): string
122 return $this->scheme;
126 * Returns the SSL policy of this node
130 public function getSSLPolicy(): int
132 return $this->sslPolicy;
136 * Returns the sub-path of this URL
140 public function getUrlPath(): string
142 return $this->urlPath;
146 * Returns the full URL of this call
148 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
150 * @param bool $ssl True, if ssl should get used
154 public function get(bool $ssl = false): string
156 if ($this->sslPolicy === self::SSL_POLICY_SELFSIGN && $ssl) {
157 return Network::switchScheme($this->url);
164 * Save current parts of the base Url
166 * @param string? $hostname
167 * @param int? $sslPolicy
168 * @param string? $urlPath
170 * @return bool true, if successful
171 * @TODO Find proper types
173 public function save($hostname = null, $sslPolicy = null, $urlPath = null): bool
175 $currUrl = $this->url;
177 $configTransaction = $this->config->beginTransaction();
179 if (!empty($hostname) && $hostname !== $this->hostname) {
180 $configTransaction->set('config', 'hostname', $hostname);
181 $this->hostname = $hostname;
184 if (isset($sslPolicy) && $sslPolicy !== $this->sslPolicy) {
185 $configTransaction->set('system', 'ssl_policy', $sslPolicy);
186 $this->sslPolicy = $sslPolicy;
189 if (isset($urlPath) && $urlPath !== $this->urlPath) {
190 $configTransaction->set('system', 'urlpath', $urlPath);
191 $this->urlPath = $urlPath;
194 $this->determineBaseUrl();
195 if ($this->url !== $currUrl) {
196 $configTransaction->set('system', 'url', $this->url);
199 $configTransaction->commit();
205 * Save the current url as base URL
209 * @return bool true, if the save was successful
211 public function saveByURL(string $url): bool
213 $parsed = @parse_url($url);
215 if (empty($parsed) || empty($parsed['host'])) {
219 $hostname = $parsed['host'];
220 if (!empty($hostname) && !empty($parsed['port'])) {
221 $hostname .= ':' . $parsed['port'];
225 if (!empty($parsed['path'])) {
226 $urlPath = trim($parsed['path'], '\\/');
230 if (!empty($parsed['scheme'])) {
231 if ($parsed['scheme'] == 'https') {
232 $sslPolicy = BaseURL::SSL_POLICY_FULL;
236 return $this->save($hostname, $sslPolicy, $urlPath);
240 * Checks, if a redirect to the HTTPS site would be necessary
244 public function checkRedirectHttps()
246 return $this->config->get('system', 'force_ssl') &&
247 ($this->getScheme() == "http") &&
248 intval($this->getSSLPolicy()) == BaseURL::SSL_POLICY_FULL &&
249 strpos($this->get(), 'https://') === 0 &&
250 !empty($this->server['REQUEST_METHOD']) &&
251 $this->server['REQUEST_METHOD'] === 'GET';
255 * @param IManageConfigValues $config The Friendica IConfiguration
256 * @param array $server The $_SERVER array
258 public function __construct(IManageConfigValues $config, array $server)
260 $this->config = $config;
261 $this->server = $server;
263 $this->determineSchema();
264 $this->checkConfig();
268 * Check the current config during loading
270 public function checkConfig()
272 $this->hostname = $this->config->get('config', 'hostname');
273 $this->urlPath = $this->config->get('system', 'urlpath');
274 $this->sslPolicy = $this->config->get('system', 'ssl_policy');
275 $this->url = $this->config->get('system', 'url');
277 if (empty($this->hostname)) {
278 $this->determineHostname();
280 if (!empty($this->hostname)) {
281 $this->config->set('config', 'hostname', $this->hostname);
285 if (!isset($this->urlPath)) {
286 $this->determineURLPath();
287 $this->config->set('system', 'urlpath', $this->urlPath);
290 if (!isset($this->sslPolicy)) {
291 if ($this->scheme == 'https') {
292 $this->sslPolicy = self::SSL_POLICY_FULL;
294 $this->sslPolicy = self::DEFAULT_SSL_SCHEME;
296 $this->config->set('system', 'ssl_policy', $this->sslPolicy);
299 if (empty($this->url)) {
300 $this->determineBaseUrl();
302 if (!empty($this->url)) {
303 $this->config->set('system', 'url', $this->url);
309 * Determines the hostname of this node if not set already
311 private function determineHostname()
313 $this->hostname = '';
315 if (!empty($this->server['SERVER_NAME'])) {
316 $this->hostname = $this->server['SERVER_NAME'];
318 if (!empty($this->server['SERVER_PORT']) && $this->server['SERVER_PORT'] != 80 && $this->server['SERVER_PORT'] != 443) {
319 $this->hostname .= ':' . $this->server['SERVER_PORT'];
325 * Figure out if we are running at the top of a domain or in a sub-directory
327 private function determineURLPath()
332 * The automatic path detection in this function is currently deactivated,
333 * see issue https://github.com/friendica/friendica/issues/6679
335 * The problem is that the function seems to be confused with some url.
336 * These then confuses the detection which changes the url path.
339 /* Relative script path to the web server root
340 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
342 $relative_script_path =
343 ($this->server['REDIRECT_URL'] ?? '') ?:
344 ($this->server['REDIRECT_URI'] ?? '') ?:
345 ($this->server['REDIRECT_SCRIPT_URL'] ?? '') ?:
346 ($this->server['SCRIPT_URL'] ?? '') ?:
347 $this->server['REQUEST_URI'] ?? '';
349 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
350 * QUERY_STRING gives pagename=module/parameter
352 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
354 if (!empty($relative_script_path)) {
356 if (!empty($this->server['QUERY_STRING'])) {
357 $this->urlPath = trim(dirname($relative_script_path, substr_count(trim($this->server['QUERY_STRING'], '/'), '/') + 1), '/');
360 $this->urlPath = trim($relative_script_path, '/');
366 * Determine the full URL based on all parts
368 private function determineBaseUrl()
372 if ($this->sslPolicy == self::SSL_POLICY_FULL) {
376 $this->url = $scheme . '://' . $this->hostname . (!empty($this->urlPath) ? '/' . $this->urlPath : '');
380 * Determine the scheme of the current used link
382 private function determineSchema()
384 $this->scheme = 'http';
386 if (!empty($this->server['HTTPS']) ||
387 !empty($this->server['HTTP_FORWARDED']) && preg_match('/proto=https/', $this->server['HTTP_FORWARDED']) ||
388 !empty($this->server['HTTP_X_FORWARDED_PROTO']) && $this->server['HTTP_X_FORWARDED_PROTO'] == 'https' ||
389 !empty($this->server['HTTP_X_FORWARDED_SSL']) && $this->server['HTTP_X_FORWARDED_SSL'] == 'on' ||
390 !empty($this->server['FRONT_END_HTTPS']) && $this->server['FRONT_END_HTTPS'] == 'on' ||
391 !empty($this->server['SERVER_PORT']) && (intval($this->server['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
393 $this->scheme = 'https';
398 * Removes the base url from an url. This avoids some mixed content problems.
400 * @param string $origURL
402 * @return string The cleaned url
404 public function remove(string $origURL): string
406 // Remove the hostname from the url if it is an internal link
407 $nurl = Strings::normaliseLink($origURL);
408 $base = Strings::normaliseLink($this->get());
409 $url = str_replace($base . '/', '', $nurl);
411 // if it is an external link return the orignal value
412 if ($url == Strings::normaliseLink($origURL)) {
420 * Redirects to another module relative to the current Friendica base URL.
421 * If you want to redirect to a external URL, use System::externalRedirectTo()
423 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
424 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
426 * @throws HTTPException\FoundException
427 * @throws HTTPException\MovedPermanentlyException
428 * @throws HTTPException\TemporaryRedirectException
430 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
432 public function redirect(string $toUrl = '', bool $ssl = false)
434 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
435 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
438 $redirectTo = $this->get($ssl) . '/' . ltrim($toUrl, '/');
439 System::externalRedirect($redirectTo);
443 * Returns the base url as string
445 public function __toString(): string
447 return (string) $this->get();