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