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