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