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