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