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