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