]> git.mxchange.org Git - friendica.git/blob - include/user.php
93b34e1f5656d270bb2bb4525fe66620219c645c
[friendica.git] / include / user.php
1 <?php
2
3 require_once('include/config.php');
4 require_once('include/network.php');
5 require_once('include/plugin.php');
6 require_once('include/text.php');
7 require_once('include/pgettext.php');
8 require_once('include/datetime.php');
9
10
11 function create_user($arr) {
12
13         // Required: { username, nickname, email } or { openid_url }
14
15         $a = get_app();
16         $result = array('success' => false, 'user' => null, 'password' => '', 'message' => '');
17
18         $using_invites = get_config('system','invitation_only');
19         $num_invites   = get_config('system','number_invites');
20
21
22         $invite_id  = ((x($arr,'invite_id'))  ? notags(trim($arr['invite_id']))  : '');
23         $username   = ((x($arr,'username'))   ? notags(trim($arr['username']))   : '');
24         $nickname   = ((x($arr,'nickname'))   ? notags(trim($arr['nickname']))   : '');
25         $email      = ((x($arr,'email'))      ? notags(trim($arr['email']))      : '');
26         $openid_url = ((x($arr,'openid_url')) ? notags(trim($arr['openid_url'])) : '');
27         $photo      = ((x($arr,'photo'))      ? notags(trim($arr['photo']))      : '');
28         $password   = ((x($arr,'password'))   ? trim($arr['password'])           : '');
29         $blocked    = ((x($arr,'blocked'))    ? intval($arr['blocked'])  : 0);
30         $verified   = ((x($arr,'verified'))   ? intval($arr['verified']) : 0);
31
32         $publish    = ((x($arr,'profile_publish_reg') && intval($arr['profile_publish_reg'])) ? 1 : 0);
33         $netpublish = ((strlen(get_config('system','directory_submit_url'))) ? $publish : 0);
34
35         $tmp_str = $openid_url;
36
37         if($using_invites) {
38                 if(! $invite_id) {
39                         $result['message'] .= t('An invitation is required.') . EOL;
40                         return $result;
41                 }
42                 $r = q("select * from register where `hash` = '%s' limit 1", dbesc($invite_id));
43                 if(! results($r)) {
44                         $result['message'] .= t('Invitation could not be verified.') . EOL;
45                         return $result;
46                 }
47         } 
48
49         if((! x($username)) || (! x($email)) || (! x($nickname))) {
50                 if($openid_url) {
51                         if(! validate_url($tmp_str)) {
52                                 $result['message'] .= t('Invalid OpenID url') . EOL;
53                                 return $result;
54                         }
55                         $_SESSION['register'] = 1;
56                         $_SESSION['openid'] = $openid_url;
57                         require_once('library/openid.php');
58                         $openid = new LightOpenID;
59                         $openid->identity = $openid_url;
60                         $openid->returnUrl = $a->get_baseurl() . '/openid'; 
61                         $openid->required = array('namePerson/friendly', 'contact/email', 'namePerson');
62                         $openid->optional = array('namePerson/first','media/image/aspect11','media/image/default');
63                         try {                   
64                                 $authurl = $openid->authUrl();
65                         } catch (Exception $e){
66                                 $result['message'] .= t("We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID."). EOL . EOL . t("The error message was:") . $e->getMessage() . EOL; 
67                                 return $result;
68                         }
69                         goaway($authurl);
70                         // NOTREACHED   
71                 }
72
73                 notice( t('Please enter the required information.') . EOL );
74                 return;
75         }
76
77         if(! validate_url($tmp_str))
78                 $openid_url = '';
79
80
81         $err = '';
82
83         // collapse multiple spaces in name
84         $username = preg_replace('/ +/',' ',$username);
85
86         if(mb_strlen($username) > 48)
87                 $result['message'] .= t('Please use a shorter name.') . EOL;
88         if(mb_strlen($username) < 3)
89                 $result['message'] .= t('Name too short.') . EOL;
90
91         // I don't really like having this rule, but it cuts down
92         // on the number of auto-registrations by Russian spammers
93         
94         //  Using preg_match was completely unreliable, due to mixed UTF-8 regex support
95         //      $no_utf = get_config('system','no_utf');
96         //      $pat = (($no_utf) ? '/^[a-zA-Z]* [a-zA-Z]*$/' : '/^\p{L}* \p{L}*$/u' ); 
97
98         // So now we are just looking for a space in the full name. 
99
100         $loose_reg = get_config('system','no_regfullname');
101         if(! $loose_reg) {
102                 $username = mb_convert_case($username,MB_CASE_TITLE,'UTF-8');
103                 if(! strpos($username,' '))
104                         $result['message'] .= t("That doesn't appear to be your full \x28First Last\x29 name.") . EOL;
105         }
106
107
108         if(! allowed_email($email))
109                 $result['message'] .= t('Your email domain is not among those allowed on this site.') . EOL;
110
111         if((! valid_email($email)) || (! validate_email($email)))
112                 $result['message'] .= t('Not a valid email address.') . EOL;
113
114         // Disallow somebody creating an account using openid that uses the admin email address,
115         // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
116
117         $adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email'])));
118
119         //if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) {
120         if((x($a->config,'admin_email')) && in_array(strtolower($email), $adminlist) && strlen($openid_url)) {
121                 $r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1",
122                         dbesc($email)
123                 );
124                 if(count($r))
125                         $result['message'] .= t('Cannot use that email.') . EOL;
126         }
127
128         $nickname = $arr['nickname'] = strtolower($nickname);
129
130         if(! preg_match("/^[a-z][a-z0-9\-\_]*$/",$nickname))
131                 $result['message'] .= t('Your "nickname" can only contain "a-z", "0-9", "-", and "_", and must also begin with a letter.') . EOL;
132         $r = q("SELECT `uid` FROM `user`
133                 WHERE `nickname` = '%s' LIMIT 1",
134                 dbesc($nickname)
135         );
136         if(count($r))
137                 $result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
138
139         // Check deleted accounts that had this nickname. Doesn't matter to us,
140         // but could be a security issue for federated platforms.
141
142         $r = q("SELECT * FROM `userd`
143                 WHERE `username` = '%s' LIMIT 1",
144                 dbesc($nickname)
145         );
146         if(count($r))
147                 $result['message'] .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
148
149         if(strlen($result['message'])) {
150                 return $result;
151         }
152
153         $new_password = ((strlen($password)) ? $password : autoname(6) . mt_rand(100,9999));
154         $new_password_encoded = hash('whirlpool',$new_password);
155
156         $result['password'] = $new_password;
157
158         require_once('include/crypto.php');
159
160         $keys = new_keypair(4096);
161
162         if($keys === false) {
163                 $result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL;
164                 return $result;
165         }
166
167         $default_service_class = get_config('system','default_service_class');
168         if(! $default_service_class)
169                 $default_service_class = '';
170
171
172         $prvkey = $keys['prvkey'];
173         $pubkey = $keys['pubkey'];
174
175         /**
176          *
177          * Create another keypair for signing/verifying
178          * salmon protocol messages. We have to use a slightly
179          * less robust key because this won't be using openssl
180          * but the phpseclib. Since it is PHP interpreted code
181          * it is not nearly as efficient, and the larger keys
182          * will take several minutes each to process.
183          *
184          */
185         
186         $sres    = new_keypair(512);
187         $sprvkey = $sres['prvkey'];
188         $spubkey = $sres['pubkey'];
189
190         $r = q("INSERT INTO `user` ( `guid`, `username`, `password`, `email`, `openid`, `nickname`,
191                 `pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone`, `service_class` )
192                 VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC', '%s' )",
193                 dbesc(generate_user_guid()),
194                 dbesc($username),
195                 dbesc($new_password_encoded),
196                 dbesc($email),
197                 dbesc($openid_url),
198                 dbesc($nickname),
199                 dbesc($pubkey),
200                 dbesc($prvkey),
201                 dbesc($spubkey),
202                 dbesc($sprvkey),
203                 dbesc(datetime_convert()),
204                 intval($verified),
205                 intval($blocked),
206                 dbesc($default_service_class)
207         );
208
209         if($r) {
210                 $r = q("SELECT * FROM `user` 
211                         WHERE `username` = '%s' AND `password` = '%s' LIMIT 1",
212                         dbesc($username),
213                         dbesc($new_password_encoded)
214                 );
215                 if($r !== false && count($r)) {
216                         $u = $r[0];
217                         $newuid = intval($r[0]['uid']);
218                 }
219         }
220         else {
221                 $result['message'] .=  t('An error occurred during registration. Please try again.') . EOL ;
222                 return $result;
223         }               
224
225         /**
226          * if somebody clicked submit twice very quickly, they could end up with two accounts 
227          * due to race condition. Remove this one.
228          */
229
230         $r = q("SELECT `uid` FROM `user`
231                 WHERE `nickname` = '%s' ",
232                 dbesc($nickname)
233         );
234         if((count($r) > 1) && $newuid) {
235                 $result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
236                 q("DELETE FROM `user` WHERE `uid` = %d LIMIT 1",
237                         intval($newuid)
238                 );
239                 return $result;
240         }
241
242         if(x($newuid) !== false) {
243                 $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )
244                         VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ",
245                         intval($newuid),
246                         t('default'),
247                         1,
248                         dbesc($username),
249                         dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"),
250                         dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"),
251                         intval($publish),
252                         intval($netpublish)
253
254                 );
255                 if($r === false) {
256                         $result['message'] .=  t('An error occurred creating your default profile. Please try again.') . EOL;
257                         // Start fresh next time.
258                         $r = q("DELETE FROM `user` WHERE `uid` = %d",
259                                 intval($newuid));
260                         return $result;
261                 }
262                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `self`, `name`, `nick`, `photo`, `thumb`, `micro`, `blocked`, `pending`, `url`, `nurl`,
263                         `request`, `notify`, `poll`, `confirm`, `poco`, `name-date`, `uri-date`, `avatar-date`, `closeness` )
264                         VALUES ( %d, '%s', 1, '%s', '%s', '%s', '%s', '%s', 0, 0, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', 0 ) ",
265                         intval($newuid),
266                         datetime_convert(),
267                         dbesc($username),
268                         dbesc($nickname),
269                         dbesc($a->get_baseurl() . "/photo/profile/{$newuid}.jpg"),
270                         dbesc($a->get_baseurl() . "/photo/avatar/{$newuid}.jpg"),
271                         dbesc($a->get_baseurl() . "/photo/micro/{$newuid}.jpg"),
272                         dbesc($a->get_baseurl() . "/profile/$nickname"),
273                         dbesc(normalise_link($a->get_baseurl() . "/profile/$nickname")),
274                         dbesc($a->get_baseurl() . "/dfrn_request/$nickname"),
275                         dbesc($a->get_baseurl() . "/dfrn_notify/$nickname"),
276                         dbesc($a->get_baseurl() . "/dfrn_poll/$nickname"),
277                         dbesc($a->get_baseurl() . "/dfrn_confirm/$nickname"),
278                         dbesc($a->get_baseurl() . "/poco/$nickname"),
279                         dbesc(datetime_convert()),
280                         dbesc(datetime_convert()),
281                         dbesc(datetime_convert())
282                 );
283
284                 // Create a group with no members. This allows somebody to use it 
285                 // right away as a default group for new contacts. 
286
287                 require_once('include/group.php');
288                 group_add($newuid, t('Friends'));
289
290                 $r = q("SELECT id FROM `group` WHERE uid = %d AND name = '%s'",
291                         intval($newuid),
292                         dbesc(t('Friends'))
293                 );
294                 if($r && count($r)) {
295                         $def_gid = $r[0]['id'];
296
297                         q("UPDATE user SET def_gid = %d WHERE uid = %d",
298                                 intval($r[0]['id']),
299                                 intval($newuid)
300                         );
301                 }
302
303                 if(get_config('system', 'newuser_private') && $def_gid) {
304                         q("UPDATE user SET allow_gid = '%s' WHERE uid = %d",
305                            dbesc("<" . $def_gid . ">"),
306                            intval($newuid)
307                         );
308                 }
309
310         }
311
312         // if we have no OpenID photo try to look up an avatar
313         if(! strlen($photo))
314                 $photo = avatar_img($email);
315
316         // unless there is no avatar-plugin loaded
317         if(strlen($photo)) {
318                 require_once('include/Photo.php');
319                 $photo_failure = false;
320
321                 $filename = basename($photo);
322                 $img_str = fetch_url($photo,true);
323                 // guess mimetype from headers or filename
324                 $type = guess_image_type($photo,true);
325
326                 
327                 $img = new Photo($img_str, $type);
328                 if($img->is_valid()) {
329
330                         $img->scaleImageSquare(175);
331
332                         $hash = photo_new_resource();
333
334                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 4 );
335
336                         if($r === false)
337                                 $photo_failure = true;
338
339                         $img->scaleImage(80);
340
341                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 5 );
342
343                         if($r === false)
344                                 $photo_failure = true;
345
346                         $img->scaleImage(48);
347
348                         $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 6 );
349
350                         if($r === false)
351                                 $photo_failure = true;
352
353                         if(! $photo_failure) {
354                                 q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ",
355                                         dbesc($hash)
356                                 );
357                         }
358                 }
359         }
360
361         call_hooks('register_account', $newuid);
362
363         $result['success'] = true;
364         $result['user'] = $u;
365         return $result;
366
367 }