]> git.mxchange.org Git - friendica.git/blob - mod/register.php
diabook: theme.php
[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         // Check deleted accounts that had this nickname. Doesn't matter to us,
154         // but could be a security issue for federated platforms.
155
156         $r = q("SELECT * FROM `userd`
157                 WHERE `username` = '%s' LIMIT 1",
158                 dbesc($nickname)
159         );
160         if(count($r))
161                 $err .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
162
163         if(strlen($err)) {
164                 notice( $err );
165                 return;
166         }
167
168
169         $new_password = autoname(6) . mt_rand(100,9999);
170         $new_password_encoded = hash('whirlpool',$new_password);
171
172         $res=openssl_pkey_new(array(
173                 'digest_alg' => 'sha1',
174                 'private_key_bits' => 4096,
175                 'encrypt_key' => false ));
176
177         // Get private key
178
179         if(empty($res)) {
180                 notice( t('SERIOUS ERROR: Generation of security keys failed.') . EOL);
181                 return;
182         }
183
184         $prvkey = '';
185
186         openssl_pkey_export($res, $prvkey);
187
188         // Get public key
189
190         $pkey = openssl_pkey_get_details($res);
191         $pubkey = $pkey["key"];
192
193         /**
194          *
195          * Create another keypair for signing/verifying
196          * salmon protocol messages. We have to use a slightly
197          * less robust key because this won't be using openssl
198          * but the phpseclib. Since it is PHP interpreted code
199          * it is not nearly as efficient, and the larger keys
200          * will take several minutes each to process.
201          *
202          */
203         
204         $sres=openssl_pkey_new(array(
205                 'digest_alg' => 'sha1',
206                 'private_key_bits' => 512,
207                 'encrypt_key' => false ));
208
209         // Get private key
210
211         $sprvkey = '';
212
213         openssl_pkey_export($sres, $sprvkey);
214
215         // Get public key
216
217         $spkey = openssl_pkey_get_details($sres);
218         $spubkey = $spkey["key"];
219
220         $r = q("INSERT INTO `user` ( `guid`, `username`, `password`, `email`, `openid`, `nickname`,
221                 `pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked` )
222                 VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d )",
223                 dbesc(generate_user_guid()),
224                 dbesc($username),
225                 dbesc($new_password_encoded),
226                 dbesc($email),
227                 dbesc($openid_url),
228                 dbesc($nickname),
229                 dbesc($pubkey),
230                 dbesc($prvkey),
231                 dbesc($spubkey),
232                 dbesc($sprvkey),
233                 dbesc(datetime_convert()),
234                 intval($verified),
235                 intval($blocked)
236                 );
237
238         if($r) {
239                 $r = q("SELECT `uid` FROM `user` 
240                         WHERE `username` = '%s' AND `password` = '%s' LIMIT 1",
241                         dbesc($username),
242                         dbesc($new_password_encoded)
243                         );
244                 if($r !== false && count($r))
245                         $newuid = intval($r[0]['uid']);
246         }
247         else {
248                 notice( t('An error occurred during registration. Please try again.') . EOL );
249                 return;
250         }               
251
252         /**
253          * if somebody clicked submit twice very quickly, they could end up with two accounts 
254          * due to race condition. Remove this one.
255          */
256
257         $r = q("SELECT `uid` FROM `user`
258                 WHERE `nickname` = '%s' ",
259                 dbesc($nickname)
260         );
261         if((count($r) > 1) && $newuid) {
262                 $err .= t('Nickname is already registered. Please choose another.') . EOL;
263                 q("DELETE FROM `user` WHERE `uid` = %d LIMIT 1",
264                         intval($newuid)
265                 );
266                 notice ($err);
267                 return;
268         }
269
270         if(x($newuid) !== false) {
271                 $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )
272                         VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ",
273                         intval($newuid),
274                         'default',
275                         1,
276                         dbesc($username),
277                         dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"),
278                         dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"),
279                         intval($publish),
280                         intval($netpublish)
281
282                 );
283                 if($r === false) {
284                         notice( t('An error occurred creating your default profile. Please try again.') . EOL );
285                         // Start fresh next time.
286                         $r = q("DELETE FROM `user` WHERE `uid` = %d",
287                                 intval($newuid));
288                         return;
289                 }
290                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `self`, `name`, `nick`, `photo`, `thumb`, `micro`, `blocked`, `pending`, `url`, `nurl`,
291                         `request`, `notify`, `poll`, `confirm`, `poco`, `name-date`, `uri-date`, `avatar-date`, `closeness` )
292                         VALUES ( %d, '%s', 1, '%s', '%s', '%s', '%s', '%s', 0, 0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 0 ) ",
293                         intval($newuid),
294                         datetime_convert(),
295                         dbesc($username),
296                         dbesc($nickname),
297                         dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"),
298                         dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"),
299                         dbesc($a->get_baseurl() . "/photo/micro/{$newuid}.jpg"),
300                         dbesc($a->get_baseurl() . "/profile/$nickname"),
301                         dbesc(normalise_link($a->get_baseurl() . "/profile/$nickname")),
302                         dbesc($a->get_baseurl() . "/dfrn_request/$nickname"),
303                         dbesc($a->get_baseurl() . "/dfrn_notify/$nickname"),
304                         dbesc($a->get_baseurl() . "/dfrn_poll/$nickname"),
305                         dbesc($a->get_baseurl() . "/dfrn_confirm/$nickname"),
306                         dbesc($a->get_baseurl() . "/poco/$nickname"),
307                         dbesc(datetime_convert()),
308                         dbesc(datetime_convert()),
309                         dbesc(datetime_convert())
310                 );
311
312
313         }
314
315         $use_gravatar = ((get_config('system','no_gravatar')) ? false : true);
316
317         // if we have an openid photo use it. 
318         // otherwise unless it is disabled, use gravatar
319
320         if($use_gravatar || strlen($photo)) {
321
322                 require_once('include/Photo.php');
323
324                 if(($use_gravatar) && (! strlen($photo))) 
325                         $photo = gravatar_img($email);
326                 $photo_failure = false;
327
328                 $filename = basename($photo);
329                 $img_str = fetch_url($photo,true);
330                 $img = new Photo($img_str);
331                 if($img->is_valid()) {
332
333                         $img->scaleImageSquare(175);
334                                         
335                         $hash = photo_new_resource();
336
337                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 4 );
338
339                         if($r === false)
340                                 $photo_failure = true;
341
342                         $img->scaleImage(80);
343
344                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 5 );
345
346                         if($r === false)
347                                 $photo_failure = true;
348
349                         $img->scaleImage(48);
350
351                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 6 );
352
353                         if($r === false)
354                                 $photo_failure = true;
355
356                         if(! $photo_failure) {
357                                 q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ",
358                                         dbesc($hash)
359                                 );
360                         }
361                 }
362         }
363
364         if($netpublish && $a->config['register_policy'] != REGISTER_APPROVE) {
365                 $url = $a->get_baseurl() . "/profile/$nickname";
366                 proc_run('php',"include/directory.php","$url");
367         }
368
369
370         call_hooks('register_account', $newuid);
371
372         if( $a->config['register_policy'] == REGISTER_OPEN ) {
373
374                 if($using_invites && $invite_id) {
375                         q("delete * from register where hash = '%s' limit 1", dbesc($invite_id));
376                         set_pconfig($newuid,'system','invites_remaining',$num_invites);
377                 }
378
379                 $email_tpl = get_intltext_template("register_open_eml.tpl");
380                 $email_tpl = replace_macros($email_tpl, array(
381                                 '$sitename' => $a->config['sitename'],
382                                 '$siteurl' =>  $a->get_baseurl(),
383                                 '$username' => $username,
384                                 '$email' => $email,
385                                 '$password' => $new_password,
386                                 '$uid' => $newuid ));
387
388                 $res = mail($email, sprintf(t('Registration details for %s'), $a->config['sitename']),
389                         $email_tpl, 
390                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
391                                 . 'Content-type: text/plain; charset=UTF-8' . "\n"
392                                 . 'Content-transfer-encoding: 8bit' );
393
394
395                 if($res) {
396                         info( t('Registration successful. Please check your email for further instructions.') . EOL ) ;
397                         goaway(z_root());
398                 }
399                 else {
400                         notice( t('Failed to send email message. Here is the message that failed.') . $email_tpl . EOL );
401                 }
402         }
403         elseif($a->config['register_policy'] == REGISTER_APPROVE) {
404                 if(! strlen($a->config['admin_email'])) {
405                         notice( t('Your registration can not be processed.') . EOL);
406                         goaway(z_root());
407                 }
408
409                 $hash = random_string();
410                 $r = q("INSERT INTO `register` ( `hash`, `created`, `uid`, `password`, `language` ) VALUES ( '%s', '%s', %d, '%s', '%s' ) ",
411                         dbesc($hash),
412                         dbesc(datetime_convert()),
413                         intval($newuid),
414                         dbesc($new_password),
415                         dbesc($lang)
416                 );
417
418                 $r = q("SELECT `language` FROM `user` WHERE `email` = '%s' LIMIT 1",
419                         dbesc($a->config['admin_email'])
420                 );
421                 if(count($r))
422                         push_lang($r[0]['language']);
423                 else
424                         push_lang('en');
425
426                 if($using_invites && $invite_id) {
427                         q("delete * from register where hash = '%s' limit 1", dbesc($invite_id));
428                         set_pconfig($newuid,'system','invites_remaining',$num_invites);
429                 }
430
431                 $email_tpl = get_intltext_template("register_verify_eml.tpl");
432                 $email_tpl = replace_macros($email_tpl, array(
433                                 '$sitename' => $a->config['sitename'],
434                                 '$siteurl' =>  $a->get_baseurl(),
435                                 '$username' => $username,
436                                 '$email' => $email,
437                                 '$password' => $new_password,
438                                 '$uid' => $newuid,
439                                 '$hash' => $hash
440                  ));
441
442                 $res = mail($a->config['admin_email'], sprintf(t('Registration request at %s'), $a->config['sitename']),
443                         $email_tpl,
444                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
445                                 . 'Content-type: text/plain; charset=UTF-8' . "\n"
446                                 . 'Content-transfer-encoding: 8bit' );
447
448                 pop_lang();
449
450                 if($res) {
451                         info( t('Your registration is pending approval by the site owner.') . EOL ) ;
452                         goaway(z_root());
453                 }
454
455         }
456
457         return;
458 }}
459
460
461
462
463
464
465 if(! function_exists('register_content')) {
466 function register_content(&$a) {
467
468         // logged in users can register others (people/pages/groups)
469         // even with closed registrations, unless specifically prohibited by site policy.
470         // 'block_extended_register' blocks all registrations, period.
471
472         $block = get_config('system','block_extended_register');
473
474         if(local_user() && ($block)) {
475                 notice("Permission denied." . EOL);
476                 return;
477         }
478
479         if((! local_user()) && ($a->config['register_policy'] == REGISTER_CLOSED)) {
480                 notice("Permission denied." . EOL);
481                 return;
482         }
483
484         $max_dailies = intval(get_config('system','max_daily_registrations'));
485         if($max_dailes) {
486                 $r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day");
487                 if($r && $r[0]['total'] >= $max_dailies) {
488                         logger('max daily registrations exceeded.');
489                         notice( t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.') . EOL);
490                         return;
491                 }
492         }
493
494         if(x($_SESSION,'theme'))
495                 unset($_SESSION['theme']);
496
497
498         $username     = ((x($_POST,'username'))     ? $_POST['username']     : ((x($_GET,'username'))     ? $_GET['username']              : ''));
499         $email        = ((x($_POST,'email'))        ? $_POST['email']        : ((x($_GET,'email'))        ? $_GET['email']                 : ''));
500         $openid_url   = ((x($_POST,'openid_url'))   ? $_POST['openid_url']   : ((x($_GET,'openid_url'))   ? $_GET['openid_url']            : ''));
501         $nickname     = ((x($_POST,'nickname'))     ? $_POST['nickname']     : ((x($_GET,'nickname'))     ? $_GET['nickname']              : ''));
502         $photo        = ((x($_POST,'photo'))        ? $_POST['photo']        : ((x($_GET,'photo'))        ? hex2bin($_GET['photo'])        : ''));
503         $invite_id    = ((x($_POST,'invite_id'))    ? $_POST['invite_id']    : ((x($_GET,'invite_id'))    ? $_GET['invite_id']             : ''));
504
505         $noid = get_config('system','no_openid');
506
507         if($noid) {
508                 $oidhtml = '';
509                 $fillwith = '';
510                 $fillext = '';
511                 $oidlabel = '';
512         }
513         else {
514                 $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" >';
515                 $fillwith = t("You may \x28optionally\x29 fill in this form via OpenID by supplying your OpenID and clicking 'Register'.");
516                 $fillext =  t('If you are not familiar with OpenID, please leave that field blank and fill in the rest of the items.');
517                 $oidlabel = t("Your OpenID \x28optional\x29: ");
518         }
519
520         // I set this and got even more fake names than before...
521
522         $realpeople = ''; // t('Members of this network prefer to communicate with real people who use their real names.');
523
524         if(get_config('system','publish_all')) {
525                 $profile_publish_reg = '<input type="hidden" name="profile_publish_reg" value="1" />';
526         }
527         else {
528                 $publish_tpl = get_markup_template("profile_publish.tpl");
529                 $profile_publish = replace_macros($publish_tpl,array(
530                         '$instance'     => 'reg',
531                         '$pubdesc'      => t('Include your profile in member directory?'),
532                         '$yes_selected' => ' checked="checked" ',
533                         '$no_selected'  => '',
534                         '$str_yes'      => t('Yes'),
535                         '$str_no'       => t('No')
536                 ));
537         }
538
539
540         $license = '';
541
542         $o = get_markup_template("register.tpl");
543         $o = replace_macros($o, array(
544                 '$oidhtml' => $oidhtml,
545                 '$invitations' => get_config('system','invitation_only'),
546                 '$invite_desc' => t('Membership on this site is by invitation only.'),
547                 '$invite_label' => t('Your invitation ID: '),
548                 '$invite_id' => $invite_id,
549                 '$realpeople' => $realpeople,
550                 '$regtitle'  => t('Registration'),
551                 '$registertext' =>((x($a->config,'register_text'))
552                         ? '<div class="error-message">' . $a->config['register_text'] . '</div>'
553                         : "" ),
554                 '$fillwith'  => $fillwith,
555                 '$fillext'   => $fillext,
556                 '$oidlabel'  => $oidlabel,
557                 '$openid'    => $openid_url,
558                 '$namelabel' => t('Your Full Name ' . "\x28" . 'e.g. Joe Smith' . "\x29" . ': '),
559                 '$addrlabel' => t('Your Email Address: '),
560                 '$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>\'.'),
561                 '$nicklabel' => t('Choose a nickname: '),
562                 '$photo'     => $photo,
563                 '$publish'   => $profile_publish,
564                 '$regbutt'   => t('Register'),
565                 '$username'  => $username,
566                 '$email'     => $email,
567                 '$nickname'  => $nickname,
568                 '$license'   => $license,
569                 '$sitename'  => $a->get_hostname()
570         ));
571         return $o;
572
573 }}
574