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\L10n;
27 use Friendica\Core\Logger;
28 use Friendica\Model\User;
29 use Friendica\Module\HTTPException\PageNotFound;
30 use Friendica\Network\HTTPException\NoContentException;
31 use Friendica\Util\Profiler;
32 use Psr\Log\LoggerInterface;
35 * All modules in Friendica should extend BaseModule, although not all modules
36 * need to extend all the methods described here
38 * The filename of the module in src/Module needs to match the class name
39 * exactly to make the module available.
41 * @author Hypolite Petovan <hypolite@mrpetovan.com>
43 abstract class BaseModule implements ICanHandleRequests
46 protected $parameters = [];
51 public function __construct(L10n $l10n, array $parameters = [])
53 $this->parameters = $parameters;
58 * Wraps the L10n::t() function for Modules
62 protected function t(string $s, ...$args): string
64 return $this->l10n->t($s, ...$args);
68 * Wraps the L10n::tt() function for Modules
72 protected function tt(string $singular, string $plurarl, int $count): string
74 return $this->l10n->tt($singular, $plurarl, $count);
80 public function rawContent()
89 public function content(): string
97 public function delete()
104 public function patch()
111 public function post()
113 // DI::baseurl()->redirect('module');
119 public function put()
123 /** Gets the name of the current class */
124 public function getClassName(): string
126 return static::class;
129 public function run(App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
131 /* The URL provided does not resolve to a valid module.
133 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
134 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
135 * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
136 * this will often succeed and eventually do the right thing.
138 * Otherwise we are going to emit a 404 not found.
140 if (static::class === PageNotFound::class) {
141 $queryString = $server['QUERY_STRING'];
142 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
143 if (!empty($queryString) && preg_match('/{[0-9]}/', $queryString) !== 0) {
147 if (!empty($queryString) && ($queryString === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
148 $logger->info('index.php: dreamhost_error_hack invoked.', ['Original URI' => $server['REQUEST_URI']]);
149 $baseUrl->redirect($server['REQUEST_URI']);
152 $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
155 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
156 if (substr($_REQUEST['pagename'] ?? '', 0, 12) == '.well-known/') {
157 header('Access-Control-Allow-Origin: *');
158 header('Access-Control-Allow-Headers: *');
159 header('Access-Control-Allow-Methods: ' . Router::GET);
160 header('Access-Control-Allow-Credentials: false');
161 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 8) == 'profile/') {
162 header('Access-Control-Allow-Origin: *');
163 header('Access-Control-Allow-Headers: *');
164 header('Access-Control-Allow-Methods: ' . Router::GET);
165 header('Access-Control-Allow-Credentials: false');
166 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 4) == 'api/') {
167 header('Access-Control-Allow-Origin: *');
168 header('Access-Control-Allow-Headers: *');
169 header('Access-Control-Allow-Methods: ' . implode(',', Router::ALLOWED_METHODS));
170 header('Access-Control-Allow-Credentials: false');
171 header('Access-Control-Expose-Headers: Link');
172 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 11) == 'oauth/token') {
173 header('Access-Control-Allow-Origin: *');
174 header('Access-Control-Allow-Headers: *');
175 header('Access-Control-Allow-Methods: ' . Router::POST);
176 header('Access-Control-Allow-Credentials: false');
179 // @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
180 // @todo Check allowed methods per requested path
181 if ($server['REQUEST_METHOD'] === Router::OPTIONS) {
182 header('Allow: ' . implode(',', Router::ALLOWED_METHODS));
183 throw new NoContentException();
188 $profiler->set(microtime(true), 'ready');
189 $timestamp = microtime(true);
191 Core\Hook::callAll($args->getModuleName() . '_mod_init', $placeholder);
193 $profiler->set(microtime(true) - $timestamp, 'init');
195 if ($server['REQUEST_METHOD'] === Router::DELETE) {
199 if ($server['REQUEST_METHOD'] === Router::PATCH) {
203 if ($server['REQUEST_METHOD'] === Router::POST) {
204 Core\Hook::callAll($args->getModuleName() . '_mod_post', $post);
208 if ($server['REQUEST_METHOD'] === Router::PUT) {
212 // "rawContent" is especially meant for technical endpoints.
213 // This endpoint doesn't need any theme initialization or other comparable stuff.
218 * Functions used to protect against Cross-Site Request Forgery
219 * 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.
220 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
221 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
222 * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
223 * A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
224 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
225 * Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
226 * 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).
228 public static function getFormSecurityToken($typename = '')
230 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
232 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
234 return $timestamp . '.' . $sec_hash;
237 public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
241 if (!empty($_REQUEST[$formname])) {
242 /// @TODO Careful, not secured!
243 $hash = $_REQUEST[$formname];
246 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
247 /// @TODO Careful, not secured!
248 $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
255 $max_livetime = 10800; // 3 hours
257 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
259 $x = explode('.', $hash);
260 if (time() > (intval($x[0]) + $max_livetime)) {
264 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
266 return ($sec_hash == $x[1]);
269 public static function getFormSecurityStandardErrorMessage()
271 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;
274 public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
276 if (!self::checkFormSecurityToken($typename, $formname)) {
277 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
278 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
279 notice(self::getFormSecurityStandardErrorMessage());
280 DI::baseUrl()->redirect($err_redirect);
284 public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
286 if (!self::checkFormSecurityToken($typename, $formname)) {
287 Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
288 Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
290 throw new \Friendica\Network\HTTPException\ForbiddenException();
294 protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
298 'label' => DI::l10n()->t('All contacts'),
299 'url' => $baseUrl . '/contacts',
300 'sel' => !$current || $current == 'all' ? 'active' : '',
303 'label' => DI::l10n()->t('Followers'),
304 'url' => $baseUrl . '/contacts/followers',
305 'sel' => $current == 'followers' ? 'active' : '',
308 'label' => DI::l10n()->t('Following'),
309 'url' => $baseUrl . '/contacts/following',
310 'sel' => $current == 'following' ? 'active' : '',
313 'label' => DI::l10n()->t('Mutual friends'),
314 'url' => $baseUrl . '/contacts/mutuals',
315 'sel' => $current == 'mutuals' ? 'active' : '',
319 if ($displayCommonTab) {
321 'label' => DI::l10n()->t('Common'),
322 'url' => $baseUrl . '/contacts/common',
323 'sel' => $current == 'common' ? 'active' : '',