3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module;
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;
37 use Friendica\Model\User;
38 use Friendica\Util\Profiler;
39 use Friendica\Util\Proxy;
40 use Psr\Log\LoggerInterface;
43 * @author Hypolite Petovan <hypolite@mrpetovan.com>
45 class Register extends BaseModule
54 public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, IManageConfigValues $config, array $server, array $parameters = [])
56 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
58 $this->tos = new Tos($l10n, $baseUrl, $args, $logger, $profiler, $response, $config, $server, $parameters);
62 * Module GET method to display any content
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.
70 protected function content(array $request = []): string
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');
77 if (Session::getLocalUser() && $block) {
78 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
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.'));
90 if (!Session::getLocalUser() && (intval(DI::config()->get('config', 'register_policy')) === self::CLOSED)) {
91 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
95 $max_dailies = intval(DI::config()->get('system', 'max_daily_registrations'));
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.'));
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'] ?? '';
112 if (Session::getLocalUser() || DI::config()->get('system', 'no_openid')) {
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): ');
122 if (DI::config()->get('system', 'publish_all')) {
123 $profile_publish = '<input type="hidden" name="profile_publish_reg" value="1" />';
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'),
136 $ask_password = !DBA::count('contact');
138 $tpl = Renderer::getMarkupTemplate('register.tpl');
140 $arr = ['template' => $tpl];
142 Hook::callAll('register_form', $arr);
144 $tpl = $arr['template'];
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: '),
168 '$publish' => $profile_publish,
169 '$regbutt' => DI::l10n()->t('Register'),
170 '$username' => $username,
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.')]
192 * Module POST method to process submitted data
194 * Extend this method if the module is supposed to process POST requests.
195 * Doesn't display any content
197 protected function post(array $request = [])
199 BaseModule::checkFormSecurityTokenRedirectOnError('/register', 'register');
201 $arr = ['post' => $_POST];
202 Hook::callAll('register_post', $arr);
204 $additional_account = false;
206 if (!Session::getLocalUser() && !empty($arr['post']['parent_password'])) {
207 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
209 } elseif (Session::getLocalUser() && !empty($arr['post']['parent_password'])) {
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));
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));
224 $max_dailies = intval(DI::config()->get('system', 'max_daily_registrations'));
226 $count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']);
227 if ($count >= $max_dailies) {
232 switch (DI::config()->get('config', 'register_policy')) {
245 if (empty($_SESSION['authenticated']) && empty($_SESSION['administrator'])) {
246 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
254 $netpublish = !empty($_POST['profile_publish_reg']);
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/');
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');
275 $arr['password1'] = $arr['confirm'] = $arr['parent_password'];
276 $arr['repeat'] = $arr['email'] = $user['email'];
278 // Overwriting the "tar pit" field with the real one
279 $arr['email'] = $arr['field1'];
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));
289 $arr['blocked'] = $blocked;
290 $arr['verified'] = $verified;
291 $arr['language'] = L10n::detectLanguage($_SERVER, $_GET, DI::config()->get('system', 'language'));
294 $result = Model\User::create($arr);
295 } catch (\Exception $e) {
296 DI::sysmsg()->addNotice($e->getMessage());
300 $user = $result['user'];
302 $base_url = DI::baseUrl()->get();
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);
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');
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']) : '');
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);
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']),
330 DI::config()->get('config', 'sitename'),
336 DI::sysmsg()->addInfo(DI::l10n()->t('Registration successful. Please check your email for further instructions.'));
337 DI::baseUrl()->redirect();
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.',
346 DI::sysmsg()->addInfo(DI::l10n()->t('Registration successful.'));
347 DI::baseUrl()->redirect();
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();
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.'));
360 DI::baseUrl()->redirect('register/');
363 Model\Register::createForApproval($user['uid'], DI::config()->get('system', 'language'), $_POST['permonlybox']);
366 if ($using_invites && $invite_id) {
367 Model\Register::deleteByHash($invite_id);
368 DI::pConfig()->set($user['uid'], 'system', 'invites_remaining', $num_invites);
371 // send email to admins
372 $admins_stmt = DBA::select(
374 ['uid', 'language', 'email'],
375 ['email' => explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')))]
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
393 DBA::close($admins_stmt);
395 // send notification to the user, that the registration is pending
396 Model\User::sendRegisterPendingEmail(
398 DI::config()->get('config', 'sitename'),
403 DI::sysmsg()->addInfo(DI::l10n()->t('Your registration is pending approval by the site owner.'));
404 DI::baseUrl()->redirect();