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