]> git.mxchange.org Git - friendica.git/blob - src/App/BaseURL.php
Remove unused cached avatar photo entries
[friendica.git] / src / App / BaseURL.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\IConfig;
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 IConfig
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()
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()
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()
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()
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($ssl = false)
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          */
172         public function save($hostname = null, $sslPolicy = null, $urlPath = null)
173         {
174                 $currHostname  = $this->hostname;
175                 $currSSLPolicy = $this->sslPolicy;
176                 $currURLPath   = $this->urlPath;
177
178                 if (!empty($hostname) && $hostname !== $this->hostname) {
179                         if ($this->config->set('config', 'hostname', $hostname)) {
180                                 $this->hostname = $hostname;
181                         } else {
182                                 return false;
183                         }
184                 }
185
186                 if (isset($sslPolicy) && $sslPolicy !== $this->sslPolicy) {
187                         if ($this->config->set('system', 'ssl_policy', $sslPolicy)) {
188                                 $this->sslPolicy = $sslPolicy;
189                         } else {
190                                 $this->hostname = $currHostname;
191                                 $this->config->set('config', 'hostname', $this->hostname);
192                                 return false;
193                         }
194                 }
195
196                 if (isset($urlPath) && $urlPath !== $this->urlPath) {
197                         if ($this->config->set('system', 'urlpath', $urlPath)) {
198                                 $this->urlPath = $urlPath;
199                         } else {
200                                 $this->hostname  = $currHostname;
201                                 $this->sslPolicy = $currSSLPolicy;
202                                 $this->config->set('config', 'hostname', $this->hostname);
203                                 $this->config->set('system', 'ssl_policy', $this->sslPolicy);
204                                 return false;
205                         }
206                 }
207
208                 $this->determineBaseUrl();
209                 if (!$this->config->set('system', 'url', $this->url)) {
210                         $this->hostname  = $currHostname;
211                         $this->sslPolicy = $currSSLPolicy;
212                         $this->urlPath   = $currURLPath;
213                         $this->determineBaseUrl();
214
215                         $this->config->set('config', 'hostname', $this->hostname);
216                         $this->config->set('system', 'ssl_policy', $this->sslPolicy);
217                         $this->config->set('system', 'urlpath', $this->urlPath);
218                         return false;
219                 }
220
221                 return true;
222         }
223
224         /**
225          * Save the current url as base URL
226          *
227          * @param $url
228          *
229          * @return bool true, if the save was successful
230          */
231         public function saveByURL($url)
232         {
233                 $parsed = @parse_url($url);
234
235                 if (empty($parsed)) {
236                         return false;
237                 }
238
239                 $hostname = $parsed['host'];
240                 if (!empty($hostname) && !empty($parsed['port'])) {
241                         $hostname .= ':' . $parsed['port'];
242                 }
243
244                 $urlPath = null;
245                 if (!empty($parsed['path'])) {
246                         $urlPath = trim($parsed['path'], '\\/');
247                 }
248
249                 $sslPolicy = null;
250                 if (!empty($parsed['scheme'])) {
251                         if ($parsed['scheme'] == 'https') {
252                                 $sslPolicy = BaseURL::SSL_POLICY_FULL;
253                         }
254                 }
255
256                 return $this->save($hostname, $sslPolicy, $urlPath);
257         }
258
259         /**
260          * Checks, if a redirect to the HTTPS site would be necessary
261          *
262          * @return bool
263          */
264         public function checkRedirectHttps()
265         {
266                 return $this->config->get('system', 'force_ssl') &&
267                        ($this->getScheme() == "http") &&
268                        intval($this->getSSLPolicy()) == BaseURL::SSL_POLICY_FULL &&
269                        strpos($this->get(), 'https://') === 0 &&
270                        !empty($this->server['REQUEST_METHOD']) &&
271                        $this->server['REQUEST_METHOD'] === 'GET';
272         }
273
274         /**
275          * @param IConfig $config The Friendica IConfiguration
276          * @param array   $server The $_SERVER array
277          */
278         public function __construct(IConfig $config, array $server)
279         {
280                 $this->config = $config;
281                 $this->server = $server;
282
283                 $this->determineSchema();
284                 $this->checkConfig();
285         }
286
287         /**
288          * Check the current config during loading
289          */
290         public function checkConfig()
291         {
292                 $this->hostname  = $this->config->get('config', 'hostname');
293                 $this->urlPath   = $this->config->get('system', 'urlpath');
294                 $this->sslPolicy = $this->config->get('system', 'ssl_policy');
295                 $this->url       = $this->config->get('system', 'url');
296
297                 if (empty($this->hostname)) {
298                         $this->determineHostname();
299
300                         if (!empty($this->hostname)) {
301                                 $this->config->set('config', 'hostname', $this->hostname);
302                         }
303                 }
304
305                 if (!isset($this->urlPath)) {
306                         $this->determineURLPath();
307                         $this->config->set('system', 'urlpath', $this->urlPath);
308                 }
309
310                 if (!isset($this->sslPolicy)) {
311                         if ($this->scheme == 'https') {
312                                 $this->sslPolicy = self::SSL_POLICY_FULL;
313                         } else {
314                                 $this->sslPolicy = self::DEFAULT_SSL_SCHEME;
315                         }
316                         $this->config->set('system', 'ssl_policy', $this->sslPolicy);
317                 }
318
319                 if (empty($this->url)) {
320                         $this->determineBaseUrl();
321
322                         if (!empty($this->url)) {
323                                 $this->config->set('system', 'url', $this->url);
324                         }
325                 }
326         }
327
328         /**
329          * Determines the hostname of this node if not set already
330          */
331         private function determineHostname()
332         {
333                 $this->hostname = '';
334
335                 if (!empty($this->server['SERVER_NAME'])) {
336                         $this->hostname = $this->server['SERVER_NAME'];
337
338                         if (!empty($this->server['SERVER_PORT']) && $this->server['SERVER_PORT'] != 80 && $this->server['SERVER_PORT'] != 443) {
339                                 $this->hostname .= ':' . $this->server['SERVER_PORT'];
340                         }
341                 }
342         }
343
344         /**
345          * Figure out if we are running at the top of a domain or in a sub-directory
346          */
347         private function determineURLPath()
348         {
349                 $this->urlPath = '';
350
351                 /*
352                  * The automatic path detection in this function is currently deactivated,
353                  * see issue https://github.com/friendica/friendica/issues/6679
354                  *
355                  * The problem is that the function seems to be confused with some url.
356                  * These then confuses the detection which changes the url path.
357                  */
358
359                 /* Relative script path to the web server root
360                  * Not all of those $_SERVER properties can be present, so we do by inverse priority order
361                  */
362                 $relative_script_path =
363                         ($this->server['REDIRECT_URL']        ?? '') ?:
364                         ($this->server['REDIRECT_URI']        ?? '') ?:
365                         ($this->server['REDIRECT_SCRIPT_URL'] ?? '') ?:
366                         ($this->server['SCRIPT_URL']          ?? '') ?:
367                          $this->server['REQUEST_URI']         ?? '';
368
369                 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
370                  * QUERY_STRING gives pagename=module/parameter
371                  *
372                  * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
373                  */
374                 if (!empty($relative_script_path)) {
375                         // Module
376                         if (!empty($this->server['QUERY_STRING'])) {
377                                 $this->urlPath = trim(dirname($relative_script_path, substr_count(trim($this->server['QUERY_STRING'], '/'), '/') + 1), '/');
378                         } else {
379                                 // Root page
380                                 $this->urlPath = trim($relative_script_path, '/');
381                         }
382                 }
383         }
384
385         /**
386          * Determine the full URL based on all parts
387          */
388         private function determineBaseUrl()
389         {
390                 $scheme = 'http';
391
392                 if ($this->sslPolicy == self::SSL_POLICY_FULL) {
393                         $scheme = 'https';
394                 }
395
396                 $this->url = $scheme . '://' . $this->hostname . (!empty($this->urlPath) ? '/' . $this->urlPath : '');
397         }
398
399         /**
400          * Determine the scheme of the current used link
401          */
402         private function determineSchema()
403         {
404                 $this->scheme = 'http';
405
406                 if (!empty($this->server['HTTPS']) ||
407                     !empty($this->server['HTTP_FORWARDED']) && preg_match('/proto=https/', $this->server['HTTP_FORWARDED']) ||
408                     !empty($this->server['HTTP_X_FORWARDED_PROTO']) && $this->server['HTTP_X_FORWARDED_PROTO'] == 'https' ||
409                     !empty($this->server['HTTP_X_FORWARDED_SSL']) && $this->server['HTTP_X_FORWARDED_SSL'] == 'on' ||
410                     !empty($this->server['FRONT_END_HTTPS']) && $this->server['FRONT_END_HTTPS'] == 'on' ||
411                     !empty($this->server['SERVER_PORT']) && (intval($this->server['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
412                 ) {
413                         $this->scheme = 'https';
414                 }
415         }
416
417         /**
418          * Removes the base url from an url. This avoids some mixed content problems.
419          *
420          * @param string $origURL
421          *
422          * @return string The cleaned url
423          */
424         public function remove(string $origURL)
425         {
426                 // Remove the hostname from the url if it is an internal link
427                 $nurl = Strings::normaliseLink($origURL);
428                 $base = Strings::normaliseLink($this->get());
429                 $url  = str_replace($base . '/', '', $nurl);
430
431                 // if it is an external link return the orignal value
432                 if ($url == Strings::normaliseLink($origURL)) {
433                         return $origURL;
434                 } else {
435                         return $url;
436                 }
437         }
438
439         /**
440          * Redirects to another module relative to the current Friendica base URL.
441          * If you want to redirect to a external URL, use System::externalRedirectTo()
442          *
443          * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
444          * @param bool   $ssl   if true, base URL will try to get called with https:// (works just for relative paths)
445          *
446          * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
447          */
448         public function redirect($toUrl = '', $ssl = false)
449         {
450                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
451                         throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
452                 }
453
454                 $redirectTo = $this->get($ssl) . '/' . ltrim($toUrl, '/');
455                 System::externalRedirect($redirectTo);
456         }
457
458         /**
459          * Returns the base url as string
460          */
461         public function __toString()
462         {
463                 return $this->get();
464         }
465 }