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