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