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