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