]> git.mxchange.org Git - friendica.git/blob - mod/register.php
aeeec7c1fa59c079170edbda7352084831e470d3
[friendica.git] / mod / register.php
1 <?php
2
3 if(! function_exists('register_post')) {
4 function register_post(&$a) {
5
6         global $lang;
7
8         $verified = 0;
9         $blocked  = 1;
10
11         $arr = array('post' => $_POST);
12         call_hooks('register_post', $arr);
13
14         $max_dailies = intval(get_config('system','max_daily_registrations'));
15         if($max_dailes) {
16                 $r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day");
17                 if($r && $r[0]['total'] >= $max_dailies) {
18                         return;
19                 }
20         }
21
22         switch($a->config['register_policy']) {
23
24         
25         case REGISTER_OPEN:
26                 $blocked = 0;
27                 $verified = 1;
28                 break;
29
30         case REGISTER_APPROVE:
31                 $blocked = 1;
32                 $verified = 0;
33                 break;
34
35         default:
36         case REGISTER_CLOSED:
37                 if((! x($_SESSION,'authenticated') && (! x($_SESSION,'administrator')))) {
38                         notice( t('Permission denied.') . EOL );
39                         return;
40                 }
41                 $blocked = 1;
42                 $verified = 0;
43                 break;
44         }
45
46         $using_invites = get_config('system','invitation_only');
47         $num_invites = get_config('system','number_invites');
48
49
50         $invite_id  = ((x($_POST,'invite_id'))  ? notags(trim($_POST['invite_id']))  : '');
51         $username   = ((x($_POST,'username'))   ? notags(trim($_POST['username']))   : '');
52         $nickname   = ((x($_POST,'nickname'))   ? notags(trim($_POST['nickname']))   : '');
53         $email      = ((x($_POST,'email'))      ? notags(trim($_POST['email']))      : '');
54         $openid_url = ((x($_POST,'openid_url')) ? notags(trim($_POST['openid_url'])) : '');
55         $photo      = ((x($_POST,'photo'))      ? notags(trim($_POST['photo']))      : '');
56         $publish    = ((x($_POST,'profile_publish_reg') && intval($_POST['profile_publish_reg'])) ? 1 : 0);
57
58         $netpublish = ((strlen(get_config('system','directory_submit_url'))) ? $publish : 0);
59                 
60         $tmp_str = $openid_url;
61
62         if($using_invites) {
63                 if(! $invite_id) {
64                         notice( t('An invitation is required.') . EOL);
65                         return;
66                 }
67                 $r = q("select * from register where `hash` = '%s' limit 1", dbesc($invite_id));
68                 if(! results($r)) {
69                         notice( t('Invitation could not be verified.') . EOL);
70                         return;
71                 }
72         } 
73
74         if((! x($username)) || (! x($email)) || (! x($nickname))) {
75                 if($openid_url) {
76                         if(! validate_url($tmp_str)) {
77                                 notice( t('Invalid OpenID url') . EOL);
78                                 return;
79                         }
80                         $_SESSION['register'] = 1;
81                         $_SESSION['openid'] = $openid_url;
82                         require_once('library/openid.php');
83                         $openid = new LightOpenID;
84                         $openid->identity = $openid_url;
85                         $openid->returnUrl = $a->get_baseurl() . '/openid'; 
86                         $openid->required = array('namePerson/friendly', 'contact/email', 'namePerson');
87                         $openid->optional = array('namePerson/first','media/image/aspect11','media/image/default');
88                         goaway($openid->authUrl());
89                         // NOTREACHED   
90                 }
91
92                 notice( t('Please enter the required information.') . EOL );
93                 return;
94         }
95
96         if(! validate_url($tmp_str))
97                 $openid_url = '';
98
99
100         $err = '';
101
102         // collapse multiple spaces in name
103         $username = preg_replace('/ +/',' ',$username);
104
105         if(mb_strlen($username) > 48)
106                 $err .= t('Please use a shorter name.') . EOL;
107         if(mb_strlen($username) < 3)
108                 $err .= t('Name too short.') . EOL;
109
110         // I don't really like having this rule, but it cuts down
111         // on the number of auto-registrations by Russian spammers
112         
113         //  Using preg_match was completely unreliable, due to mixed UTF-8 regex support
114         //      $no_utf = get_config('system','no_utf');
115         //      $pat = (($no_utf) ? '/^[a-zA-Z]* [a-zA-Z]*$/' : '/^\p{L}* \p{L}*$/u' ); 
116
117         // So now we are just looking for a space in the full name. 
118         
119         $loose_reg = get_config('system','no_regfullname');
120         if(! $loose_reg) {
121                 $username = mb_convert_case($username,MB_CASE_TITLE,'UTF-8');
122                 if(! strpos($username,' '))
123                         $err .= t("That doesn't appear to be your full \x28First Last\x29 name.") . EOL;
124         }
125
126
127         if(! allowed_email($email))
128                         $err .= t('Your email domain is not among those allowed on this site.') . EOL;
129
130         if((! valid_email($email)) || (! validate_email($email)))
131                 $err .= t('Not a valid email address.') . EOL;
132
133         // Disallow somebody creating an account using openid that uses the admin email address,
134         // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
135
136         if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) {
137                 $r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1",
138                         dbesc($email)
139                 );
140                 if(count($r))
141                         $err .= t('Cannot use that email.') . EOL;
142         }
143
144         $nickname = $_POST['nickname'] = strtolower($nickname);
145
146         if(! preg_match("/^[a-z][a-z0-9\-\_]*$/",$nickname))
147                 $err .= t('Your "nickname" can only contain "a-z", "0-9", "-", and "_", and must also begin with a letter.') . EOL;
148         $r = q("SELECT `uid` FROM `user`
149                 WHERE `nickname` = '%s' LIMIT 1",
150                 dbesc($nickname)
151         );
152         if(count($r))
153                 $err .= t('Nickname is already registered. Please choose another.') . EOL;
154
155         // Check deleted accounts that had this nickname. Doesn't matter to us,
156         // but could be a security issue for federated platforms.
157
158         $r = q("SELECT * FROM `userd`
159                 WHERE `username` = '%s' LIMIT 1",
160                 dbesc($nickname)
161         );
162         if(count($r))
163                 $err .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
164
165         if(strlen($err)) {
166                 notice( $err );
167                 return;
168         }
169
170
171         $new_password = autoname(6) . mt_rand(100,9999);
172         $new_password_encoded = hash('whirlpool',$new_password);
173
174         require_once('include/crypto.php');
175
176         $result = new_keypair(1024);
177
178         if($result === false) {
179                 notice( t('SERIOUS ERROR: Generation of security keys failed.') . EOL);
180                 return;
181         }
182
183         $prvkey = $result['prvkey'];
184         $pubkey = $result['pubkey'];
185
186         /**
187          *
188          * Create another keypair for signing/verifying
189          * salmon protocol messages. We have to use a slightly
190          * less robust key because this won't be using openssl
191          * but the phpseclib. Since it is PHP interpreted code
192          * it is not nearly as efficient, and the larger keys
193          * will take several minutes each to process.
194          *
195          */
196         
197         $sres    = new_keypair(512);
198         $sprvkey = $sres['prvkey'];
199         $spubkey = $sres['pubkey'];
200
201         $r = q("INSERT INTO `user` ( `guid`, `username`, `password`, `email`, `openid`, `nickname`,
202                 `pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone` )
203                 VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC' )",
204                 dbesc(generate_user_guid()),
205                 dbesc($username),
206                 dbesc($new_password_encoded),
207                 dbesc($email),
208                 dbesc($openid_url),
209                 dbesc($nickname),
210                 dbesc($pubkey),
211                 dbesc($prvkey),
212                 dbesc($spubkey),
213                 dbesc($sprvkey),
214                 dbesc(datetime_convert()),
215                 intval($verified),
216                 intval($blocked)
217                 );
218
219         if($r) {
220                 $r = q("SELECT `uid` FROM `user` 
221                         WHERE `username` = '%s' AND `password` = '%s' LIMIT 1",
222                         dbesc($username),
223                         dbesc($new_password_encoded)
224                         );
225                 if($r !== false && count($r))
226                         $newuid = intval($r[0]['uid']);
227         }
228         else {
229                 notice( t('An error occurred during registration. Please try again.') . EOL );
230                 return;
231         }               
232
233         /**
234          * if somebody clicked submit twice very quickly, they could end up with two accounts 
235          * due to race condition. Remove this one.
236          */
237
238         $r = q("SELECT `uid` FROM `user`
239                 WHERE `nickname` = '%s' ",
240                 dbesc($nickname)
241         );
242         if((count($r) > 1) && $newuid) {
243                 $err .= t('Nickname is already registered. Please choose another.') . EOL;
244                 q("DELETE FROM `user` WHERE `uid` = %d LIMIT 1",
245                         intval($newuid)
246                 );
247                 notice ($err);
248                 return;
249         }
250
251         if(x($newuid) !== false) {
252                 $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )
253                         VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ",
254                         intval($newuid),
255                         'default',
256                         1,
257                         dbesc($username),
258                         dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"),
259                         dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"),
260                         intval($publish),
261                         intval($netpublish)
262
263                 );
264                 if($r === false) {
265                         notice( t('An error occurred creating your default profile. Please try again.') . EOL );
266                         // Start fresh next time.
267                         $r = q("DELETE FROM `user` WHERE `uid` = %d",
268                                 intval($newuid));
269                         return;
270                 }
271                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `self`, `name`, `nick`, `photo`, `thumb`, `micro`, `blocked`, `pending`, `url`, `nurl`,
272                         `request`, `notify`, `poll`, `confirm`, `poco`, `name-date`, `uri-date`, `avatar-date`, `closeness` )
273                         VALUES ( %d, '%s', 1, '%s', '%s', '%s', '%s', '%s', 0, 0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 0 ) ",
274                         intval($newuid),
275                         datetime_convert(),
276                         dbesc($username),
277                         dbesc($nickname),
278                         dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"),
279                         dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"),
280                         dbesc($a->get_baseurl() . "/photo/micro/{$newuid}.jpg"),
281                         dbesc($a->get_baseurl() . "/profile/$nickname"),
282                         dbesc(normalise_link($a->get_baseurl() . "/profile/$nickname")),
283                         dbesc($a->get_baseurl() . "/dfrn_request/$nickname"),
284                         dbesc($a->get_baseurl() . "/dfrn_notify/$nickname"),
285                         dbesc($a->get_baseurl() . "/dfrn_poll/$nickname"),
286                         dbesc($a->get_baseurl() . "/dfrn_confirm/$nickname"),
287                         dbesc($a->get_baseurl() . "/poco/$nickname"),
288                         dbesc(datetime_convert()),
289                         dbesc(datetime_convert()),
290                         dbesc(datetime_convert())
291                 );
292
293                 // Create a group with no members. This allows somebody to use it 
294                 // right away as a default group for new contacts. 
295
296                 require_once('include/group.php');
297                 group_add($newuid, t('Friends'));
298
299         }
300
301         // if we have no OpenID photo try to look up an avatar
302         if(! strlen($photo))
303                 $photo = avatar_img($email);
304
305         // unless there is no avatar-plugin loaded
306         if(strlen($photo)) {
307                 require_once('include/Photo.php');
308                 $photo_failure = false;
309
310                 $filename = basename($photo);
311                 $img_str = fetch_url($photo,true);
312                 $img = new Photo($img_str);
313                 if($img->is_valid()) {
314
315                         $img->scaleImageSquare(175);
316
317                         $hash = photo_new_resource();
318
319                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 4 );
320
321                         if($r === false)
322                                 $photo_failure = true;
323
324                         $img->scaleImage(80);
325
326                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 5 );
327
328                         if($r === false)
329                                 $photo_failure = true;
330
331                         $img->scaleImage(48);
332
333                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 6 );
334
335                         if($r === false)
336                                 $photo_failure = true;
337
338                         if(! $photo_failure) {
339                                 q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ",
340                                         dbesc($hash)
341                                 );
342                         }
343                 }
344         }
345
346         if($netpublish && $a->config['register_policy'] != REGISTER_APPROVE) {
347                 $url = $a->get_baseurl() . "/profile/$nickname";
348                 proc_run('php',"include/directory.php","$url");
349         }
350
351
352         call_hooks('register_account', $newuid);
353
354         if( $a->config['register_policy'] == REGISTER_OPEN ) {
355
356                 if($using_invites && $invite_id) {
357                         q("delete * from register where hash = '%s' limit 1", dbesc($invite_id));
358                         set_pconfig($newuid,'system','invites_remaining',$num_invites);
359                 }
360
361                 $email_tpl = get_intltext_template("register_open_eml.tpl");
362                 $email_tpl = replace_macros($email_tpl, array(
363                                 '$sitename' => $a->config['sitename'],
364                                 '$siteurl' =>  $a->get_baseurl(),
365                                 '$username' => $username,
366                                 '$email' => $email,
367                                 '$password' => $new_password,
368                                 '$uid' => $newuid ));
369
370                 $res = mail($email, sprintf(t('Registration details for %s'), $a->config['sitename']),
371                         $email_tpl, 
372                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
373                                 . 'Content-type: text/plain; charset=UTF-8' . "\n"
374                                 . 'Content-transfer-encoding: 8bit' );
375
376
377                 if($res) {
378                         info( t('Registration successful. Please check your email for further instructions.') . EOL ) ;
379                         goaway(z_root());
380                 }
381                 else {
382                         notice( t('Failed to send email message. Here is the message that failed.') . $email_tpl . EOL );
383                 }
384         }
385         elseif($a->config['register_policy'] == REGISTER_APPROVE) {
386                 if(! strlen($a->config['admin_email'])) {
387                         notice( t('Your registration can not be processed.') . EOL);
388                         goaway(z_root());
389                 }
390
391                 $hash = random_string();
392                 $r = q("INSERT INTO `register` ( `hash`, `created`, `uid`, `password`, `language` ) VALUES ( '%s', '%s', %d, '%s', '%s' ) ",
393                         dbesc($hash),
394                         dbesc(datetime_convert()),
395                         intval($newuid),
396                         dbesc($new_password),
397                         dbesc($lang)
398                 );
399
400                 $r = q("SELECT `language` FROM `user` WHERE `email` = '%s' LIMIT 1",
401                         dbesc($a->config['admin_email'])
402                 );
403                 if(count($r))
404                         push_lang($r[0]['language']);
405                 else
406                         push_lang('en');
407
408                 if($using_invites && $invite_id) {
409                         q("delete * from register where hash = '%s' limit 1", dbesc($invite_id));
410                         set_pconfig($newuid,'system','invites_remaining',$num_invites);
411                 }
412
413                 $email_tpl = get_intltext_template("register_verify_eml.tpl");
414                 $email_tpl = replace_macros($email_tpl, array(
415                                 '$sitename' => $a->config['sitename'],
416                                 '$siteurl' =>  $a->get_baseurl(),
417                                 '$username' => $username,
418                                 '$email' => $email,
419                                 '$password' => $new_password,
420                                 '$uid' => $newuid,
421                                 '$hash' => $hash
422                  ));
423
424                 $res = mail($a->config['admin_email'], sprintf(t('Registration request at %s'), $a->config['sitename']),
425                         $email_tpl,
426                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
427                                 . 'Content-type: text/plain; charset=UTF-8' . "\n"
428                                 . 'Content-transfer-encoding: 8bit' );
429
430                 pop_lang();
431
432                 if($res) {
433                         info( t('Your registration is pending approval by the site owner.') . EOL ) ;
434                         goaway(z_root());
435                 }
436
437         }
438
439         return;
440 }}
441
442
443
444
445
446
447 if(! function_exists('register_content')) {
448 function register_content(&$a) {
449
450         // logged in users can register others (people/pages/groups)
451         // even with closed registrations, unless specifically prohibited by site policy.
452         // 'block_extended_register' blocks all registrations, period.
453
454         $block = get_config('system','block_extended_register');
455
456         if(local_user() && ($block)) {
457                 notice("Permission denied." . EOL);
458                 return;
459         }
460
461         if((! local_user()) && ($a->config['register_policy'] == REGISTER_CLOSED)) {
462                 notice("Permission denied." . EOL);
463                 return;
464         }
465
466         $max_dailies = intval(get_config('system','max_daily_registrations'));
467         if($max_dailes) {
468                 $r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day");
469                 if($r && $r[0]['total'] >= $max_dailies) {
470                         logger('max daily registrations exceeded.');
471                         notice( t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.') . EOL);
472                         return;
473                 }
474         }
475
476         if(x($_SESSION,'theme'))
477                 unset($_SESSION['theme']);
478
479
480         $username     = ((x($_POST,'username'))     ? $_POST['username']     : ((x($_GET,'username'))     ? $_GET['username']              : ''));
481         $email        = ((x($_POST,'email'))        ? $_POST['email']        : ((x($_GET,'email'))        ? $_GET['email']                 : ''));
482         $openid_url   = ((x($_POST,'openid_url'))   ? $_POST['openid_url']   : ((x($_GET,'openid_url'))   ? $_GET['openid_url']            : ''));
483         $nickname     = ((x($_POST,'nickname'))     ? $_POST['nickname']     : ((x($_GET,'nickname'))     ? $_GET['nickname']              : ''));
484         $photo        = ((x($_POST,'photo'))        ? $_POST['photo']        : ((x($_GET,'photo'))        ? hex2bin($_GET['photo'])        : ''));
485         $invite_id    = ((x($_POST,'invite_id'))    ? $_POST['invite_id']    : ((x($_GET,'invite_id'))    ? $_GET['invite_id']             : ''));
486
487         $noid = get_config('system','no_openid');
488
489         if($noid) {
490                 $oidhtml = '';
491                 $fillwith = '';
492                 $fillext = '';
493                 $oidlabel = '';
494         }
495         else {
496                 $oidhtml = '<label for="register-openid" id="label-register-openid" >$oidlabel</label><input type="text" maxlength="60" size="32" name="openid_url" class="openid" id="register-openid" value="$openid" >';
497                 $fillwith = t("You may \x28optionally\x29 fill in this form via OpenID by supplying your OpenID and clicking 'Register'.");
498                 $fillext =  t('If you are not familiar with OpenID, please leave that field blank and fill in the rest of the items.');
499                 $oidlabel = t("Your OpenID \x28optional\x29: ");
500         }
501
502         // I set this and got even more fake names than before...
503
504         $realpeople = ''; // t('Members of this network prefer to communicate with real people who use their real names.');
505
506         if(get_config('system','publish_all')) {
507                 $profile_publish_reg = '<input type="hidden" name="profile_publish_reg" value="1" />';
508         }
509         else {
510                 $publish_tpl = get_markup_template("profile_publish.tpl");
511                 $profile_publish = replace_macros($publish_tpl,array(
512                         '$instance'     => 'reg',
513                         '$pubdesc'      => t('Include your profile in member directory?'),
514                         '$yes_selected' => ' checked="checked" ',
515                         '$no_selected'  => '',
516                         '$str_yes'      => t('Yes'),
517                         '$str_no'       => t('No')
518                 ));
519         }
520
521
522         $license = '';
523
524         $o = get_markup_template("register.tpl");
525
526         $arr = array('template' => $o);
527
528         call_hooks('register_form',$arr);
529
530         $o = replace_macros($o, array(
531                 '$oidhtml' => $oidhtml,
532                 '$invitations' => get_config('system','invitation_only'),
533                 '$invite_desc' => t('Membership on this site is by invitation only.'),
534                 '$invite_label' => t('Your invitation ID: '),
535                 '$invite_id' => $invite_id,
536                 '$realpeople' => $realpeople,
537                 '$regtitle'  => t('Registration'),
538                 '$registertext' =>((x($a->config,'register_text'))
539                         ? '<div class="error-message">' . $a->config['register_text'] . '</div>'
540                         : "" ),
541                 '$fillwith'  => $fillwith,
542                 '$fillext'   => $fillext,
543                 '$oidlabel'  => $oidlabel,
544                 '$openid'    => $openid_url,
545                 '$namelabel' => t('Your Full Name ' . "\x28" . 'e.g. Joe Smith' . "\x29" . ': '),
546                 '$addrlabel' => t('Your Email Address: '),
547                 '$nickdesc'  => t('Choose a profile nickname. This must begin with a text character. Your profile address on this site will then be \'<strong>nickname@$sitename</strong>\'.'),
548                 '$nicklabel' => t('Choose a nickname: '),
549                 '$photo'     => $photo,
550                 '$publish'   => $profile_publish,
551                 '$regbutt'   => t('Register'),
552                 '$username'  => $username,
553                 '$email'     => $email,
554                 '$nickname'  => $nickname,
555                 '$license'   => $license,
556                 '$sitename'  => $a->get_hostname()
557         ));
558         return $o;
559
560 }}
561