]> git.mxchange.org Git - friendica.git/blob - src/App/BaseURL.php
Create specific module to display HTML message when a conversation isn't found in...
[friendica.git] / src / App / BaseURL.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\App;
23
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;
29
30 /**
31  * A class which checks and contains the basic
32  * environment for the BaseURL (url, urlpath, ssl_policy, hostname, scheme)
33  */
34 class BaseURL
35 {
36         /**
37          * No SSL necessary
38          */
39         const SSL_POLICY_NONE = 0;
40
41         /**
42          * SSL is necessary
43          */
44         const SSL_POLICY_FULL = 1;
45
46         /**
47          * SSL is optional, but preferred
48          */
49         const SSL_POLICY_SELFSIGN = 2;
50
51         /**
52          * Define the Default SSL scheme
53          */
54         const DEFAULT_SSL_SCHEME = self::SSL_POLICY_SELFSIGN;
55
56         /**
57          * The Friendica Config
58          *
59          * @var IManageConfigValues
60          */
61         private $config;
62
63         /**
64          * The server side variables
65          *
66          * @var array
67          */
68         private $server;
69
70         /**
71          * The hostname of the Base URL
72          *
73          * @var string
74          */
75         private $hostname;
76
77         /**
78          * The SSL_POLICY of the Base URL
79          *
80          * @var int
81          */
82         private $sslPolicy;
83
84         /**
85          * The URL sub-path of the Base URL
86          *
87          * @var string
88          */
89         private $urlPath;
90
91         /**
92          * The full URL
93          *
94          * @var string
95          */
96         private $url;
97
98         /**
99          * The current scheme of this call
100          *
101          * @var string
102          */
103         private $scheme;
104
105         /**
106          * Returns the hostname of this node
107          *
108          * @return string
109          */
110         public function getHostname(): string
111         {
112                 return $this->hostname;
113         }
114
115         /**
116          * Returns the current scheme of this call
117          *
118          * @return string
119          */
120         public function getScheme(): string
121         {
122                 return $this->scheme;
123         }
124
125         /**
126          * Returns the SSL policy of this node
127          *
128          * @return int
129          */
130         public function getSSLPolicy(): int
131         {
132                 return $this->sslPolicy;
133         }
134
135         /**
136          * Returns the sub-path of this URL
137          *
138          * @return string
139          */
140         public function getUrlPath(): string
141         {
142                 return $this->urlPath;
143         }
144
145         /**
146          * Returns the full URL of this call
147          *
148          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
149          *
150          * @param bool $ssl True, if ssl should get used
151          *
152          * @return string
153          */
154         public function get(bool $ssl = false): string
155         {
156                 if ($this->sslPolicy === self::SSL_POLICY_SELFSIGN && $ssl) {
157                         return Network::switchScheme($this->url);
158                 }
159
160                 return $this->url;
161         }
162
163         /**
164          * Save current parts of the base Url
165          *
166          * @param string? $hostname
167          * @param int?    $sslPolicy
168          * @param string? $urlPath
169          *
170          * @return bool true, if successful
171          * @TODO Find proper types
172          */
173         public function save($hostname = null, $sslPolicy = null, $urlPath = null): bool
174         {
175                 $currUrl = $this->url;
176
177                 $configTransaction = $this->config->beginTransaction();
178
179                 if (!empty($hostname) && $hostname !== $this->hostname) {
180                         $configTransaction->set('config', 'hostname', $hostname);
181                         $this->hostname = $hostname;
182                 }
183
184                 if (isset($sslPolicy) && $sslPolicy !== $this->sslPolicy) {
185                         $configTransaction->set('system', 'ssl_policy', $sslPolicy);
186                         $this->sslPolicy = $sslPolicy;
187                 }
188
189                 if (isset($urlPath) && $urlPath !== $this->urlPath) {
190                         $configTransaction->set('system', 'urlpath', $urlPath);
191                         $this->urlPath = $urlPath;
192                 }
193
194                 $this->determineBaseUrl();
195                 if ($this->url !== $currUrl) {
196                         $configTransaction->set('system', 'url', $this->url);
197                 }
198
199                 $configTransaction->commit();
200
201                 return true;
202         }
203
204         /**
205          * Save the current url as base URL
206          *
207          * @param string $url
208          *
209          * @return bool true, if the save was successful
210          */
211         public function saveByURL(string $url): bool
212         {
213                 $parsed = @parse_url($url);
214
215                 if (empty($parsed) || empty($parsed['host'])) {
216                         return false;
217                 }
218
219                 $hostname = $parsed['host'];
220                 if (!empty($hostname) && !empty($parsed['port'])) {
221                         $hostname .= ':' . $parsed['port'];
222                 }
223
224                 $urlPath = null;
225                 if (!empty($parsed['path'])) {
226                         $urlPath = trim($parsed['path'], '\\/');
227                 }
228
229                 $sslPolicy = null;
230                 if (!empty($parsed['scheme'])) {
231                         if ($parsed['scheme'] == 'https') {
232                                 $sslPolicy = BaseURL::SSL_POLICY_FULL;
233                         }
234                 }
235
236                 return $this->save($hostname, $sslPolicy, $urlPath);
237         }
238
239         /**
240          * Checks, if a redirect to the HTTPS site would be necessary
241          *
242          * @return bool
243          */
244         public function checkRedirectHttps()
245         {
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';
252         }
253
254         /**
255          * @param IManageConfigValues $config The Friendica IConfiguration
256          * @param array               $server The $_SERVER array
257          */
258         public function __construct(IManageConfigValues $config, array $server)
259         {
260                 $this->config    = $config;
261                 $this->server    = $server;
262                 $this->hostname  = $this->config->get('config', 'hostname');
263                 $this->urlPath   = $this->config->get('system', 'urlpath') ?? '';
264                 $this->sslPolicy = $this->config->get('system', 'ssl_policy') ?? static::DEFAULT_SSL_SCHEME;
265                 $this->url       = $this->config->get('system', 'url');
266
267                 if (empty($this->hostname) || empty($this->url)) {
268                         throw new \Exception('Invalid config - Missing system.url or config.hostname');
269                 }
270
271                 $this->determineSchema();
272         }
273
274         /**
275          * Determine the full URL based on all parts
276          */
277         private function determineBaseUrl()
278         {
279                 $scheme = 'http';
280
281                 if ($this->sslPolicy == self::SSL_POLICY_FULL) {
282                         $scheme = 'https';
283                 }
284
285                 $this->url = $scheme . '://' . $this->hostname . (!empty($this->urlPath) ? '/' . $this->urlPath : '');
286         }
287
288         /**
289          * Determine the scheme of the current used link
290          */
291         private function determineSchema()
292         {
293                 $this->scheme = 'http';
294
295                 if (!empty($this->server['HTTPS']) ||
296                     !empty($this->server['HTTP_FORWARDED']) && preg_match('/proto=https/', $this->server['HTTP_FORWARDED']) ||
297                     !empty($this->server['HTTP_X_FORWARDED_PROTO']) && $this->server['HTTP_X_FORWARDED_PROTO'] == 'https' ||
298                     !empty($this->server['HTTP_X_FORWARDED_SSL']) && $this->server['HTTP_X_FORWARDED_SSL'] == 'on' ||
299                     !empty($this->server['FRONT_END_HTTPS']) && $this->server['FRONT_END_HTTPS'] == 'on' ||
300                     !empty($this->server['SERVER_PORT']) && (intval($this->server['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
301                 ) {
302                         $this->scheme = 'https';
303                 }
304         }
305
306         /**
307          * Removes the base url from an url. This avoids some mixed content problems.
308          *
309          * @param string $origURL
310          *
311          * @return string The cleaned url
312          */
313         public function remove(string $origURL): string
314         {
315                 // Remove the hostname from the url if it is an internal link
316                 $nurl = Strings::normaliseLink($origURL);
317                 $base = Strings::normaliseLink($this->get());
318                 $url  = str_replace($base . '/', '', $nurl);
319
320                 // if it is an external link return the orignal value
321                 if ($url == Strings::normaliseLink($origURL)) {
322                         return $origURL;
323                 } else {
324                         return $url;
325                 }
326         }
327
328         /**
329          * Redirects to another module relative to the current Friendica base URL.
330          * If you want to redirect to a external URL, use System::externalRedirectTo()
331          *
332          * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
333          * @param bool   $ssl   if true, base URL will try to get called with https:// (works just for relative paths)
334          *
335          * @throws HTTPException\FoundException
336          * @throws HTTPException\MovedPermanentlyException
337          * @throws HTTPException\TemporaryRedirectException
338          *
339          * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
340          */
341         public function redirect(string $toUrl = '', bool $ssl = false)
342         {
343                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
344                         throw new HTTPException\InternalServerErrorException("$toUrl is not a relative path, please use System::externalRedirectTo");
345                 }
346
347                 $redirectTo = $this->get($ssl) . '/' . ltrim($toUrl, '/');
348                 System::externalRedirect($redirectTo);
349         }
350
351         /**
352          * Returns the base url as string
353          */
354         public function __toString(): string
355         {
356                 return (string) $this->get();
357         }
358 }