File manager - Edit - /home/opticamezl/www/newok/User.tar
Back
UserHelper.php 0000644 00000051066 15173101146 0007342 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2007 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; use Joomla\Authentication\Password\Argon2idHandler; use Joomla\Authentication\Password\Argon2iHandler; use Joomla\Authentication\Password\BCryptHandler; use Joomla\CMS\Access\Access; use Joomla\CMS\Authentication\Password\ChainedHandler; use Joomla\CMS\Authentication\Password\CheckIfRehashNeededHandlerInterface; use Joomla\CMS\Authentication\Password\MD5Handler; use Joomla\CMS\Authentication\Password\PHPassHandler; use Joomla\CMS\Crypt\Crypt; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; use Joomla\CMS\Object\CMSObject; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Session\SessionManager; use Joomla\CMS\Uri\Uri; use Joomla\Database\Exception\ExecutionFailureException; use Joomla\Database\ParameterType; use Joomla\Utilities\ArrayHelper; // phpcs:disable PSR1.Files.SideEffects \defined('JPATH_PLATFORM') or die; // phpcs:enable PSR1.Files.SideEffects /** * Authorisation helper class, provides static methods to perform various tasks relevant * to the Joomla user and authorisation classes * * This class has influences and some method logic from the Horde Auth package * * @since 1.7.0 */ abstract class UserHelper { /** * Constant defining the Argon2i password algorithm for use with password hashes * * Note: PHP's native `PASSWORD_ARGON2I` constant is not used as PHP may be compiled without this constant * * @var string * @since 4.0.0 */ public const HASH_ARGON2I = 'argon2i'; /** * B/C constant `PASSWORD_ARGON2I` for PHP < 7.4 (using integer) * * Note: PHP's native `PASSWORD_ARGON2I` constant is not used as PHP may be compiled without this constant * * @var integer * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Use UserHelper::HASH_ARGON2I instead */ public const HASH_ARGON2I_BC = 2; /** * Constant defining the Argon2id password algorithm for use with password hashes * * Note: PHP's native `PASSWORD_ARGON2ID` constant is not used as PHP may be compiled without this constant * * @var string * @since 4.0.0 */ public const HASH_ARGON2ID = 'argon2id'; /** * B/C constant `PASSWORD_ARGON2ID` for PHP < 7.4 (using integer) * * Note: PHP's native `PASSWORD_ARGON2ID` constant is not used as PHP may be compiled without this constant * * @var integer * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Use UserHelper::HASH_ARGON2ID instead */ public const HASH_ARGON2ID_BC = 3; /** * Constant defining the BCrypt password algorithm for use with password hashes * * @var string * @since 4.0.0 */ public const HASH_BCRYPT = '2y'; /** * B/C constant `PASSWORD_BCRYPT` for PHP < 7.4 (using integer) * * @var integer * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Use UserHelper::HASH_BCRYPT instead */ public const HASH_BCRYPT_BC = 1; /** * Constant defining the MD5 password algorithm for use with password hashes * * @var string * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Support for MD5 hashed passwords will be removed use any of the other hashing methods */ public const HASH_MD5 = 'md5'; /** * Constant defining the PHPass password algorithm for use with password hashes * * @var string * @since 4.0.0 * * @deprecated 4.0 will be removed in 6.0 * Support for PHPass hashed passwords will be removed use any of the other hashing methods */ public const HASH_PHPASS = 'phpass'; /** * Mapping array for the algorithm handler * * @var array * @since 4.0.0 */ public const HASH_ALGORITHMS = [ self::HASH_ARGON2I => Argon2iHandler::class, self::HASH_ARGON2I_BC => Argon2iHandler::class, self::HASH_ARGON2ID => Argon2idHandler::class, self::HASH_ARGON2ID_BC => Argon2idHandler::class, self::HASH_BCRYPT => BCryptHandler::class, self::HASH_BCRYPT_BC => BCryptHandler::class, self::HASH_MD5 => MD5Handler::class, self::HASH_PHPASS => PHPassHandler::class, ]; /** * Method to add a user to a group. * * @param integer $userId The id of the user. * @param integer $groupId The id of the group. * * @return boolean True on success * * @since 1.7.0 * @throws \RuntimeException */ public static function addUserToGroup($userId, $groupId) { // Cast as integer until method is typehinted. $userId = (int) $userId; $groupId = (int) $groupId; // Get the user object. $user = new User($userId); // Add the user to the group if necessary. if (!\in_array($groupId, $user->groups)) { // Check whether the group exists. $db = Factory::getDbo(); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__usergroups')) ->where($db->quoteName('id') . ' = :groupId') ->bind(':groupId', $groupId, ParameterType::INTEGER); $db->setQuery($query); // If the group does not exist, return an exception. if ($db->loadResult() === null) { throw new \RuntimeException('Access Usergroup Invalid'); } // Add the group data to the user object. $user->groups[$groupId] = $groupId; // Reindex the array for prepared statements binding $user->groups = array_values($user->groups); // Store the user object. $user->save(); } // Set the group data for any preloaded user objects. $temp = User::getInstance($userId); $temp->groups = $user->groups; if (Factory::getSession()->getId()) { // Set the group data for the user object in the session. $temp = Factory::getUser(); if ($temp->id == $userId) { $temp->groups = $user->groups; } } return true; } /** * Method to get a list of groups a user is in. * * @param integer $userId The id of the user. * * @return array List of groups * * @since 1.7.0 */ public static function getUserGroups($userId) { // Get the user object. $user = User::getInstance((int) $userId); return $user->groups ?? []; } /** * Method to remove a user from a group. * * @param integer $userId The id of the user. * @param integer $groupId The id of the group. * * @return boolean True on success * * @since 1.7.0 */ public static function removeUserFromGroup($userId, $groupId) { // Get the user object. $user = User::getInstance((int) $userId); // Remove the user from the group if necessary. $key = array_search($groupId, $user->groups); if ($key !== false) { unset($user->groups[$key]); $user->groups = array_values($user->groups); // Store the user object. $user->save(); } // Set the group data for any preloaded user objects. $temp = Factory::getUser((int) $userId); $temp->groups = $user->groups; // Set the group data for the user object in the session. $temp = Factory::getUser(); if ($temp->id == $userId) { $temp->groups = $user->groups; } return true; } /** * Method to set the groups for a user. * * @param integer $userId The id of the user. * @param array $groups An array of group ids to put the user in. * * @return boolean True on success * * @since 1.7.0 */ public static function setUserGroups($userId, $groups) { // Get the user object. $user = User::getInstance((int) $userId); // Set the group ids. $groups = ArrayHelper::toInteger($groups); $user->groups = $groups; // Get the titles for the user groups. $db = Factory::getDbo(); $query = $db->getQuery(true) ->select($db->quoteName(['id', 'title'])) ->from($db->quoteName('#__usergroups')) ->whereIn($db->quoteName('id'), $user->groups); $db->setQuery($query); $results = $db->loadObjectList(); // Set the titles for the user groups. for ($i = 0, $n = \count($results); $i < $n; $i++) { $user->groups[$results[$i]->id] = $results[$i]->id; } // Store the user object. $user->save(); // Set the group data for any preloaded user objects. $temp = Factory::getUser((int) $userId); $temp->groups = $user->groups; if (Factory::getSession()->getId()) { // Set the group data for the user object in the session. $temp = Factory::getUser(); if ($temp->id == $userId) { $temp->groups = $user->groups; } } return true; } /** * Gets the user profile information * * @param integer $userId The id of the user. * * @return object * * @since 1.7.0 */ public static function getProfile($userId = 0) { if ($userId == 0) { $user = Factory::getUser(); $userId = $user->id; } // Get the dispatcher and load the user's plugins. PluginHelper::importPlugin('user'); $data = new CMSObject(); $data->id = $userId; // Trigger the data preparation event. Factory::getApplication()->triggerEvent('onContentPrepareData', ['com_users.profile', &$data]); return $data; } /** * Method to activate a user * * @param string $activation Activation string * * @return boolean True on success * * @since 1.7.0 */ public static function activateUser($activation) { $db = Factory::getDbo(); // Let's get the id of the user we want to activate $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__users')) ->where($db->quoteName('activation') . ' = :activation') ->where($db->quoteName('block') . ' = 1') ->where($db->quoteName('lastvisitDate') . ' IS NULL') ->bind(':activation', $activation); $db->setQuery($query); $id = (int) $db->loadResult(); // Is it a valid user to activate? if ($id) { $user = User::getInstance($id); $user->set('block', '0'); $user->set('activation', ''); // Time to take care of business.... store the user. if (!$user->save()) { Log::add($user->getError(), Log::WARNING, 'jerror'); return false; } } else { Log::add(Text::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'), Log::WARNING, 'jerror'); return false; } return true; } /** * Returns userid if a user exists * * @param string $username The username to search on. * * @return integer The user id or 0 if not found. * * @since 1.7.0 */ public static function getUserId($username) { // Initialise some variables $db = Factory::getDbo(); $query = $db->getQuery(true) ->select($db->quoteName('id')) ->from($db->quoteName('#__users')) ->where($db->quoteName('username') . ' = :username') ->bind(':username', $username) ->setLimit(1); $db->setQuery($query); return $db->loadResult(); } /** * Hashes a password using the current encryption. * * @param string $password The plaintext password to encrypt. * @param string|integer $algorithm The hashing algorithm to use, represented by `HASH_*` class constants, or a container service ID. * @param array $options The options for the algorithm to use. * * @return string The encrypted password. * * @since 3.2.1 * @throws \InvalidArgumentException when the algorithm is not supported */ public static function hashPassword($password, $algorithm = self::HASH_BCRYPT, array $options = []) { $container = Factory::getContainer(); // If the algorithm is a valid service ID, use that service to generate the hash if ($container->has($algorithm)) { return $container->get($algorithm)->hashPassword($password, $options); } // Try to load handler if (isset(self::HASH_ALGORITHMS[$algorithm])) { return $container->get(self::HASH_ALGORITHMS[$algorithm])->hashPassword($password, $options); } // Unsupported algorithm, sorry! throw new \InvalidArgumentException(sprintf('The %s algorithm is not supported for hashing passwords.', $algorithm)); } /** * Formats a password using the current encryption. If the user ID is given * and the hash does not fit the current hashing algorithm, it automatically * updates the hash. * * @param string $password The plaintext password to check. * @param string $hash The hash to verify against. * @param integer $userId ID of the user if the password hash should be updated * * @return boolean True if the password and hash match, false otherwise * * @since 3.2.1 */ public static function verifyPassword($password, $hash, $userId = 0) { $passwordAlgorithm = self::HASH_BCRYPT; $container = Factory::getContainer(); // Cheaply try to determine the algorithm in use otherwise fall back to the chained handler if (strpos($hash, '$P$') === 0) { /** @var PHPassHandler $handler */ $handler = $container->get(PHPassHandler::class); } elseif (strpos($hash, '$argon2id') === 0) { // Check for Argon2id hashes /** @var Argon2idHandler $handler */ $handler = $container->get(Argon2idHandler::class); $passwordAlgorithm = self::HASH_ARGON2ID; } elseif (strpos($hash, '$argon2i') === 0) { // Check for Argon2i hashes /** @var Argon2iHandler $handler */ $handler = $container->get(Argon2iHandler::class); $passwordAlgorithm = self::HASH_ARGON2I; } elseif (strpos($hash, '$2') === 0) { // Check for bcrypt hashes /** @var BCryptHandler $handler */ $handler = $container->get(BCryptHandler::class); } else { /** @var ChainedHandler $handler */ $handler = $container->get(ChainedHandler::class); } $match = $handler->validatePassword($password, $hash); $rehash = $handler instanceof CheckIfRehashNeededHandlerInterface ? $handler->checkIfRehashNeeded($hash) : false; // If we have a match and rehash = true, rehash the password with the current algorithm. if ((int) $userId > 0 && $match && $rehash) { $user = new User($userId); $user->password = static::hashPassword($password, $passwordAlgorithm); $user->save(); } return $match; } /** * Generate a random password * * @param integer $length Length of the password to generate * * @return string Random Password * * @since 1.7.0 */ public static function genRandomPassword($length = 8) { $salt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $base = \strlen($salt); $makepass = ''; /* * Start with a cryptographic strength random string, then convert it to * a string with the numeric base of the salt. * Shift the base conversion on each character so the character * distribution is even, and randomize the start shift so it's not * predictable. */ $random = Crypt::genRandomBytes($length + 1); $shift = \ord($random[0]); for ($i = 1; $i <= $length; ++$i) { $makepass .= $salt[($shift + \ord($random[$i])) % $base]; $shift += \ord($random[$i]); } return $makepass; } /** * Method to get a hashed user agent string that does not include browser version. * Used when frequent version changes cause problems. * * @return string A hashed user agent string with version replaced by 'abcd' * * @since 3.2 */ public static function getShortHashedUserAgent() { $ua = Factory::getApplication()->client; $uaString = $ua->userAgent; $browserVersion = $ua->browserVersion; if ($browserVersion) { $uaShort = str_replace($browserVersion, 'abcd', $uaString); } else { $uaShort = $uaString; } return md5(Uri::base() . $uaShort); } /** * Check if there is a super user in the user ids. * * @param array $userIds An array of user IDs on which to operate * * @return boolean True on success, false on failure * * @since 3.6.5 */ public static function checkSuperUserInUsers(array $userIds) { foreach ($userIds as $userId) { foreach (static::getUserGroups($userId) as $userGroupId) { if (Access::checkGroup($userGroupId, 'core.admin')) { return true; } } } return false; } /** * Destroy all active session for a given user id * * @param int $userId Id of user * @param boolean $keepCurrent Keep the session of the currently acting user * @param int $clientId Application client id * * @return boolean * * @since 3.9.28 */ public static function destroyUserSessions($userId, $keepCurrent = false, $clientId = null) { // Destroy all sessions for the user account if able if (!Factory::getApplication()->get('session_metadata', true)) { return false; } $db = Factory::getDbo(); try { $userId = (int) $userId; $query = $db->getQuery(true) ->select($db->quoteName('session_id')) ->from($db->quoteName('#__session')) ->where($db->quoteName('userid') . ' = :userid') ->bind(':userid', $userId, ParameterType::INTEGER); if ($clientId !== null) { $clientId = (int) $clientId; $query->where($db->quoteName('client_id') . ' = :client_id') ->bind(':client_id', $clientId, ParameterType::INTEGER); } $sessionIds = $db->setQuery($query)->loadColumn(); } catch (ExecutionFailureException $e) { return false; } // Convert PostgreSQL Session IDs into strings (see GitHub #33822) foreach ($sessionIds as &$sessionId) { if (is_resource($sessionId) && get_resource_type($sessionId) === 'stream') { $sessionId = stream_get_contents($sessionId); } } // If true, removes the current session id from the purge list if ($keepCurrent) { $sessionIds = array_diff($sessionIds, [Factory::getSession()->getId()]); } // If there aren't any active sessions then there's nothing to do here if (empty($sessionIds)) { return false; } /** @var SessionManager $sessionManager */ $sessionManager = Factory::getContainer()->get('session.manager'); $sessionManager->destroySessions($sessionIds); try { $db->setQuery( $db->getQuery(true) ->delete($db->quoteName('#__session')) ->whereIn($db->quoteName('session_id'), $sessionIds, ParameterType::LARGE_OBJECT) )->execute(); } catch (ExecutionFailureException $e) { // No issue, let things go } } } UserFactoryAwareInterface.php 0000644 00000001351 15173101146 0012323 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2023 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface to be implemented by classes depending on a user factory. * * @since 4.4.0 */ interface UserFactoryAwareInterface { /** * Set the user factory to use. * * @param UserFactoryInterface $factory The user factory to use. * * @return void * * @since 4.4.0 */ public function setUserFactory(UserFactoryInterface $factory): void; } UserFactoryAwareTrait.php 0000644 00000002552 15173101146 0011512 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2023 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Defines the trait for a UserFactoryInterface Aware Class. * * @since 4.4.0 */ trait UserFactoryAwareTrait { /** * UserFactoryInterface * * @var UserFactoryInterface * @since 4.4.0 */ private $userFactory; /** * Get the UserFactoryInterface. * * @return UserFactoryInterface * * @since 4.4.0 * @throws \UnexpectedValueException May be thrown if the UserFactory has not been set. */ protected function getUserFactory(): UserFactoryInterface { if ($this->userFactory) { return $this->userFactory; } throw new \UnexpectedValueException('UserFactory not set in ' . __CLASS__); } /** * Set the user factory to use. * * @param UserFactoryInterface $userFactory The user factory to use. * * @return void * * @since 4.4.0 */ public function setUserFactory(UserFactoryInterface $userFactory): void { $this->userFactory = $userFactory; } } UserFactory.php 0000644 00000003350 15173101146 0007523 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; use Joomla\Database\DatabaseInterface; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Default factory for creating User objects * * @since 4.0.0 */ class UserFactory implements UserFactoryInterface { /** * The database. * * @var DatabaseInterface */ private $db; /** * UserFactory constructor. * * @param DatabaseInterface $db The database */ public function __construct(DatabaseInterface $db) { $this->db = $db; } /** * Method to get an instance of a user for the given id. * * @param int $id The id * * @return User * * @since 4.0.0 */ public function loadUserById(int $id): User { return new User($id); } /** * Method to get an instance of a user for the given username. * * @param string $username The username * * @return User * * @since 4.0.0 */ public function loadUserByUsername(string $username): User { // Initialise some variables $query = $this->db->getQuery(true) ->select($this->db->quoteName('id')) ->from($this->db->quoteName('#__users')) ->where($this->db->quoteName('username') . ' = :username') ->bind(':username', $username) ->setLimit(1); $this->db->setQuery($query); return $this->loadUserById((int) $this->db->loadResult()); } } CurrentUserTrait.php 0000644 00000003011 15173101146 0010534 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2022 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; use Joomla\CMS\Factory; // phpcs:disable PSR1.Files.SideEffects \defined('JPATH_PLATFORM') or die; // phpcs:enable PSR1.Files.SideEffects /** * Trait for classes which require a user to work with. * * @since 4.2.0 */ trait CurrentUserTrait { /** * The current user object. * * @var User * @since 4.2.0 */ private $currentUser; /** * Returns the current user, if none is set the identity of the global app * is returned. This will change in 6.0 and an empty user will be returned. * * @return User * * @since 4.2.0 */ protected function getCurrentUser(): User { if (!$this->currentUser) { @trigger_error( sprintf('User must be set in %s. This will not be caught anymore in 6.0', __METHOD__), E_USER_DEPRECATED ); $this->currentUser = Factory::getApplication()->getIdentity() ?: Factory::getUser(); } return $this->currentUser; } /** * Sets the current user. * * @param User $currentUser The current user object * * @return void * * @since 4.2.0 */ public function setCurrentUser(User $currentUser): void { $this->currentUser = $currentUser; } } CurrentUserInterface.php 0000644 00000001305 15173101146 0011355 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2022 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface to be implemented by classes depending on a current user. * * @since 4.2.0 */ interface CurrentUserInterface { /** * Sets the current user. * * @param User $currentUser The current user object * * @return void * * @since 4.2.0 */ public function setCurrentUser(User $currentUser): void; } User.php 0000644 00000060640 15173101146 0006200 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2006 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; use Joomla\CMS\Access\Access; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\Log\Log; use Joomla\CMS\Object\CMSObject; use Joomla\CMS\Plugin\PluginHelper; use Joomla\CMS\Table\Table; use Joomla\Registry\Registry; use Joomla\Utilities\ArrayHelper; // phpcs:disable PSR1.Files.SideEffects \defined('JPATH_PLATFORM') or die; // phpcs:enable PSR1.Files.SideEffects /** * User class. Handles all application interaction with a user * * @since 1.7.0 */ class User extends CMSObject { /** * A cached switch for if this user has root access rights. * * @var boolean * @since 1.7.0 */ protected $isRoot = null; /** * Unique id * * @var integer * @since 1.7.0 */ public $id = null; /** * The user's real name (or nickname) * * @var string * @since 1.7.0 */ public $name = null; /** * The login name * * @var string * @since 1.7.0 */ public $username = null; /** * The email * * @var string * @since 1.7.0 */ public $email = null; /** * MD5 encrypted password * * @var string * @since 1.7.0 */ public $password = null; /** * Clear password, only available when a new password is set for a user * * @var string * @since 1.7.0 */ public $password_clear = ''; /** * Block status * * @var integer * @since 1.7.0 */ public $block = null; /** * Should this user receive system email * * @var integer * @since 1.7.0 */ public $sendEmail = null; /** * Date the user was registered * * @var string * @since 1.7.0 */ public $registerDate = null; /** * Date of last visit * * @var string * @since 1.7.0 */ public $lastvisitDate = null; /** * Activation hash * * @var string * @since 1.7.0 */ public $activation = null; /** * User parameters * * @var Registry * @since 1.7.0 */ public $params = null; /** * Associative array of user names => group ids * * @var array * @since 1.7.0 */ public $groups = []; /** * Guest status * * @var integer * @since 1.7.0 */ public $guest = null; /** * Last Reset Time * * @var string * @since 3.0.1 */ public $lastResetTime = null; /** * Count since last Reset Time * * @var integer * @since 3.0.1 */ public $resetCount = null; /** * Flag to require the user's password be reset * * @var integer * @since 3.2 */ public $requireReset = null; /** * User parameters * * @var Registry * @since 1.7.0 */ protected $_params = null; /** * Authorised access groups * * @var array * @since 1.7.0 */ protected $_authGroups = null; /** * Authorised access levels * * @var array * @since 1.7.0 */ protected $_authLevels = null; /** * Authorised access actions * * @var array * @since 1.7.0 */ protected $_authActions = null; /** * Error message * * @var string * @since 1.7.0 */ protected $_errorMsg = null; /** * @var array User instances container. * @since 1.7.3 */ protected static $instances = []; /** * The access level id * * @var integer * @since 4.3.0 * * @deprecated 4.4.0 will be removed in 6.0 as this property is not used anymore */ public $aid = null; /** * Constructor activating the default information of the language * * @param integer $identifier The primary key of the user to load (optional). * * @since 1.7.0 */ public function __construct($identifier = 0) { // Create the user parameters object $this->_params = new Registry(); // Load the user if it exists if (!empty($identifier)) { $this->load($identifier); } else { // Initialise $this->id = 0; $this->sendEmail = 0; $this->aid = 0; $this->guest = 1; } } /** * Returns the global User object, only creating it if it doesn't already exist. * * @param integer $identifier The primary key of the user to load (optional). * * @return User The User object. * * @since 1.7.0 * @deprecated 4.3 will be removed in 6.0 * Load the user service from the dependency injection container or via $app->getIdentity() * Example: Factory::getContainer()->get(UserFactoryInterface::class)->loadUserById($id) */ public static function getInstance($identifier = 0) { @trigger_error( sprintf( '%1$s() is deprecated. Load the user from the dependency injection container or via %2$s::getApplication()->getIdentity().', __METHOD__, __CLASS__ ), E_USER_DEPRECATED ); // Find the user id if (!is_numeric($identifier)) { return Factory::getContainer()->get(UserFactoryInterface::class)->loadUserByUsername($identifier); } else { $id = $identifier; } // If the $id is zero, just return an empty User. // Note: don't cache this user because it'll have a new ID on save! if ($id === 0) { return Factory::getContainer()->get(UserFactoryInterface::class)->loadUserById($id); } // Check if the user ID is already cached. if (empty(self::$instances[$id])) { self::$instances[$id] = Factory::getContainer()->get(UserFactoryInterface::class)->loadUserById($id); } return self::$instances[$id]; } /** * Method to get a parameter value * * @param string $key Parameter key * @param mixed $default Parameter default value * * @return mixed The value or the default if it did not exist * * @since 1.7.0 */ public function getParam($key, $default = null) { return $this->_params->get($key, $default); } /** * Method to set a parameter * * @param string $key Parameter key * @param mixed $value Parameter value * * @return mixed Set parameter value * * @since 1.7.0 */ public function setParam($key, $value) { return $this->_params->set($key, $value); } /** * Method to set a default parameter if it does not exist * * @param string $key Parameter key * @param mixed $value Parameter value * * @return mixed Set parameter value * * @since 1.7.0 */ public function defParam($key, $value) { return $this->_params->def($key, $value); } /** * Method to check User object authorisation against an access control * object and optionally an access extension object * * @param string $action The name of the action to check for permission. * @param string $assetname The name of the asset on which to perform the action. * * @return boolean True if authorised * * @since 1.7.0 */ public function authorise($action, $assetname = null) { // Make sure we only check for core.admin once during the run. if ($this->isRoot === null) { $this->isRoot = false; // Check for the configuration file failsafe. $rootUser = Factory::getApplication()->get('root_user'); // The root_user variable can be a numeric user ID or a username. if (is_numeric($rootUser) && $this->id > 0 && $this->id == $rootUser) { $this->isRoot = true; } elseif ($this->username && $this->username == $rootUser) { $this->isRoot = true; } elseif ($this->id > 0) { // Get all groups against which the user is mapped. $identities = $this->getAuthorisedGroups(); array_unshift($identities, $this->id * -1); if (Access::getAssetRules(1)->allow('core.admin', $identities)) { $this->isRoot = true; return true; } } } return $this->isRoot ? true : (bool) Access::check($this->id, $action, $assetname); } /** * Method to return a list of all categories that a user has permission for a given action * * @param string $component The component from which to retrieve the categories * @param string $action The name of the section within the component from which to retrieve the actions. * * @return array List of categories that this group can do this action to (empty array if none). Categories must be published. * * @since 1.7.0 */ public function getAuthorisedCategories($component, $action) { // Brute force method: get all published category rows for the component and check each one // @todo: Modify the way permissions are stored in the db to allow for faster implementation and better scaling $db = Factory::getDbo(); $subQuery = $db->getQuery(true) ->select($db->quoteName(['id', 'asset_id'])) ->from($db->quoteName('#__categories')) ->where( [ $db->quoteName('extension') . ' = :component', $db->quoteName('published') . ' = 1', ] ); $query = $db->getQuery(true) ->select($db->quoteName(['c.id', 'a.name'])) ->from('(' . $subQuery . ') AS ' . $db->quoteName('c')) ->join('INNER', $db->quoteName('#__assets', 'a'), $db->quoteName('c.asset_id') . ' = ' . $db->quoteName('a.id')) ->bind(':component', $component); $db->setQuery($query); $allCategories = $db->loadObjectList('id'); $allowedCategories = []; foreach ($allCategories as $category) { if ($this->authorise($action, $category->name)) { $allowedCategories[] = (int) $category->id; } } return $allowedCategories; } /** * Gets an array of the authorised access levels for the user * * @return array * * @since 1.7.0 */ public function getAuthorisedViewLevels() { if ($this->_authLevels === null) { $this->_authLevels = []; } if (empty($this->_authLevels)) { $this->_authLevels = Access::getAuthorisedViewLevels($this->id); } return $this->_authLevels; } /** * Gets an array of the authorised user groups * * @return array * * @since 1.7.0 */ public function getAuthorisedGroups() { if ($this->_authGroups === null) { $this->_authGroups = []; } if (empty($this->_authGroups)) { $this->_authGroups = Access::getGroupsByUser($this->id); } return $this->_authGroups; } /** * Clears the access rights cache of this user * * @return void * * @since 3.4.0 */ public function clearAccessRights() { $this->_authLevels = null; $this->_authGroups = null; $this->isRoot = null; Access::clearStatics(); } /** * Pass through method to the table for setting the last visit date * * @param integer $timestamp The timestamp, defaults to 'now'. * * @return boolean True on success. * * @since 1.7.0 */ public function setLastVisit($timestamp = null) { // Create the user table object /** @var \Joomla\CMS\Table\User $table */ $table = $this->getTable(); $table->load($this->id); return $table->setLastVisit($timestamp); } /** * Method to get the user timezone. * * If the user didn't set a timezone, it will return the server timezone * * @return \DateTimeZone * * @since 3.7.0 */ public function getTimezone() { $timezone = $this->getParam('timezone', Factory::getApplication()->get('offset', 'GMT')); return new \DateTimeZone($timezone); } /** * Method to get the user parameters * * @param object $params The user parameters object * * @return void * * @since 1.7.0 */ public function setParameters($params) { $this->_params = $params; } /** * Method to get the user table object * * This function uses a static variable to store the table name of the user table to * instantiate. You can call this function statically to set the table name if * needed. * * @param string $type The user table name to be used * @param string $prefix The user table prefix to be used * * @return Table The user table object * * @note At 4.0 this method will no longer be static * @since 1.7.0 */ public static function getTable($type = null, $prefix = 'JTable') { static $tabletype; // Set the default tabletype; if (!isset($tabletype)) { $tabletype['name'] = 'user'; $tabletype['prefix'] = 'JTable'; } // Set a custom table type is defined if (isset($type)) { $tabletype['name'] = $type; $tabletype['prefix'] = $prefix; } // Create the user table object return Table::getInstance($tabletype['name'], $tabletype['prefix']); } /** * Method to bind an associative array of data to a user object * * @param array &$array The associative array to bind to the object * * @return boolean True on success * * @since 1.7.0 */ public function bind(&$array) { // Let's check to see if the user is new or not if (empty($this->id)) { // Check the password and create the crypted password if (empty($array['password'])) { $array['password'] = UserHelper::genRandomPassword(32); $array['password2'] = $array['password']; } // Not all controllers check the password, although they should. // Hence this code is required: if (isset($array['password2']) && $array['password'] != $array['password2']) { Factory::getApplication()->enqueueMessage(Text::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'), 'error'); return false; } $this->password_clear = ArrayHelper::getValue($array, 'password', '', 'string'); $array['password'] = UserHelper::hashPassword($array['password']); // Set the registration timestamp $this->set('registerDate', Factory::getDate()->toSql()); } else { // Updating an existing user if (!empty($array['password'])) { if ($array['password'] != $array['password2']) { $this->setError(Text::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH')); return false; } $this->password_clear = ArrayHelper::getValue($array, 'password', '', 'string'); // Check if the user is reusing the current password if required to reset their password if ($this->requireReset == 1 && UserHelper::verifyPassword($this->password_clear, $this->password)) { $this->setError(Text::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD')); return false; } $array['password'] = UserHelper::hashPassword($array['password']); // Reset the change password flag $array['requireReset'] = 0; } else { $array['password'] = $this->password; } // Prevent updating internal fields unset($array['registerDate']); unset($array['lastvisitDate']); unset($array['lastResetTime']); unset($array['resetCount']); } if (\array_key_exists('params', $array)) { $this->_params->loadArray($array['params']); if (\is_array($array['params'])) { $params = (string) $this->_params; } else { $params = $array['params']; } $this->params = $params; } // Bind the array if (!$this->setProperties($array)) { $this->setError(Text::_('JLIB_USER_ERROR_BIND_ARRAY')); return false; } // Make sure its an integer $this->id = (int) $this->id; return true; } /** * Method to save the User object to the database * * @param boolean $updateOnly Save the object only if not a new user * Currently only used in the user reset password method. * * @return boolean True on success * * @since 1.7.0 * @throws \RuntimeException */ public function save($updateOnly = false) { // Create the user table object $table = $this->getTable(); $this->params = (string) $this->_params; $table->bind($this->getProperties()); // Allow an exception to be thrown. try { // Check and store the object. if (!$table->check()) { $this->setError($table->getError()); return false; } // If user is made a Super Admin group and user is NOT a Super Admin // @todo ACL - this needs to be acl checked $my = Factory::getUser(); // Are we creating a new user $isNew = empty($this->id); // If we aren't allowed to create new users return if ($isNew && $updateOnly) { return true; } // Get the old user $oldUser = new User($this->id); // Access Checks // The only mandatory check is that only Super Admins can operate on other Super Admin accounts. // To add additional business rules, use a user plugin and throw an Exception with onUserBeforeSave. // Check if I am a Super Admin $iAmSuperAdmin = $my->authorise('core.admin'); $iAmRehashingSuperadmin = false; if (($my->id == 0 && !$isNew) && $this->id == $oldUser->id && $oldUser->authorise('core.admin') && $oldUser->password != $this->password) { $iAmRehashingSuperadmin = true; } // Check if we are using a CLI application $isCli = false; if (Factory::getApplication()->isCli()) { $isCli = true; } // We are only worried about edits to this account if I am not a Super Admin. if ($iAmSuperAdmin != true && $iAmRehashingSuperadmin != true && $isCli != true) { // I am not a Super Admin, and this one is, so fail. if (!$isNew && Access::check($this->id, 'core.admin')) { throw new \RuntimeException('User not Super Administrator'); } if ($this->groups != null) { // I am not a Super Admin and I'm trying to make one. foreach ($this->groups as $groupId) { if (Access::checkGroup($groupId, 'core.admin')) { throw new \RuntimeException('User not Super Administrator'); } } } } // Unset the activation token, if the mail address changes - that affects both, activation and PW resets if ($this->email !== $oldUser->email && $this->id !== 0 && !empty($this->activation) && !$this->block) { $table->activation = ''; } // Fire the onUserBeforeSave event. PluginHelper::importPlugin('user'); $result = Factory::getApplication()->triggerEvent('onUserBeforeSave', [$oldUser->getProperties(), $isNew, $this->getProperties()]); if (\in_array(false, $result, true)) { // Plugin will have to raise its own error or throw an exception. return false; } // Store the user data in the database $result = $table->store(); // Set the id for the User object in case we created a new user. if (empty($this->id)) { $this->id = $table->get('id'); } if ($my->id == $table->id) { $registry = new Registry($table->params); $my->setParameters($registry); } // Fire the onUserAfterSave event Factory::getApplication()->triggerEvent('onUserAfterSave', [$this->getProperties(), $isNew, $result, $this->getError()]); } catch (\Exception $e) { $this->setError($e->getMessage()); return false; } return $result; } /** * Method to delete the User object from the database * * @return boolean True on success * * @since 1.7.0 */ public function delete() { PluginHelper::importPlugin('user'); // Trigger the onUserBeforeDelete event Factory::getApplication()->triggerEvent('onUserBeforeDelete', [$this->getProperties()]); // Create the user table object $table = $this->getTable(); if (!$result = $table->delete($this->id)) { $this->setError($table->getError()); } // Trigger the onUserAfterDelete event Factory::getApplication()->triggerEvent('onUserAfterDelete', [$this->getProperties(), $result, $this->getError()]); return $result; } /** * Method to load a User object by user id number * * @param mixed $id The user id of the user to load * * @return boolean True on success * * @since 1.7.0 */ public function load($id) { // Create the user table object $table = $this->getTable(); // Load the UserModel object based on the user id or throw a warning. if (!$table->load($id)) { // Reset to guest user $this->guest = 1; Log::add(Text::sprintf('JLIB_USER_ERROR_UNABLE_TO_LOAD_USER', $id), Log::WARNING, 'jerror'); return false; } /* * Set the user parameters using the default XML file. We might want to * extend this in the future to allow for the ability to have custom * user parameters, but for right now we'll leave it how it is. */ if ($table->params) { $this->_params->loadString($table->params); } // Assuming all is well at this point let's bind the data $this->setProperties($table->getProperties()); // The user is no longer a guest if ($this->id != 0) { $this->guest = 0; } else { $this->guest = 1; } return true; } /** * Method to allow serialize the object with minimal properties. * * @return array The names of the properties to include in serialization. * * @since 3.6.0 */ public function __sleep() { return ['id']; } /** * Method to recover the full object on unserialize. * * @return void * * @since 3.6.0 */ public function __wakeup() { // Initialise some variables $this->_params = new Registry(); // Load the user if it exists if (!empty($this->id) && $this->load($this->id)) { // Push user into cached instances. self::$instances[$this->id] = $this; } else { // Initialise $this->id = 0; $this->sendEmail = 0; $this->aid = 0; $this->guest = 1; } } } UserFactoryInterface.php 0000644 00000001670 15173101146 0011347 0 ustar 00 <?php /** * Joomla! Content Management System * * @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; // phpcs:disable PSR1.Files.SideEffects \defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Interface defining a factory which can create User objects * * @since 4.0.0 */ interface UserFactoryInterface { /** * Method to get an instance of a user for the given id. * * @param int $id The id * * @return User * * @since 4.0.0 */ public function loadUserById(int $id): User; /** * Method to get an instance of a user for the given username. * * @param string $username The username * * @return User * * @since 4.0.0 */ public function loadUserByUsername(string $username): User; }
| ver. 1.4 |
Github
|
.
| PHP 8.3.23 | Generation time: 0 |
proxy
|
phpinfo
|
Settings