]> git.mxchange.org Git - friendica.git/blob - src/BaseModule.php
Merge remote-tracking branch 'origin/2022.12-rc' into fixes
[friendica.git] / src / BaseModule.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;
23
24 use Friendica\App\Router;
25 use Friendica\Capabilities\ICanHandleRequests;
26 use Friendica\Capabilities\ICanCreateResponses;
27 use Friendica\Core\Hook;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Logger;
30 use Friendica\Model\User;
31 use Friendica\Module\Response;
32 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
33 use Friendica\Network\HTTPException;
34 use Friendica\Util\Profiler;
35 use Psr\Http\Message\ResponseInterface;
36 use Psr\Log\LoggerInterface;
37
38 /**
39  * All modules in Friendica should extend BaseModule, although not all modules
40  * need to extend all the methods described here
41  *
42  * The filename of the module in src/Module needs to match the class name
43  * exactly to make the module available.
44  *
45  * @author Hypolite Petovan <hypolite@mrpetovan.com>
46  */
47 abstract class BaseModule implements ICanHandleRequests
48 {
49         /** @var array */
50         protected $parameters = [];
51         /** @var L10n */
52         protected $l10n;
53         /** @var App\BaseURL */
54         protected $baseUrl;
55         /** @var App\Arguments */
56         protected $args;
57         /** @var LoggerInterface */
58         protected $logger;
59         /** @var Profiler */
60         protected $profiler;
61         /** @var array */
62         protected $server;
63         /** @var ICanCreateResponses */
64         protected $response;
65
66         public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
67         {
68                 $this->parameters = $parameters;
69                 $this->l10n       = $l10n;
70                 $this->baseUrl    = $baseUrl;
71                 $this->args       = $args;
72                 $this->logger     = $logger;
73                 $this->profiler   = $profiler;
74                 $this->server     = $server;
75                 $this->response   = $response;
76         }
77
78         /**
79          * Wraps the L10n::t() function for Modules
80          *
81          * @see L10n::t()
82          */
83         protected function t(string $s, ...$args): string
84         {
85                 return $this->l10n->t($s, ...$args);
86         }
87
88         /**
89          * Wraps the L10n::tt() function for Modules
90          *
91          * @see L10n::tt()
92          */
93         protected function tt(string $singular, string $plurarl, int $count): string
94         {
95                 return $this->l10n->tt($singular, $plurarl, $count);
96         }
97
98         /**
99          * Module GET method to display raw content from technical endpoints
100          *
101          * Extend this method if the module is supposed to return communication data,
102          * e.g. from protocol implementations.
103          *
104          * @param string[] $request The $_REQUEST content
105          * @return void
106          */
107         protected function rawContent(array $request = [])
108         {
109                 // echo '';
110                 // exit;
111         }
112
113         /**
114          * Module GET method to display any content
115          *
116          * Extend this method if the module is supposed to return any display
117          * through a GET request. It can be an HTML page through templating or a
118          * XML feed or a JSON output.
119          *
120          * @param string[] $request The $_REQUEST content
121          * @return string
122          */
123         protected function content(array $request = []): string
124         {
125                 return '';
126         }
127
128         /**
129          * Module DELETE method to process submitted data
130          *
131          * Extend this method if the module is supposed to process DELETE requests.
132          * Doesn't display any content
133          *
134          * @param string[] $request The $_REQUEST content
135          * @return void
136          */
137         protected function delete(array $request = [])
138         {
139         }
140
141         /**
142          * Module PATCH method to process submitted data
143          *
144          * Extend this method if the module is supposed to process PATCH requests.
145          * Doesn't display any content
146          *
147          * @param string[] $request The $_REQUEST content
148          * @return void
149          */
150         protected function patch(array $request = [])
151         {
152         }
153
154         /**
155          * Module POST method to process submitted data
156          *
157          * Extend this method if the module is supposed to process POST requests.
158          * Doesn't display any content
159          *
160          * @param string[] $request The $_REQUEST content
161          * @return void
162          */
163         protected function post(array $request = [])
164         {
165                 // $this->baseUrl->redirect('module');
166         }
167
168         /**
169          * Module PUT method to process submitted data
170          *
171          * Extend this method if the module is supposed to process PUT requests.
172          * Doesn't display any content
173          *
174          * @param string[] $request The $_REQUEST content
175          * @return void
176          */
177         protected function put(array $request = [])
178         {
179         }
180
181         /**
182          * {@inheritDoc}
183          */
184         public function run(array $request = []): ResponseInterface
185         {
186                 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
187                 if (substr($this->args->getQueryString(), 0, 12) == '.well-known/') {
188                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
189                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
190                         $this->response->setHeader(Router::GET, 'Access-Control-Allow-Methods');
191                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
192                 } elseif (substr($this->args->getQueryString(), 0, 8) == 'profile/') {
193                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
194                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
195                         $this->response->setHeader(Router::GET, 'Access-Control-Allow-Methods');
196                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
197                 } elseif (substr($this->args->getQueryString(), 0, 4) == 'api/') {
198                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
199                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
200                         $this->response->setHeader(implode(',', Router::ALLOWED_METHODS), 'Access-Control-Allow-Methods');
201                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
202                         $this->response->setHeader('Link', 'Access-Control-Expose-Headers');
203                 } elseif (substr($this->args->getQueryString(), 0, 11) == 'oauth/token') {
204                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
205                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
206                         $this->response->setHeader(Router::POST, 'Access-Control-Allow-Methods');
207                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
208                 }
209
210                 $placeholder = '';
211
212                 $this->profiler->set(microtime(true), 'ready');
213                 $timestamp = microtime(true);
214
215                 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
216
217                 $this->profiler->set(microtime(true) - $timestamp, 'init');
218
219                 switch ($this->args->getMethod()) {
220                         case Router::DELETE:
221                                 $this->delete($request);
222                                 break;
223                         case Router::PATCH:
224                                 $this->patch($request);
225                                 break;
226                         case Router::POST:
227                                 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $request);
228                                 $this->post($request);
229                                 break;
230                         case Router::PUT:
231                                 $this->put($request);
232                                 break;
233                 }
234
235                 $timestamp = microtime(true);
236                 // "rawContent" is especially meant for technical endpoints.
237                 // This endpoint doesn't need any theme initialization or other comparable stuff.
238                 $this->rawContent($request);
239
240                 try {
241                         $arr = ['content' => ''];
242                         Hook::callAll(static::class . '_mod_content', $arr);
243                         $this->response->addContent($arr['content']);
244                         $this->response->addContent($this->content($request));
245                 } catch (HTTPException $e) {
246                         $this->response->addContent((new ModuleHTTPException())->content($e));
247                 } finally {
248                         $this->profiler->set(microtime(true) - $timestamp, 'content');
249                 }
250
251                 return $this->response->generate();
252         }
253
254         /**
255          * Checks request inputs and sets default parameters
256          *
257          * @param array $defaults Associative array of expected request keys and their default typed value. A null
258          *                        value will remove the request key from the resulting value array.
259          * @param array $input    Custom REQUEST array, superglobal instead
260          *
261          * @return array Request data
262          */
263         protected function checkDefaults(array $defaults, array $input): array
264         {
265                 $request = [];
266
267                 foreach ($defaults as $parameter => $defaultvalue) {
268                         $request[$parameter] = $this->getRequestValue($input, $parameter, $defaultvalue);
269                 }
270
271                 foreach ($input ?? [] as $parameter => $value) {
272                         if ($parameter == 'pagename') {
273                                 continue;
274                         }
275                         if (!in_array($parameter, array_keys($defaults))) {
276                                 $this->logger->notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => $this->args->getCommand()]);
277                         }
278                 }
279
280                 $this->logger->debug('Got request parameters', ['request' => $request, 'command' => $this->args->getCommand()]);
281                 return $request;
282         }
283
284         /**
285          * Fetch a request value and apply default values and check against minimal and maximal values
286          *
287          * @param array $input Input fields
288          * @param string $parameter Parameter
289          * @param mixed $default Default
290          * @param mixed $minimal_value Minimal value
291          * @param mixed $maximum_value Maximum value
292          * @return mixed null on error anything else on success (?)
293          */
294         public function getRequestValue(array $input, string $parameter, $default = null, $minimal_value = null, $maximum_value = null)
295         {
296                 if (is_string($default)) {
297                         $value = (string)($input[$parameter] ?? $default);
298                 } elseif (is_int($default)) {
299                         $value = filter_var($input[$parameter] ?? $default, FILTER_VALIDATE_INT);
300                         if (!is_null($minimal_value)) {
301                                 $value = max(filter_var($minimal_value, FILTER_VALIDATE_INT), $value);
302                         }
303                         if (!is_null($maximum_value)) {
304                                 $value = min(filter_var($maximum_value, FILTER_VALIDATE_INT), $value);
305                         }
306                 } elseif (is_float($default)) {
307                         $value = filter_var($input[$parameter] ?? $default, FILTER_VALIDATE_FLOAT);
308                         if (!is_null($minimal_value)) {
309                                 $value = max(filter_var($minimal_value, FILTER_VALIDATE_FLOAT), $value);
310                         }
311                         if (!is_null($maximum_value)) {
312                                 $value = min(filter_var($maximum_value, FILTER_VALIDATE_FLOAT), $value);
313                         }
314                 } elseif (is_array($default)) {
315                         $value = filter_var($input[$parameter] ?? $default, FILTER_DEFAULT, ['flags' => FILTER_FORCE_ARRAY]);
316                 } elseif (is_bool($default)) {
317                         $value = filter_var($input[$parameter] ?? $default, FILTER_VALIDATE_BOOLEAN);
318                 } elseif (is_null($default)) {
319                         $value = $input[$parameter] ?? null;
320                 } else {
321                         $this->logger->notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($default)]);
322                         $value = null;
323                 }
324
325                 return $value;
326         }
327
328         /**
329          * Functions used to protect against Cross-Site Request Forgery
330          * The security token has to base on at least one value that an attacker can't know - here it's the session ID and the private key.
331          * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
332          * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
333          * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
334          *    A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
335          *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
336          *    Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
337          *    so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types).
338          *
339          * @param string $typename Type name
340          * @return string Security hash with timestamp
341          */
342         public static function getFormSecurityToken(string $typename = ''): string
343         {
344                 $user      = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
345                 $timestamp = time();
346                 $sec_hash  = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
347
348                 return $timestamp . '.' . $sec_hash;
349         }
350
351         /**
352          * Checks if form's security (CSRF) token is valid.
353          *
354          * @param string $typename ???
355          * @param string $formname Name of form/field (???)
356          * @return bool Whether it is valid
357          */
358         public static function checkFormSecurityToken(string $typename = '', string $formname = 'form_security_token'): bool
359         {
360                 $hash = null;
361
362                 if (!empty($_REQUEST[$formname])) {
363                         /// @TODO Careful, not secured!
364                         $hash = $_REQUEST[$formname];
365                 }
366
367                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
368                         /// @TODO Careful, not secured!
369                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
370                 }
371
372                 if (empty($hash)) {
373                         return false;
374                 }
375
376                 $max_livetime = 10800; // 3 hours
377
378                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
379
380                 $x = explode('.', $hash);
381                 if (time() > (intval($x[0]) + $max_livetime)) {
382                         return false;
383                 }
384
385                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
386
387                 return ($sec_hash == $x[1]);
388         }
389
390         public static function getFormSecurityStandardErrorMessage(): string
391         {
392                 return DI::l10n()->t("The form security token was not correct. This probably happened because the form has been opened for too long \x28>3 hours\x29 before submitting it.");
393         }
394
395         public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token')
396         {
397                 if (!self::checkFormSecurityToken($typename, $formname)) {
398                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
399                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
400                         DI::sysmsg()->addNotice(self::getFormSecurityStandardErrorMessage());
401                         DI::baseUrl()->redirect($err_redirect);
402                 }
403         }
404
405         public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token')
406         {
407                 if (!self::checkFormSecurityToken($typename, $formname)) {
408                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
409                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
410
411                         throw new \Friendica\Network\HTTPException\ForbiddenException();
412                 }
413         }
414
415         protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab): array
416         {
417                 $tabs = [
418                         [
419                                 'label' => DI::l10n()->t('All contacts'),
420                                 'url'   => $baseUrl . '/contacts',
421                                 'sel'   => !$current || $current == 'all' ? 'active' : '',
422                         ],
423                         [
424                                 'label' => DI::l10n()->t('Followers'),
425                                 'url'   => $baseUrl . '/contacts/followers',
426                                 'sel'   => $current == 'followers' ? 'active' : '',
427                         ],
428                         [
429                                 'label' => DI::l10n()->t('Following'),
430                                 'url'   => $baseUrl . '/contacts/following',
431                                 'sel'   => $current == 'following' ? 'active' : '',
432                         ],
433                         [
434                                 'label' => DI::l10n()->t('Mutual friends'),
435                                 'url'   => $baseUrl . '/contacts/mutuals',
436                                 'sel'   => $current == 'mutuals' ? 'active' : '',
437                         ],
438                 ];
439
440                 if ($displayCommonTab) {
441                         $tabs[] = [
442                                 'label' => DI::l10n()->t('Common'),
443                                 'url'   => $baseUrl . '/contacts/common',
444                                 'sel'   => $current == 'common' ? 'active' : '',
445                         ];
446                 }
447
448                 return $tabs;
449         }
450 }