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