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\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Logger;
29 use Friendica\Model\User;
30 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
31 use Friendica\Network\HTTPException;
32 use Friendica\Util\Profiler;
33 use Psr\Log\LoggerInterface;
36 * All modules in Friendica should extend BaseModule, although not all modules
37 * need to extend all the methods described here
39 * The filename of the module in src/Module needs to match the class name
40 * exactly to make the module available.
42 * @author Hypolite Petovan <hypolite@mrpetovan.com>
44 abstract class BaseModule implements ICanHandleRequests
47 protected $parameters = [];
50 /** @var App\BaseURL */
52 /** @var App\Arguments */
54 /** @var LoggerInterface */
61 public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, array $server, array $parameters = [])
63 $this->parameters = $parameters;
65 $this->baseUrl = $baseUrl;
67 $this->logger = $logger;
68 $this->profiler = $profiler;
69 $this->server = $server;
73 * Wraps the L10n::t() function for Modules
77 protected function t(string $s, ...$args): string
79 return $this->l10n->t($s, ...$args);
83 * Wraps the L10n::tt() function for Modules
87 protected function tt(string $singular, string $plurarl, int $count): string
89 return $this->l10n->tt($singular, $plurarl, $count);
93 * Module GET method to display raw content from technical endpoints
95 * Extend this method if the module is supposed to return communication data,
96 * e.g. from protocol implementations.
98 * @param string[] $request The $_REQUEST content
100 protected function rawContent(array $request = [])
107 * Module GET method to display any content
109 * Extend this method if the module is supposed to return any display
110 * through a GET request. It can be an HTML page through templating or a
111 * XML feed or a JSON output.
113 * @param string[] $request The $_REQUEST content
115 protected function content(array $request = []): string
121 * Module DELETE method to process submitted data
123 * Extend this method if the module is supposed to process DELETE requests.
124 * Doesn't display any content
126 protected function delete()
131 * Module PATCH method to process submitted data
133 * Extend this method if the module is supposed to process PATCH requests.
134 * Doesn't display any content
136 protected function patch()
141 * Module POST method to process submitted data
143 * Extend this method if the module is supposed to process POST requests.
144 * Doesn't display any content
146 * @param string[] $request The $_REQUEST content
147 * @param string[] $post The $_POST content
150 protected function post(array $request = [], array $post = [])
152 // $this->baseUrl->redirect('module');
156 * Module PUT method to process submitted data
158 * Extend this method if the module is supposed to process PUT requests.
159 * Doesn't display any content
161 protected function put()
165 /** Gets the name of the current class */
166 public function getClassName(): string
168 return static::class;
174 public function run(array $post = [], array $request = []): string
176 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
177 if (substr($request['pagename'] ?? '', 0, 12) == '.well-known/') {
178 header('Access-Control-Allow-Origin: *');
179 header('Access-Control-Allow-Headers: *');
180 header('Access-Control-Allow-Methods: ' . Router::GET);
181 header('Access-Control-Allow-Credentials: false');
182 } elseif (substr($request['pagename'] ?? '', 0, 8) == 'profile/') {
183 header('Access-Control-Allow-Origin: *');
184 header('Access-Control-Allow-Headers: *');
185 header('Access-Control-Allow-Methods: ' . Router::GET);
186 header('Access-Control-Allow-Credentials: false');
187 } elseif (substr($request['pagename'] ?? '', 0, 4) == 'api/') {
188 header('Access-Control-Allow-Origin: *');
189 header('Access-Control-Allow-Headers: *');
190 header('Access-Control-Allow-Methods: ' . implode(',', Router::ALLOWED_METHODS));
191 header('Access-Control-Allow-Credentials: false');
192 header('Access-Control-Expose-Headers: Link');
193 } elseif (substr($request['pagename'] ?? '', 0, 11) == 'oauth/token') {
194 header('Access-Control-Allow-Origin: *');
195 header('Access-Control-Allow-Headers: *');
196 header('Access-Control-Allow-Methods: ' . Router::POST);
197 header('Access-Control-Allow-Credentials: false');
202 $this->profiler->set(microtime(true), 'ready');
203 $timestamp = microtime(true);
205 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
207 $this->profiler->set(microtime(true) - $timestamp, 'init');
209 if ($this->server['REQUEST_METHOD'] === Router::DELETE) {
213 if ($this->server['REQUEST_METHOD'] === Router::PATCH) {
217 if ($this->server['REQUEST_METHOD'] === Router::POST) {
218 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post);
219 $this->post($request, $post);
222 if ($this->server['REQUEST_METHOD'] === Router::PUT) {
226 // "rawContent" is especially meant for technical endpoints.
227 // This endpoint doesn't need any theme initialization or other comparable stuff.
228 $this->rawContent($request);
231 $arr = ['content' => ''];
232 Hook::callAll(static::class . '_mod_content', $arr);
233 $content = $arr['content'];
234 return $content . $this->content($_REQUEST);
235 } catch (HTTPException $e) {
236 return (new ModuleHTTPException())->content($e);
241 * Functions used to protect against Cross-Site Request Forgery
242 * 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.
243 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
244 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
245 * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
246 * A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
247 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
248 * Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
249 * 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).
251 public static function getFormSecurityToken($typename = '')
253 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
255 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
257 return $timestamp . '.' . $sec_hash;
260 public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
264 if (!empty($_REQUEST[$formname])) {
265 /// @TODO Careful, not secured!
266 $hash = $_REQUEST[$formname];
269 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
270 /// @TODO Careful, not secured!
271 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
278 $max_livetime = 10800; // 3 hours
280 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
282 $x = explode('.', $hash);
283 if (time() > (intval($x[0]) + $max_livetime)) {
287 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
289 return ($sec_hash == $x[1]);
292 public static function getFormSecurityStandardErrorMessage()
294 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;
297 public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
299 if (!self::checkFormSecurityToken($typename, $formname)) {
300 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
301 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
302 notice(self::getFormSecurityStandardErrorMessage());
303 DI::baseUrl()->redirect($err_redirect);
307 public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
309 if (!self::checkFormSecurityToken($typename, $formname)) {
310 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
311 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
313 throw new \Friendica\Network\HTTPException\ForbiddenException();
317 protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
321 'label' => DI::l10n()->t('All contacts'),
322 'url' => $baseUrl . '/contacts',
323 'sel' => !$current || $current == 'all' ? 'active' : '',
326 'label' => DI::l10n()->t('Followers'),
327 'url' => $baseUrl . '/contacts/followers',
328 'sel' => $current == 'followers' ? 'active' : '',
331 'label' => DI::l10n()->t('Following'),
332 'url' => $baseUrl . '/contacts/following',
333 'sel' => $current == 'following' ? 'active' : '',
336 'label' => DI::l10n()->t('Mutual friends'),
337 'url' => $baseUrl . '/contacts/mutuals',
338 'sel' => $current == 'mutuals' ? 'active' : '',
342 if ($displayCommonTab) {
344 'label' => DI::l10n()->t('Common'),
345 'url' => $baseUrl . '/contacts/common',
346 'sel' => $current == 'common' ? 'active' : '',