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