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