]> git.mxchange.org Git - friendica.git/blob - src/Module/Contact/Redir.php
Removed redundant maximagesize = INF statements
[friendica.git] / src / Module / Contact / Redir.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Module\Contact;
23
24 use Friendica\Core\L10n;
25 use Friendica\App;
26 use Friendica\Core\Session\Capability\IHandleUserSessions;
27 use Friendica\Database\Database;
28 use Friendica\Model\Contact;
29 use Friendica\Module\Response;
30 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
31 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
32 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
33 use Friendica\Network\HTTPException;
34 use Friendica\Util\Profiler;
35 use Friendica\Util\Strings;
36 use Psr\Log\LoggerInterface;
37
38 class Redir extends \Friendica\BaseModule
39 {
40         /** @var IHandleUserSessions */
41         private $session;
42         /** @var Database */
43         private $database;
44         /** @var App */
45         private $app;
46         /** @var ICanSendHttpRequests */
47         private $httpClient;
48
49         public function __construct(ICanSendHttpRequests $httpClient, App $app, Database $database, IHandleUserSessions $session, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
50         {
51                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
52
53                 $this->session    = $session;
54                 $this->database   = $database;
55                 $this->app        = $app;
56                 $this->httpClient = $httpClient;
57         }
58
59         protected function rawContent(array $request = [])
60         {
61                 if (!$this->session->isAuthenticated()) {
62                         throw new HTTPException\ForbiddenException($this->t('Access denied.'));
63                 }
64
65                 $url = $request['url'] ?? '';
66
67                 $cid = $this->parameters['id'] ?? 0;
68
69                 // Try magic auth before the legacy stuff
70                 $this->magic($cid, $url);
71
72                 $this->legacy($cid, $url);
73         }
74
75         /**
76          * @param int    $cid
77          * @param string $url
78          * @return void
79          * @throws HTTPException\ForbiddenException
80          * @throws HTTPException\InternalServerErrorException
81          * @throws HTTPException\NotFoundException
82          * @throws \ImagickException
83          */
84         private function magic(int $cid, string $url)
85         {
86                 $visitor = $this->session->getMyUrl();
87                 if (!empty($visitor)) {
88                         $this->logger->info('Got my url', ['visitor' => $visitor]);
89                 }
90
91                 $contact = $this->database->selectFirst('contact', ['url'], ['id' => $cid]);
92                 if (!$contact) {
93                         $this->logger->info('Contact not found', ['id' => $cid]);
94                         throw new HTTPException\NotFoundException($this->t('Contact not found.'));
95                 } else {
96                         $contact_url = $contact['url'];
97                         $this->checkUrl($contact_url, $url);
98                         $target_url = $url ?: $contact_url;
99                 }
100
101                 $basepath = Contact::getBasepath($contact_url);
102
103                 // We don't use magic auth when there is no visitor, we are on the same system, or we visit our own stuff
104                 if (empty($visitor) || Strings::compareLink($basepath, $this->baseUrl) || Strings::compareLink($contact_url, $visitor)) {
105                         $this->logger->info('Redirecting without magic', ['target' => $target_url, 'visitor' => $visitor, 'contact' => $contact_url]);
106                         $this->app->redirect($target_url);
107                 }
108
109                 // Test for magic auth on the target system
110                 $response = $this->httpClient->head($basepath . '/magic', [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::HTML]);
111                 if ($response->isSuccess()) {
112                         $separator = strpos($target_url, '?') ? '&' : '?';
113                         $target_url .= $separator . 'zrl=' . urlencode($visitor) . '&addr=' . urlencode($contact_url);
114
115                         $this->logger->info('Redirecting with magic', ['target' => $target_url, 'visitor' => $visitor, 'contact' => $contact_url]);
116                         $this->app->redirect($target_url);
117                 } else {
118                         $this->logger->info('No magic for contact', ['contact' => $contact_url]);
119                 }
120         }
121
122         /**
123          * @param int    $cid
124          * @param string $url
125          * @return void
126          * @throws HTTPException\BadRequestException
127          * @throws HTTPException\ForbiddenException
128          * @throws HTTPException\InternalServerErrorException
129          * @throws HTTPException\NotFoundException
130          */
131         private function legacy(int $cid, string $url): void
132         {
133                 if (empty($cid)) {
134                         throw new HTTPException\BadRequestException($this->t('Bad Request.'));
135                 }
136
137                 $fields  = ['id', 'uid', 'nurl', 'url', 'addr', 'name'];
138                 $contact = $this->database->selectFirst('contact', $fields, ['id' => $cid, 'uid' => [0, $this->session->getLocalUserId()]]);
139                 if (!$contact) {
140                         throw new HTTPException\NotFoundException($this->t('Contact not found.'));
141                 }
142
143                 $contact_url = $contact['url'];
144
145                 if (!empty($this->app->getContactId()) && $this->app->getContactId() == $cid) {
146                         // Local user is already authenticated.
147                         $this->checkUrl($contact_url, $url);
148                         $this->app->redirect($url ?: $contact_url);
149                 }
150
151                 if ($contact['uid'] == 0 && $this->session->getLocalUserId()) {
152                         // Let's have a look if there is an established connection
153                         // between the public contact we have found and the local user.
154                         $contact = $this->database->selectFirst('contact', $fields, ['nurl' => $contact['nurl'], 'uid' => $this->session->getLocalUserId()]);
155                         if ($contact) {
156                                 $cid = $contact['id'];
157                         }
158
159                         if (!empty($this->app->getContactId()) && $this->app->getContactId() == $cid) {
160                                 // Local user is already authenticated.
161                                 $this->checkUrl($contact_url, $url);
162                                 $target_url = $url ?: $contact_url;
163                                 $this->logger->info($contact['name'] . " is already authenticated. Redirecting to " . $target_url);
164                                 $this->app->redirect($target_url);
165                         }
166                 }
167
168                 if ($this->session->getRemoteUserId()) {
169                         $host       = substr($this->baseUrl->getUrlPath() . ($this->baseUrl->getUrlPath() ? '/' . $this->baseUrl->getUrlPath() : ''), strpos($this->baseUrl->getUrlPath(), '://') + 3);
170                         $remotehost = substr($contact['addr'], strpos($contact['addr'], '@') + 1);
171
172                         // On a local instance we have to check if the local user has already authenticated
173                         // with the local contact. Otherwise, the local user would ask the local contact
174                         // for authentification everytime he/she is visiting a profile page of the local
175                         // contact.
176                         if (($host == $remotehost) && ($this->session->getRemoteContactID($this->session->get('visitor_visiting')) == $this->session->get('visitor_id'))) {
177                                 // Remote user is already authenticated.
178                                 $this->checkUrl($contact_url, $url);
179                                 $target_url = $url ?: $contact_url;
180                                 $this->logger->info($contact['name'] . " is already authenticated. Redirecting to " . $target_url);
181                                 $this->app->redirect($target_url);
182                         }
183                 }
184
185                 if (empty($url)) {
186                         throw new HTTPException\BadRequestException($this->t('Bad Request.'));
187                 }
188
189                 // If we don't have a connected contact, redirect with
190                 // the 'zrl' parameter.
191                 $my_profile = $this->session->getMyUrl();
192
193                 if (!empty($my_profile) && !Strings::compareLink($my_profile, $url)) {
194                         $separator = strpos($url, '?') ? '&' : '?';
195
196                         $url .= $separator . 'zrl=' . urlencode($my_profile);
197                 }
198
199                 $this->logger->info('redirecting to ' . $url);
200                 $this->app->redirect($url);
201         }
202
203
204         private function checkUrl(string $contact_url, string $url)
205         {
206                 if (empty($contact_url) || empty($url)) {
207                         return;
208                 }
209
210                 $url_host = parse_url($url, PHP_URL_HOST);
211                 if (empty($url_host)) {
212                         $url_host = parse_url($this->baseUrl, PHP_URL_HOST);
213                 }
214
215                 $contact_url_host = parse_url($contact_url, PHP_URL_HOST);
216
217                 if ($url_host == $contact_url_host) {
218                         return;
219                 }
220
221                 $this->logger->error('URL check host mismatch', ['contact' => $contact_url, 'url' => $url]);
222                 throw new HTTPException\ForbiddenException($this->t('Access denied.'));
223         }
224 }