]> git.mxchange.org Git - friendica.git/blob - src/Module/Register.php
Merge pull request #13599 from Raroun/Fix_for_Pull_Request_#13596_missing_a_hidden...
[friendica.git] / src / Module / Register.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Module;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Config\Capability\IManageConfigValues;
28 use Friendica\Core\Hook;
29 use Friendica\Core\L10n;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model;
36 use Friendica\Model\User;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Proxy;
39 use Psr\Log\LoggerInterface;
40
41 /**
42  * @author Hypolite Petovan <hypolite@mrpetovan.com>
43  */
44 class Register extends BaseModule
45 {
46         const CLOSED  = 0;
47         const APPROVE = 1;
48         const OPEN    = 2;
49
50         /** @var Tos */
51         protected $tos;
52
53         public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, IManageConfigValues $config, array $server, array $parameters = [])
54         {
55                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
56
57                 $this->tos = new Tos($l10n, $baseUrl, $args, $logger, $profiler, $response, $config, $server, $parameters);
58         }
59
60         /**
61          * Module GET method to display any content
62          *
63          * Extend this method if the module is supposed to return any display
64          * through a GET request. It can be an HTML page through templating or a
65          * XML feed or a JSON output.
66          *
67          * @return string
68          */
69         protected function content(array $request = []): string
70         {
71                 // logged in users can register others (people/pages/groups)
72                 // even with closed registrations, unless specifically prohibited by site policy.
73                 // 'block_extended_register' blocks all registrations, period.
74                 $block = DI::config()->get('system', 'block_extended_register');
75
76                 if (DI::userSession()->getLocalUserId() && $block) {
77                         DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
78                         return '';
79                 }
80
81                 if (DI::userSession()->getLocalUserId()) {
82                         $user = DBA::selectFirst('user', ['parent-uid'], ['uid' => DI::userSession()->getLocalUserId()]);
83                         if (!empty($user['parent-uid'])) {
84                                 DI::sysmsg()->addNotice(DI::l10n()->t('Only parent users can create additional accounts.'));
85                                 return '';
86                         }
87                 }
88
89                 if (!DI::userSession()->getLocalUserId() && (intval(DI::config()->get('config', 'register_policy')) === self::CLOSED)) {
90                         DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
91                         return '';
92                 }
93
94                 $max_dailies = intval(DI::config()->get('system', 'max_daily_registrations'));
95                 if ($max_dailies) {
96                         $count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']);
97                         if ($count >= $max_dailies) {
98                                 Logger::notice('max daily registrations exceeded.');
99                                 DI::sysmsg()->addNotice(DI::l10n()->t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.'));
100                                 return '';
101                         }
102                 }
103
104                 $username   = $_REQUEST['username']   ?? '';
105                 $email      = $_REQUEST['email']      ?? '';
106                 $openid_url = $_REQUEST['openid_url'] ?? '';
107                 $nickname   = $_REQUEST['nickname']   ?? '';
108                 $photo      = $_REQUEST['photo']      ?? '';
109                 $invite_id  = $_REQUEST['invite_id']  ?? '';
110
111                 if (DI::userSession()->getLocalUserId() || DI::config()->get('system', 'no_openid')) {
112                         $fillwith = '';
113                         $fillext  = '';
114                         $oidlabel = '';
115                 } else {
116                         $fillwith = DI::l10n()->t('You may (optionally) fill in this form via OpenID by supplying your OpenID and clicking "Register".');
117                         $fillext  = DI::l10n()->t('If you are not familiar with OpenID, please leave that field blank and fill in the rest of the items.');
118                         $oidlabel = DI::l10n()->t('Your OpenID (optional): ');
119                 }
120
121                 if (DI::config()->get('system', 'publish_all')) {
122                         $profile_publish = '<input type="hidden" name="profile_publish_reg" value="1" />';
123                 } else {
124                         $publish_tpl = Renderer::getMarkupTemplate('profile/publish.tpl');
125                         $profile_publish = Renderer::replaceMacros($publish_tpl, [
126                                 '$instance'     => 'reg',
127                                 '$pubdesc'      => DI::l10n()->t('Include your profile in member directory?'),
128                                 '$yes_selected' => '',
129                                 '$no_selected'  => ' checked="checked"',
130                                 '$str_yes'      => DI::l10n()->t('Yes'),
131                                 '$str_no'       => DI::l10n()->t('No'),
132                         ]);
133                 }
134
135                 $ask_password = !DBA::count('contact');
136
137                 $tpl = Renderer::getMarkupTemplate('register.tpl');
138
139                 $arr = ['template' => $tpl];
140
141                 Hook::callAll('register_form', $arr);
142
143                 $tpl = $arr['template'];
144
145                 $o = Renderer::replaceMacros($tpl, [
146                         '$invitations'  => DI::config()->get('system', 'invitation_only'),
147                         '$permonly'     => intval(DI::config()->get('config', 'register_policy')) === self::APPROVE,
148                         '$permonlybox'  => ['permonlybox', DI::l10n()->t('Note for the admin'), '', DI::l10n()->t('Leave a message for the admin, why you want to join this node'), DI::l10n()->t('Required')],
149                         '$invite_desc'  => DI::l10n()->t('Membership on this site is by invitation only.'),
150                         '$invite_label' => DI::l10n()->t('Your invitation code: '),
151                         '$invite_id'    => $invite_id,
152                         '$regtitle'     => DI::l10n()->t('Registration'),
153                         '$registertext' => BBCode::convertForUriId(User::getSystemUriId(), DI::config()->get('config', 'register_text', '')),
154                         '$fillwith'     => $fillwith,
155                         '$fillext'      => $fillext,
156                         '$oidlabel'     => $oidlabel,
157                         '$openid'       => $openid_url,
158                         '$namelabel'    => DI::l10n()->t('Your Display Name (as you would like it to be displayed on this system'),
159                         '$addrlabel'    => DI::l10n()->t('Your Email Address: (Initial information will be send there, so this has to be an existing address.)'),
160                         '$addrlabel2'   => DI::l10n()->t('Please repeat your e-mail address:'),
161                         '$ask_password' => $ask_password,
162                         '$password1'    => ['password1', DI::l10n()->t('New Password:'), '', DI::l10n()->t('Leave empty for an auto generated password.')],
163                         '$password2'    => ['confirm', DI::l10n()->t('Confirm:'), '', ''],
164                         '$nickdesc'     => DI::l10n()->t('Choose a profile nickname. This must begin with a text character. Your profile address on this site will then be "<strong>nickname@%s</strong>".', DI::baseUrl()->getHost()),
165                         '$nicklabel'    => DI::l10n()->t('Choose a nickname: '),
166                         '$photo'        => $photo,
167                         '$publish'      => $profile_publish,
168                         '$regbutt'      => DI::l10n()->t('Register'),
169                         '$username'     => $username,
170                         '$email'        => $email,
171                         '$nickname'     => $nickname,
172                         '$sitename'     => DI::baseUrl()->getHost(),
173                         '$importh'      => DI::l10n()->t('Import'),
174                         '$importt'      => DI::l10n()->t('Import your profile to this friendica instance'),
175                         '$showtoslink'  => DI::config()->get('system', 'tosdisplay'),
176                         '$tostext'      => DI::l10n()->t('Terms of Service'),
177                         '$showprivstatement' => DI::config()->get('system', 'tosprivstatement'),
178                         '$privstatement'=> $this->tos->privacy_complete,
179                         '$form_security_token' => BaseModule::getFormSecurityToken('register'),
180                         '$explicit_content' => DI::config()->get('system', 'explicit_content', false),
181                         '$explicit_content_note' => DI::l10n()->t('Note: This node explicitly contains adult content'),
182                         '$additional'   => !empty(DI::userSession()->getLocalUserId()),
183                         '$parent_password' => ['parent_password', DI::l10n()->t('Parent Password:'), '', DI::l10n()->t('Please enter the password of the parent account to legitimize your request.')]
184
185                 ]);
186
187                 return $o;
188         }
189
190         /**
191          * Module POST method to process submitted data
192          *
193          * Extend this method if the module is supposed to process POST requests.
194          * Doesn't display any content
195          */
196         protected function post(array $request = [])
197         {
198                 BaseModule::checkFormSecurityTokenRedirectOnError('/register', 'register');
199
200                 $arr = ['post' => $_POST];
201                 Hook::callAll('register_post', $arr);
202
203                 $additional_account = false;
204
205                 if (!DI::userSession()->getLocalUserId() && !empty($arr['post']['parent_password'])) {
206                         DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
207                         return;
208                 } elseif (DI::userSession()->getLocalUserId() && !empty($arr['post']['parent_password'])) {
209                         try {
210                                 Model\User::getIdFromPasswordAuthentication(DI::userSession()->getLocalUserId(), $arr['post']['parent_password']);
211                         } catch (\Exception $ex) {
212                                 DI::sysmsg()->addNotice(DI::l10n()->t("Password doesn't match."));
213                                 $regdata = ['nickname' => $arr['post']['nickname'], 'username' => $arr['post']['username']];
214                                 DI::baseUrl()->redirect('register?' . http_build_query($regdata));
215                         }
216                         $additional_account = true;
217                 } elseif (DI::userSession()->getLocalUserId()) {
218                         DI::sysmsg()->addNotice(DI::l10n()->t('Please enter your password.'));
219                         $regdata = ['nickname' => $arr['post']['nickname'], 'username' => $arr['post']['username']];
220                         DI::baseUrl()->redirect('register?' . http_build_query($regdata));
221                 }
222
223                 $max_dailies = intval(DI::config()->get('system', 'max_daily_registrations'));
224                 if ($max_dailies) {
225                         $count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']);
226                         if ($count >= $max_dailies) {
227                                 return;
228                         }
229                 }
230
231                 switch (DI::config()->get('config', 'register_policy')) {
232                         case self::OPEN:
233                                 $blocked = 0;
234                                 $verified = 1;
235                                 break;
236
237                         case self::APPROVE:
238                                 $blocked = 1;
239                                 $verified = 0;
240                                 break;
241
242                         case self::CLOSED:
243                         default:
244                                 if (empty($_SESSION['authenticated']) && empty($_SESSION['administrator'])) {
245                                         DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
246                                         return;
247                                 }
248                                 $blocked = 1;
249                                 $verified = 0;
250                                 break;
251                 }
252
253                 $netpublish = !empty($_POST['profile_publish_reg']);
254
255                 $arr = $_POST;
256
257                 // Is there text in the tar pit?
258                 if (!empty($arr['email'])) {
259                         Logger::info('Tar pit', $arr);
260                         DI::sysmsg()->addNotice(DI::l10n()->t('You have entered too much information.'));
261                         DI::baseUrl()->redirect('register/');
262                 }
263
264                 if ($additional_account) {
265                         $user = DBA::selectFirst('user', ['email'], ['uid' => DI::userSession()->getLocalUserId()]);
266                         if (!DBA::isResult($user)) {
267                                 DI::sysmsg()->addNotice(DI::l10n()->t('User not found.'));
268                                 DI::baseUrl()->redirect('register');
269                         }
270
271                         $blocked = 0;
272                         $verified = 1;
273
274                         $arr['password1'] = $arr['confirm'] = $arr['parent_password'];
275                         $arr['repeat'] = $arr['email'] = $user['email'];
276                 } else {
277                         // Overwriting the "tar pit" field with the real one
278                         $arr['email'] = $arr['field1'];
279                 }
280
281                 if ($arr['email'] != $arr['repeat']) {
282                         Logger::info('Mail mismatch', $arr);
283                         DI::sysmsg()->addNotice(DI::l10n()->t('Please enter the identical mail address in the second field.'));
284                         $regdata = ['email' => $arr['email'], 'nickname' => $arr['nickname'], 'username' => $arr['username']];
285                         DI::baseUrl()->redirect('register?' . http_build_query($regdata));
286                 }
287
288                 $arr['blocked'] = $blocked;
289                 $arr['verified'] = $verified;
290                 $arr['language'] = L10n::detectLanguage($_SERVER, $_GET, DI::config()->get('system', 'language'));
291
292                 try {
293                         $result = Model\User::create($arr);
294                 } catch (\Exception $e) {
295                         DI::sysmsg()->addNotice($e->getMessage());
296                         return;
297                 }
298
299                 $user = $result['user'];
300
301                 $base_url = (string)DI::baseUrl();
302
303                 if ($netpublish && intval(DI::config()->get('config', 'register_policy')) !== self::APPROVE) {
304                         $url = $base_url . '/profile/' . $user['nickname'];
305                         Worker::add(Worker::PRIORITY_LOW, 'Directory', $url);
306                 }
307
308                 if ($additional_account) {
309                         DBA::update('user', ['parent-uid' => DI::userSession()->getLocalUserId()], ['uid' => $user['uid']]);
310                         DI::sysmsg()->addInfo(DI::l10n()->t('The additional account was created.'));
311                         DI::baseUrl()->redirect('delegation');
312                 }
313
314                 $using_invites = DI::config()->get('system', 'invitation_only');
315                 $num_invites   = DI::config()->get('system', 'number_invites');
316                 $invite_id = (!empty($_POST['invite_id']) ? trim($_POST['invite_id']) : '');
317
318                 if (intval(DI::config()->get('config', 'register_policy')) === self::OPEN) {
319                         if ($using_invites && $invite_id) {
320                                 Model\Register::deleteByHash($invite_id);
321                                 DI::pConfig()->set($user['uid'], 'system', 'invites_remaining', $num_invites);
322                         }
323
324                         // Only send a password mail when the password wasn't manually provided
325                         if (empty($_POST['password1']) || empty($_POST['confirm'])) {
326                                 $res = Model\User::sendRegisterOpenEmail(
327                                         DI::l10n()->withLang($arr['language']),
328                                         $user,
329                                         DI::config()->get('config', 'sitename'),
330                                         $base_url,
331                                         $result['password']
332                                 );
333
334                                 if ($res) {
335                                         DI::sysmsg()->addInfo(DI::l10n()->t('Registration successful. Please check your email for further instructions.'));
336                                         if (DI::config()->get('system', 'register_notification')) {
337                                                 $this->sendNotification($user, 'SYSTEM_REGISTER_NEW');
338                                         }
339                                         DI::baseUrl()->redirect();
340                                 } else {
341                                         DI::sysmsg()->addNotice(
342                                                 DI::l10n()->t('Failed to send email message. Here your accout details:<br> login: %s<br> password: %s<br><br>You can change your password after login.',
343                                                         $user['email'],
344                                                         $result['password'])
345                                         );
346                                 }
347                         } else {
348                                 DI::sysmsg()->addInfo(DI::l10n()->t('Registration successful.'));
349                                 if (DI::config()->get('system', 'register_notification')) {
350                                         $this->sendNotification($user, 'SYSTEM_REGISTER_NEW');
351                                 }
352                                 DI::baseUrl()->redirect();
353                         }
354                 } elseif (intval(DI::config()->get('config', 'register_policy')) === self::APPROVE) {
355                         if (!User::getAdminEmailList()) {
356                                 $this->logger->critical('Registration policy is set to APPROVE but no admin email address has been set in config.admin_email');
357                                 DI::sysmsg()->addNotice(DI::l10n()->t('Your registration can not be processed.'));
358                                 DI::baseUrl()->redirect();
359                         }
360
361                         // Check if the note to the admin is actually filled out
362                         if (empty($_POST['permonlybox'])) {
363                                 DI::sysmsg()->addNotice(DI::l10n()->t('You have to leave a request note for the admin.')
364                                         . DI::l10n()->t('Your registration can not be processed.'));
365
366                                 $this->baseUrl->redirect('register');
367                         }
368
369                         try {
370                                 Model\Register::createForApproval($user['uid'], DI::config()->get('system', 'language'), $_POST['permonlybox']);
371                         } catch (\Throwable $e) {
372                                 $this->logger->error('Unable to create a `register` record.', ['user' => $user]);
373                                 DI::sysmsg()->addNotice(DI::l10n()->t('An internal error occured.')
374                                         . DI::l10n()->t('Your registration can not be processed.'));
375                                 $this->baseUrl->redirect('register');
376                         }
377
378                         // invite system
379                         if ($using_invites && $invite_id) {
380                                 Model\Register::deleteByHash($invite_id);
381                                 DI::pConfig()->set($user['uid'], 'system', 'invites_remaining', $num_invites);
382                         }
383
384                         // send notification to the admin
385                         $this->sendNotification($user, 'SYSTEM_REGISTER_REQUEST');
386
387                         // send notification to the user, that the registration is pending
388                         Model\User::sendRegisterPendingEmail(
389                                 $user,
390                                 DI::config()->get('config', 'sitename'),
391                                 $base_url,
392                                 $result['password']
393                         );
394
395                         DI::sysmsg()->addInfo(DI::l10n()->t('Your registration is pending approval by the site owner.'));
396                         DI::baseUrl()->redirect();
397                 }
398         }
399
400         private function sendNotification(array $user, string $event)
401         {
402                 foreach (User::getAdminListForEmailing(['uid', 'language', 'email']) as $admin) {
403                         DI::notify()->createFromArray([
404                                 'type'                      => Model\Notification\Type::SYSTEM,
405                                 'event'                     => $event,
406                                 'uid'                       => $admin['uid'],
407                                 'link'                      => DI::baseUrl() . '/moderation/users/',
408                                 'source_name'               => $user['username'],
409                                 'source_mail'               => $user['email'],
410                                 'source_nick'               => $user['nickname'],
411                                 'source_link'               => DI::baseUrl() . '/moderation/users/',
412                                 'source_photo'              => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
413                                 'show_in_notification_page' => false
414                         ]);
415                 }
416         }
417 }