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\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Photo;
19 use Friendica\Object\Image;
20 use Friendica\Util\Crypto;
24 require_once 'boot.php';
25 require_once 'include/dba.php';
26 require_once 'include/enotify.php';
27 require_once 'include/network.php';
28 require_once 'library/openid.php';
29 require_once 'include/pgettext.php';
30 require_once 'include/text.php';
32 * @brief This class handles User related functions
37 * @brief Get owner data by user id
40 * @return boolean|array
42 public static function getOwnerDataById($uid) {
43 $r = dba::fetch_first("SELECT
45 `user`.`prvkey` AS `uprvkey`,
51 `user`.`account-type`,
55 ON `user`.`uid` = `contact`.`uid`
56 WHERE `contact`.`uid` = ?
61 if (!DBM::is_result($r)) {
68 * @brief Returns the default group for a given user and network
70 * @param int $uid User id
71 * @param string $network network name
73 * @return int group id
75 public static function getDefaultGroup($uid, $network = '')
79 if ($network == NETWORK_OSTATUS) {
80 $default_group = PConfig::get($uid, "ostatus", "default_group");
83 if ($default_group != 0) {
84 return $default_group;
87 $user = dba::selectFirst('user', ['def_gid'], ['uid' => $uid]);
89 if (DBM::is_result($user)) {
90 $default_group = $user["def_gid"];
93 return $default_group;
98 * @brief Authenticate a user with a clear text password
100 * User info can be any of the following:
103 * - User email or username or nickname
104 * - User array with at least the uid and the hashed password
106 * @param mixed $user_info
107 * @param string $password
110 public static function authenticate($user_info, $password)
112 if (is_object($user_info)) {
113 $user = (array) $user_info;
114 } elseif (is_int($user_info)) {
115 $user = dba::selectFirst('user', ['uid', 'password', 'legacy_password'],
119 'account_expired' => 0,
120 'account_removed' => 0,
124 } elseif (is_string($user_info)) {
125 $user = dba::fetch_first('SELECT `uid`, `password`, `legacy_password`
127 WHERE (`email` = ? OR `username` = ? OR `nickname` = ?)
129 AND `account_expired` = 0
130 AND `account_removed` = 0
141 if (!DBM::is_result($user)
142 || !isset($user['uid'])
143 || !isset($user['password'])
144 || !isset($user['legacy_password'])
146 throw new Exception('Not enough information to authenticate');
149 if ($user['legacy_password']) {
150 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
151 self::updatePassword($user['uid'], $password);
155 } elseif (password_verify($password, $user['password'])) {
156 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
157 self::updatePassword($user['uid'], $password);
167 * Generates a human-readable random password
171 public static function generateNewPassword()
173 return autoname(6) . mt_rand(100, 9999);
177 * Legacy hashing function, kept for password migration purposes
179 * @param string $password
182 private static function hashPasswordLegacy($password)
184 return hash('whirlpool', $password);
188 * Global user password hashing function
190 * @param string $password
193 public static function hashPassword($password)
195 return password_hash($password, PASSWORD_DEFAULT);
199 * Updates a user row with a new plaintext password
202 * @param string $password
205 public static function updatePassword($uid, $password)
207 return self::updatePasswordHashed($uid, self::hashPassword($password));
211 * Updates a user row with a new hashed password.
212 * Empties the password reset token field just in case.
215 * @param string $pasword_hashed
218 private static function updatePasswordHashed($uid, $pasword_hashed)
221 'password' => $pasword_hashed,
223 'pwdreset_time' => null,
224 'legacy_password' => false
226 return dba::update('user', $fields, ['uid' => $uid]);
230 * @brief Catch-all user creation function
232 * Creates a user from the provided data array, either form fields or OpenID.
233 * Required: { username, nickname, email } or { openid_url }
235 * Performs the following:
236 * - Sends to the OpenId auth URL (if relevant)
237 * - Creates new key pairs for crypto
238 * - Create self-contact
239 * - Create profile image
245 public static function create(array $data)
248 $return = ['user' => null, 'password' => ''];
250 $using_invites = Config::get('system', 'invitation_only');
251 $num_invites = Config::get('system', 'number_invites');
253 $invite_id = x($data, 'invite_id') ? notags(trim($data['invite_id'])) : '';
254 $username = x($data, 'username') ? notags(trim($data['username'])) : '';
255 $nickname = x($data, 'nickname') ? notags(trim($data['nickname'])) : '';
256 $email = x($data, 'email') ? notags(trim($data['email'])) : '';
257 $openid_url = x($data, 'openid_url') ? notags(trim($data['openid_url'])) : '';
258 $photo = x($data, 'photo') ? notags(trim($data['photo'])) : '';
259 $password = x($data, 'password') ? trim($data['password']) : '';
260 $password1 = x($data, 'password1') ? trim($data['password1']) : '';
261 $confirm = x($data, 'confirm') ? trim($data['confirm']) : '';
262 $blocked = x($data, 'blocked') ? intval($data['blocked']) : 0;
263 $verified = x($data, 'verified') ? intval($data['verified']) : 0;
265 $publish = x($data, 'profile_publish_reg') && intval($data['profile_publish_reg']) ? 1 : 0;
266 $netpublish = strlen(Config::get('system', 'directory')) ? $publish : 0;
268 if ($password1 != $confirm) {
269 throw new Exception(t('Passwords do not match. Password unchanged.'));
270 } elseif ($password1 != '') {
271 $password = $password1;
274 if ($using_invites) {
276 throw new Exception(t('An invitation is required.'));
279 if (!dba::exists('register', ['hash' => $invite_id])) {
280 throw new Exception(t('Invitation could not be verified.'));
284 if (!x($username) || !x($email) || !x($nickname)) {
286 if (!validate_url($openid_url)) {
287 throw new Exception(t('Invalid OpenID url'));
289 $_SESSION['register'] = 1;
290 $_SESSION['openid'] = $openid_url;
292 $openid = new \LightOpenID;
293 $openid->identity = $openid_url;
294 $openid->returnUrl = System::baseUrl() . '/openid';
295 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
296 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
298 $authurl = $openid->authUrl();
299 } catch (Exception $e) {
300 throw new Exception(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(), 0, $e);
306 throw new Exception(t('Please enter the required information.'));
309 if (!validate_url($openid_url)) {
315 // collapse multiple spaces in name
316 $username = preg_replace('/ +/', ' ', $username);
318 if (mb_strlen($username) > 48) {
319 throw new Exception(t('Please use a shorter name.'));
321 if (mb_strlen($username) < 3) {
322 throw new Exception(t('Name too short.'));
325 // So now we are just looking for a space in the full name.
326 $loose_reg = Config::get('system', 'no_regfullname');
328 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
329 if (!strpos($username, ' ')) {
330 throw new Exception(t("That doesn't appear to be your full \x28First Last\x29 name."));
334 if (!allowed_email($email)) {
335 throw new Exception(t('Your email domain is not among those allowed on this site.'));
338 if (!valid_email($email) || !validate_email($email)) {
339 throw new Exception(t('Not a valid email address.'));
342 if (dba::exists('user', ['email' => $email])) {
343 throw new Exception(t('Cannot use that email.'));
346 // Disallow somebody creating an account using openid that uses the admin email address,
347 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
348 if (x($a->config, 'admin_email') && strlen($openid_url)) {
349 $adminlist = explode(',', str_replace(' ', '', strtolower($a->config['admin_email'])));
350 if (in_array(strtolower($email), $adminlist)) {
351 throw new Exception(t('Cannot use that email.'));
355 $nickname = $data['nickname'] = strtolower($nickname);
357 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
358 throw new Exception(t('Your "nickname" can only contain "a-z", "0-9" and "_".'));
361 // Check existing and deleted accounts for this nickname.
362 if (dba::exists('user', ['nickname' => $nickname])
363 || dba::exists('userd', ['username' => $nickname])
365 throw new Exception(t('Nickname is already registered. Please choose another.'));
368 $new_password = strlen($password) ? $password : User::generateNewPassword();
369 $new_password_encoded = self::hashPassword($new_password);
371 $return['password'] = $new_password;
373 $keys = Crypto::newKeypair(4096);
374 if ($keys === false) {
375 throw new Exception(t('SERIOUS ERROR: Generation of security keys failed.'));
378 $prvkey = $keys['prvkey'];
379 $pubkey = $keys['pubkey'];
381 // Create another keypair for signing/verifying salmon protocol messages.
382 $sres = Crypto::newKeypair(512);
383 $sprvkey = $sres['prvkey'];
384 $spubkey = $sres['pubkey'];
386 $insert_result = dba::insert('user', [
387 'guid' => generate_user_guid(),
388 'username' => $username,
389 'password' => $new_password_encoded,
391 'openid' => $openid_url,
392 'nickname' => $nickname,
395 'spubkey' => $spubkey,
396 'sprvkey' => $sprvkey,
397 'verified' => $verified,
398 'blocked' => $blocked,
400 'register_date' => datetime_convert(),
401 'default-location' => ''
404 if ($insert_result) {
405 $uid = dba::lastInsertId();
406 $user = dba::selectFirst('user', [], ['uid' => $uid]);
408 throw new Exception(t('An error occurred during registration. Please try again.'));
412 throw new Exception(t('An error occurred during registration. Please try again.'));
415 // if somebody clicked submit twice very quickly, they could end up with two accounts
416 // due to race condition. Remove this one.
417 $user_count = dba::count('user', ['nickname' => $nickname]);
418 if ($user_count > 1) {
419 dba::delete('user', ['uid' => $uid]);
421 throw new Exception(t('Nickname is already registered. Please choose another.'));
424 $insert_result = dba::insert('profile', [
427 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
428 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
429 'publish' => $publish,
431 'net-publish' => $netpublish,
432 'profile-name' => t('default')
434 if (!$insert_result) {
435 dba::delete('user', ['uid' => $uid]);
437 throw new Exception(t('An error occurred creating your default profile. Please try again.'));
440 // Create the self contact
441 if (!Contact::createSelfFromUserId($uid)) {
442 dba::delete('user', ['uid' => $uid]);
444 throw new Exception(t('An error occurred creating your self contact. Please try again.'));
447 // Create a group with no members. This allows somebody to use it
448 // right away as a default group for new contacts.
449 $def_gid = Group::create($uid, t('Friends'));
451 dba::delete('user', ['uid' => $uid]);
453 throw new Exception(t('An error occurred creating your default contact group. Please try again.'));
456 $fields = ['def_gid' => $def_gid];
457 if (Config::get('system', 'newuser_private') && $def_gid) {
458 $fields['allow_gid'] = '<' . $def_gid . '>';
461 dba::update('user', $fields, ['uid' => $uid]);
463 // if we have no OpenID photo try to look up an avatar
464 if (!strlen($photo)) {
465 $photo = avatar_img($email);
468 // unless there is no avatar-addon loaded
469 if (strlen($photo)) {
470 $photo_failure = false;
472 $filename = basename($photo);
473 $img_str = fetch_url($photo, true);
474 // guess mimetype from headers or filename
475 $type = Image::guessType($photo, true);
477 $Image = new Image($img_str, $type);
478 if ($Image->isValid()) {
479 $Image->scaleToSquare(175);
481 $hash = photo_new_resource();
483 $r = Photo::store($Image, $uid, 0, $hash, $filename, t('Profile Photos'), 4);
486 $photo_failure = true;
489 $Image->scaleDown(80);
491 $r = Photo::store($Image, $uid, 0, $hash, $filename, t('Profile Photos'), 5);
494 $photo_failure = true;
497 $Image->scaleDown(48);
499 $r = Photo::store($Image, $uid, 0, $hash, $filename, t('Profile Photos'), 6);
502 $photo_failure = true;
505 if (!$photo_failure) {
506 dba::update('photo', ['profile' => 1], ['resource-id' => $hash]);
511 Addon::callHooks('register_account', $uid);
513 $return['user'] = $user;
518 * @brief Sends pending registration confiĆmation email
520 * @param string $email
521 * @param string $sitename
522 * @param string $username
523 * @return NULL|boolean from notification() and email() inherited
525 public static function sendRegisterPendingEmail($email, $sitename, $username)
529 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
532 $body = sprintf($body, $username, $sitename);
534 return notification([
535 'type' => SYSTEM_EMAIL,
536 'to_email' => $email,
537 'subject'=> sprintf( t('Registration at %s'), $sitename),
542 * @brief Sends registration confirmation
544 * It's here as a function because the mail is sent from different parts
546 * @param string $email
547 * @param string $sitename
548 * @param string $siteurl
549 * @param string $username
550 * @param string $password
551 * @return NULL|boolean from notification() and email() inherited
553 public static function sendRegisterOpenEmail($email, $sitename, $siteurl, $username, $password)
555 $preamble = deindent(t('
557 Thank you for registering at %2$s. Your account has been created.
560 The login details are as follows:
565 You may change your password from your account "Settings" page after logging
568 Please take a few moments to review the other account settings on that page.
570 You may also wish to add some basic information to your default profile
571 (on the "Profiles" page) so that other people can easily find you.
573 We recommend setting your full name, adding a profile photo,
574 adding some profile "keywords" (very useful in making new friends) - and
575 perhaps what country you live in; if you do not wish to be more specific
578 We fully respect your right to privacy, and none of these items are necessary.
579 If you are new and do not know anybody here, they may help
580 you to make some new and interesting friends.
583 Thank you and welcome to %2$s.'));
585 $preamble = sprintf($preamble, $username, $sitename);
586 $body = sprintf($body, $email, $sitename, $siteurl, $username, $password);
588 return notification([
589 'type' => SYSTEM_EMAIL,
590 'to_email' => $email,
591 'subject'=> sprintf( t('Registration details for %s'), $sitename),
592 'preamble'=> $preamble,
597 * @param object $uid user to remove
600 public static function remove($uid)
606 logger('Removing user: ' . $uid);
608 $user = dba::selectFirst('user', [], ['uid' => $uid]);
610 Addon::callHooks('remove_user', $user);
612 // save username (actually the nickname as it is guaranteed
613 // unique), so it cannot be re-registered in the future.
614 dba::insert('userd', ['username' => $user['nickname']]);
616 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
617 dba::update('user', ['account_removed' => true, 'account_expires_on' => datetime_convert()], ['uid' => $uid]);
618 Worker::add(PRIORITY_HIGH, "Notifier", "removeme", $uid);
620 // Send an update to the directory
621 Worker::add(PRIORITY_LOW, "Directory", $user['url']);
623 if ($uid == local_user()) {
624 unset($_SESSION['authenticated']);
625 unset($_SESSION['uid']);
626 goaway(System::baseUrl());