Spade
Mini Shell
PK�]�[�p%��Q�QUser.phpnu�[���<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
namespace Joomla\CMS\User;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Access\Access;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Table\Table;
use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;
/**
* User class. Handles all application interaction with a user
*
* @since 1.7.0
*/
class User extends \JObject
{
/**
* 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 = array();
/**
* 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 int
* @since 3.0.1
*/
public $resetCount = null;
/**
* Flag to require the user's password be reset
*
* @var int
* @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;
/**
* UserWrapper object
*
* @var UserWrapper
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
protected $userHelper = null;
/**
* @var array User instances container.
* @since 1.7.3
*/
protected static $instances = array();
/**
* Constructor activating the default information of the language
*
* @param integer $identifier The primary key of the user to load
(optional).
* @param UserWrapper $userHelper The UserWrapper for the static
methods. [@deprecated 4.0]
*
* @since 1.7.0
*/
public function __construct($identifier = 0, UserWrapper $userHelper =
null)
{
if (null === $userHelper)
{
$userHelper = new UserWrapper;
}
$this->userHelper = $userHelper;
// 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).
* @param UserWrapper $userHelper The UserWrapper for the static
methods. [@deprecated 4.0]
*
* @return User The User object.
*
* @since 1.7.0
*/
public static function getInstance($identifier = 0, UserWrapper
$userHelper = null)
{
if (null === $userHelper)
{
$userHelper = new UserWrapper;
}
// Find the user id
if (!is_numeric($identifier))
{
if (!$id = $userHelper->getUserId($identifier))
{
// If the $identifier doesn't match with any id, just return an
empty User.
return new User;
}
}
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 new User;
}
// Check if the user ID is already cached.
if (empty(self::$instances[$id]))
{
$user = new User($id, $userHelper);
self::$instances[$id] = $user;
}
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 = \JFactory::getConfig()->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 = \JFactory::getDbo();
$subQuery = $db->getQuery(true)
->select('id,asset_id')
->from('#__categories')
->where('extension = ' . $db->quote($component))
->where('published = 1');
$query = $db->getQuery(true)
->select('c.id AS id, a.name AS asset_name')
->from('(' . (string) $subQuery . ') AS c')
->join('INNER', '#__assets AS a ON c.asset_id =
a.id');
$db->setQuery($query);
$allCategories = $db->loadObjectList('id');
$allowedCategories = array();
foreach ($allCategories as $category)
{
if ($this->authorise($action, $category->asset_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 = array();
}
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 = array();
}
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
$table = $this->getTable();
$table->load($this->id);
return $table->setLastVisit($timestamp);
}
/**
* Method to get the user parameters
*
* This method used to load the user parameters from a file.
*
* @return object The user parameters object.
*
* @since 1.7.0
* @deprecated 4.0 - Instead use User::getParam()
*/
public function getParameters()
{
// @codeCoverageIgnoreStart
\JLog::add('User::getParameters() is deprecated.
User::getParam().', \JLog::WARNING, 'deprecated');
return $this->_params;
// @codeCoverageIgnoreEnd
}
/**
* 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',
\JFactory::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 object 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'] =
$this->userHelper->genRandomPassword();
$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'])
{
\JFactory::getApplication()->enqueueMessage(\JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'),
'error');
return false;
}
$this->password_clear = ArrayHelper::getValue($array,
'password', '', 'string');
$array['password'] =
$this->userHelper->hashPassword($array['password']);
// Set the registration timestamp
$this->set('registerDate',
\JFactory::getDate()->toSql());
}
else
{
// Updating an existing user
if (!empty($array['password']))
{
if ($array['password'] != $array['password2'])
{
$this->setError(\JText::_('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 &&
$this->userHelper->verifyPassword($this->password_clear,
$this->password))
{
$this->setError(\JText::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD'));
return false;
}
$array['password'] =
$this->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(\JText::_('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 = \JFactory::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;
}
// We are only worried about edits to this account if I am not a Super
Admin.
if ($iAmSuperAdmin != true && $iAmRehashingSuperadmin != 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');
}
}
}
}
// Fire the onUserBeforeSave event.
PluginHelper::importPlugin('user');
$dispatcher = \JEventDispatcher::getInstance();
$result = $dispatcher->trigger('onUserBeforeSave',
array($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
$dispatcher->trigger('onUserAfterSave',
array($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
$dispatcher = \JEventDispatcher::getInstance();
$dispatcher->trigger('onUserBeforeDelete',
array($this->getProperties()));
// Create the user table object
$table = $this->getTable();
if (!$result = $table->delete($this->id))
{
$this->setError($table->getError());
}
// Trigger the onUserAfterDelete event
$dispatcher->trigger('onUserAfterDelete',
array($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;
\JLog::add(\JText::sprintf('JLIB_USER_ERROR_UNABLE_TO_LOAD_USER',
$id), \JLog::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 array('id');
}
/**
* Method to recover the full object on unserialize.
*
* @return void
*
* @since 3.6.0
*/
public function __wakeup()
{
// Initialise some variables
$this->userHelper = new UserWrapper;
$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;
}
}
}
PK�]�[�u�T�TUserHelper.phpnu�[���<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
namespace Joomla\CMS\User;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Access\Access;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Utilities\ArrayHelper;
/**
* 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
{
/**
* 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)
{
// Get the user object.
$user = new User((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Check whether the group exists.
$db = \JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int)
$groupId);
$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;
// Store the user object.
$user->save();
}
// Set the group data for any preloaded user objects.
$temp = User::getInstance((int) $userId);
$temp->groups = $user->groups;
if (\JFactory::getSession()->getId())
{
// Set the group data for the user object in the session.
$temp = \JFactory::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 isset($user->groups) ? $user->groups : array();
}
/**
* 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)
{
// Remove the user from the group.
unset($user->groups[$key]);
// Store the user object.
$user->save();
}
// Set the group data for any preloaded user objects.
$temp = \JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = \JFactory::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 = \JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id') . ', ' .
$db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' .
implode(' OR ' . $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();
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = \JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = \JFactory::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 = \JFactory::getUser();
$userId = $user->id;
}
// Get the dispatcher and load the user's plugins.
$dispatcher = \JEventDispatcher::getInstance();
PluginHelper::importPlugin('user');
$data = new \JObject;
$data->id = $userId;
// Trigger the data preparation event.
$dispatcher->trigger('onContentPrepareData',
array('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 = \JFactory::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') . ' = ' .
$db->quote($activation))
->where($db->quoteName('block') . ' = 1')
->where($db->quoteName('lastvisitDate') . ' =
' . $db->quote($db->getNullDate()));
$db->setQuery($query);
$id = (int) $db->loadResult();
// Is it a valid user to activate?
if ($id)
{
$user = User::getInstance((int) $id);
$user->set('block', '0');
$user->set('activation', '');
// Time to take care of business.... store the user.
if (!$user->save())
{
\JLog::add($user->getError(), \JLog::WARNING, 'jerror');
return false;
}
}
else
{
\JLog::add(\JText::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'),
\JLog::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 = \JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('username') . ' = ' .
$db->quote($username));
$db->setQuery($query, 0, 1);
return $db->loadResult();
}
/**
* Hashes a password using the current encryption.
*
* @param string $password The plaintext password to encrypt.
* @param integer $algorithm The hashing algorithm to use, represented
by `PASSWORD_*` constants.
* @param array $options The options for the algorithm to use.
*
* @return string The encrypted password.
*
* @since 3.2.1
*/
public static function hashPassword($password, $algorithm =
PASSWORD_BCRYPT, array $options = array())
{
// \JCrypt::hasStrongPasswordSupport() includes a fallback for us in the
worst case
\JCrypt::hasStrongPasswordSupport();
return password_hash($password, $algorithm, $options);
}
/**
* 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 = PASSWORD_BCRYPT;
// If we are using phpass
if (strpos($hash, '$P$') === 0)
{
// Use PHPass's portable hashes with a cost of 10.
$phpass = new \PasswordHash(10, true);
$match = $phpass->CheckPassword($password, $hash);
$rehash = true;
}
// Check for Argon2id hashes
elseif (strpos($hash, '$argon2id') === 0)
{
// This implementation is not supported through any existing polyfills
$match = password_verify($password, $hash);
$rehash = password_needs_rehash($hash, PASSWORD_ARGON2ID);
$passwordAlgorithm = PASSWORD_ARGON2ID;
}
// Check for Argon2i hashes
elseif (strpos($hash, '$argon2i') === 0)
{
// This implementation is not supported through any existing polyfills
$match = password_verify($password, $hash);
$rehash = password_needs_rehash($hash, PASSWORD_ARGON2I);
$passwordAlgorithm = PASSWORD_ARGON2I;
}
// Check for bcrypt hashes
elseif (strpos($hash, '$2') === 0)
{
// \JCrypt::hasStrongPasswordSupport() includes a fallback for us in the
worst case
\JCrypt::hasStrongPasswordSupport();
$match = password_verify($password, $hash);
$rehash = password_needs_rehash($hash, PASSWORD_BCRYPT);
}
elseif (substr($hash, 0, 8) == '{SHA256}')
{
// Check the password
$parts = explode(':', $hash);
$salt = @$parts[1];
$testcrypt = static::getCryptedPassword($password, $salt,
'sha256', true);
$match = \JCrypt::timingSafeCompare($hash, $testcrypt);
$rehash = true;
}
else
{
// Check the password
$parts = explode(':', $hash);
$salt = @$parts[1];
$rehash = true;
// Compile the hash to compare
// If the salt is empty AND there is a ':' in the original
hash, we must append ':' at the end
$testcrypt = md5($password . $salt) . ($salt ? ':' . $salt :
(strpos($hash, ':') !== false ? ':' : ''));
$match = \JCrypt::timingSafeCompare($hash, $testcrypt);
}
// 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;
}
/**
* Formats a password using the old encryption methods.
*
* @param string $plaintext The plaintext password to encrypt.
* @param string $salt The salt to use to encrypt the
password. []
* If not present, a new salt will be
* generated.
* @param string $encryption The kind of password encryption to use.
* Defaults to md5-hex.
* @param boolean $showEncrypt Some password systems prepend the kind
of
* encryption to the crypted password
({SHA},
* etc). Defaults to false.
*
* @return string The encrypted password.
*
* @since 1.7.0
* @deprecated 4.0
*/
public static function getCryptedPassword($plaintext, $salt =
'', $encryption = 'md5-hex', $showEncrypt = false)
{
// Get the salt to use.
$salt = static::getSalt($encryption, $salt, $plaintext);
// Encrypt the password.
switch ($encryption)
{
case 'plain':
return $plaintext;
case 'sha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
return ($showEncrypt) ? '{SHA}' . $encrypted : $encrypted;
case 'crypt':
case 'crypt-des':
case 'crypt-md5':
case 'crypt-blowfish':
return ($showEncrypt ? '{crypt}' : '') .
crypt($plaintext, $salt);
case 'md5-base64':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
return ($showEncrypt) ? '{MD5}' . $encrypted : $encrypted;
case 'ssha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt) .
$salt);
return ($showEncrypt) ? '{SSHA}' . $encrypted : $encrypted;
case 'smd5':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt) .
$salt);
return ($showEncrypt) ? '{SMD5}' . $encrypted : $encrypted;
case 'aprmd5':
$length = strlen($plaintext);
$context = $plaintext . '$apr1$' . $salt;
$binary = static::_bin(md5($plaintext . $salt . $plaintext));
for ($i = $length; $i > 0; $i -= 16)
{
$context .= substr($binary, 0, ($i > 16 ? 16 : $i));
}
for ($i = $length; $i > 0; $i >>= 1)
{
$context .= ($i & 1) ? chr(0) : $plaintext[0];
}
$binary = static::_bin(md5($context));
for ($i = 0; $i < 1000; $i++)
{
$new = ($i & 1) ? $plaintext : substr($binary, 0, 16);
if ($i % 3)
{
$new .= $salt;
}
if ($i % 7)
{
$new .= $plaintext;
}
$new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
$binary = static::_bin(md5($new));
}
$p = array();
for ($i = 0; $i < 5; $i++)
{
$k = $i + 6;
$j = $i + 12;
if ($j == 16)
{
$j = 5;
}
$p[] = static::_toAPRMD5((ord($binary[$i]) << 16) |
(ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
}
return '$apr1$' . $salt . '$' .
implode('', $p) . static::_toAPRMD5(ord($binary[11]), 3);
case 'sha256':
$encrypted = ($salt) ? hash('sha256', $plaintext . $salt) .
':' . $salt : hash('sha256', $plaintext);
return ($showEncrypt) ? '{SHA256}' . $encrypted :
'{SHA256}' . $encrypted;
case 'md5-hex':
default:
$encrypted = ($salt) ? md5($plaintext . $salt) : md5($plaintext);
return ($showEncrypt) ? '{MD5}' . $encrypted : $encrypted;
}
}
/**
* Returns a salt for the appropriate kind of password encryption using
the old encryption methods.
* Optionally takes a seed and a plaintext password, to extract the seed
* of an existing password, or for encryption types that use the plaintext
* in the generation of the salt.
*
* @param string $encryption The kind of password encryption to use.
* Defaults to md5-hex.
* @param string $seed The seed to get the salt from (probably a
* previously generated password). Defaults
to
* generating a new seed.
* @param string $plaintext The plaintext password that we're
generating
* a salt for. Defaults to none.
*
* @return string The generated or extracted salt.
*
* @since 1.7.0
* @deprecated 4.0
*/
public static function getSalt($encryption = 'md5-hex', $seed =
'', $plaintext = '')
{
// Encrypt the password.
switch ($encryption)
{
case 'crypt':
case 'crypt-des':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '',
$seed), 0, 2);
}
else
{
return substr(md5(mt_rand()), 0, 2);
}
break;
case 'sha256':
if ($seed)
{
return preg_replace('|^{sha256}|i', '', $seed);
}
else
{
return static::genRandomPassword(16);
}
break;
case 'crypt-md5':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '',
$seed), 0, 12);
}
else
{
return '$1$' . substr(md5(\JCrypt::genRandomBytes()), 0, 8)
. '$';
}
break;
case 'crypt-blowfish':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '',
$seed), 0, 30);
}
else
{
return '$2y$10$' . substr(md5(\JCrypt::genRandomBytes()), 0,
22) . '$';
}
break;
case 'ssha':
if ($seed)
{
return substr(preg_replace('|^{SSHA}|', '',
$seed), -20);
}
else
{
return mhash_keygen_s2k(MHASH_SHA1, $plaintext,
substr(pack('h*', md5(\JCrypt::genRandomBytes())), 0, 8), 4);
}
break;
case 'smd5':
if ($seed)
{
return substr(preg_replace('|^{SMD5}|', '',
$seed), -16);
}
else
{
return mhash_keygen_s2k(MHASH_MD5, $plaintext,
substr(pack('h*', md5(\JCrypt::genRandomBytes())), 0, 8), 4);
}
break;
case 'aprmd5': // 64 characters that are valid for APRMD5
passwords.
$APRMD5 =
'./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($seed)
{
return substr(preg_replace('/^\$apr1\$(.{8}).*/',
'\\1', $seed), 0, 8);
}
else
{
$salt = '';
for ($i = 0; $i < 8; $i++)
{
$salt .= $APRMD5[mt_rand(0, 63)];
}
return $salt;
}
break;
default:
$salt = '';
if ($seed)
{
$salt = $seed;
}
return $salt;
break;
}
}
/**
* 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 = \JCrypt::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;
}
/**
* Converts to allowed 64 characters for APRMD5 passwords.
*
* @param string $value The value to convert.
* @param integer $count The number of characters to convert.
*
* @return string $value converted to the 64 MD5 characters.
*
* @since 1.7.0
*/
protected static function _toAPRMD5($value, $count)
{
// 64 characters that are valid for APRMD5 passwords.
$APRMD5 =
'./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$aprmd5 = '';
$count = abs($count);
while (--$count)
{
$aprmd5 .= $APRMD5[$value & 0x3f];
$value >>= 6;
}
return $aprmd5;
}
/**
* Converts hexadecimal string to binary data.
*
* @param string $hex Hex data.
*
* @return string Binary data.
*
* @since 1.7.0
*/
private static function _bin($hex)
{
$bin = '';
$length = strlen($hex);
for ($i = 0; $i < $length; $i += 2)
{
$tmp = sscanf(substr($hex, $i, 2), '%x');
$bin .= chr(array_shift($tmp));
}
return $bin;
}
/**
* Method to remove a cookie record from the database and the browser
*
* @param string $userId User ID for this user
* @param string $cookieName Series id (cookie name decoded)
*
* @return boolean True on success
*
* @since 3.2
* @deprecated 4.0 This is handled in the authentication plugin itself.
The 'invalid' column in the db should be removed as well
*/
public static function invalidateCookie($userId, $cookieName)
{
$db = \JFactory::getDbo();
$query = $db->getQuery(true);
// Invalidate cookie in the database
$query
->update($db->quoteName('#__user_keys'))
->set($db->quoteName('invalid') . ' = 1')
->where($db->quoteName('user_id') . ' = ' .
$db->quote($userId));
$db->setQuery($query)->execute();
// Destroy the cookie in the browser.
$app = \JFactory::getApplication();
$app->input->cookie->set($cookieName, '', 1,
$app->get('cookie_path', '/'),
$app->get('cookie_domain', ''));
return true;
}
/**
* Clear all expired tokens for all users.
*
* @return mixed Database query result
*
* @since 3.2
* @deprecated 4.0 This is handled in the authentication plugin itself
*/
public static function clearExpiredTokens()
{
$now = time();
$db = \JFactory::getDbo();
$query = $db->getQuery(true)
->delete('#__user_keys')
->where($db->quoteName('time') . ' < ' .
$db->quote($now));
return $db->setQuery($query)->execute();
}
/**
* Method to get the remember me cookie data
*
* @return mixed An array of information from an authentication cookie
or false if there is no cookie
*
* @since 3.2
* @deprecated 4.0 This is handled in the authentication plugin itself
*/
public static function getRememberCookieData()
{
// Create the cookie name
$cookieName = static::getShortHashedUserAgent();
// Fetch the cookie value
$app = \JFactory::getApplication();
$cookieValue = $app->input->cookie->get($cookieName);
if (!empty($cookieValue))
{
return explode('.', $cookieValue);
}
else
{
return false;
}
}
/**
* 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 = \JFactory::getApplication()->client;
$uaString = $ua->userAgent;
$browserVersion = $ua->browserVersion;
$uaShort = str_replace($browserVersion, 'abcd', $uaString);
return md5(\JUri::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;
}
}
PK�]�[r�;0B B UserWrapper.phpnu�[���<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
namespace Joomla\CMS\User;
defined('JPATH_PLATFORM') or die;
/**
* Wrapper class for UserHelper
*
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
class UserWrapper
{
/**
* Helper wrapper method for addUserToGroup
*
* @param integer $userId The id of the user.
* @param integer $groupId The id of the group.
*
* @return boolean True on success
*
* @see UserHelper::addUserToGroup()
* @since 3.4
* @throws \RuntimeException
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function addUserToGroup($userId, $groupId)
{
return UserHelper::addUserToGroup($userId, $groupId);
}
/**
* Helper wrapper method for getUserGroups
*
* @param integer $userId The id of the user.
*
* @return array List of groups
*
* @see UserHelper::addUserToGroup()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function getUserGroups($userId)
{
return UserHelper::getUserGroups($userId);
}
/**
* Helper wrapper method for removeUserFromGroup
*
* @param integer $userId The id of the user.
* @param integer $groupId The id of the group.
*
* @return boolean True on success
*
* @see UserHelper::removeUserFromGroup()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function removeUserFromGroup($userId, $groupId)
{
return UserHelper::removeUserFromGroup($userId, $groupId);
}
/**
* Helper wrapper method for setUserGroups
*
* @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
*
* @see UserHelper::setUserGroups()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function setUserGroups($userId, $groups)
{
return UserHelper::setUserGroups($userId, $groups);
}
/**
* Helper wrapper method for getProfile
*
* @param integer $userId The id of the user.
*
* @return object
*
* @see UserHelper::getProfile()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function getProfile($userId = 0)
{
return UserHelper::getProfile($userId);
}
/**
* Helper wrapper method for activateUser
*
* @param string $activation Activation string
*
* @return boolean True on success
*
* @see UserHelper::activateUser()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function activateUser($activation)
{
return UserHelper::activateUser($activation);
}
/**
* Helper wrapper method for getUserId
*
* @param string $username The username to search on.
*
* @return integer The user id or 0 if not found.
*
* @see UserHelper::getUserId()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function getUserId($username)
{
return UserHelper::getUserId($username);
}
/**
* Helper wrapper method for hashPassword
*
* @param string $password The plaintext password to encrypt.
* @param integer $algorithm The hashing algorithm to use, represented
by `PASSWORD_*` constants.
* @param array $options The options for the algorithm to use.
*
* @return string The encrypted password.
*
* @see UserHelper::hashPassword()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function hashPassword($password, $algorithm = PASSWORD_BCRYPT,
array $options = array())
{
return UserHelper::hashPassword($password, $algorithm, $options);
}
/**
* Helper wrapper method for verifyPassword
*
* @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
*
* @see UserHelper::verifyPassword()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function verifyPassword($password, $hash, $userId = 0)
{
return UserHelper::verifyPassword($password, $hash, $userId);
}
/**
* Helper wrapper method for getCryptedPassword
*
* @param string $plaintext The plaintext password to encrypt.
* @param string $salt The salt to use to encrypt the
password. []
* If not present, a new salt will be
* generated.
* @param string $encryption The kind of password encryption to use.
* Defaults to md5-hex.
* @param boolean $showEncrypt Some password systems prepend the kind
of
* encryption to the crypted password
({SHA},
* etc). Defaults to false.
*
* @return string The encrypted password.
*
* @see UserHelper::getCryptedPassword()
* @since 3.4
* @deprecated 4.0
*/
public function getCryptedPassword($plaintext, $salt = '',
$encryption = 'md5-hex', $showEncrypt = false)
{
return UserHelper::getCryptedPassword($plaintext, $salt, $encryption,
$showEncrypt);
}
/**
* Helper wrapper method for getSalt
*
* @param string $encryption The kind of password encryption to use.
* Defaults to md5-hex.
* @param string $seed The seed to get the salt from (probably a
* previously generated password). Defaults
to
* generating a new seed.
* @param string $plaintext The plaintext password that we're
generating
* a salt for. Defaults to none.
*
* @return string The generated or extracted salt.
*
* @see UserHelper::getSalt()
* @since 3.4
* @deprecated 4.0
*/
public function getSalt($encryption = 'md5-hex', $seed =
'', $plaintext = '')
{
return UserHelper::getSalt($encryption, $seed, $plaintext);
}
/**
* Helper wrapper method for genRandomPassword
*
* @param integer $length Length of the password to generate
*
* @return string Random Password
*
* @see UserHelper::genRandomPassword()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function genRandomPassword($length = 8)
{
return UserHelper::genRandomPassword($length);
}
/**
* Helper wrapper method for invalidateCookie
*
* @param string $userId User ID for this user
* @param string $cookieName Series id (cookie name decoded)
*
* @return boolean True on success
*
* @see UserHelper::invalidateCookie()
* @since 3.4
* @deprecated 4.0
*/
public function invalidateCookie($userId, $cookieName)
{
return UserHelper::invalidateCookie($userId, $cookieName);
}
/**
* Helper wrapper method for clearExpiredTokens
*
* @return mixed Database query result
*
* @see UserHelper::clearExpiredTokens()
* @since 3.4
* @deprecated 4.0
*/
public function clearExpiredTokens()
{
return UserHelper::clearExpiredTokens();
}
/**
* Helper wrapper method for getRememberCookieData
*
* @return mixed An array of information from an authentication cookie
or false if there is no cookie
*
* @see UserHelper::getRememberCookieData()
* @since 3.4
* @deprecated 4.0
*/
public function getRememberCookieData()
{
return UserHelper::getRememberCookieData();
}
/**
* Helper wrapper method for getShortHashedUserAgent
*
* @return string A hashed user agent string with version replaced by
'abcd'
*
* @see UserHelper::getShortHashedUserAgent()
* @since 3.4
* @deprecated 4.0 Use `Joomla\CMS\User\UserHelper` directly
*/
public function getShortHashedUserAgent()
{
return UserHelper::getShortHashedUserAgent();
}
}
PK�]�[�p%��Q�QUser.phpnu�[���PK�]�[�u�T�T�QUserHelper.phpnu�[���PK�]�[r�;0B
B �UserWrapper.phpnu�[���PK���