]> git.mxchange.org Git - friendica.git/blob - src/BaseModule.php
Switch `static::$parameters` to `$this->parameters`
[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\Capabilities\ICanHandleRequests;
25 use Friendica\Core\Logger;
26 use Friendica\Model\User;
27
28 /**
29  * All modules in Friendica should extend BaseModule, although not all modules
30  * need to extend all the methods described here
31  *
32  * The filename of the module in src/Module needs to match the class name
33  * exactly to make the module available.
34  *
35  * @author Hypolite Petovan <hypolite@mrpetovan.com>
36  */
37 abstract class BaseModule implements ICanHandleRequests
38 {
39         /** @var array */
40         protected $parameters = [];
41
42         public function __construct(array $parameters = [])
43         {
44                 $this->parameters = $parameters;
45         }
46
47         /**
48          * {@inheritDoc}
49          */
50         public function init()
51         {
52         }
53
54         /**
55          * {@inheritDoc}
56          */
57         public function rawContent()
58         {
59                 // echo '';
60                 // exit;
61         }
62
63         /**
64          * {@inheritDoc}
65          */
66         public function content(): string
67         {
68                 return '';
69         }
70
71         /**
72          * {@inheritDoc}
73          */
74         public function delete()
75         {
76         }
77
78         /**
79          * {@inheritDoc}
80          */
81         public function patch()
82         {
83         }
84
85         /**
86          * {@inheritDoc}
87          */
88         public function post()
89         {
90                 // DI::baseurl()->redirect('module');
91         }
92
93         /**
94          * {@inheritDoc}
95          */
96         public function afterpost()
97         {
98         }
99
100         /**
101          * {@inheritDoc}
102          */
103         public function put()
104         {
105         }
106
107         /** Gets the name of the current class */
108         public function getClassName(): string
109         {
110                 return static::class;
111         }
112
113         /*
114          * Functions used to protect against Cross-Site Request Forgery
115          * 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.
116          * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
117          * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amount of time (3hours).
118          * The "typename" separates the security tokens of different types of forms. This could be relevant in the following case:
119          *    A security token is used to protect a link from CSRF (e.g. the "delete this profile"-link).
120          *    If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
121          *    Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
122          *    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).
123          */
124         public static function getFormSecurityToken($typename = '')
125         {
126                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
127                 $timestamp = time();
128                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $timestamp . $typename);
129
130                 return $timestamp . '.' . $sec_hash;
131         }
132
133         public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token')
134         {
135                 $hash = null;
136
137                 if (!empty($_REQUEST[$formname])) {
138                         /// @TODO Careful, not secured!
139                         $hash = $_REQUEST[$formname];
140                 }
141
142                 if (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
143                         /// @TODO Careful, not secured!
144                         $hash = $_SERVER['HTTP_X_CSRF_TOKEN'];
145                 }
146
147                 if (empty($hash)) {
148                         return false;
149                 }
150
151                 $max_livetime = 10800; // 3 hours
152
153                 $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
154
155                 $x = explode('.', $hash);
156                 if (time() > (intval($x[0]) + $max_livetime)) {
157                         return false;
158                 }
159
160                 $sec_hash = hash('whirlpool', ($user['guid'] ?? '') . ($user['prvkey'] ?? '') . session_id() . $x[0] . $typename);
161
162                 return ($sec_hash == $x[1]);
163         }
164
165         public static function getFormSecurityStandardErrorMessage()
166         {
167                 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;
168         }
169
170         public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token')
171         {
172                 if (!self::checkFormSecurityToken($typename, $formname)) {
173                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
174                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
175                         notice(self::getFormSecurityStandardErrorMessage());
176                         DI::baseUrl()->redirect($err_redirect);
177                 }
178         }
179
180         public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token')
181         {
182                 if (!self::checkFormSecurityToken($typename, $formname)) {
183                         Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
184                         Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
185
186                         throw new \Friendica\Network\HTTPException\ForbiddenException();
187                 }
188         }
189
190         protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
191         {
192                 $tabs = [
193                         [
194                                 'label' => DI::l10n()->t('All contacts'),
195                                 'url'   => $baseUrl . '/contacts',
196                                 'sel'   => !$current || $current == 'all' ? 'active' : '',
197                         ],
198                         [
199                                 'label' => DI::l10n()->t('Followers'),
200                                 'url'   => $baseUrl . '/contacts/followers',
201                                 'sel'   => $current == 'followers' ? 'active' : '',
202                         ],
203                         [
204                                 'label' => DI::l10n()->t('Following'),
205                                 'url'   => $baseUrl . '/contacts/following',
206                                 'sel'   => $current == 'following' ? 'active' : '',
207                         ],
208                         [
209                                 'label' => DI::l10n()->t('Mutual friends'),
210                                 'url'   => $baseUrl . '/contacts/mutuals',
211                                 'sel'   => $current == 'mutuals' ? 'active' : '',
212                         ],
213                 ];
214
215                 if ($displayCommonTab) {
216                         $tabs[] = [
217                                 'label' => DI::l10n()->t('Common'),
218                                 'url'   => $baseUrl . '/contacts/common',
219                                 'sel'   => $current == 'common' ? 'active' : '',
220                         ];
221                 }
222
223                 return $tabs;
224         }
225 }