3 * @copyright Copyright (C) 2010-2021, 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\ICanReadAndWriteToResponds;
27 use Friendica\Capabilities\IRespondToRequests;
28 use Friendica\Core\Hook;
29 use Friendica\Core\L10n;
30 use Friendica\Core\Logger;
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\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 ICanReadAndWriteToResponds */
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 protected function delete()
137 * Module PATCH method to process submitted data
139 * Extend this method if the module is supposed to process PATCH requests.
140 * Doesn't display any content
142 protected function patch()
147 * Module POST method to process submitted data
149 * Extend this method if the module is supposed to process POST requests.
150 * Doesn't display any content
152 * @param string[] $request The $_REQUEST content
153 * @param string[] $post The $_POST content
156 protected function post(array $request = [], array $post = [])
158 // $this->baseUrl->redirect('module');
162 * Module PUT method to process submitted data
164 * Extend this method if the module is supposed to process PUT requests.
165 * Doesn't display any content
167 protected function put()
171 /** Gets the name of the current class */
172 public function getClassName(): string
174 return static::class;
180 public function run(array $post = [], array $request = []): IRespondToRequests
182 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
183 if (substr($request['pagename'] ?? '', 0, 12) == '.well-known/') {
184 header('Access-Control-Allow-Origin: *');
185 header('Access-Control-Allow-Headers: *');
186 header('Access-Control-Allow-Methods: ' . Router::GET);
187 header('Access-Control-Allow-Credentials: false');
188 } elseif (substr($request['pagename'] ?? '', 0, 8) == 'profile/') {
189 header('Access-Control-Allow-Origin: *');
190 header('Access-Control-Allow-Headers: *');
191 header('Access-Control-Allow-Methods: ' . Router::GET);
192 header('Access-Control-Allow-Credentials: false');
193 } elseif (substr($request['pagename'] ?? '', 0, 4) == 'api/') {
194 header('Access-Control-Allow-Origin: *');
195 header('Access-Control-Allow-Headers: *');
196 header('Access-Control-Allow-Methods: ' . implode(',', Router::ALLOWED_METHODS));
197 header('Access-Control-Allow-Credentials: false');
198 header('Access-Control-Expose-Headers: Link');
199 } elseif (substr($request['pagename'] ?? '', 0, 11) == 'oauth/token') {
200 header('Access-Control-Allow-Origin: *');
201 header('Access-Control-Allow-Headers: *');
202 header('Access-Control-Allow-Methods: ' . Router::POST);
203 header('Access-Control-Allow-Credentials: false');
208 $this->profiler->set(microtime(true), 'ready');
209 $timestamp = microtime(true);
211 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
213 $this->profiler->set(microtime(true) - $timestamp, 'init');
214 $this->response->setType(IRespondToRequests::TYPE_CONTENT);
216 switch ($this->server['REQUEST_METHOD']) {
218 $this->response->setType(IRespondToRequests::TYPE_DELETE);
222 $this->response->setType(IRespondToRequests::TYPE_PATCH);
226 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post);
227 $this->response->setType(IRespondToRequests::TYPE_POST);
228 $this->post($request, $post);
231 $this->response->setType(IRespondToRequests::TYPE_PUT);
235 // "rawContent" is especially meant for technical endpoints.
236 // This endpoint doesn't need any theme initialization or other comparable stuff.
237 $this->rawContent($request);
240 $arr = ['content' => ''];
241 Hook::callAll(static::class . '_mod_content', $arr);
242 $this->response->addContent($arr['content']);
243 $this->response->addContent($this->content($_REQUEST));
244 } catch (HTTPException $e) {
245 $this->response->addContent((new ModuleHTTPException())->content($e));
250 return $this->response;
254 * Functions used to protect against Cross-Site Request Forgery
255 * 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.
256 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
257 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
258 * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
259 * A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
260 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
261 * Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
262 * 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).
264 public static function getFormSecurityToken($typename = '')
266 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
268 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
270 return $timestamp . '.' . $sec_hash;
273 public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
277 if (!empty($_REQUEST[$formname])) {
278 /// @TODO Careful, not secured!
279 $hash = $_REQUEST[$formname];
282 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
283 /// @TODO Careful, not secured!
284 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
291 $max_livetime = 10800; // 3 hours
293 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
295 $x = explode('.', $hash);
296 if (time() > (intval($x[0]) + $max_livetime)) {
300 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
302 return ($sec_hash == $x[1]);
305 public static function getFormSecurityStandardErrorMessage()
307 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;
310 public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
312 if (!self::checkFormSecurityToken($typename, $formname)) {
313 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
314 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
315 notice(self::getFormSecurityStandardErrorMessage());
316 DI::baseUrl()->redirect($err_redirect);
320 public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
322 if (!self::checkFormSecurityToken($typename, $formname)) {
323 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
324 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
326 throw new \Friendica\Network\HTTPException\ForbiddenException();
330 protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
334 'label' => DI::l10n()->t('All contacts'),
335 'url' => $baseUrl . '/contacts',
336 'sel' => !$current || $current == 'all' ? 'active' : '',
339 'label' => DI::l10n()->t('Followers'),
340 'url' => $baseUrl . '/contacts/followers',
341 'sel' => $current == 'followers' ? 'active' : '',
344 'label' => DI::l10n()->t('Following'),
345 'url' => $baseUrl . '/contacts/following',
346 'sel' => $current == 'following' ? 'active' : '',
349 'label' => DI::l10n()->t('Mutual friends'),
350 'url' => $baseUrl . '/contacts/mutuals',
351 'sel' => $current == 'mutuals' ? 'active' : '',
355 if ($displayCommonTab) {
357 'label' => DI::l10n()->t('Common'),
358 'url' => $baseUrl . '/contacts/common',
359 'sel' => $current == 'common' ? 'active' : '',