3 * @copyright Copyright (C) 2010-2022, 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\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;
39 * All modules in Friendica should extend BaseModule, although not all modules
40 * need to extend all the methods described here
42 * The filename of the module in src/Module needs to match the class name
43 * exactly to make the module available.
45 * @author Hypolite Petovan <hypolite@mrpetovan.com>
47 abstract class BaseModule implements ICanHandleRequests
50 protected $parameters = [];
53 /** @var App\BaseURL */
55 /** @var App\Arguments */
57 /** @var LoggerInterface */
63 /** @var ICanCreateResponses */
66 public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
68 $this->parameters = $parameters;
70 $this->baseUrl = $baseUrl;
72 $this->logger = $logger;
73 $this->profiler = $profiler;
74 $this->server = $server;
75 $this->response = $response;
79 * Wraps the L10n::t() function for Modules
83 protected function t(string $s, ...$args): string
85 return $this->l10n->t($s, ...$args);
89 * Wraps the L10n::tt() function for Modules
93 protected function tt(string $singular, string $plurarl, int $count): string
95 return $this->l10n->tt($singular, $plurarl, $count);
99 * Module GET method to display raw content from technical endpoints
101 * Extend this method if the module is supposed to return communication data,
102 * e.g. from protocol implementations.
104 * @param string[] $request The $_REQUEST content
106 protected function rawContent(array $request = [])
113 * Module GET method to display any content
115 * Extend this method if the module is supposed to return any display
116 * through a GET request. It can be an HTML page through templating or a
117 * XML feed or a JSON output.
119 * @param string[] $request The $_REQUEST content
121 protected function content(array $request = []): string
127 * Module DELETE method to process submitted data
129 * Extend this method if the module is supposed to process DELETE requests.
130 * Doesn't display any content
132 * @param string[] $request The $_REQUEST content
134 protected function delete(array $request = [])
139 * Module PATCH method to process submitted data
141 * Extend this method if the module is supposed to process PATCH requests.
142 * Doesn't display any content
144 * @param string[] $request The $_REQUEST content
146 protected function patch(array $request = [])
151 * Module POST method to process submitted data
153 * Extend this method if the module is supposed to process POST requests.
154 * Doesn't display any content
156 * @param string[] $request The $_REQUEST content
159 protected function post(array $request = [])
161 // $this->baseUrl->redirect('module');
165 * Module PUT method to process submitted data
167 * Extend this method if the module is supposed to process PUT requests.
168 * Doesn't display any content
170 * @param string[] $request The $_REQUEST content
172 protected function put(array $request = [])
179 public function run(array $request = []): ResponseInterface
181 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
182 if (substr($this->args->getQueryString(), 0, 12) == '.well-known/') {
183 $this->response->setHeader('*', 'Access-Control-Allow-Origin');
184 $this->response->setHeader('*', 'Access-Control-Allow-Headers');
185 $this->response->setHeader(Router::GET, 'Access-Control-Allow-Methods');
186 $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
187 } elseif (substr($this->args->getQueryString(), 0, 8) == 'profile/') {
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, 4) == 'api/') {
193 $this->response->setHeader('*', 'Access-Control-Allow-Origin');
194 $this->response->setHeader('*', 'Access-Control-Allow-Headers');
195 $this->response->setHeader(implode(',', Router::ALLOWED_METHODS), 'Access-Control-Allow-Methods');
196 $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
197 $this->response->setHeader('Link', 'Access-Control-Expose-Headers');
198 } elseif (substr($this->args->getQueryString(), 0, 11) == 'oauth/token') {
199 $this->response->setHeader('*', 'Access-Control-Allow-Origin');
200 $this->response->setHeader('*', 'Access-Control-Allow-Headers');
201 $this->response->setHeader(Router::POST, 'Access-Control-Allow-Methods');
202 $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
207 $this->profiler->set(microtime(true), 'ready');
208 $timestamp = microtime(true);
210 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
212 $this->profiler->set(microtime(true) - $timestamp, 'init');
214 switch ($this->args->getMethod()) {
216 $this->delete($request);
219 $this->patch($request);
222 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $request);
223 $this->post($request);
226 $this->put($request);
230 $timestamp = microtime(true);
231 // "rawContent" is especially meant for technical endpoints.
232 // This endpoint doesn't need any theme initialization or other comparable stuff.
233 $this->rawContent($request);
236 $arr = ['content' => ''];
237 Hook::callAll(static::class . '_mod_content', $arr);
238 $this->response->addContent($arr['content']);
239 $this->response->addContent($this->content($request));
240 } catch (HTTPException $e) {
241 $this->response->addContent((new ModuleHTTPException())->content($e));
243 $this->profiler->set(microtime(true) - $timestamp, 'content');
246 return $this->response->generate();
250 * Checks request inputs and sets default parameters
252 * @param array $defaults Associative array of expected request keys and their default typed value. A null
253 * value will remove the request key from the resulting value array.
254 * @param array $input Custom REQUEST array, superglobal instead
256 * @return array Request data
258 protected function checkDefaults(array $defaults, array $input): array
262 foreach ($defaults as $parameter => $defaultvalue) {
263 $request[$parameter] = $this->getRequestValue($input, $parameter, $defaultvalue);
266 foreach ($input ?? [] as $parameter => $value) {
267 if ($parameter == 'pagename') {
270 if (!in_array($parameter, array_keys($defaults))) {
271 $this->logger->notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => $this->args->getCommand()]);
275 $this->logger->debug('Got request parameters', ['request' => $request, 'command' => $this->args->getCommand()]);
280 * Fetch a request value and apply default values and check against minimal and maximal values
282 * @param array $input
283 * @param string $parameter
284 * @param mixed $default
285 * @param mixed $minimal_value
286 * @param mixed $maximum_value
289 public function getRequestValue(array $input, string $parameter, $default = null, $minimal_value = null, $maximum_value = null)
291 if (is_string($default)) {
292 $value = (string)($input[$parameter] ?? $default);
293 } elseif (is_int($default)) {
294 $value = filter_var($input[$parameter] ?? $default, FILTER_VALIDATE_INT);
295 if (!is_null($minimal_value)) {
296 $value = max(filter_var($minimal_value, FILTER_VALIDATE_INT), $value);
298 if (!is_null($maximum_value)) {
299 $value = min(filter_var($maximum_value, FILTER_VALIDATE_INT), $value);
301 } elseif (is_float($default)) {
302 $value = filter_var($input[$parameter] ?? $default, FILTER_VALIDATE_FLOAT);
303 if (!is_null($minimal_value)) {
304 $value = max(filter_var($minimal_value, FILTER_VALIDATE_FLOAT), $value);
306 if (!is_null($maximum_value)) {
307 $value = min(filter_var($maximum_value, FILTER_VALIDATE_FLOAT), $value);
309 } elseif (is_array($default)) {
310 $value = filter_var($input[$parameter] ?? $default, FILTER_DEFAULT, ['flags' => FILTER_FORCE_ARRAY]);
311 } elseif (is_bool($default)) {
312 $value = filter_var($input[$parameter] ?? $default, FILTER_VALIDATE_BOOLEAN);
313 } elseif (is_null($default)) {
314 $value = $input[$parameter] ?? null;
316 $this->logger->notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($default)]);
324 * Functions used to protect against Cross-Site Request Forgery
325 * 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.
326 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
327 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
328 * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
329 * A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
330 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
331 * Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
332 * 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).
334 public static function getFormSecurityToken(string $typename = '')
336 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
338 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
340 return $timestamp . '.' . $sec_hash;
344 * Checks if form's security (CSRF) token is valid.
346 * @param string $typename ???
347 * @param string $formname Name of form/field (???)
348 * @return bool Whether it is valid
350 public static function checkFormSecurityToken(string $typename = '', string $formname = 'form_security_token'): bool
354 if (!empty($_REQUEST[$formname])) {
355 /// @TODO Careful, not secured!
356 $hash = $_REQUEST[$formname];
359 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
360 /// @TODO Careful, not secured!
361 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
368 $max_livetime = 10800; // 3 hours
370 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
372 $x = explode('.', $hash);
373 if (time() > (intval($x[0]) + $max_livetime)) {
377 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
379 return ($sec_hash == $x[1]);
382 public static function getFormSecurityStandardErrorMessage(): string
384 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.") . EOL;
387 public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token')
389 if (!self::checkFormSecurityToken($typename, $formname)) {
390 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
391 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
392 notice(self::getFormSecurityStandardErrorMessage());
393 DI::baseUrl()->redirect($err_redirect);
397 public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token')
399 if (!self::checkFormSecurityToken($typename, $formname)) {
400 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
401 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
403 throw new \Friendica\Network\HTTPException\ForbiddenException();
407 protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
411 'label' => DI::l10n()->t('All contacts'),
412 'url' => $baseUrl . '/contacts',
413 'sel' => !$current || $current == 'all' ? 'active' : '',
416 'label' => DI::l10n()->t('Followers'),
417 'url' => $baseUrl . '/contacts/followers',
418 'sel' => $current == 'followers' ? 'active' : '',
421 'label' => DI::l10n()->t('Following'),
422 'url' => $baseUrl . '/contacts/following',
423 'sel' => $current == 'following' ? 'active' : '',
426 'label' => DI::l10n()->t('Mutual friends'),
427 'url' => $baseUrl . '/contacts/mutuals',
428 'sel' => $current == 'mutuals' ? 'active' : '',
432 if ($displayCommonTab) {
434 'label' => DI::l10n()->t('Common'),
435 'url' => $baseUrl . '/contacts/common',
436 'sel' => $current == 'common' ? 'active' : '',