]> git.mxchange.org Git - friendica.git/blob - src/BaseModule.php
Inherit `ApiResponse` from `Response`
[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\Capabilities\ICanCreateResponses;
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;
37
38 /**
39  * All modules in Friendica should extend BaseModule, although not all modules
40  * need to extend all the methods described here
41  *
42  * The filename of the module in src/Module needs to match the class name
43  * exactly to make the module available.
44  *
45  * @author Hypolite Petovan <hypolite@mrpetovan.com>
46  */
47 abstract class BaseModule implements ICanHandleRequests
48 {
49         /** @var array */
50         protected $parameters = [];
51         /** @var L10n */
52         protected $l10n;
53         /** @var App\BaseURL */
54         protected $baseUrl;
55         /** @var App\Arguments */
56         protected $args;
57         /** @var LoggerInterface */
58         protected $logger;
59         /** @var Profiler */
60         protected $profiler;
61         /** @var array */
62         protected $server;
63         /** @var ICanCreateResponses */
64         protected $response;
65
66         public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
67         {
68                 $this->parameters = $parameters;
69                 $this->l10n       = $l10n;
70                 $this->baseUrl    = $baseUrl;
71                 $this->args       = $args;
72                 $this->logger     = $logger;
73                 $this->profiler   = $profiler;
74                 $this->server     = $server;
75                 $this->response   = $response;
76         }
77
78         /**
79          * Wraps the L10n::t() function for Modules
80          *
81          * @see L10n::t()
82          */
83         protected function t(string $s, ...$args): string
84         {
85                 return $this->l10n->t($s, ...$args);
86         }
87
88         /**
89          * Wraps the L10n::tt() function for Modules
90          *
91          * @see L10n::tt()
92          */
93         protected function tt(string $singular, string $plurarl, int $count): string
94         {
95                 return $this->l10n->tt($singular, $plurarl, $count);
96         }
97
98         /**
99          * Module GET method to display raw content from technical endpoints
100          *
101          * Extend this method if the module is supposed to return communication data,
102          * e.g. from protocol implementations.
103          *
104          * @param string[] $request The $_REQUEST content
105          */
106         protected function rawContent(array $request = [])
107         {
108                 // echo '';
109                 // exit;
110         }
111
112         /**
113          * Module GET method to display any content
114          *
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.
118          *
119          * @param string[] $request The $_REQUEST content
120          */
121         protected function content(array $request = []): string
122         {
123                 return '';
124         }
125
126         /**
127          * Module DELETE method to process submitted data
128          *
129          * Extend this method if the module is supposed to process DELETE requests.
130          * Doesn't display any content
131          */
132         protected function delete()
133         {
134         }
135
136         /**
137          * Module PATCH method to process submitted data
138          *
139          * Extend this method if the module is supposed to process PATCH requests.
140          * Doesn't display any content
141          */
142         protected function patch()
143         {
144         }
145
146         /**
147          * Module POST method to process submitted data
148          *
149          * Extend this method if the module is supposed to process POST requests.
150          * Doesn't display any content
151          *
152          * @param string[] $request The $_REQUEST content
153          * @param string[] $post    The $_POST content
154          *
155          */
156         protected function post(array $request = [], array $post = [])
157         {
158                 // $this->baseUrl->redirect('module');
159         }
160
161         /**
162          * Module PUT method to process submitted data
163          *
164          * Extend this method if the module is supposed to process PUT requests.
165          * Doesn't display any content
166          */
167         protected function put()
168         {
169         }
170
171         /**
172          * {@inheritDoc}
173          */
174         public function run(array $post = [], array $request = []): IRespondToRequests
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                 switch ($this->server['REQUEST_METHOD'] ?? Router::GET) {
210                         case Router::DELETE:
211                                 $this->delete();
212                                 break;
213                         case Router::PATCH:
214                                 $this->patch();
215                                 break;
216                         case Router::POST:
217                                 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post);
218                                 $this->post($request, $post);
219                                 break;
220                         case Router::PUT:
221                                 $this->put();
222                                 break;
223                         default:
224                                 $timestamp = microtime(true);
225                                 // "rawContent" is especially meant for technical endpoints.
226                                 // This endpoint doesn't need any theme initialization or other comparable stuff.
227                                 $this->rawContent($request);
228
229                                 try {
230                                         $arr = ['content' => ''];
231                                         Hook::callAll(static::class . '_mod_content', $arr);
232                                         $this->response->addContent($arr['content']);
233                                         $this->response->addContent($this->content($_REQUEST));
234                                 } catch (HTTPException $e) {
235                                         $this->response->addContent((new ModuleHTTPException())->content($e));
236                                 } finally {
237                                         $this->profiler->set(microtime(true) - $timestamp, 'content');
238                                 }
239                                 break;
240                 }
241
242                 return $this->response;
243         }
244
245         /*
246          * Functions used to protect against Cross-Site Request Forgery
247          * 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.
248          * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
249          * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
250          * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
251          *    A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
252          *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
253          *    Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
254          *    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).
255          */
256         public static function getFormSecurityToken($typename = '')
257         {
258                 $user      = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
259                 $timestamp = time();
260                 $sec_hash  = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
261
262                 return $timestamp . '.' . $sec_hash;
263         }
264
265         public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
266         {
267                 $hash = null;
268
269                 if (!empty($_REQUEST[$formname])) {
270                         /// @TODO Careful, not secured!
271                         $hash = $_REQUEST[$formname];
272                 }
273
274                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
275                         /// @TODO Careful, not secured!
276                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
277                 }
278
279                 if (empty($hash)) {
280                         return false;
281                 }
282
283                 $max_livetime = 10800; // 3 hours
284
285                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
286
287                 $x = explode('.', $hash);
288                 if (time() > (intval($x[0]) + $max_livetime)) {
289                         return false;
290                 }
291
292                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
293
294                 return ($sec_hash == $x[1]);
295         }
296
297         public static function getFormSecurityStandardErrorMessage()
298         {
299                 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;
300         }
301
302         public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
303         {
304                 if (!self::checkFormSecurityToken($typename, $formname)) {
305                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
306                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
307                         notice(self::getFormSecurityStandardErrorMessage());
308                         DI::baseUrl()->redirect($err_redirect);
309                 }
310         }
311
312         public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
313         {
314                 if (!self::checkFormSecurityToken($typename, $formname)) {
315                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
316                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
317
318                         throw new \Friendica\Network\HTTPException\ForbiddenException();
319                 }
320         }
321
322         protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
323         {
324                 $tabs = [
325                         [
326                                 'label' => DI::l10n()->t('All contacts'),
327                                 'url'   => $baseUrl . '/contacts',
328                                 'sel'   => !$current || $current == 'all' ? 'active' : '',
329                         ],
330                         [
331                                 'label' => DI::l10n()->t('Followers'),
332                                 'url'   => $baseUrl . '/contacts/followers',
333                                 'sel'   => $current == 'followers' ? 'active' : '',
334                         ],
335                         [
336                                 'label' => DI::l10n()->t('Following'),
337                                 'url'   => $baseUrl . '/contacts/following',
338                                 'sel'   => $current == 'following' ? 'active' : '',
339                         ],
340                         [
341                                 'label' => DI::l10n()->t('Mutual friends'),
342                                 'url'   => $baseUrl . '/contacts/mutuals',
343                                 'sel'   => $current == 'mutuals' ? 'active' : '',
344                         ],
345                 ];
346
347                 if ($displayCommonTab) {
348                         $tabs[] = [
349                                 'label' => DI::l10n()->t('Common'),
350                                 'url'   => $baseUrl . '/contacts/common',
351                                 'sel'   => $current == 'common' ? 'active' : '',
352                         ];
353                 }
354
355                 return $tabs;
356         }
357 }