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