3 * @file src/Model/User.php
4 * @brief This file includes the User class with user related database functions
6 namespace Friendica\Model;
8 use DivineOmega\PasswordExposed;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Object\Image;
20 use Friendica\Util\Crypto;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
27 * @brief This class handles User related functions
34 * PAGE_FLAGS_NORMAL is a typical personal profile account
35 * PAGE_FLAGS_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
36 * PAGE_FLAGS_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
37 * write access to wall and comments (no email and not included in page owner's ACL lists)
38 * PAGE_FLAGS_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
42 const PAGE_FLAGS_NORMAL = 0;
43 const PAGE_FLAGS_SOAPBOX = 1;
44 const PAGE_FLAGS_COMMUNITY = 2;
45 const PAGE_FLAGS_FREELOVE = 3;
46 const PAGE_FLAGS_BLOG = 4;
47 const PAGE_FLAGS_PRVGROUP = 5;
55 * ACCOUNT_TYPE_PERSON - the account belongs to a person
56 * Associated page types: PAGE_FLAGS_NORMAL, PAGE_FLAGS_SOAPBOX, PAGE_FLAGS_FREELOVE
58 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
59 * Associated page type: PAGE_FLAGS_SOAPBOX
61 * ACCOUNT_TYPE_NEWS - the account is a news reflector
62 * Associated page type: PAGE_FLAGS_SOAPBOX
64 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
65 * Associated page types: PAGE_COMMUNITY, PAGE_FLAGS_PRVGROUP
67 * ACCOUNT_TYPE_RELAY - the account is a relay
68 * This will only be assigned to contacts, not to user accounts
71 const ACCOUNT_TYPE_PERSON = 0;
72 const ACCOUNT_TYPE_ORGANISATION = 1;
73 const ACCOUNT_TYPE_NEWS = 2;
74 const ACCOUNT_TYPE_COMMUNITY = 3;
75 const ACCOUNT_TYPE_RELAY = 4;
81 * Returns true if a user record exists with the provided id
87 public static function exists($uid)
89 return DBA::exists('user', ['uid' => $uid]);
94 * @return array|boolean User record if it exists, false otherwise
97 public static function getById($uid)
99 return DBA::selectFirst('user', [], ['uid' => $uid]);
103 * @brief Returns the user id of a given profile URL
107 * @return integer user id
110 public static function getIdForURL($url)
112 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => Strings::normaliseLink($url), 'self' => true]);
113 if (!DBA::isResult($self)) {
121 * @brief Get owner data by user id
124 * @return boolean|array
127 public static function getOwnerDataById($uid) {
128 $r = DBA::fetchFirst("SELECT
130 `user`.`prvkey` AS `uprvkey`,
136 `user`.`account-type`,
138 `user`.`account_removed`
141 ON `user`.`uid` = `contact`.`uid`
142 WHERE `contact`.`uid` = ?
147 if (!DBA::isResult($r)) {
151 if (empty($r['nickname'])) {
155 // Check if the returned data is valid, otherwise fix it. See issue #6122
156 $url = System::baseUrl() . '/profile/' . $r['nickname'];
157 $addr = $r['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
159 if (($addr != $r['addr']) || ($r['url'] != $url) || ($r['nurl'] != Strings::normaliseLink($r['url']))) {
160 Contact::updateSelfFromUserID($uid);
167 * @brief Get owner data by nick name
170 * @return boolean|array
173 public static function getOwnerDataByNick($nick)
175 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
177 if (!DBA::isResult($user)) {
181 return self::getOwnerDataById($user['uid']);
185 * @brief Returns the default group for a given user and network
187 * @param int $uid User id
188 * @param string $network network name
190 * @return int group id
191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 public static function getDefaultGroup($uid, $network = '')
197 if ($network == Protocol::OSTATUS) {
198 $default_group = PConfig::get($uid, "ostatus", "default_group");
201 if ($default_group != 0) {
202 return $default_group;
205 $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
207 if (DBA::isResult($user)) {
208 $default_group = $user["def_gid"];
211 return $default_group;
216 * Authenticate a user with a clear text password
218 * @brief Authenticate a user with a clear text password
219 * @param mixed $user_info
220 * @param string $password
221 * @return int|boolean
222 * @deprecated since version 3.6
223 * @see User::getIdFromPasswordAuthentication()
225 public static function authenticate($user_info, $password)
228 return self::getIdFromPasswordAuthentication($user_info, $password);
229 } catch (Exception $ex) {
235 * Returns the user id associated with a successful password authentication
237 * @brief Authenticate a user with a clear text password
238 * @param mixed $user_info
239 * @param string $password
240 * @return int User Id if authentication is successful
243 public static function getIdFromPasswordAuthentication($user_info, $password)
245 $user = self::getAuthenticationInfo($user_info);
247 if (strpos($user['password'], '$') === false) {
248 //Legacy hash that has not been replaced by a new hash yet
249 if (self::hashPasswordLegacy($password) === $user['password']) {
250 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
254 } elseif (!empty($user['legacy_password'])) {
255 //Legacy hash that has been double-hashed and not replaced by a new hash yet
256 //Warning: `legacy_password` is not necessary in sync with the content of `password`
257 if (password_verify(self::hashPasswordLegacy($password), $user['password'])) {
258 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
262 } elseif (password_verify($password, $user['password'])) {
264 if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
265 self::updatePasswordHashed($user['uid'], self::hashPassword($password));
271 throw new Exception(L10n::t('Login failed'));
275 * Returns authentication info from various parameters types
277 * User info can be any of the following:
280 * - User email or username or nickname
281 * - User array with at least the uid and the hashed password
283 * @param mixed $user_info
287 private static function getAuthenticationInfo($user_info)
291 if (is_object($user_info) || is_array($user_info)) {
292 if (is_object($user_info)) {
293 $user = (array) $user_info;
298 if (!isset($user['uid'])
299 || !isset($user['password'])
300 || !isset($user['legacy_password'])
302 throw new Exception(L10n::t('Not enough information to authenticate'));
304 } elseif (is_int($user_info) || is_string($user_info)) {
305 if (is_int($user_info)) {
306 $user = DBA::selectFirst('user', ['uid', 'password', 'legacy_password'],
310 'account_expired' => 0,
311 'account_removed' => 0,
316 $fields = ['uid', 'password', 'legacy_password'];
317 $condition = ["(`email` = ? OR `username` = ? OR `nickname` = ?)
318 AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified`",
319 $user_info, $user_info, $user_info];
320 $user = DBA::selectFirst('user', $fields, $condition);
323 if (!DBA::isResult($user)) {
324 throw new Exception(L10n::t('User not found'));
332 * Generates a human-readable random password
336 public static function generateNewPassword()
338 return ucfirst(Strings::getRandomName(8)) . mt_rand(1000, 9999);
342 * Checks if the provided plaintext password has been exposed or not
344 * @param string $password
347 public static function isPasswordExposed($password)
349 $cache = new \DivineOmega\DOFileCachePSR6\CacheItemPool();
350 $cache->changeConfig([
351 'cacheDirectory' => get_temppath() . '/password-exposed-cache/',
354 $PasswordExposedCHecker = new PasswordExposed\PasswordExposedChecker(null, $cache);
356 return $PasswordExposedCHecker->passwordExposed($password) === PasswordExposed\PasswordStatus::EXPOSED;
360 * Legacy hashing function, kept for password migration purposes
362 * @param string $password
365 private static function hashPasswordLegacy($password)
367 return hash('whirlpool', $password);
371 * Global user password hashing function
373 * @param string $password
377 public static function hashPassword($password)
379 if (!trim($password)) {
380 throw new Exception(L10n::t('Password can\'t be empty'));
383 return password_hash($password, PASSWORD_DEFAULT);
387 * Updates a user row with a new plaintext password
390 * @param string $password
394 public static function updatePassword($uid, $password)
396 $password = trim($password);
398 if (empty($password)) {
399 throw new Exception(L10n::t('Empty passwords are not allowed.'));
402 if (!Config::get('system', 'disable_password_exposed', false) && self::isPasswordExposed($password)) {
403 throw new Exception(L10n::t('The new password has been exposed in a public data dump, please choose another.'));
406 $allowed_characters = '!"#$%&\'()*+,-./;<=>?@[\]^_`{|}~';
408 if (!preg_match('/^[a-z0-9' . preg_quote($allowed_characters, '/') . ']+$/i', $password)) {
409 throw new Exception(L10n::t('The password can\'t contain accentuated letters, white spaces or colons (:)'));
412 return self::updatePasswordHashed($uid, self::hashPassword($password));
416 * Updates a user row with a new hashed password.
417 * Empties the password reset token field just in case.
420 * @param string $pasword_hashed
424 private static function updatePasswordHashed($uid, $pasword_hashed)
427 'password' => $pasword_hashed,
429 'pwdreset_time' => null,
430 'legacy_password' => false
432 return DBA::update('user', $fields, ['uid' => $uid]);
436 * @brief Checks if a nickname is in the list of the forbidden nicknames
438 * Check if a nickname is forbidden from registration on the node by the
439 * admin. Forbidden nicknames (e.g. role namess) can be configured in the
442 * @param string $nickname The nickname that should be checked
443 * @return boolean True is the nickname is blocked on the node
444 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
446 public static function isNicknameBlocked($nickname)
448 $forbidden_nicknames = Config::get('system', 'forbidden_nicknames', '');
450 // if the config variable is empty return false
451 if (empty($forbidden_nicknames)) {
455 // check if the nickname is in the list of blocked nicknames
456 $forbidden = explode(',', $forbidden_nicknames);
457 $forbidden = array_map('trim', $forbidden);
458 if (in_array(strtolower($nickname), $forbidden)) {
467 * @brief Catch-all user creation function
469 * Creates a user from the provided data array, either form fields or OpenID.
470 * Required: { username, nickname, email } or { openid_url }
472 * Performs the following:
473 * - Sends to the OpenId auth URL (if relevant)
474 * - Creates new key pairs for crypto
475 * - Create self-contact
476 * - Create profile image
480 * @throws \ErrorException
481 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482 * @throws \ImagickException
485 public static function create(array $data)
488 $return = ['user' => null, 'password' => ''];
490 $using_invites = Config::get('system', 'invitation_only');
492 $invite_id = !empty($data['invite_id']) ? Strings::escapeTags(trim($data['invite_id'])) : '';
493 $username = !empty($data['username']) ? Strings::escapeTags(trim($data['username'])) : '';
494 $nickname = !empty($data['nickname']) ? Strings::escapeTags(trim($data['nickname'])) : '';
495 $email = !empty($data['email']) ? Strings::escapeTags(trim($data['email'])) : '';
496 $openid_url = !empty($data['openid_url']) ? Strings::escapeTags(trim($data['openid_url'])) : '';
497 $photo = !empty($data['photo']) ? Strings::escapeTags(trim($data['photo'])) : '';
498 $password = !empty($data['password']) ? trim($data['password']) : '';
499 $password1 = !empty($data['password1']) ? trim($data['password1']) : '';
500 $confirm = !empty($data['confirm']) ? trim($data['confirm']) : '';
501 $blocked = !empty($data['blocked']);
502 $verified = !empty($data['verified']);
503 $language = !empty($data['language']) ? Strings::escapeTags(trim($data['language'])) : 'en';
505 $publish = !empty($data['profile_publish_reg']);
506 $netpublish = $publish && Config::get('system', 'directory');
508 if ($password1 != $confirm) {
509 throw new Exception(L10n::t('Passwords do not match. Password unchanged.'));
510 } elseif ($password1 != '') {
511 $password = $password1;
514 if ($using_invites) {
516 throw new Exception(L10n::t('An invitation is required.'));
519 if (!Register::existsByHash($invite_id)) {
520 throw new Exception(L10n::t('Invitation could not be verified.'));
524 if (empty($username) || empty($email) || empty($nickname)) {
526 if (!Network::isUrlValid($openid_url)) {
527 throw new Exception(L10n::t('Invalid OpenID url'));
529 $_SESSION['register'] = 1;
530 $_SESSION['openid'] = $openid_url;
532 $openid = new LightOpenID($a->getHostName());
533 $openid->identity = $openid_url;
534 $openid->returnUrl = System::baseUrl() . '/openid';
535 $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson'];
536 $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default'];
538 $authurl = $openid->authUrl();
539 } catch (Exception $e) {
540 throw new Exception(L10n::t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . EOL . EOL . L10n::t('The error message was:') . $e->getMessage(), 0, $e);
542 System::externalRedirect($authurl);
546 throw new Exception(L10n::t('Please enter the required information.'));
549 if (!Network::isUrlValid($openid_url)) {
553 // collapse multiple spaces in name
554 $username = preg_replace('/ +/', ' ', $username);
556 $username_min_length = max(1, min(64, intval(Config::get('system', 'username_min_length', 3))));
557 $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
559 if ($username_min_length > $username_max_length) {
560 Logger::log(L10n::t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length), Logger::WARNING);
561 $tmp = $username_min_length;
562 $username_min_length = $username_max_length;
563 $username_max_length = $tmp;
566 if (mb_strlen($username) < $username_min_length) {
567 throw new Exception(L10n::tt('Username should be at least %s character.', 'Username should be at least %s characters.', $username_min_length));
570 if (mb_strlen($username) > $username_max_length) {
571 throw new Exception(L10n::tt('Username should be at most %s character.', 'Username should be at most %s characters.', $username_max_length));
574 // So now we are just looking for a space in the full name.
575 $loose_reg = Config::get('system', 'no_regfullname');
577 $username = mb_convert_case($username, MB_CASE_TITLE, 'UTF-8');
578 if (strpos($username, ' ') === false) {
579 throw new Exception(L10n::t("That doesn't appear to be your full (First Last) name."));
583 if (!Network::isEmailDomainAllowed($email)) {
584 throw new Exception(L10n::t('Your email domain is not among those allowed on this site.'));
587 if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !Network::isEmailDomainValid($email)) {
588 throw new Exception(L10n::t('Not a valid email address.'));
590 if (self::isNicknameBlocked($nickname)) {
591 throw new Exception(L10n::t('The nickname was blocked from registration by the nodes admin.'));
594 if (Config::get('system', 'block_extended_register', false) && DBA::exists('user', ['email' => $email])) {
595 throw new Exception(L10n::t('Cannot use that email.'));
598 // Disallow somebody creating an account using openid that uses the admin email address,
599 // since openid bypasses email verification. We'll allow it if there is not yet an admin account.
600 if (Config::get('config', 'admin_email') && strlen($openid_url)) {
601 $adminlist = explode(',', str_replace(' ', '', strtolower(Config::get('config', 'admin_email'))));
602 if (in_array(strtolower($email), $adminlist)) {
603 throw new Exception(L10n::t('Cannot use that email.'));
607 $nickname = $data['nickname'] = strtolower($nickname);
609 if (!preg_match('/^[a-z0-9][a-z0-9\_]*$/', $nickname)) {
610 throw new Exception(L10n::t('Your nickname can only contain a-z, 0-9 and _.'));
613 // Check existing and deleted accounts for this nickname.
614 if (DBA::exists('user', ['nickname' => $nickname])
615 || DBA::exists('userd', ['username' => $nickname])
617 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
620 $new_password = strlen($password) ? $password : User::generateNewPassword();
621 $new_password_encoded = self::hashPassword($new_password);
623 $return['password'] = $new_password;
625 $keys = Crypto::newKeypair(4096);
626 if ($keys === false) {
627 throw new Exception(L10n::t('SERIOUS ERROR: Generation of security keys failed.'));
630 $prvkey = $keys['prvkey'];
631 $pubkey = $keys['pubkey'];
633 // Create another keypair for signing/verifying salmon protocol messages.
634 $sres = Crypto::newKeypair(512);
635 $sprvkey = $sres['prvkey'];
636 $spubkey = $sres['pubkey'];
638 $insert_result = DBA::insert('user', [
639 'guid' => System::createUUID(),
640 'username' => $username,
641 'password' => $new_password_encoded,
643 'openid' => $openid_url,
644 'nickname' => $nickname,
647 'spubkey' => $spubkey,
648 'sprvkey' => $sprvkey,
649 'verified' => $verified,
650 'blocked' => $blocked,
651 'language' => $language,
653 'register_date' => DateTimeFormat::utcNow(),
654 'default-location' => ''
657 if ($insert_result) {
658 $uid = DBA::lastInsertId();
659 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
661 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
665 throw new Exception(L10n::t('An error occurred during registration. Please try again.'));
668 // if somebody clicked submit twice very quickly, they could end up with two accounts
669 // due to race condition. Remove this one.
670 $user_count = DBA::count('user', ['nickname' => $nickname]);
671 if ($user_count > 1) {
672 DBA::delete('user', ['uid' => $uid]);
674 throw new Exception(L10n::t('Nickname is already registered. Please choose another.'));
677 $insert_result = DBA::insert('profile', [
680 'photo' => System::baseUrl() . "/photo/profile/{$uid}.jpg",
681 'thumb' => System::baseUrl() . "/photo/avatar/{$uid}.jpg",
682 'publish' => $publish,
684 'net-publish' => $netpublish,
685 'profile-name' => L10n::t('default')
687 if (!$insert_result) {
688 DBA::delete('user', ['uid' => $uid]);
690 throw new Exception(L10n::t('An error occurred creating your default profile. Please try again.'));
693 // Create the self contact
694 if (!Contact::createSelfFromUserId($uid)) {
695 DBA::delete('user', ['uid' => $uid]);
697 throw new Exception(L10n::t('An error occurred creating your self contact. Please try again.'));
700 // Create a group with no members. This allows somebody to use it
701 // right away as a default group for new contacts.
702 $def_gid = Group::create($uid, L10n::t('Friends'));
704 DBA::delete('user', ['uid' => $uid]);
706 throw new Exception(L10n::t('An error occurred creating your default contact group. Please try again.'));
709 $fields = ['def_gid' => $def_gid];
710 if (Config::get('system', 'newuser_private') && $def_gid) {
711 $fields['allow_gid'] = '<' . $def_gid . '>';
714 DBA::update('user', $fields, ['uid' => $uid]);
716 // if we have no OpenID photo try to look up an avatar
717 if (!strlen($photo)) {
718 $photo = Network::lookupAvatarByEmail($email);
721 // unless there is no avatar-addon loaded
722 if (strlen($photo)) {
723 $photo_failure = false;
725 $filename = basename($photo);
726 $img_str = Network::fetchUrl($photo, true);
727 // guess mimetype from headers or filename
728 $type = Image::guessType($photo, true);
730 $Image = new Image($img_str, $type);
731 if ($Image->isValid()) {
732 $Image->scaleToSquare(300);
734 $hash = Photo::newResource();
736 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 4);
739 $photo_failure = true;
742 $Image->scaleDown(80);
744 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 5);
747 $photo_failure = true;
750 $Image->scaleDown(48);
752 $r = Photo::store($Image, $uid, 0, $hash, $filename, L10n::t('Profile Photos'), 6);
755 $photo_failure = true;
758 if (!$photo_failure) {
759 Photo::update(['profile' => 1], ['resource-id' => $hash]);
764 Hook::callAll('register_account', $uid);
766 $return['user'] = $user;
771 * @brief Sends pending registration confirmation email
773 * @param array $user User record array
774 * @param string $sitename
775 * @param string $siteurl
776 * @param string $password Plaintext password
777 * @return NULL|boolean from notification() and email() inherited
778 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
780 public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password)
782 $body = Strings::deindent(L10n::t('
784 Thank you for registering at %2$s. Your account is pending for approval by the administrator.
786 Your login details are as follows:
792 $user['username'], $sitename, $siteurl, $user['nickname'], $password
795 return notification([
796 'type' => SYSTEM_EMAIL,
797 'uid' => $user['uid'],
798 'to_email' => $user['email'],
799 'subject' => L10n::t('Registration at %s', $sitename),
805 * @brief Sends registration confirmation
807 * It's here as a function because the mail is sent from different parts
809 * @param array $user User record array
810 * @param string $sitename
811 * @param string $siteurl
812 * @param string $password Plaintext password
813 * @return NULL|boolean from notification() and email() inherited
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
816 public static function sendRegisterOpenEmail($user, $sitename, $siteurl, $password)
818 $preamble = Strings::deindent(L10n::t('
820 Thank you for registering at %2$s. Your account has been created.
822 $user['username'], $sitename
824 $body = Strings::deindent(L10n::t('
825 The login details are as follows:
831 You may change your password from your account "Settings" page after logging
834 Please take a few moments to review the other account settings on that page.
836 You may also wish to add some basic information to your default profile
837 ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
839 We recommend setting your full name, adding a profile photo,
840 adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
841 perhaps what country you live in; if you do not wish to be more specific
844 We fully respect your right to privacy, and none of these items are necessary.
845 If you are new and do not know anybody here, they may help
846 you to make some new and interesting friends.
848 If you ever want to delete your account, you can do so at %3$s/removeme
850 Thank you and welcome to %2$s.',
851 $user['nickname'], $sitename, $siteurl, $user['username'], $password
854 return notification([
855 'uid' => $user['uid'],
856 'language' => $user['language'],
857 'type' => SYSTEM_EMAIL,
858 'to_email' => $user['email'],
859 'subject' => L10n::t('Registration details for %s', $sitename),
860 'preamble' => $preamble,
866 * @param object $uid user to remove
868 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
870 public static function remove($uid)
876 Logger::log('Removing user: ' . $uid);
878 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
880 Hook::callAll('remove_user', $user);
882 // save username (actually the nickname as it is guaranteed
883 // unique), so it cannot be re-registered in the future.
884 DBA::insert('userd', ['username' => $user['nickname']]);
886 // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
887 DBA::update('user', ['account_removed' => true, 'account_expires_on' => DateTimeFormat::utc('now + 7 day')], ['uid' => $uid]);
888 Worker::add(PRIORITY_HIGH, 'Notifier', 'removeme', $uid);
890 // Send an update to the directory
891 $self = DBA::selectFirst('contact', ['url'], ['uid' => $uid, 'self' => true]);
892 Worker::add(PRIORITY_LOW, 'Directory', $self['url']);
894 // Remove the user relevant data
895 Worker::add(PRIORITY_NEGLIGIBLE, 'RemoveUser', $uid);
901 * Return all identities to a user
903 * @param int $uid The user id
904 * @return array All identities for this user
906 * Example for a return:
910 * 'username' => 'maxmuster',
911 * 'nickname' => 'Max Mustermann'
915 * 'username' => 'johndoe',
916 * 'nickname' => 'John Doe'
921 public static function identities($uid)
925 $user = DBA::selectFirst('user', ['uid', 'nickname', 'username', 'parent-uid'], ['uid' => $uid]);
926 if (!DBA::isResult($user)) {
930 if ($user['parent-uid'] == 0) {
931 // First add our own entry
932 $identities = [['uid' => $user['uid'],
933 'username' => $user['username'],
934 'nickname' => $user['nickname']]];
936 // Then add all the children
937 $r = DBA::select('user', ['uid', 'username', 'nickname'],
938 ['parent-uid' => $user['uid'], 'account_removed' => false]);
939 if (DBA::isResult($r)) {
940 $identities = array_merge($identities, DBA::toArray($r));
943 // First entry is our parent
944 $r = DBA::select('user', ['uid', 'username', 'nickname'],
945 ['uid' => $user['parent-uid'], 'account_removed' => false]);
946 if (DBA::isResult($r)) {
947 $identities = DBA::toArray($r);
950 // Then add all siblings
951 $r = DBA::select('user', ['uid', 'username', 'nickname'],
952 ['parent-uid' => $user['parent-uid'], 'account_removed' => false]);
953 if (DBA::isResult($r)) {
954 $identities = array_merge($identities, DBA::toArray($r));
958 $r = DBA::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
960 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
961 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
964 if (DBA::isResult($r)) {
965 $identities = array_merge($identities, DBA::toArray($r));
972 * Returns statistical information about the current users of this node
978 public static function getStatistics()
982 'active_users_halfyear' => 0,
983 'active_users_monthly' => 0,
986 $userStmt = DBA::p("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item`
988 INNER JOIN `profile` ON `profile`.`uid` = `user`.`uid` AND `profile`.`is-default`
989 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
990 WHERE (`profile`.`publish` OR `profile`.`net-publish`) AND `user`.`verified`
991 AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
992 AND NOT `user`.`account_expired`");
994 if (!DBA::isResult($userStmt)) {
998 $halfyear = time() - (180 * 24 * 60 * 60);
999 $month = time() - (30 * 24 * 60 * 60);
1001 while ($user = DBA::fetch($userStmt)) {
1002 $statistics['total_users']++;
1004 if ((strtotime($user['login_date']) > $halfyear) ||
1005 (strtotime($user['last-item']) > $halfyear)) {
1006 $statistics['active_users_halfyear']++;
1009 if ((strtotime($user['login_date']) > $month) ||
1010 (strtotime($user['last-item']) > $month)) {
1011 $statistics['active_users_monthly']++;