first commit

This commit is contained in:
alazhar
2020-01-02 22:20:31 +07:00
commit 10eb3340ad
5753 changed files with 631345 additions and 0 deletions

View File

@ -0,0 +1,456 @@
<?php
/**
* @package Joomla.Platform
* @subpackage User
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Authentication class, provides an interface for the Joomla authentication system
*
* @package Joomla.Platform
* @subpackage User
* @since 11.1
*/
class JAuthentication extends JObject
{
// Shared success status
/**
* This is the status code returned when the authentication is success (permit login)
* @const STATUS_SUCCESS successful response
* @since 11.2
*/
const STATUS_SUCCESS = 1;
// These are for authentication purposes (username and password is valid)
/**
* Status to indicate cancellation of authentication (unused)
* @const STATUS_CANCEL cancelled request (unused)
* @since 11.2
*/
const STATUS_CANCEL = 2;
/**
* This is the status code returned when the authentication failed (prevent login if no success)
* @const STATUS_FAILURE failed request
* @since 11.2
*/
const STATUS_FAILURE = 4;
// These are for authorisation purposes (can the user login)
/**
* This is the status code returned when the account has expired (prevent login)
* @const STATUS_EXPIRED an expired account (will prevent login)
* @since 11.2
*/
const STATUS_EXPIRED = 8;
/**
* This is the status code returned when the account has been denied (prevent login)
* @const STATUS_DENIED denied request (will prevent login)
* @since 11.2
*/
const STATUS_DENIED = 16;
/**
* This is the status code returned when the account doesn't exist (not an error)
* @const STATUS_UNKNOWN unknown account (won't permit or prevent login)
* @since 11.2
*/
const STATUS_UNKNOWN = 32;
/**
* An array of Observer objects to notify
*
* @var array
* @since 12.1
*/
protected $observers = array();
/**
* The state of the observable object
*
* @var mixed
* @since 12.1
*/
protected $state = null;
/**
* A multi dimensional array of [function][] = key for observers
*
* @var array
* @since 12.1
*/
protected $methods = array();
/**
* @var JAuthentication JAuthentication instances container.
* @since 11.3
*/
protected static $instance;
/**
* Constructor
*
* @since 11.1
*/
public function __construct()
{
$isLoaded = JPluginHelper::importPlugin('authentication');
if (!$isLoaded)
{
JLog::add(JText::_('JLIB_USER_ERROR_AUTHENTICATION_LIBRARIES'), JLog::WARNING, 'jerror');
}
}
/**
* Returns the global authentication object, only creating it
* if it doesn't already exist.
*
* @return JAuthentication The global JAuthentication object
*
* @since 11.1
*/
public static function getInstance()
{
if (empty(self::$instance))
{
self::$instance = new JAuthentication;
}
return self::$instance;
}
/**
* Get the state of the JAuthentication object
*
* @return mixed The state of the object.
*
* @since 11.1
*/
public function getState()
{
return $this->state;
}
/**
* Attach an observer object
*
* @param object $observer An observer object to attach
*
* @return void
*
* @since 11.1
*/
public function attach($observer)
{
if (is_array($observer))
{
if (!isset($observer['handler']) || !isset($observer['event']) || !is_callable($observer['handler']))
{
return;
}
// Make sure we haven't already attached this array as an observer
foreach ($this->observers as $check)
{
if (is_array($check) && $check['event'] == $observer['event'] && $check['handler'] == $observer['handler'])
{
return;
}
}
$this->observers[] = $observer;
end($this->observers);
$methods = array($observer['event']);
}
else
{
if (!($observer instanceof JAuthentication))
{
return;
}
// Make sure we haven't already attached this object as an observer
$class = get_class($observer);
foreach ($this->observers as $check)
{
if ($check instanceof $class)
{
return;
}
}
$this->observers[] = $observer;
$methods = array_diff(get_class_methods($observer), get_class_methods('JPlugin'));
}
$key = key($this->observers);
foreach ($methods as $method)
{
$method = strtolower($method);
if (!isset($this->methods[$method]))
{
$this->methods[$method] = array();
}
$this->methods[$method][] = $key;
}
}
/**
* Detach an observer object
*
* @param object $observer An observer object to detach.
*
* @return boolean True if the observer object was detached.
*
* @since 11.1
*/
public function detach($observer)
{
$retval = false;
$key = array_search($observer, $this->observers);
if ($key !== false)
{
unset($this->observers[$key]);
$retval = true;
foreach ($this->methods as &$method)
{
$k = array_search($key, $method);
if ($k !== false)
{
unset($method[$k]);
}
}
}
return $retval;
}
/**
* Finds out if a set of login credentials are valid by asking all observing
* objects to run their respective authentication routines.
*
* @param array $credentials Array holding the user credentials.
* @param array $options Array holding user options.
*
* @return JAuthenticationResponse Response object with status variable filled in for last plugin or first successful plugin.
*
* @see JAuthenticationResponse
* @since 11.1
*/
public function authenticate($credentials, $options = array())
{
// Get plugins
$plugins = JPluginHelper::getPlugin('authentication');
// Create authentication response
$response = new JAuthenticationResponse;
/*
* Loop through the plugins and check of the credentials can be used to authenticate
* the user
*
* Any errors raised in the plugin should be returned via the JAuthenticationResponse
* and handled appropriately.
*/
foreach ($plugins as $plugin)
{
$className = 'plg' . $plugin->type . $plugin->name;
if (class_exists($className))
{
$plugin = new $className($this, (array) $plugin);
}
else
{
// Bail here if the plugin can't be created
JLog::add(JText::sprintf('JLIB_USER_ERROR_AUTHENTICATION_FAILED_LOAD_PLUGIN', $className), JLog::WARNING, 'jerror');
continue;
}
// Try to authenticate
$plugin->onUserAuthenticate($credentials, $options, $response);
// If authentication is successful break out of the loop
if ($response->status === self::STATUS_SUCCESS)
{
if (empty($response->type))
{
$response->type = isset($plugin->_name) ? $plugin->_name : $plugin->name;
}
break;
}
}
if (empty($response->username))
{
$response->username = $credentials['username'];
}
if (empty($response->fullname))
{
$response->fullname = $credentials['username'];
}
if (empty($response->password))
{
$response->password = $credentials['password'];
}
return $response;
}
/**
* Authorises that a particular user should be able to login
*
* @param JAuthenticationResponse $response response including username of the user to authorise
* @param array $options list of options
*
* @return array[JAuthenticationResponse] results of authorisation
*
* @since 11.2
*/
public static function authorise($response, $options = array())
{
// Get plugins in case they haven't been imported already
JPluginHelper::importPlugin('user');
JPluginHelper::importPlugin('authentication');
$dispatcher = JEventDispatcher::getInstance();
$results = $dispatcher->trigger('onUserAuthorisation', array($response, $options));
return $results;
}
}
/**
* Authentication response class, provides an object for storing user and error details
*
* @package Joomla.Platform
* @subpackage User
* @since 11.1
*/
class JAuthenticationResponse
{
/**
* Response status (see status codes)
*
* @var string
* @since 11.1
*/
public $status = JAuthentication::STATUS_FAILURE;
/**
* The type of authentication that was successful
*
* @var string
* @since 11.1
*/
public $type = '';
/**
* The error message
*
* @var string
* @since 11.1
*/
public $error_message = '';
/**
* Any UTF-8 string that the End User wants to use as a username.
*
* @var string
* @since 11.1
*/
public $username = '';
/**
* Any UTF-8 string that the End User wants to use as a password.
*
* @var string
* @since 11.1
*/
public $password = '';
/**
* The email address of the End User as specified in section 3.4.1 of [RFC2822]
*
* @var string
* @since 11.1
*/
public $email = '';
/**
* UTF-8 string free text representation of the End User's full name.
*
* @var string
* @since 11.1
*
*/
public $fullname = '';
/**
* The End User's date of birth as YYYY-MM-DD. Any values whose representation uses
* fewer than the specified number of digits should be zero-padded. The length of this
* value MUST always be 10. If the End User user does not want to reveal any particular
* component of this value, it MUST be set to zero.
*
* For instance, if a End User wants to specify that his date of birth is in 1980, but
* not the month or day, the value returned SHALL be "1980-00-00".
*
* @var string
* @since 11.1
*/
public $birthdate = '';
/**
* The End User's gender, "M" for male, "F" for female.
*
* @var string
* @since 11.1
*/
public $gender = '';
/**
* UTF-8 string free text that SHOULD conform to the End User's country's postal system.
*
* @var string
* @since 11.1
*/
public $postcode = '';
/**
* The End User's country of residence as specified by ISO3166.
*
* @var string
* @since 11.1
*/
public $country = '';
/**
* End User's preferred language as specified by ISO639.
*
* @var string
* @since 11.1
*/
public $language = '';
/**
* ASCII string from TimeZone database
*
* @var string
* @since 11.1
*/
public $timezone = '';
}

View File

@ -0,0 +1,599 @@
<?php
/**
* @package Joomla.Platform
* @subpackage User
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* 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
*
* @package Joomla.Platform
* @subpackage User
* @since 11.1
*/
abstract class JUserHelper
{
/**
* 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 11.1
* @throws RuntimeException
*/
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// 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;
}
/**
* 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 11.1
*/
public static function getUserGroups($userId)
{
// Get the user object.
$user = JUser::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 11.1
*/
public static function removeUserFromGroup($userId, $groupId)
{
// Get the user object.
$user = JUser::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 11.1
*/
public static function setUserGroups($userId, $groups)
{
// Get the user object.
$user = JUser::getInstance((int) $userId);
// Set the group ids.
JArrayHelper::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 11.1
*/
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();
JPluginHelper::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 11.1
*/
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('0000-00-00 00:00:00'));
$db->setQuery($query);
$id = (int) $db->loadResult();
// Is it a valid user to activate?
if ($id)
{
$user = JUser::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 11.1
*/
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();
}
/**
* Formats a password using the current encryption.
*
* @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 $show_encrypt Some password systems prepend the kind of
* encryption to the crypted password ({SHA},
* etc). Defaults to false.
*
* @return string The encrypted password.
*
* @since 11.1
*/
public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
{
// Get the salt to use.
$salt = self::getSalt($encryption, $salt, $plaintext);
// Encrypt the password.
switch ($encryption)
{
case 'plain':
return $plaintext;
case 'sha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
return ($show_encrypt) ? '{SHA}' . $encrypted : $encrypted;
case 'crypt':
case 'crypt-des':
case 'crypt-md5':
case 'crypt-blowfish':
return ($show_encrypt ? '{crypt}' : '') . crypt($plaintext, $salt);
case 'md5-base64':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
case 'ssha':
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt) . $salt);
return ($show_encrypt) ? '{SSHA}' . $encrypted : $encrypted;
case 'smd5':
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt) . $salt);
return ($show_encrypt) ? '{SMD5}' . $encrypted : $encrypted;
case 'aprmd5':
$length = strlen($plaintext);
$context = $plaintext . '$apr1$' . $salt;
$binary = self::_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 = self::_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 = self::_bin(md5($new));
}
$p = array();
for ($i = 0; $i < 5; $i++)
{
$k = $i + 6;
$j = $i + 12;
if ($j == 16)
{
$j = 5;
}
$p[] = self::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
}
return '$apr1$' . $salt . '$' . implode('', $p) . self::_toAPRMD5(ord($binary[11]), 3);
case 'md5-hex':
default:
$encrypted = ($salt) ? md5($plaintext . $salt) : md5($plaintext);
return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
}
}
/**
* Returns a salt for the appropriate kind of password encryption.
* 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 11.1
*/
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 'crypt-md5':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
}
else
{
return '$1$' . substr(md5(mt_rand()), 0, 8) . '$';
}
break;
case 'crypt-blowfish':
if ($seed)
{
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
}
else
{
return '$2$' . substr(md5(mt_rand()), 0, 12) . '$';
}
break;
case 'ssha':
if ($seed)
{
return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
}
else
{
return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 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(mt_rand())), 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{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 11.1
*/
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 11.1
*/
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 11.1
*/
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;
}
}

View File

@ -0,0 +1 @@
<!DOCTYPE html><title></title>

View File

@ -0,0 +1,842 @@
<?php
/**
* @package Joomla.Platform
* @subpackage User
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* User class. Handles all application interaction with a user
*
* @package Joomla.Platform
* @subpackage User
* @since 11.1
*/
class JUser extends JObject
{
/**
* A cached switch for if this user has root access rights.
*
* @var boolean
* @since 11.1
*/
protected $isRoot = null;
/**
* Unique id
*
* @var integer
* @since 11.1
*/
public $id = null;
/**
* The users real name (or nickname)
* @var string
* @since 11.1
*/
public $name = null;
/**
* The login name
*
* @var string
* @since 11.1
*/
public $username = null;
/**
* The email
*
* @var string
* @since 11.1
*/
public $email = null;
/**
* MD5 encrypted password
*
* @var string
* @since 11.1
*/
public $password = null;
/**
* Clear password, only available when a new password is set for a user
*
* @var string
* @since 11.1
*/
public $password_clear = '';
/**
* Block status
*
* @var integer
* @since 11.1
*/
public $block = null;
/**
* Should this user receive system email
*
* @var integer
* @since 11.1
*/
public $sendEmail = null;
/**
* Date the user was registered
*
* @var datetime
* @since 11.1
*/
public $registerDate = null;
/**
* Date of last visit
*
* @var datetime
* @since 11.1
*/
public $lastvisitDate = null;
/**
* Activation hash
*
* @var string
* @since 11.1
*/
public $activation = null;
/**
* User parameters
*
* @var JRegistry
* @since 11.1
*/
public $params = null;
/**
* Associative array of user names => group ids
*
* @var array
* @since 11.1
*/
public $groups = array();
/**
* Guest status
*
* @var boolean
* @since 11.1
*/
public $guest = null;
/**
* Last Reset Time
*
* @var string
* @since 12.2
*/
public $lastResetTime = null;
/**
* Count since last Reset Time
*
* @var int
* @since 12.2
*/
public $resetCount = null;
/**
* User parameters
* @var JRegistry
* @since 11.1
*/
protected $_params = null;
/**
* Authorised access groups
*
* @var array
* @since 11.1
*/
protected $_authGroups = null;
/**
* Authorised access levels
*
* @var array
* @since 11.1
*/
protected $_authLevels = null;
/**
* Authorised access actions
*
* @var array
* @since 11.1
*/
protected $_authActions = null;
/**
* Error message
*
* @var string
* @since 11.1
*/
protected $_errorMsg = null;
/**
* @var array JUser instances container.
* @since 11.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).
*
* @since 11.1
*/
public function __construct($identifier = 0)
{
// Create the user parameters object
$this->_params = new JRegistry;
// 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 user to load - Can be an integer or string - If string, it is converted to ID automatically.
*
* @return JUser The User object.
*
* @since 11.1
*/
public static function getInstance($identifier = 0)
{
// Find the user id
if (!is_numeric($identifier))
{
if (!$id = JUserHelper::getUserId($identifier))
{
JLog::add(JText::sprintf('JLIB_USER_ERROR_ID_NOT_EXISTS', $identifier), JLog::WARNING, 'jerror');
$retval = false;
return $retval;
}
}
else
{
$id = $identifier;
}
// If the $id is zero, just return an empty JUser.
// Note: don't cache this user because it'll have a new ID on save!
if ($id === 0)
{
return new JUser;
}
// Check if the user ID is already cached.
if (empty(self::$instances[$id]))
{
$user = new JUser($id);
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 11.1
*/
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 11.1
*/
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 11.1
*/
public function defParam($key, $value)
{
return $this->_params->def($key, $value);
}
/**
* Method to check JUser 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 11.1
*/
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.
$config = JFactory::getConfig();
$rootUser = $config->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;
}
else
{
// Get all groups against which the user is mapped.
$identities = $this->getAuthorisedGroups();
array_unshift($identities, $this->id * -1);
if (JAccess::getAssetRules(1)->allow('core.admin', $identities))
{
$this->isRoot = true;
return true;
}
}
}
return $this->isRoot ? true : JAccess::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 11.1
*/
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();
$query = $db->getQuery(true)
->select('c.id AS id, a.name AS asset_name')
->from('#__categories AS c')
->join('INNER', '#__assets AS a ON c.asset_id = a.id')
->where('c.extension = ' . $db->quote($component))
->where('c.published = 1');
$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 11.1
*/
public function getAuthorisedViewLevels()
{
if ($this->_authLevels === null)
{
$this->_authLevels = array();
}
if (empty($this->_authLevels))
{
$this->_authLevels = JAccess::getAuthorisedViewLevels($this->id);
}
return $this->_authLevels;
}
/**
* Gets an array of the authorised user groups
*
* @return array
*
* @since 11.1
*/
public function getAuthorisedGroups()
{
if ($this->_authGroups === null)
{
$this->_authGroups = array();
}
if (empty($this->_authGroups))
{
$this->_authGroups = JAccess::getGroupsByUser($this->id);
}
return $this->_authGroups;
}
/**
* 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 11.1
*/
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 11.1
* @deprecated 12.3 (Platform) & 4.0 (CMS) - Instead use JUser::getParam()
*/
public function getParameters()
{
// @codeCoverageIgnoreStart
JLog::add('JUser::getParameters() is deprecated. JUser::getParam().', JLog::WARNING, 'deprecated');
return $this->_params;
// @codeCoverageIgnoreEnd
}
/**
* Method to get the user parameters
*
* @param object $params The user parameters object
*
* @return void
*
* @since 11.1
*/
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
*
* @since 11.1
*/
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 JTable::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 11.1
*/
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'] = JUserHelper::genRandomPassword();
$array['password2'] = $array['password'];
}
// TODO: Backend controller checks the password, frontend doesn't but should.
// Hence this code is required:
if (isset($array['password2']) && $array['password'] != $array['password2'])
{
$this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH'));
return false;
}
$this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string');
$salt = JUserHelper::genRandomPassword(32);
$crypt = JUserHelper::getCryptedPassword($array['password'], $salt);
$array['password'] = $crypt . ':' . $salt;
// Set the registration timestamp
$this->set('registerDate', JFactory::getDate()->toSql());
// Check that username is not greater than 150 characters
$username = $this->get('username');
if (strlen($username) > 150)
{
$username = substr($username, 0, 150);
$this->set('username', $username);
}
// Check that password is not greater than 100 characters
$password = $this->get('password');
if (strlen($password) > 100)
{
$password = substr($password, 0, 100);
$this->set('password', $password);
}
}
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 = JArrayHelper::getValue($array, 'password', '', 'string');
$salt = JUserHelper::genRandomPassword(32);
$crypt = JUserHelper::getCryptedPassword($array['password'], $salt);
$array['password'] = $crypt . ':' . $salt;
}
else
{
$array['password'] = $this->password;
}
}
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 JUser 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 11.1
* @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 JUser($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');
// We are only worried about edits to this account if I am not a Super Admin.
if ($iAmSuperAdmin != true)
{
if ($isNew)
{
// Check if the new user is being put into a Super Admin group.
foreach ($this->groups as $groupId)
{
if (JAccess::checkGroup($groupId, 'core.admin'))
{
throw new RuntimeException('User not Super Administrator');
}
}
}
else
{
// I am not a Super Admin, and this one is, so fail.
if (JAccess::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 (JAccess::checkGroup($groupId, 'core.admin'))
{
throw new RuntimeException('User not Super Administrator');
}
}
}
}
}
// Fire the onUserBeforeSave event.
JPluginHelper::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 JUser object in case we created a new user.
if (empty($this->id))
{
$this->id = $table->get('id');
}
if ($my->id == $table->id)
{
$registry = new JRegistry;
$registry->loadString($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 JUser object from the database
*
* @return boolean True on success
*
* @since 11.1
*/
public function delete()
{
JPluginHelper::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 JUser object by user id number
*
* @param mixed $id The user id of the user to load
*
* @return boolean True on success
*
* @since 11.1
*/
public function load($id)
{
// Create the user table object
$table = $this->getTable();
// Load the JUserModel 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.
*/
$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;
}
}