]> git.mxchange.org Git - friendica.git/blob - src/Module/Register.php
Remove deprecated App::getHostName() - process methods to DI::baseUrl()->getHostName()
[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                         '$ask_password' => $ask_password,
125                         '$password1'    => ['password1', L10n::t('New Password:'), '', L10n::t('Leave empty for an auto generated password.')],
126                         '$password2'    => ['confirm', L10n::t('Confirm:'), '', ''],
127                         '$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()),
128                         '$nicklabel'    => L10n::t('Choose a nickname: '),
129                         '$photo'        => $photo,
130                         '$publish'      => $profile_publish,
131                         '$regbutt'      => L10n::t('Register'),
132                         '$username'     => $username,
133                         '$email'        => $email,
134                         '$nickname'     => $nickname,
135                         '$sitename'     => DI::baseUrl()->getHostname()(),
136                         '$importh'      => L10n::t('Import'),
137                         '$importt'      => L10n::t('Import your profile to this friendica instance'),
138                         '$showtoslink'  => Config::get('system', 'tosdisplay'),
139                         '$tostext'      => L10n::t('Terms of Service'),
140                         '$showprivstatement' => Config::get('system', 'tosprivstatement'),
141                         '$privstatement'=> $tos->privacy_complete,
142                         '$form_security_token' => BaseModule::getFormSecurityToken('register'),
143                         '$explicit_content' => Config::get('system', 'explicit_content', false),
144                         '$explicit_content_note' => L10n::t('Note: This node explicitly contains adult content')
145                 ]);
146
147                 return $o;
148         }
149
150         /**
151          * @brief Module POST method to process submitted data
152          *
153          * Extend this method if the module is supposed to process POST requests.
154          * Doesn't display any content
155          */
156         public static function post(array $parameters = [])
157         {
158                 BaseModule::checkFormSecurityTokenRedirectOnError('/register', 'register');
159
160                 $a = DI::app();
161
162                 $arr = ['post' => $_POST];
163                 Hook::callAll('register_post', $arr);
164
165                 $max_dailies = intval(Config::get('system', 'max_daily_registrations'));
166                 if ($max_dailies) {
167                         $count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']);
168                         if ($count >= $max_dailies) {
169                                 return;
170                         }
171                 }
172
173                 switch (Config::get('config', 'register_policy')) {
174                         case self::OPEN:
175                                 $blocked = 0;
176                                 $verified = 1;
177                                 break;
178
179                         case self::APPROVE:
180                                 $blocked = 1;
181                                 $verified = 0;
182                                 break;
183
184                         case self::CLOSED:
185                         default:
186                                 if (empty($_SESSION['authenticated']) && empty($_SESSION['administrator'])) {
187                                         \notice(L10n::t('Permission denied.') . EOL);
188                                         return;
189                                 }
190                                 $blocked = 1;
191                                 $verified = 0;
192                                 break;
193                 }
194
195                 $netpublish = !empty($_POST['profile_publish_reg']);
196
197                 $arr = $_POST;
198
199                 $arr['blocked'] = $blocked;
200                 $arr['verified'] = $verified;
201                 $arr['language'] = L10nClass::detectLanguage($_SERVER, $_GET, DI::config()->get('system', 'language'));
202
203                 try {
204                         $result = Model\User::create($arr);
205                 } catch (\Exception $e) {
206                         \notice($e->getMessage());
207                         return;
208                 }
209
210                 $user = $result['user'];
211
212                 $base_url = DI::baseUrl()->get();
213
214                 if ($netpublish && intval(Config::get('config', 'register_policy')) !== self::APPROVE) {
215                         $url = $base_url . '/profile/' . $user['nickname'];
216                         Worker::add(PRIORITY_LOW, 'Directory', $url);
217                 }
218
219                 $using_invites = Config::get('system', 'invitation_only');
220                 $num_invites   = Config::get('system', 'number_invites');
221                 $invite_id = (!empty($_POST['invite_id']) ? Strings::escapeTags(trim($_POST['invite_id'])) : '');
222
223                 if (intval(Config::get('config', 'register_policy')) === self::OPEN) {
224                         if ($using_invites && $invite_id) {
225                                 Model\Register::deleteByHash($invite_id);
226                                 PConfig::set($user['uid'], 'system', 'invites_remaining', $num_invites);
227                         }
228
229                         // Only send a password mail when the password wasn't manually provided
230                         if (empty($_POST['password1']) || empty($_POST['confirm'])) {
231                                 $res = Model\User::sendRegisterOpenEmail(
232                                         L10n::withLang($arr['language']),
233                                         $user,
234                                         Config::get('config', 'sitename'),
235                                         $base_url,
236                                         $result['password']
237                                 );
238
239                                 if ($res) {
240                                         \info(L10n::t('Registration successful. Please check your email for further instructions.') . EOL);
241                                         DI::baseUrl()->redirect();
242                                 } else {
243                                         \notice(
244                                                 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.',
245                                                         $user['email'],
246                                                         $result['password'])
247                                         );
248                                 }
249                         } else {
250                                 \info(L10n::t('Registration successful.') . EOL);
251                                 DI::baseUrl()->redirect();
252                         }
253                 } elseif (intval(Config::get('config', 'register_policy')) === self::APPROVE) {
254                         if (!strlen(Config::get('config', 'admin_email'))) {
255                                 \notice(L10n::t('Your registration can not be processed.') . EOL);
256                                 DI::baseUrl()->redirect();
257                         }
258
259                         // Check if the note to the admin is actually filled out
260                         if (empty($_POST['permonlybox'])) {
261                                 \notice(L10n::t('You have to leave a request note for the admin.')
262                                         . L10n::t('Your registration can not be processed.') . EOL);
263
264                                 DI::baseUrl()->redirect('register/');
265                         }
266                         // Is there text in the tar pit?
267                         if (!empty($_POST['registertarpit'])) {
268                                 \notice(L10n::t('You have entered too much information.'));
269                                 DI::baseUrl()->redirect('register/');
270                         }
271
272                         Model\Register::createForApproval($user['uid'], Config::get('system', 'language'), $_POST['permonlybox']);
273
274                         // invite system
275                         if ($using_invites && $invite_id) {
276                                 Model\Register::deleteByHash($invite_id);
277                                 PConfig::set($user['uid'], 'system', 'invites_remaining', $num_invites);
278                         }
279
280                         // send email to admins
281                         $admins_stmt = DBA::select(
282                                 'user',
283                                 ['uid', 'language', 'email'],
284                                 ['email' => explode(',', str_replace(' ', '', Config::get('config', 'admin_email')))]
285                         );
286
287                         // send notification to admins
288                         while ($admin = DBA::fetch($admins_stmt)) {
289                                 \notification([
290                                         'type'         => NOTIFY_SYSTEM,
291                                         'event'        => 'SYSTEM_REGISTER_REQUEST',
292                                         'source_name'  => $user['username'],
293                                         'source_mail'  => $user['email'],
294                                         'source_nick'  => $user['nickname'],
295                                         'source_link'  => $base_url . '/admin/users/',
296                                         'link'         => $base_url . '/admin/users/',
297                                         'source_photo' => $base_url . '/photo/avatar/' . $user['uid'] . '.jpg',
298                                         'to_email'     => $admin['email'],
299                                         'uid'          => $admin['uid'],
300                                         'language'     => ($admin['language'] ?? '') ?: 'en',
301                                         'show_in_notification_page' => false
302                                 ]);
303                         }
304                         DBA::close($admins_stmt);
305
306                         // send notification to the user, that the registration is pending
307                         Model\User::sendRegisterPendingEmail(
308                                 $user,
309                                 Config::get('config', 'sitename'),
310                                 $base_url,
311                                 $result['password']
312                         );
313
314                         \info(L10n::t('Your registration is pending approval by the site owner.') . EOL);
315                         DI::baseUrl()->redirect();
316                 }
317
318                 return;
319         }
320 }