]> git.mxchange.org Git - friendica.git/blob - src/Module/Register.php
Merge pull request #9488 from annando/profile-query
[friendica.git] / src / Module / Register.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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'), '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                 $a = DI::app();
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
254                 // Overwriting the "tar pit" field with the real one
255                 $arr['email'] = $arr['field1'];
256
257                 if ($additional_account) {
258                         $user = DBA::selectFirst('user', ['email'], ['uid' => local_user()]);
259                         if (!DBA::isResult($user)) {
260                                 notice(DI::l10n()->t('User not found.'));
261                                 DI::baseUrl()->redirect('register');
262                         }
263
264                         $blocked = 0;
265                         $verified = 1;
266
267                         $arr['password1'] = $arr['confirm'] = $arr['parent_password'];
268                         $arr['repeat'] = $arr['email'] = $user['email'];
269                 }
270
271                 if ($arr['email'] != $arr['repeat']) {
272                         Logger::info('Mail mismatch', $arr);
273                         notice(DI::l10n()->t('Please enter the identical mail address in the second field.'));
274                         $regdata = ['email' => $arr['email'], 'nickname' => $arr['nickname'], 'username' => $arr['username']];
275                         DI::baseUrl()->redirect('register?' . http_build_query($regdata));
276                 }
277
278                 $arr['blocked'] = $blocked;
279                 $arr['verified'] = $verified;
280                 $arr['language'] = L10n::detectLanguage($_SERVER, $_GET, DI::config()->get('system', 'language'));
281
282                 try {
283                         $result = Model\User::create($arr);
284                 } catch (\Exception $e) {
285                         notice($e->getMessage());
286                         return;
287                 }
288
289                 $user = $result['user'];
290
291                 $base_url = DI::baseUrl()->get();
292
293                 if ($netpublish && intval(DI::config()->get('config', 'register_policy')) !== self::APPROVE) {
294                         $url = $base_url . '/profile/' . $user['nickname'];
295                         Worker::add(PRIORITY_LOW, 'Directory', $url);
296                 }
297
298                 if ($additional_account) {
299                         DBA::update('user', ['parent-uid' => local_user()], ['uid' => $user['uid']]);
300                         info(DI::l10n()->t('The additional account was created.'));
301                         DI::baseUrl()->redirect('delegation');
302                 }
303
304                 $using_invites = DI::config()->get('system', 'invitation_only');
305                 $num_invites   = DI::config()->get('system', 'number_invites');
306                 $invite_id = (!empty($_POST['invite_id']) ? Strings::escapeTags(trim($_POST['invite_id'])) : '');
307
308                 if (intval(DI::config()->get('config', 'register_policy')) === self::OPEN) {
309                         if ($using_invites && $invite_id) {
310                                 Model\Register::deleteByHash($invite_id);
311                                 DI::pConfig()->set($user['uid'], 'system', 'invites_remaining', $num_invites);
312                         }
313
314                         // Only send a password mail when the password wasn't manually provided
315                         if (empty($_POST['password1']) || empty($_POST['confirm'])) {
316                                 $res = Model\User::sendRegisterOpenEmail(
317                                         DI::l10n()->withLang($arr['language']),
318                                         $user,
319                                         DI::config()->get('config', 'sitename'),
320                                         $base_url,
321                                         $result['password']
322                                 );
323
324                                 if ($res) {
325                                         info(DI::l10n()->t('Registration successful. Please check your email for further instructions.'));
326                                         DI::baseUrl()->redirect();
327                                 } else {
328                                         notice(
329                                                 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.',
330                                                         $user['email'],
331                                                         $result['password'])
332                                         );
333                                 }
334                         } else {
335                                 info(DI::l10n()->t('Registration successful.'));
336                                 DI::baseUrl()->redirect();
337                         }
338                 } elseif (intval(DI::config()->get('config', 'register_policy')) === self::APPROVE) {
339                         if (!strlen(DI::config()->get('config', 'admin_email'))) {
340                                 notice(DI::l10n()->t('Your registration can not be processed.'));
341                                 DI::baseUrl()->redirect();
342                         }
343
344                         // Check if the note to the admin is actually filled out
345                         if (empty($_POST['permonlybox'])) {
346                                 notice(DI::l10n()->t('You have to leave a request note for the admin.')
347                                         . DI::l10n()->t('Your registration can not be processed.'));
348
349                                 DI::baseUrl()->redirect('register/');
350                         }
351
352                         Model\Register::createForApproval($user['uid'], DI::config()->get('system', 'language'), $_POST['permonlybox']);
353
354                         // invite system
355                         if ($using_invites && $invite_id) {
356                                 Model\Register::deleteByHash($invite_id);
357                                 DI::pConfig()->set($user['uid'], 'system', 'invites_remaining', $num_invites);
358                         }
359
360                         // send email to admins
361                         $admins_stmt = DBA::select(
362                                 'user',
363                                 ['uid', 'language', 'email'],
364                                 ['email' => explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')))]
365                         );
366
367                         // send notification to admins
368                         while ($admin = DBA::fetch($admins_stmt)) {
369                                 \notification([
370                                         'type'         => Model\Notify\Type::SYSTEM,
371                                         'event'        => 'SYSTEM_REGISTER_REQUEST',
372                                         'source_name'  => $user['username'],
373                                         'source_mail'  => $user['email'],
374                                         'source_nick'  => $user['nickname'],
375                                         'source_link'  => $base_url . '/admin/users/',
376                                         'link'         => $base_url . '/admin/users/',
377                                         'source_photo' => $base_url . '/photo/avatar/' . $user['uid'] . '.jpg',
378                                         'to_email'     => $admin['email'],
379                                         'uid'          => $admin['uid'],
380                                         'language'     => ($admin['language'] ?? '') ?: 'en',
381                                         'show_in_notification_page' => false
382                                 ]);
383                         }
384                         DBA::close($admins_stmt);
385
386                         // send notification to the user, that the registration is pending
387                         Model\User::sendRegisterPendingEmail(
388                                 $user,
389                                 DI::config()->get('config', 'sitename'),
390                                 $base_url,
391                                 $result['password']
392                         );
393
394                         info(DI::l10n()->t('Your registration is pending approval by the site owner.'));
395                         DI::baseUrl()->redirect();
396                 }
397
398                 return;
399         }
400 }