4 * @file src/Model/User.php
5 * @brief This file includes the User class with user related database functions
8 namespace Friendica\Model;
10 use Friendica\Core\Config;
11 use Friendica\Core\System;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Object\Contact;
15 use Friendica\Object\Photo;
18 require_once 'boot.php';
19 require_once 'include/crypto.php';
20 require_once 'include/enotify.php';
21 require_once 'include/group.php';
22 require_once 'include/network.php';
23 require_once 'library/openid.php';
24 require_once 'include/pgettext.php';
25 require_once 'include/plugin.php';
26 require_once 'include/text.php';
28 * @brief This class handles User related functions
33 * @brief Authenticate a user with a clear text password
35 * User info can be any of the following:
38 * - User email or username or nickname
39 * - User array with at least the uid and the hashed password
41 * @param mixed $user_info
42 * @param string $password
45 public static function authenticate($user_info, $password)
47 if (is_object($user_info)) {
48 $user = (array) $user_info;
49 } elseif (is_int($user_info)) {
50 $user = dba::select('user',
55 'account_expired' => 0,
56 'account_removed' => 0,
61 } elseif (is_string($user_info)) {
62 $user = dba::fetch_first('SELECT `uid`, `password`
64 WHERE (`email` = ? OR `username` = ? OR `nickname` = ?)
66 AND `account_expired` = 0
67 AND `account_removed` = 0
78 if (!DBM::is_result($user) || !isset($user['uid']) || !isset($user['password'])) {
82 $password_hashed = hash('whirlpool', $password);
84 if ($password_hashed !== $user['password']) {
92 * @brief Catch-all user creation function
94 * Creates a user from the provided data array, either form fields or OpenID.
95 * Required: { username, nickname, email } or { openid_url }
97 * Performs the following:
98 * - Sends to the OpenId auth URL (if relevant)
99 * - Creates new key pairs for crypto
100 * - Create self-contact
101 * - Create profile image
106 public static function create(array $data)
109 $result = array('success' => false, 'user' => null, 'password' => '', 'message' => '');
111 $using_invites = Config::get('system', 'invitation_only');
112 $num_invites = Config::get('system', 'number_invites');
114 $invite_id = x($data, 'invite_id') ? notags(trim($data['invite_id'])) : '';
115 $username = x($data, 'username') ? notags(trim($data['username'])) : '';
116 $nickname = x($data, 'nickname') ? notags(trim($data['nickname'])) : '';
117 $email = x($data, 'email') ? notags(trim($data['email'])) : '';
118 $openid_url = x($data, 'openid_url') ? notags(trim($data['openid_url'])) : '';
119 $photo = x($data, 'photo') ? notags(trim($data['photo'])) : '';
120 $password = x($data, 'password') ? trim($data['password']) : '';
121 $password1 = x($data, 'password1') ? trim($data['password1']) : '';
122 $confirm = x($data, 'confirm') ? trim($data['confirm']) : '';
123 $blocked = x($data, 'blocked') ? intval($data['blocked']) : 0;
124 $verified = x($data, 'verified') ? intval($data['verified']) : 0;
126 $publish = x($data, 'profile_publish_reg') && intval($data['profile_publish_reg']) ? 1 : 0;
127 $netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0;
129 if ($password1 != $confirm) {
130 $result['message'] .= t('Passwords do not match. Password unchanged.') . EOL;
132 } elseif ($password1 != "") {
133 $password = $password1;
136 $tmp_str = $openid_url;
138 if ($using_invites) {
140 $result['message'] .= t('An invitation is required.') . EOL;
143 $r = q("SELECT * FROM `register` WHERE `hash` = '%s' LIMIT 1", dbesc($invite_id));
145 $result['message'] .= t('Invitation could not be verified.') . EOL;
150 if (!x($username) || !x($email) || !x($nickname)) {
152 if (!validate_url($tmp_str)) {
153 $result['message'] .= t('Invalid OpenID url') . EOL;
156 $_SESSION['register'] = 1;
157 $_SESSION['openid'] = $openid_url;
159 $openid = new LightOpenID;
160 $openid->identity = $openid_url;
161 $openid->returnUrl = System::baseUrl() . '/openid';
162 $openid->required = array('namePerson/friendly', 'contact/email', 'namePerson');
163 $openid->optional = array('namePerson/first', 'media/image/aspect11', 'media/image/default');
165 $authurl = $openid->authUrl();
166 } catch (Exception $e) {
167 $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;
174 notice(t('Please enter the required information.') . EOL);
178 if (!validate_url($tmp_str)) {
184 // collapse multiple spaces in name
185 $username = preg_replace('/ +/', ' ', $username);
187 if (mb_strlen($username) > 48) {
188 $result['message'] .= t('Please use a shorter name.') . EOL;
190 if (mb_strlen($username) < 3) {
191 $result['message'] .= t('Name too short.') . EOL;
194 // So now we are just looking for a space in the full name.
196 $loose_reg = Config::get('system', 'no_regfullname');
198 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
199 if (!strpos($username, ' ')) {
200 $result['message'] .= t("That doesn't appear to be your full \x28First Last\x29 name.") . EOL;
205 if (!allowed_email($email)) {
206 $result['message'] .= t('Your email domain is not among those allowed on this site.') . EOL;
209 if (!valid_email($email) || !validate_email($email)) {
210 $result['message'] .= t('Not a valid email address.') . EOL;
213 // Disallow somebody creating an account using openid that uses the admin email address,
214 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
216 $adminlist = explode(",", str_replace(" ", "", strtolower($a->config['admin_email'])));
218 //if((x($a->config,'admin_email')) && (strcasecmp($email,$a->config['admin_email']) == 0) && strlen($openid_url)) {
219 if (x($a->config, 'admin_email') && in_array(strtolower($email), $adminlist) && strlen($openid_url)) {
220 $r = q("SELECT * FROM `user` WHERE `email` = '%s' LIMIT 1",
223 if (DBM::is_result($r)) {
224 $result['message'] .= t('Cannot use that email.') . EOL;
228 $nickname = $data['nickname'] = strtolower($nickname);
230 if (!preg_match("/^[a-z0-9][a-z0-9\_]*$/", $nickname)) {
231 $result['message'] .= t('Your "nickname" can only contain "a-z", "0-9" and "_".') . EOL;
234 $r = q("SELECT `uid` FROM `user`
235 WHERE `nickname` = '%s' LIMIT 1",
238 if (DBM::is_result($r)) {
239 $result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
242 // Check deleted accounts that had this nickname. Doesn't matter to us,
243 // but could be a security issue for federated platforms.
245 $r = q("SELECT * FROM `userd`
246 WHERE `username` = '%s' LIMIT 1",
249 if (DBM::is_result($r)) {
250 $result['message'] .= t('Nickname was once registered here and may not be re-used. Please choose another.') . EOL;
253 if (strlen($result['message'])) {
257 $new_password = strlen($password) ? $password : autoname(6) . mt_rand(100, 9999);
258 $new_password_encoded = hash('whirlpool', $new_password);
260 $result['password'] = $new_password;
262 $keys = new_keypair(4096);
264 if ($keys === false) {
265 $result['message'] .= t('SERIOUS ERROR: Generation of security keys failed.') . EOL;
269 $prvkey = $keys['prvkey'];
270 $pubkey = $keys['pubkey'];
272 // Create another keypair for signing/verifying salmon protocol messages.
273 $sres = new_keypair(512);
274 $sprvkey = $sres['prvkey'];
275 $spubkey = $sres['pubkey'];
277 $r = q("INSERT INTO `user` (`guid`, `username`, `password`, `email`, `openid`, `nickname`,
278 `pubkey`, `prvkey`, `spubkey`, `sprvkey`, `register_date`, `verified`, `blocked`, `timezone`, `default-location`)
279 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 'UTC', '')",
280 dbesc(generate_user_guid()),
282 dbesc($new_password_encoded),
290 dbesc(datetime_convert()),
296 $r = q("SELECT * FROM `user`
297 WHERE `username` = '%s' AND `password` = '%s' LIMIT 1",
299 dbesc($new_password_encoded)
301 if (DBM::is_result($r)) {
303 $newuid = intval($r[0]['uid']);
306 $result['message'] .= t('An error occurred during registration. Please try again.') . EOL;
311 * if somebody clicked submit twice very quickly, they could end up with two accounts
312 * due to race condition. Remove this one.
314 $r = q("SELECT `uid` FROM `user`
315 WHERE `nickname` = '%s' ",
318 if (DBM::is_result($r) && count($r) > 1 && $newuid) {
319 $result['message'] .= t('Nickname is already registered. Please choose another.') . EOL;
320 dba::delete('user', array('uid' => $newuid));
324 if (x($newuid) !== false) {
325 $r = q("INSERT INTO `profile` ( `uid`, `profile-name`, `is-default`, `name`, `photo`, `thumb`, `publish`, `net-publish` )
326 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, %d ) ",
331 dbesc(System::baseUrl() . "/photo/profile/{$newuid}.jpg"),
332 dbesc(System::baseUrl() . "/photo/avatar/{$newuid}.jpg"),
337 $result['message'] .= t('An error occurred creating your default profile. Please try again.') . EOL;
338 // Start fresh next time.
339 dba::delete('user', array('uid' => $newuid));
343 // Create the self contact
344 Contact::createSelfFromUserId($newuid);
346 // Create a group with no members. This allows somebody to use it
347 // right away as a default group for new contacts.
349 group_add($newuid, t('Friends'));
351 $r = q("SELECT `id` FROM `group` WHERE `uid` = %d AND `name` = '%s'",
355 if (DBM::is_result($r)) {
356 $def_gid = $r[0]['id'];
358 q("UPDATE `user` SET `def_gid` = %d WHERE `uid` = %d",
364 if (Config::get('system', 'newuser_private') && $def_gid) {
365 q("UPDATE `user` SET `allow_gid` = '%s' WHERE `uid` = %d",
366 dbesc("<" . $def_gid . ">"),
372 // if we have no OpenID photo try to look up an avatar
373 if (!strlen($photo)) {
374 $photo = avatar_img($email);
377 // unless there is no avatar-plugin loaded
378 if (strlen($photo)) {
379 $photo_failure = false;
381 $filename = basename($photo);
382 $img_str = fetch_url($photo, true);
383 // guess mimetype from headers or filename
384 $type = Photo::guessImageType($photo, true);
387 $img = new Photo($img_str, $type);
388 if ($img->isValid()) {
389 $img->scaleImageSquare(175);
391 $hash = photo_new_resource();
393 $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 4);
396 $photo_failure = true;
399 $img->scaleImage(80);
401 $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 5);
404 $photo_failure = true;
407 $img->scaleImage(48);
409 $r = $img->store($newuid, 0, $hash, $filename, t('Profile Photos'), 6);
412 $photo_failure = true;
415 if (!$photo_failure) {
416 q("UPDATE `photo` SET `profile` = 1 WHERE `resource-id` = '%s' ",
423 call_hooks('register_account', $newuid);
425 $result['success'] = true;
426 $result['user'] = $u;
431 * @brief Sends pending registration confiĆmation email
433 * @param string $email
434 * @param string $sitename
435 * @param string $username
436 * @return NULL|boolean from notification() and email() inherited
438 public static function sendRegisterPendingEmail($email, $sitename, $username)
442 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
445 $body = sprintf($body, $username, $sitename);
447 return notification(array(
448 'type' => SYSTEM_EMAIL,
449 'to_email' => $email,
450 'subject'=> sprintf( t('Registration at %s'), $sitename),
455 * @brief Sends registration confirmation
457 * It's here as a function because the mail is sent from different parts
459 * @param string $email
460 * @param string $sitename
461 * @param string $siteurl
462 * @param string $username
463 * @param string $password
464 * @return NULL|boolean from notification() and email() inherited
466 public static function sendRegisterOpenEmail($email, $sitename, $siteurl, $username, $password)
468 $preamble = deindent(t('
470 Thank you for registering at %2$s. Your account has been created.
473 The login details are as follows:
478 You may change your password from your account "Settings" page after logging
481 Please take a few moments to review the other account settings on that page.
483 You may also wish to add some basic information to your default profile
484 (on the "Profiles" page) so that other people can easily find you.
486 We recommend setting your full name, adding a profile photo,
487 adding some profile "keywords" (very useful in making new friends) - and
488 perhaps what country you live in; if you do not wish to be more specific
491 We fully respect your right to privacy, and none of these items are necessary.
492 If you are new and do not know anybody here, they may help
493 you to make some new and interesting friends.
496 Thank you and welcome to %2$s.'));
498 $preamble = sprintf($preamble, $username, $sitename);
499 $body = sprintf($body, $email, $sitename, $siteurl, $username, $password);
501 return notification(array(
502 'type' => SYSTEM_EMAIL,
503 'to_email' => $email,
504 'subject'=> sprintf( t('Registration details for %s'), $sitename),
505 'preamble'=> $preamble,
510 * @param object $uid user to remove
513 public static function remove($uid)
519 logger('Removing user: ' . $uid);
521 $user = dba::select('user', [], ['uid' => $uid], ['limit' => 1]);
523 call_hooks('remove_user', $user);
525 // save username (actually the nickname as it is guaranteed
526 // unique), so it cannot be re-registered in the future.
527 dba::insert('userd', ['username' => $user['nickname']]);
529 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
530 dba::update('user', ['account_removed' => true, 'account_expires_on' => datetime_convert()], ['uid' => $uid]);
531 Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
533 // Send an update to the directory
534 Worker::add(PRIORITY_LOW, "Directory", $user['url']);
536 if ($uid == local_user()) {
537 unset($_SESSION['authenticated']);
538 unset($_SESSION['uid']);
539 goaway(System::baseUrl());