]> git.mxchange.org Git - friendica.git/blob - src/BaseModule.php
65fc8f307c49dbdca624c43dd11072dfa4956a95
[friendica.git] / src / BaseModule.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica;
23
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;
34
35 /**
36  * All modules in Friendica should extend BaseModule, although not all modules
37  * need to extend all the methods described here
38  *
39  * The filename of the module in src/Module needs to match the class name
40  * exactly to make the module available.
41  *
42  * @author Hypolite Petovan <hypolite@mrpetovan.com>
43  */
44 abstract class BaseModule implements ICanHandleRequests
45 {
46         /** @var array */
47         protected $parameters = [];
48         /** @var L10n */
49         protected $l10n;
50         /** @var App\BaseURL */
51         protected $baseUrl;
52         /** @var App\Arguments */
53         protected $args;
54         /** @var LoggerInterface */
55         protected $logger;
56         /** @var Profiler */
57         protected $profiler;
58         /** @var array */
59         protected $server;
60
61         public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, array $server, array $parameters = [])
62         {
63                 $this->parameters = $parameters;
64                 $this->l10n       = $l10n;
65                 $this->baseUrl    = $baseUrl;
66                 $this->args       = $args;
67                 $this->logger     = $logger;
68                 $this->profiler   = $profiler;
69                 $this->server     = $server;
70         }
71
72         /**
73          * Wraps the L10n::t() function for Modules
74          *
75          * @see L10n::t()
76          */
77         protected function t(string $s, ...$args): string
78         {
79                 return $this->l10n->t($s, ...$args);
80         }
81
82         /**
83          * Wraps the L10n::tt() function for Modules
84          *
85          * @see L10n::tt()
86          */
87         protected function tt(string $singular, string $plurarl, int $count): string
88         {
89                 return $this->l10n->tt($singular, $plurarl, $count);
90         }
91
92         /**
93          * Module GET method to display raw content from technical endpoints
94          *
95          * Extend this method if the module is supposed to return communication data,
96          * e.g. from protocol implementations.
97          *
98          * @param string[] $request The $_REQUEST content
99          */
100         protected function rawContent(array $request = [])
101         {
102                 // echo '';
103                 // exit;
104         }
105
106         /**
107          * Module GET method to display any content
108          *
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.
112          *
113          * @param string[] $request The $_REQUEST content
114          */
115         protected function content(array $request = []): string
116         {
117                 return '';
118         }
119
120         /**
121          * Module DELETE method to process submitted data
122          *
123          * Extend this method if the module is supposed to process DELETE requests.
124          * Doesn't display any content
125          */
126         protected function delete()
127         {
128         }
129
130         /**
131          * Module PATCH method to process submitted data
132          *
133          * Extend this method if the module is supposed to process PATCH requests.
134          * Doesn't display any content
135          */
136         protected function patch()
137         {
138         }
139
140         /**
141          * Module POST method to process submitted data
142          *
143          * Extend this method if the module is supposed to process POST requests.
144          * Doesn't display any content
145          *
146          * @param string[] $request The $_REQUEST content
147          * @param string[] $post    The $_POST content
148          *
149          */
150         protected function post(array $request = [], array $post = [])
151         {
152                 // $this->baseUrl->redirect('module');
153         }
154
155         /**
156          * Module PUT method to process submitted data
157          *
158          * Extend this method if the module is supposed to process PUT requests.
159          * Doesn't display any content
160          */
161         protected function put()
162         {
163         }
164
165         /** Gets the name of the current class */
166         public function getClassName(): string
167         {
168                 return static::class;
169         }
170
171         /**
172          * {@inheritDoc}
173          */
174         public function run(array $post = [], array $request = []): string
175         {
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');
198                 }
199
200                 $placeholder = '';
201
202                 $this->profiler->set(microtime(true), 'ready');
203                 $timestamp = microtime(true);
204
205                 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
206
207                 $this->profiler->set(microtime(true) - $timestamp, 'init');
208
209                 if ($this->server['REQUEST_METHOD'] === Router::DELETE) {
210                         $this->delete();
211                 }
212
213                 if ($this->server['REQUEST_METHOD'] === Router::PATCH) {
214                         $this->patch();
215                 }
216
217                 if ($this->server['REQUEST_METHOD'] === Router::POST) {
218                         Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post);
219                         $this->post($request, $post);
220                 }
221
222                 if ($this->server['REQUEST_METHOD'] === Router::PUT) {
223                         $this->put();
224                 }
225
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);
229
230                 try {
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);
237                 }
238         }
239
240         /*
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).
250          */
251         public static function getFormSecurityToken($typename = '')
252         {
253                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
254                 $timestamp = time();
255                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
256
257                 return $timestamp . '.' . $sec_hash;
258         }
259
260         public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
261         {
262                 $hash = null;
263
264                 if (!empty($_REQUEST[$formname])) {
265                         /// @TODO Careful, not secured!
266                         $hash = $_REQUEST[$formname];
267                 }
268
269                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
270                         /// @TODO Careful, not secured!
271                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
272                 }
273
274                 if (empty($hash)) {
275                         return false;
276                 }
277
278                 $max_livetime = 10800; // 3 hours
279
280                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
281
282                 $x = explode('.', $hash);
283                 if (time() > (intval($x[0]) + $max_livetime)) {
284                         return false;
285                 }
286
287                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
288
289                 return ($sec_hash == $x[1]);
290         }
291
292         public static function getFormSecurityStandardErrorMessage()
293         {
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;
295         }
296
297         public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
298         {
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);
304                 }
305         }
306
307         public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
308         {
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]);
312
313                         throw new \Friendica\Network\HTTPException\ForbiddenException();
314                 }
315         }
316
317         protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
318         {
319                 $tabs = [
320                         [
321                                 'label' => DI::l10n()->t('All contacts'),
322                                 'url'   => $baseUrl . '/contacts',
323                                 'sel'   => !$current || $current == 'all' ? 'active' : '',
324                         ],
325                         [
326                                 'label' => DI::l10n()->t('Followers'),
327                                 'url'   => $baseUrl . '/contacts/followers',
328                                 'sel'   => $current == 'followers' ? 'active' : '',
329                         ],
330                         [
331                                 'label' => DI::l10n()->t('Following'),
332                                 'url'   => $baseUrl . '/contacts/following',
333                                 'sel'   => $current == 'following' ? 'active' : '',
334                         ],
335                         [
336                                 'label' => DI::l10n()->t('Mutual friends'),
337                                 'url'   => $baseUrl . '/contacts/mutuals',
338                                 'sel'   => $current == 'mutuals' ? 'active' : '',
339                         ],
340                 ];
341
342                 if ($displayCommonTab) {
343                         $tabs[] = [
344                                 'label' => DI::l10n()->t('Common'),
345                                 'url'   => $baseUrl . '/contacts/common',
346                                 'sel'   => $current == 'common' ? 'active' : '',
347                         ];
348                 }
349
350                 return $tabs;
351         }
352 }