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