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