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