]> git.mxchange.org Git - friendica.git/blob - src/BaseModule.php
Use Args::getMethod() at various places
[friendica.git] / src / BaseModule.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Core\Hook;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Logger;
30 use Friendica\Model\User;
31 use Friendica\Module\Response;
32 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
33 use Friendica\Network\HTTPException;
34 use Friendica\Util\Profiler;
35 use Psr\Http\Message\ResponseInterface;
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          * @param string[] $request The $_REQUEST content
133          */
134         protected function delete(array $request = [])
135         {
136         }
137
138         /**
139          * Module PATCH method to process submitted data
140          *
141          * Extend this method if the module is supposed to process PATCH requests.
142          * Doesn't display any content
143          *
144          * @param string[] $request The $_REQUEST content
145          */
146         protected function patch(array $request = [])
147         {
148         }
149
150         /**
151          * Module POST method to process submitted data
152          *
153          * Extend this method if the module is supposed to process POST requests.
154          * Doesn't display any content
155          *
156          * @param string[] $request The $_REQUEST content
157          *
158          */
159         protected function post(array $request = [])
160         {
161                 // $this->baseUrl->redirect('module');
162         }
163
164         /**
165          * Module PUT method to process submitted data
166          *
167          * Extend this method if the module is supposed to process PUT requests.
168          * Doesn't display any content
169          *
170          * @param string[] $request The $_REQUEST content
171          */
172         protected function put(array $request = [])
173         {
174         }
175
176         /**
177          * Module OPTIONS method to process submitted data
178          *
179          * Extend this method if the module is supposed to process OPTIONS requests.
180          * Doesn't display any content
181          *
182          * @param string[] $request The $_REQUEST content
183          */
184         protected function options(array $request = [])
185         {
186         }
187
188         /**
189          * {@inheritDoc}
190          */
191         public function run(array $request = []): ResponseInterface
192         {
193                 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
194                 if (substr($this->args->getQueryString(), 0, 12) == '.well-known/') {
195                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
196                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
197                         $this->response->setHeader(Router::GET, 'Access-Control-Allow-Methods');
198                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
199                 } elseif (substr($this->args->getQueryString(), 0, 8) == 'profile/') {
200                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
201                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
202                         $this->response->setHeader(Router::GET, 'Access-Control-Allow-Methods');
203                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
204                 } elseif (substr($this->args->getQueryString(), 0, 4) == 'api/') {
205                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
206                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
207                         $this->response->setHeader(implode(',', Router::ALLOWED_METHODS), 'Access-Control-Allow-Methods');
208                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
209                         $this->response->setHeader('Link', 'Access-Control-Expose-Headers');
210                 } elseif (substr($this->args->getQueryString(), 0, 11) == 'oauth/token') {
211                         $this->response->setHeader('*', 'Access-Control-Allow-Origin');
212                         $this->response->setHeader('*', 'Access-Control-Allow-Headers');
213                         $this->response->setHeader(Router::POST, 'Access-Control-Allow-Methods');
214                         $this->response->setHeader('false', 'Access-Control-Allow-Credentials');
215                 }
216
217                 $placeholder = '';
218
219                 $this->profiler->set(microtime(true), 'ready');
220                 $timestamp = microtime(true);
221
222                 Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
223
224                 $this->profiler->set(microtime(true) - $timestamp, 'init');
225
226                 switch ($this->args->getMethod() ?? Router::GET) {
227                         case Router::DELETE:
228                                 $this->delete($request);
229                                 break;
230                         case Router::PATCH:
231                                 $this->patch($request);
232                                 break;
233                         case Router::POST:
234                                 Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $request);
235                                 $this->post($request);
236                                 break;
237                         case Router::PUT:
238                                 $this->put($request);
239                                 break;
240                         case Router::OPTIONS:
241                                 $this->options($request);
242                                 break;
243                 }
244
245                 $timestamp = microtime(true);
246                 // "rawContent" is especially meant for technical endpoints.
247                 // This endpoint doesn't need any theme initialization or other comparable stuff.
248                 $this->rawContent($request);
249
250                 try {
251                         $arr = ['content' => ''];
252                         Hook::callAll(static::class . '_mod_content', $arr);
253                         $this->response->addContent($arr['content']);
254                         $this->response->addContent($this->content($request));
255                 } catch (HTTPException $e) {
256                         $this->response->addContent((new ModuleHTTPException())->content($e));
257                 } finally {
258                         $this->profiler->set(microtime(true) - $timestamp, 'content');
259                 }
260
261                 return $this->response->generate();
262         }
263
264         /**
265          * Checks request inputs and sets default parameters
266          *
267          * @param array $defaults Associative array of expected request keys and their default typed value. A null
268          *                        value will remove the request key from the resulting value array.
269          * @param array $input    Custom REQUEST array, superglobal instead
270          *
271          * @return array Request data
272          */
273         protected function checkDefaults(array $defaults, array $input): array
274         {
275                 $request = [];
276
277                 foreach ($defaults as $parameter => $defaultvalue) {
278                         if (is_string($defaultvalue)) {
279                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
280                         } elseif (is_int($defaultvalue)) {
281                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
282                         } elseif (is_float($defaultvalue)) {
283                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
284                         } elseif (is_array($defaultvalue)) {
285                                 $request[$parameter] = $input[$parameter] ?? [];
286                         } elseif (is_bool($defaultvalue)) {
287                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
288                         } else {
289                                 $this->logger->notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
290                         }
291                 }
292
293                 foreach ($input ?? [] as $parameter => $value) {
294                         if ($parameter == 'pagename') {
295                                 continue;
296                         }
297                         if (!in_array($parameter, array_keys($defaults))) {
298                                 $this->logger->notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => $this->args->getCommand()]);
299                         }
300                 }
301
302                 $this->logger->debug('Got request parameters', ['request' => $request, 'command' => $this->args->getCommand()]);
303                 return $request;
304         }
305
306         /*
307          * Functions used to protect against Cross-Site Request Forgery
308          * 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.
309          * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
310          * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
311          * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
312          *    A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
313          *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
314          *    Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
315          *    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).
316          */
317         public static function getFormSecurityToken($typename = '')
318         {
319                 $user      = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
320                 $timestamp = time();
321                 $sec_hash  = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
322
323                 return $timestamp . '.' . $sec_hash;
324         }
325
326         public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
327         {
328                 $hash = null;
329
330                 if (!empty($_REQUEST[$formname])) {
331                         /// @TODO Careful, not secured!
332                         $hash = $_REQUEST[$formname];
333                 }
334
335                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
336                         /// @TODO Careful, not secured!
337                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
338                 }
339
340                 if (empty($hash)) {
341                         return false;
342                 }
343
344                 $max_livetime = 10800; // 3 hours
345
346                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
347
348                 $x = explode('.', $hash);
349                 if (time() > (intval($x[0]) + $max_livetime)) {
350                         return false;
351                 }
352
353                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
354
355                 return ($sec_hash == $x[1]);
356         }
357
358         public static function getFormSecurityStandardErrorMessage()
359         {
360                 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;
361         }
362
363         public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
364         {
365                 if (!self::checkFormSecurityToken($typename, $formname)) {
366                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
367                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
368                         notice(self::getFormSecurityStandardErrorMessage());
369                         DI::baseUrl()->redirect($err_redirect);
370                 }
371         }
372
373         public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
374         {
375                 if (!self::checkFormSecurityToken($typename, $formname)) {
376                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
377                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
378
379                         throw new \Friendica\Network\HTTPException\ForbiddenException();
380                 }
381         }
382
383         protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
384         {
385                 $tabs = [
386                         [
387                                 'label' => DI::l10n()->t('All contacts'),
388                                 'url'   => $baseUrl . '/contacts',
389                                 'sel'   => !$current || $current == 'all' ? 'active' : '',
390                         ],
391                         [
392                                 'label' => DI::l10n()->t('Followers'),
393                                 'url'   => $baseUrl . '/contacts/followers',
394                                 'sel'   => $current == 'followers' ? 'active' : '',
395                         ],
396                         [
397                                 'label' => DI::l10n()->t('Following'),
398                                 'url'   => $baseUrl . '/contacts/following',
399                                 'sel'   => $current == 'following' ? 'active' : '',
400                         ],
401                         [
402                                 'label' => DI::l10n()->t('Mutual friends'),
403                                 'url'   => $baseUrl . '/contacts/mutuals',
404                                 'sel'   => $current == 'mutuals' ? 'active' : '',
405                         ],
406                 ];
407
408                 if ($displayCommonTab) {
409                         $tabs[] = [
410                                 'label' => DI::l10n()->t('Common'),
411                                 'url'   => $baseUrl . '/contacts/common',
412                                 'sel'   => $current == 'common' ? 'active' : '',
413                         ];
414                 }
415
416                 return $tabs;
417         }
418 }