3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
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;
41 * All modules in Friendica should extend BaseModule, although not all modules
42 * need to extend all the methods described here
44 * The filename of the module in src/Module needs to match the class name
45 * exactly to make the module available.
47 * @author Hypolite Petovan <hypolite@mrpetovan.com>
49 abstract class BaseModule implements ICanHandleRequests
52 protected $parameters = [];
55 /** @var App\BaseURL */
57 /** @var App\Arguments */
59 /** @var LoggerInterface */
65 /** @var ICanCreateResponses */
68 public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
70 $this->parameters = $parameters;
72 $this->baseUrl = $baseUrl;
74 $this->logger = $logger;
75 $this->profiler = $profiler;
76 $this->server = $server;
77 $this->response = $response;
81 * Wraps the L10n::t() function for Modules
85 protected function t(string $s, ...$args): string
87 return $this->l10n->t($s, ...$args);
91 * Wraps the L10n::tt() function for Modules
95 protected function tt(string $singular, string $plural, int $count): string
97 return $this->l10n->tt($singular, $plural, $count);
101 * Module GET method to display raw content from technical endpoints
103 * Extend this method if the module is supposed to return communication data,
104 * e.g. from protocol implementations.
106 * @param string[] $request The $_REQUEST content
109 protected function rawContent(array $request = [])
111 // $this->httpExit(...);
115 * Module GET method to display any content
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.
121 * @param string[] $request The $_REQUEST content
124 protected function content(array $request = []): string
130 * Module DELETE method to process submitted data
132 * Extend this method if the module is supposed to process DELETE requests.
133 * Doesn't display any content
135 * @param string[] $request The $_REQUEST content
138 protected function delete(array $request = [])
143 * Module PATCH method to process submitted data
145 * Extend this method if the module is supposed to process PATCH requests.
146 * Doesn't display any content
148 * @param string[] $request The $_REQUEST content
151 protected function patch(array $request = [])
156 * Module POST method to process submitted data
158 * Extend this method if the module is supposed to process POST requests.
159 * Doesn't display any content
161 * @param string[] $request The $_REQUEST content
164 protected function post(array $request = [])
166 // $this->baseUrl->redirect('module');
170 * Module PUT method to process submitted data
172 * Extend this method if the module is supposed to process PUT requests.
173 * Doesn't display any content
175 * @param string[] $request The $_REQUEST content
178 protected function put(array $request = [])
185 public function run(ModuleHTTPException $httpException, array $request = []): ResponseInterface
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');
213 $this->profiler->set(microtime(true), 'ready');
214 $timestamp = microtime(true);
216 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
218 $this->profiler->set(microtime(true) - $timestamp, 'init');
220 switch ($this->args->getMethod()) {
222 $this->delete($request);
225 $this->patch($request);
228 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $request);
229 $this->post($request);
232 $this->put($request);
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);
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)) {
256 $this->response->setStatus($e->getCode(), $e->getMessage());
257 $this->response->addContent($httpException->content($e));
259 $this->profiler->set(microtime(true) - $timestamp, 'content');
262 return $this->response->generate();
266 * Checks request inputs and sets default parameters
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
272 * @return array Request data
274 protected function checkDefaults(array $defaults, array $input): array
278 foreach ($defaults as $parameter => $defaultvalue) {
279 $request[$parameter] = $this->getRequestValue($input, $parameter, $defaultvalue);
282 foreach ($input ?? [] as $parameter => $value) {
283 if ($parameter == 'pagename') {
286 if (!in_array($parameter, array_keys($defaults))) {
287 $this->logger->notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => $this->args->getCommand()]);
291 $this->logger->debug('Got request parameters', ['request' => $request, 'command' => $this->args->getCommand()]);
296 * Fetch a request value and apply default values and check against minimal and maximal values
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 (?)
305 public function getRequestValue(array $input, string $parameter, $default = null, $minimal_value = null, $maximum_value = null)
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);
314 if (!is_null($maximum_value)) {
315 $value = min(filter_var($maximum_value, FILTER_VALIDATE_INT), $value);
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);
322 if (!is_null($maximum_value)) {
323 $value = min(filter_var($maximum_value, FILTER_VALIDATE_FLOAT), $value);
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;
332 $this->logger->notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($default)]);
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).
350 * @param string $typename Type name
351 * @return string Security hash with timestamp
353 public static function getFormSecurityToken(string $typename = ''): string
355 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
357 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
359 return $timestamp . '.' . $sec_hash;
363 * Checks if form's security (CSRF) token is valid.
365 * @param string $typename ???
366 * @param string $formname Name of form/field (???)
367 * @return bool Whether it is valid
369 public static function checkFormSecurityToken(string $typename = '', string $formname = 'form_security_token'): bool
373 if (!empty($_REQUEST[$formname])) {
374 /// @TODO Careful, not secured!
375 $hash = $_REQUEST[$formname];
378 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
379 /// @TODO Careful, not secured!
380 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
387 $max_livetime = 10800; // 3 hours
389 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
391 $x = explode('.', $hash);
392 if (time() > (intval($x[0]) + $max_livetime)) {
396 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
398 return ($sec_hash == $x[1]);
401 public static function getFormSecurityStandardErrorMessage(): string
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.");
406 public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token')
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);
416 public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token')
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]);
422 throw new \Friendica\Network\HTTPException\ForbiddenException();
426 protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab): array
430 'label' => DI::l10n()->t('All contacts'),
431 'url' => $baseUrl . '/contacts',
432 'sel' => !$current || $current == 'all' ? 'active' : '',
435 'label' => DI::l10n()->t('Followers'),
436 'url' => $baseUrl . '/contacts/followers',
437 'sel' => $current == 'followers' ? 'active' : '',
440 'label' => DI::l10n()->t('Following'),
441 'url' => $baseUrl . '/contacts/following',
442 'sel' => $current == 'following' ? 'active' : '',
445 'label' => DI::l10n()->t('Mutual friends'),
446 'url' => $baseUrl . '/contacts/mutuals',
447 'sel' => $current == 'mutuals' ? 'active' : '',
451 if ($displayCommonTab) {
453 'label' => DI::l10n()->t('Common'),
454 'url' => $baseUrl . '/contacts/common',
455 'sel' => $current == 'common' ? 'active' : '',
463 * This function adds the content and a content-type HTTP header to the output.
464 * After finishing the process is getting killed.
466 * @param string $content
467 * @param string $type
468 * @param string|null $content_type
470 * @throws HTTPException\InternalServerErrorException
472 public function httpExit(string $content, string $type = Response::TYPE_HTML, ?string $content_type = null)
474 $this->response->setType($type, $content_type);
475 $this->response->addContent($content);
476 System::echoResponse($this->response->generate());
482 * Send HTTP status header and exit.
484 * @param integer $httpCode HTTP status result value
485 * @param string $message Error message. Optional.
486 * @param mixed $content Response body. Optional.
489 public function httpError(int $httpCode, string $message = '', $content = '')
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'] ?? '']);
495 $this->response->setStatus($httpCode, $message);
497 $this->httpExit($content);
501 * Display the response using JSON to encode the content
503 * @param mixed $content
504 * @param string $content_type
505 * @param int $options A combination of json_encode() binary flags
507 * @throws HTTPException\InternalServerErrorException
510 public function jsonExit($content, string $content_type = 'application/json', int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
512 $this->httpExit(json_encode($content, $options), ICanCreateResponses::TYPE_JSON, $content_type);
516 * Display a non-200 HTTP code response using JSON to encode the content and exit
518 * @param int $httpCode
519 * @param mixed $content
520 * @param string $content_type
522 * @throws HTTPException\InternalServerErrorException
524 public function jsonError(int $httpCode, $content, string $content_type = 'application/json')
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'] ?? '']);
530 $this->response->setStatus($httpCode);
531 $this->jsonExit($content, $content_type);