]> git.mxchange.org Git - friendica.git/blob - src/BaseModule.php
9b3bd8a5703d4c9f140a39ab97caa927c59fd15c
[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\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;
33
34 /**
35  * All modules in Friendica should extend BaseModule, although not all modules
36  * need to extend all the methods described here
37  *
38  * The filename of the module in src/Module needs to match the class name
39  * exactly to make the module available.
40  *
41  * @author Hypolite Petovan <hypolite@mrpetovan.com>
42  */
43 abstract class BaseModule implements ICanHandleRequests
44 {
45         /** @var array */
46         protected $parameters = [];
47
48         /** @var L10n */
49         protected $l10n;
50
51         public function __construct(L10n $l10n, array $parameters = [])
52         {
53                 $this->parameters = $parameters;
54                 $this->l10n       = $l10n;
55         }
56
57         /**
58          * Wraps the L10n::t() function for Modules
59          *
60          * @see L10n::t()
61          */
62         protected function t(string $s, ...$args): string
63         {
64                 return $this->l10n->t($s, ...$args);
65         }
66
67         /**
68          * Wraps the L10n::tt() function for Modules
69          *
70          * @see L10n::tt()
71          */
72         protected function tt(string $singular, string $plurarl, int $count): string
73         {
74                 return $this->l10n->tt($singular, $plurarl, $count);
75         }
76
77         /**
78          * {@inheritDoc}
79          */
80         public function rawContent()
81         {
82                 // echo '';
83                 // exit;
84         }
85
86         /**
87          * {@inheritDoc}
88          */
89         public function content(): string
90         {
91                 return '';
92         }
93
94         /**
95          * {@inheritDoc}
96          */
97         public function delete()
98         {
99         }
100
101         /**
102          * {@inheritDoc}
103          */
104         public function patch()
105         {
106         }
107
108         /**
109          * {@inheritDoc}
110          */
111         public function post()
112         {
113                 // DI::baseurl()->redirect('module');
114         }
115
116         /**
117          * {@inheritDoc}
118          */
119         public function put()
120         {
121         }
122
123         /** Gets the name of the current class */
124         public function getClassName(): string
125         {
126                 return static::class;
127         }
128
129         public function run(App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
130         {
131                 /* The URL provided does not resolve to a valid module.
132                  *
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.
137                  *
138                  * Otherwise we are going to emit a 404 not found.
139                  */
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) {
144                                 exit();
145                         }
146
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']);
150                         }
151
152                         $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
153                 }
154
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');
177                 }
178
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();
184                 }
185
186                 $placeholder = '';
187
188                 $profiler->set(microtime(true), 'ready');
189                 $timestamp = microtime(true);
190
191                 Core\Hook::callAll($args->getModuleName() . '_mod_init', $placeholder);
192
193                 $profiler->set(microtime(true) - $timestamp, 'init');
194
195                 if ($server['REQUEST_METHOD'] === Router::DELETE) {
196                         $this->delete();
197                 }
198
199                 if ($server['REQUEST_METHOD'] === Router::PATCH) {
200                         $this->patch();
201                 }
202
203                 if ($server['REQUEST_METHOD'] === Router::POST) {
204                         Core\Hook::callAll($args->getModuleName() . '_mod_post', $post);
205                         $this->post();
206                 }
207
208                 if ($server['REQUEST_METHOD'] === Router::PUT) {
209                         $this->put();
210                 }
211
212                 // "rawContent" is especially meant for technical endpoints.
213                 // This endpoint doesn't need any theme initialization or other comparable stuff.
214                 $this->rawContent();
215         }
216
217         /*
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).
227          */
228         public static function getFormSecurityToken($typename = '')
229         {
230                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
231                 $timestamp = time();
232                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
233
234                 return $timestamp . '.' . $sec_hash;
235         }
236
237         public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
238         {
239                 $hash = null;
240
241                 if (!empty($_REQUEST[$formname])) {
242                         /// @TODO Careful, not secured!
243                         $hash = $_REQUEST[$formname];
244                 }
245
246                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
247                         /// @TODO Careful, not secured!
248                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
249                 }
250
251                 if (empty($hash)) {
252                         return false;
253                 }
254
255                 $max_livetime = 10800; // 3 hours
256
257                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
258
259                 $x = explode('.', $hash);
260                 if (time() > (intval($x[0]) + $max_livetime)) {
261                         return false;
262                 }
263
264                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
265
266                 return ($sec_hash == $x[1]);
267         }
268
269         public static function getFormSecurityStandardErrorMessage()
270         {
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;
272         }
273
274         public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
275         {
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);
281                 }
282         }
283
284         public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
285         {
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]);
289
290                         throw new \Friendica\Network\HTTPException\ForbiddenException();
291                 }
292         }
293
294         protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
295         {
296                 $tabs = [
297                         [
298                                 'label' => DI::l10n()->t('All contacts'),
299                                 'url'   => $baseUrl . '/contacts',
300                                 'sel'   => !$current || $current == 'all' ? 'active' : '',
301                         ],
302                         [
303                                 'label' => DI::l10n()->t('Followers'),
304                                 'url'   => $baseUrl . '/contacts/followers',
305                                 'sel'   => $current == 'followers' ? 'active' : '',
306                         ],
307                         [
308                                 'label' => DI::l10n()->t('Following'),
309                                 'url'   => $baseUrl . '/contacts/following',
310                                 'sel'   => $current == 'following' ? 'active' : '',
311                         ],
312                         [
313                                 'label' => DI::l10n()->t('Mutual friends'),
314                                 'url'   => $baseUrl . '/contacts/mutuals',
315                                 'sel'   => $current == 'mutuals' ? 'active' : '',
316                         ],
317                 ];
318
319                 if ($displayCommonTab) {
320                         $tabs[] = [
321                                 'label' => DI::l10n()->t('Common'),
322                                 'url'   => $baseUrl . '/contacts/common',
323                                 'sel'   => $current == 'common' ? 'active' : '',
324                         ];
325                 }
326
327                 return $tabs;
328         }
329 }