Issue #2026347 by Berdir: Adding methods to UserInterface/AccountInterface.

8.0.x
Alex Pott 2013-07-09 14:46:44 +01:00
parent 79e0e8da48
commit 45a9e859d6
26 changed files with 745 additions and 317 deletions

View File

@ -2772,6 +2772,13 @@ function template_preprocess_page(&$variables) {
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
$variables['theme_hook_suggestions'] = $suggestions;
}
// Prepare render array for messages. drupal_get_messages() is called later,
// when this variable is rendered in a theme function or template file.
$variables['messages'] = array(
'#theme' => 'status_messages',
'#access' => $variables['show_messages'],
);
}
/**
@ -2797,11 +2804,6 @@ function template_process_page(&$variables) {
$variables['title'] = drupal_get_title();
}
// Generate messages last in order to capture as many as possible for the
// current page.
if (!isset($variables['messages'])) {
$variables['messages'] = $variables['show_messages'] ? array('#theme' => 'status_messages') : '';
}
}
/**

View File

@ -55,4 +55,63 @@ interface AccountInterface {
*/
public function getSessionData();
/**
* Returns TRUE if the account is authenticated.
*
* @return bool
* TRUE if the account is authenticated.
*/
public function isAuthenticated();
/**
* Returns TRUE if the account is anonymous.
*
* @return bool
* TRUE if the account is anonymous.
*/
public function isAnonymous();
/**
* Returns the preferred language code of the account.
*
* @param string $default
* (optional) Default language code to return if the account
* has no valid language, defaults to the site default language.
*
* @return string
* The language code that is preferred by the account.
*/
public function getPreferredLangcode($default = NULL);
/**
* Returns the preferred administrative language code of the account.
*
* Defines which language is used on administrative pages.
*
* @param string $default
* (optional) Default language code to return if the account
* has no valid language, defaults to the site default language.
*
* @return string
* The language code that is preferred by the account.
*/
public function getPreferredAdminLangcode($default = NULL);
/**
* Returns the username of this account.
*
* By default, the passed-in object's 'name' property is used if it exists, or
* else, the site-defined value for the 'anonymous' variable. However, a module
* may override this by implementing
* hook_user_format_name_alter(&$name, $account).
*
* @see hook_user_format_name_alter()
*
* @return
* An unsanitized string with the username to display. The code receiving
* this result must ensure that check_plain() is called on it before it is
* printed to the page.
*/
public function getUsername();
}

View File

@ -65,6 +65,27 @@ class UserSession implements AccountInterface {
*/
public $timestamp;
/**
* The name of this account.
*
* @var string
*/
public $name;
/**
* The preferred language code of the account.
*
* @var string
*/
protected $preferred_langcode;
/**
* The preferred administrative language code of the account.
*
* @var string
*/
protected $preferred_admin_langcode;
/**
* Constructs a new user session.
*
@ -112,4 +133,53 @@ class UserSession implements AccountInterface {
return $this->sid;
}
/**
* {@inheritdoc}
*/
public function isAuthenticated() {
return $this->uid > 0;
}
/**
* {@inheritdoc}
*/
public function isAnonymous() {
return $this->uid == 0;
}
/**
* {@inheritdoc}
*/
function getPreferredLangcode($default = NULL) {
$language_list = language_list();
if (!empty($this->preferred_langcode) && isset($language_list[$this->preferred_langcode])) {
return $language_list[$this->preferred_langcode]->id;
}
else {
return $default ? $default : language_default()->id;
}
}
/**
* {@inheritdoc}
*/
function getPreferredAdminLangcode($default = NULL) {
$language_list = language_list();
if (!empty($this->preferred_admin_langcode) && isset($language_list[$this->preferred_admin_langcode])) {
return $language_list[$this->preferred_admin_langcode]->id;
}
else {
return $default ? $default : language_default()->id;
}
}
/**
* {@inheritdoc}
*/
public function getUsername() {
$name = $this->name ?: \Drupal::config('user.settings')->get('anonymous');
\Drupal::moduleHandler()->alter('user_format_name', $name, $this);
return $name;
}
}

View File

@ -86,7 +86,7 @@ class EmailAction extends ConfigurableActionBase {
$recipient_accounts = $this->storageController->loadByProperties(array('mail' => $recipient));
$recipient_account = reset($recipient_accounts);
if ($recipient_account) {
$langcode = user_preferred_langcode($recipient_account);
$langcode = $recipient_account->getPreferredLangcode();
}
else {
$langcode = language_default()->id;

View File

@ -164,7 +164,7 @@ class MessageFormController extends EntityFormControllerNG {
elseif ($recipient = $message->getPersonalRecipient()) {
// Send to the user in the user's preferred language.
$to = $recipient->mail->value;
$recipient_langcode = user_preferred_langcode($recipient);
$recipient_langcode = $recipient->getPreferredLangcode();
$params['recipient'] = $recipient->getBCEntity();
}
else {

View File

@ -99,7 +99,7 @@ function dblog_event($id) {
}
$username = array(
'#theme' => 'username',
'#account' => $dblog,
'#account' => user_load($dblog->uid),
);
$rows = array(
array(

View File

@ -124,7 +124,6 @@ class DbLogController implements ControllerInterface {
$query = $this->database->select('watchdog', 'w')
->extend('Drupal\Core\Database\Query\PagerSelectExtender')
->extend('Drupal\Core\Database\Query\TableSortExtender');
$query->leftJoin('users', 'u', 'w.uid = u.uid');
$query->fields('w', array(
'wid',
'uid',
@ -134,8 +133,7 @@ class DbLogController implements ControllerInterface {
'message',
'variables',
'link',
));
$query->addField('u', 'name');
));
if (!empty($filter['where'])) {
$query->where($filter['where'], $filter['args']);
@ -164,7 +162,7 @@ class DbLogController implements ControllerInterface {
}
$username = array(
'#theme' => 'username',
'#account' => $dblog,
'#account' => user_load($dblog->uid),
);
$rows[] = array(
'data' => array(

View File

@ -1211,7 +1211,7 @@ function template_preprocess_forum_icon(&$variables) {
* - topic: The topic object.
*/
function template_preprocess_forum_submitted(&$variables) {
$variables['author'] = isset($variables['topic']->uid) ? theme('username', array('account' => $variables['topic'])) : '';
$variables['author'] = isset($variables['topic']->uid) ? theme('username', array('account' => user_load($variables['topic']->uid))) : '';
$variables['time'] = isset($variables['topic']->created) ? format_interval(REQUEST_TIME - $variables['topic']->created) : '';
}

View File

@ -463,8 +463,9 @@ function language_get_default_langcode($entity_type, $bundle) {
case 'authors_default':
global $user;
if (!empty($user->preferred_langcode)) {
$default_value = $user->preferred_langcode;
$language_code = $user->getPreferredLangcode();
if (!empty($language_code)) {
$default_value = $language_code;
}
else {
$default_value = $language_interface->id;

View File

@ -191,8 +191,12 @@ function language_from_user($languages) {
// User preference (only for authenticated users).
global $user;
if ($user->uid && !empty($user->preferred_langcode) && isset($languages[$user->preferred_langcode])) {
return $user->preferred_langcode;
if ($user->id()) {
$langcode = $user->getPreferredLangcode();
$default_langcode = language_default()->id;
if (!empty($langcode) && $langcode != $default_langcode && isset($languages[$langcode])) {
return $langcode;
}
}
// No language preference from the user.
@ -216,9 +220,13 @@ function language_from_user_admin(array $languages, Request $request = NULL) {
// User preference (only for authenticated users).
global $user;
$request_path = $request ? urldecode(trim($request->getPathInfo(), '/')) : _current_path();
if ($user->uid && !empty($user->preferred_admin_langcode) && isset($languages[$user->preferred_admin_langcode]) && path_is_admin($request_path)) {
return $user->preferred_admin_langcode;
if ($user->id()) {
$request_path = $request ? urldecode(trim($request->getPathInfo(), '/')) : _current_path();
$langcode = $user->getPreferredAdminLangcode();
$default_langcode = language_default()->id;
if (!empty($langcode) && $langcode != $default_langcode && isset($languages[$langcode]) && path_is_admin($request_path)) {
return $langcode;
}
}
// No language preference from the user or not on an admin path.
@ -241,7 +249,7 @@ function language_from_session($languages) {
// an authenticated user.
if (isset($_GET[$param]) && isset($languages[$langcode = $_GET[$param]])) {
global $user;
if ($user->uid) {
if ($user->id()) {
$_SESSION[$param] = $langcode;
}
return $langcode;
@ -479,7 +487,7 @@ function language_url_rewrite_session(&$path, &$options) {
// request processing.
if (!isset($query_rewrite)) {
global $user;
if (!$user->uid) {
if (!$user->id()) {
$languages = language_list();
$query_param = check_plain(config('language.negotiation')->get('session.parameter'));
$query_value = isset($_GET[$query_param]) ? check_plain($_GET[$query_param]) : NULL;

View File

@ -70,7 +70,7 @@ class LocaleConfigSubscriber implements EventSubscriberInterface {
$context->set('locale.language', $language);
}
elseif ($account = $context->get('user.account')) {
$context->set('locale.language', language_load(user_preferred_langcode($account)));
$context->set('locale.language', language_load($account->getPreferredLangcode()));
}
elseif ($language = $this->languageManager->getLanguage(Language::TYPE_INTERFACE)) {
$context->set('locale.language', $language);

View File

@ -276,7 +276,7 @@ function node_admin_nodes() {
);
$form['nodes'][$node->nid]['author'] = array(
'#theme' => 'username',
'#account' => $node,
'#account' => user_load($node->uid),
);
$form['nodes'][$node->nid]['status'] = array(
'#markup' => $node->status ? t('published') : t('not published'),

View File

@ -693,7 +693,7 @@ function template_preprocess_node(&$variables) {
// http://drupal.org/node/1941286.
$username = array(
'#theme' => 'username',
'#account' => $node,
'#account' => user_load($node->uid),
'#link_options' => array('attributes' => array('rel' => 'author')),
);
$variables['name'] = drupal_render($username);
@ -951,7 +951,7 @@ function node_search_execute($keys = NULL, $conditions = NULL) {
$uri = $node->uri();
$username = array(
'#theme' => 'username',
'#account' => $node,
'#account' => user_load($node->uid),
);
$results[] = array(
'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE, 'language' => $language))),

View File

@ -253,7 +253,7 @@ function node_revision_overview($node) {
if ($revision->current_vid > 0) {
$username = array(
'#theme' => 'username',
'#account' => $revision,
'#account' => user_load($revision->uid),
);
$row[] = array('data' => t('!date by !username', array('!date' => l(format_date($revision->revision_timestamp, 'short'), "node/$node->nid"), '!username' => drupal_render($username)))
. (($revision->log != '') ? '<p class="revision-log">' . filter_xss($revision->log) . '</p>' : ''),
@ -263,7 +263,7 @@ function node_revision_overview($node) {
else {
$username = array(
'#theme' => 'username',
'#account' => $revision,
'#account' => user_load($revision->uid),
);
$row[] = t('!date by !username', array('!date' => l(format_date($revision->revision_timestamp, 'short'), "node/$node->nid/revisions/$revision->vid/view"), '!username' => drupal_render($username)))
. (($revision->log != '') ? '<p class="revision-log">' . filter_xss($revision->log) . '</p>' : '');

View File

@ -50,7 +50,7 @@ class CSRFAccessCheck implements AccessCheckInterface {
// 2. the user was successfully authenticated and
// 3. the request comes with a session cookie.
if (!in_array($method, array('GET', 'HEAD', 'OPTIONS', 'TRACE'))
&& user_is_logged_in()
&& $GLOBALS['user']->isAuthenticated()
&& $cookie
) {
$csrf_token = $request->headers->get('X-CSRF-Token');

View File

@ -11,6 +11,7 @@ use Drupal\Component\Utility\Crypt;
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Session\UserSession;
use Drupal\simpletest\WebTestBase;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request;
@ -148,15 +149,12 @@ abstract class UpgradePathTestBase extends WebTestBase {
// Ensure that the session is not written to the new environment and replace
// the global $user session with uid 1 from the new test site.
drupal_save_session(FALSE);
// Login as uid 1.
$user = db_query('SELECT * FROM {users} WHERE uid = :uid', array(':uid' => 1))->fetchObject();
// Load roles for the user object.
$roles = array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID);
$result = db_query('SELECT rid, uid FROM {users_roles} WHERE uid = :uid', array(':uid' => 1));
foreach ($result as $record) {
$roles[$record->rid] = $record->rid;
}
$user->roles = $roles;
// Load values for uid 1.
$values = db_query('SELECT * FROM {users} WHERE uid = :uid', array(':uid' => 1))->fetchAssoc();
// Load rolest.
$values['roles'] = array_merge(array(DRUPAL_AUTHENTICATED_RID), db_query('SELECT rid FROM {users_roles} WHERE uid = :uid', array(':uid' => 1))->fetchCol());
// Create a new user session object.
$user = new UserSession($values);
// Generate and set a D8-compatible session cookie.
$this->prepareD8Session();

View File

@ -83,7 +83,7 @@ function tracker_page($account = NULL, $set_title = FALSE) {
'type' => check_plain(node_get_type_label($node)),
// Do not use $node->label(), because $node comes from the database.
'title' => array('data' => l($node->title, 'node/' . $node->nid) . ' ' . drupal_render($mark_build)),
'author' => array('data' => array('#theme' => 'username', '#account' => $node)),
'author' => array('data' => array('#theme' => 'username', '#account' => user_load($node->uid))),
'replies' => array('class' => array('replies'), 'data' => $comments),
'last updated' => array('data' => t('!time ago', array('!time' => format_interval(REQUEST_TIME - $node->last_activity)))),
);

View File

@ -355,7 +355,7 @@ function _update_cron_notify() {
$default_langcode = language_default()->id;
foreach ($notify_list as $target) {
if ($target_user = user_load_by_mail($target)) {
$target_langcode = user_preferred_langcode($target_user);
$target_langcode = $target_user->getPreferredLangcode();
}
else {
$target_langcode = $default_langcode;

View File

@ -176,9 +176,9 @@ abstract class AccountFormController extends EntityFormController {
'#format' => isset($account->signature_format) ? $account->signature_format : NULL,
);
$user_preferred_langcode = $register ? $language_interface->id : user_preferred_langcode($account);
$user_preferred_langcode = $register ? $language_interface->id : $account->getPreferredLangcode();
$user_preferred_admin_langcode = $register ? $language_interface->id : user_preferred_langcode($account, 'admin');
$user_preferred_admin_langcode = $register ? $language_interface->id : $account->getPreferredAdminLangcode();
// Is default the interface language?
include_once DRUPAL_ROOT . '/core/includes/language.inc';

View File

@ -29,7 +29,7 @@ class MaintenanceModeSubscriber implements EventSubscriberInterface {
$path = $request->attributes->get('system_path');
if ($site_status == MENU_SITE_OFFLINE) {
// If the site is offline, log out unprivileged users.
if (user_is_logged_in() && !user_access('access site in maintenance mode')) {
if ($GLOBALS['user']->isAuthenticated() && !user_access('access site in maintenance mode')) {
user_logout();
// Redirect to homepage.
$event->setResponse(new RedirectResponse(url('<front>', array('absolute' => TRUE))));
@ -56,7 +56,7 @@ class MaintenanceModeSubscriber implements EventSubscriberInterface {
}
}
}
if (user_is_logged_in()) {
if ($GLOBALS['user']->isAuthenticated()) {
if ($path == 'user/login') {
// If user is logged in, redirect to 'user' instead of giving 403.
$event->setResponse(new RedirectResponse(url('user', array('absolute' => TRUE))));
@ -64,7 +64,7 @@ class MaintenanceModeSubscriber implements EventSubscriberInterface {
}
if ($path == 'user/register') {
// Authenticated user should be redirected to user edit page.
$event->setResponse(new RedirectResponse(url('user/' . $GLOBALS['user']->uid . '/edit', array('absolute' => TRUE))));
$event->setResponse(new RedirectResponse(url('user/' . $GLOBALS['user']->id() . '/edit', array('absolute' => TRUE))));
return;
}
}

View File

@ -66,12 +66,12 @@ class UserNewBlock extends BlockBase {
*/
public function build() {
// Retrieve a list of new users who have accessed the site successfully.
$items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, $this->configuration['whois_new_count'])->fetchAll();
$uids = db_query_range('SELECT uid FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, $this->configuration['whois_new_count'])->fetchCol();
$build = array(
'#theme' => 'item_list__user__new',
'#items' => array(),
);
foreach ($items as $account) {
foreach (user_load_multiple($uids) as $account) {
$username = array(
'#theme' => 'username',
'#account' => $account,

View File

@ -51,134 +51,6 @@ use Drupal\Core\Language\Language;
*/
class User extends EntityNG implements UserInterface {
/**
* The user ID.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $uid;
/**
* The user UUID.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $uuid;
/**
* The unique user name.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $name;
/**
* The user's password (hashed).
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $pass;
/**
* The user's email address.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $mail;
/**
* The user's default theme.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $theme;
/**
* The user's signature.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $signature;
/**
* The user's signature format.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $signature_format;
/**
* The timestamp when the user was created.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $created;
/**
* The timestamp when the user last accessed the site. A value of 0 means the
* user has never accessed the site.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $access;
/**
* The timestamp when the user last logged in. A value of 0 means the user has
* never logged in.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $login;
/**
* Whether the user is active (1) or blocked (0).
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $status;
/**
* The user's timezone.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $timezone;
/**
* The user's langcode.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $langcode;
/**
* The user's preferred langcode for receiving emails and viewing the site.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $preferred_langcode;
/**
* The user's preferred langcode for viewing administration pages.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $preferred_admin_langcode;
/**
* The email address used for initial account creation.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $init;
/**
* The user's roles.
*
* @var \Drupal\Core\Entity\Field\FieldInterface
*/
public $roles;
/**
* {@inheritdoc}
*/
@ -186,30 +58,6 @@ class User extends EntityNG implements UserInterface {
return $this->get('uid')->value;
}
/**
* {@inheritdoc}
*/
protected function init() {
parent::init();
unset($this->access);
unset($this->created);
unset($this->init);
unset($this->login);
unset($this->mail);
unset($this->name);
unset($this->pass);
unset($this->preferred_admin_langcode);
unset($this->preferred_langcode);
unset($this->roles);
unset($this->signature);
unset($this->signature_format);
unset($this->status);
unset($this->theme);
unset($this->timezone);
unset($this->uid);
unset($this->uuid);
}
/**
* {@inheritdoc}
*/
@ -300,6 +148,7 @@ class User extends EntityNG implements UserInterface {
$storage_controller->deleteUserRoles($uids);
}
/**
* {@inheritdoc}
*/
@ -336,7 +185,6 @@ class User extends EntityNG implements UserInterface {
public function getSessionData() {
return array();
}
/**
* {@inheritdoc}
*/
@ -367,4 +215,182 @@ class User extends EntityNG implements UserInterface {
$this->set('roles', array_diff($this->getRoles(), array($rid)));
}
/**
* {@inheritdoc}
*/
public function getPassword() {
return $this->get('pass')->value;
}
/**
* {@inheritdoc}
*/
public function setPassword($password) {
$this->get('pass')->value = $password;
}
/**
* {@inheritdoc}
*/
public function getEmail() {
return $this->get('mail')->value;
}
/**
* {@inheritdoc}
*/
public function setEmail($mail) {
$this->get('mail')->value = $mail;
}
/**
* {@inheritdoc}
*/
public function getDefaultTheme() {
return $this->get('theme')->value;
}
/**
* {@inheritdoc}
*/
public function getSignature() {
return $this->get('signature')->value;
}
/**
* {@inheritdoc}
*/
public function getSignatureFormat() {
return $this->get('signature_format')->value;
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function getLastAccessedTime() {
return $this->get('access')->value;
}
/**
* {@inheritdoc}
*/
public function setLastAccessTime($timestamp) {
$this->get('access')->value = $timestamp;
}
/**
* {@inheritdoc}
*/
public function getLastLoginTime() {
return $this->get('login')->value;
}
/**
* {@inheritdoc}
*/
public function setLastLoginTime($timestamp) {
$this->get('login')->value = $timestamp;
}
/**
* {@inheritdoc}
*/
public function isActive() {
return $this->get('status')->value == 1;
}
/**
* {@inheritdoc}
*/
public function isBlocked() {
return $this->get('status')->value == 0;
}
/**
* {@inheritdoc}
*/
public function activate() {
$this->get('status')->value = 1;
return $this;
}
/**
* {@inheritdoc}
*/
public function block() {
$this->get('status')->value = 0;
return $this;
}
/**
* {@inheritdoc}
*/
public function getTimeZone() {
return $this->get('timezone')->value;
}
/**
* {@inheritdoc}
*/
function getPreferredLangcode($default = NULL) {
$language_list = language_list();
$preferred_langcode = $this->get('preferred_langcode')->value;
if (!empty($preferred_langcode) && isset($language_list[$preferred_langcode])) {
return $language_list[$preferred_langcode]->id;
}
else {
return $default ? $default : language_default()->id;
}
}
/**
* {@inheritdoc}
*/
function getPreferredAdminLangcode($default = NULL) {
$language_list = language_list();
$preferred_langcode = $this->get('preferred_admin_langcode')->value;
if (!empty($preferred_langcode) && isset($language_list[$preferred_langcode])) {
return $language_list[$preferred_langcode]->id;
}
else {
return $default ? $default : language_default()->id;
}
}
/**
* {@inheritdoc}
*/
public function getInitialEmail() {
return $this->get('init')->value;
}
/**
* {@inheritdoc}
*/
public function isAuthenticated() {
return $this->id() > 0;
}
/**
* {@inheritdoc}
*/
public function isAnonymous() {
return $this->id() == 0;
}
/**
* {@inheritdoc}
*/
public function getUsername() {
$name = $this->get('name')->value ?: \Drupal::config('user.settings')->get('anonymous');
\Drupal::moduleHandler()->alter('user_format_name', $name, $this);
return $name;
}
}

View File

@ -124,7 +124,7 @@ class User extends ArgumentValidatorPluginBase {
}
else {
if ($type == 'name' || $type == 'either') {
$name = !empty($GLOBALS['user']->name) ? $GLOBALS['user']->name : config('user.settings')->get('anonymous');
$name = $GLOBALS['user']->getUserName() ?: config('user.settings')->get('anonymous');
if ($argument == $name) {
$account = clone $GLOBALS['user'];
}
@ -138,26 +138,23 @@ class User extends ArgumentValidatorPluginBase {
}
if (!isset($account)) {
$account = $this->database->select('users', 'u')
->fields('u', array('uid', 'name'))
$uid = $this->database->select('users', 'u')
->fields('u', array('uid'))
->condition($condition, $argument)
->execute()
->fetchObject();
}
if (empty($account)) {
// User not found.
return FALSE;
->fetchField();
if ($uid === FALSE) {
// User not found.
return FALSE;
}
}
$account = user_load($uid);
// See if we're filtering users based on roles.
if (!empty($this->options['restrict_roles']) && !empty($this->options['roles'])) {
$roles = $this->options['roles'];
$account->roles = array();
$account->roles[] = $account->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
foreach ($account->getRoles() as $rid) {
$account->roles[] = $rid;
}
if (!(bool) array_intersect($account->roles, $roles)) {
if (!(bool) array_intersect($account->getRoles(), $roles)) {
return FALSE;
}
}
@ -174,7 +171,7 @@ class User extends ArgumentValidatorPluginBase {
if ($this->options['type'] == 'name') {
$users = user_load_multiple($args);
foreach ($users as $uid => $account) {
$args[$uids_arg_keys[$uid]] = $account->name;
$args[$uids_arg_keys[$uid]] = $account->label();
}
}
}

View File

@ -14,6 +14,13 @@ use Drupal\Core\Entity\EntityBCDecorator;
*/
class UserBCDecorator extends EntityBCDecorator implements UserInterface {
/**
* The decorated user entity.
*
* @var \Drupal\user\UserInterface
*/
protected $decorated;
/**
* {@inheritdoc}
*/
@ -76,4 +83,166 @@ class UserBCDecorator extends EntityBCDecorator implements UserInterface {
$this->decorated->removeRole($rid);
}
/**
* {@inheritdoc}
*/
public function getPassword() {
return $this->decorated->getPassword();
}
/**
* {@inheritdoc}
*/
public function setPassword($password) {
$this->decorated->setPassword($password);
}
/**
* {@inheritdoc}
*/
public function getEmail() {
return $this->decorated->getEmail();
}
/**
* {@inheritdoc}
*/
public function setEmail($mail) {
$this->decorated->setEmail($mail);
}
/**
* {@inheritdoc}
*/
public function getDefaultTheme() {
return $this->decorated->getDefaultTheme();
}
/**
* {@inheritdoc}
*/
public function getSignature() {
return $this->decorated->getDefaultTheme();
}
/**
* {@inheritdoc}
*/
public function getSignatureFormat() {
return $this->decorated->getSignatureFormat();
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
return $this->decorated->getCreatedTime();
}
/**
* {@inheritdoc}
*/
public function getLastAccessedTime() {
return $this->decorated->getLastAccessedTime();
}
/**
* {@inheritdoc}
*/
public function setLastAccessTime($timestamp) {
$this->decorated->setLastAccessTime($timestamp);
}
/**
* {@inheritdoc}
*/
public function getLastLoginTime() {
return $this->decorated->getLastLoginTime();
}
/**
* {@inheritdoc}
*/
public function setLastLoginTime($timestamp) {
$this->decorated->setLastLoginTime($timestamp);
}
/**
* {@inheritdoc}
*/
public function isActive() {
$this->decorated->isActive();
}
/**
* {@inheritdoc}
*/
public function isBlocked() {
return $this->decorated->isBlocked();
}
/**
* {@inheritdoc}
*/
public function activate() {
return $this->decorated->activate();
}
/**
* {@inheritdoc}
*/
public function block() {
return $this->decorated->block();
}
/**
* {@inheritdoc}
*/
public function getTimeZone() {
return $this->decorated->getTimeZone();
}
/**
* {@inheritdoc}
*/
public function getPreferredLangcode($default = NULL) {
return $this->decorated->getPreferredLangcode($default);
}
/**
* {@inheritdoc}
*/
public function getPreferredAdminLangcode($default = NULL) {
return $this->decorated->getPreferredAdminLangcode($default);
}
/**
* {@inheritdoc}
*/
public function getInitialEmail() {
return $this->decorated->getInitialEmail();
}
/**
* {@inheritdoc}
*/
public function isAuthenticated() {
return $this->decorated->id() > 0;
}
/**
* {@inheritdoc}
*/
public function isAnonymous() {
return $this->decorated->id() == 0;
}
/**
* {@inheritdoc}
*/
public function getUsername() {
return $this->decorated->getUsername();
}
}

View File

@ -50,4 +50,152 @@ interface UserInterface extends EntityInterface, AccountInterface {
*/
public function removeRole($rid);
/**
* Returns the hashed password.
*
* @return string
* The hashed password.
*/
public function getPassword();
/**
* Sets the user password.
*
* @param string $password
* The new unhashed password.
*/
public function setPassword($password);
/**
* Returns the e-mail address of the user.
*
* @return string
* The e-mail address.
*/
public function getEmail();
/**
* Sets the e-mail address of the user.
*
* @param string $mail
* The new e-mail address of the user.
*/
public function setEmail($mail);
/**
* Returns the default theme of the user.
*
* @return string
* Name of the theme.
*/
public function getDefaultTheme();
/**
* Returns the user signature.
*
* @todo: Convert this to a configurable field.
*
* @return string
* The signature text.
*/
public function getSignature();
/**
* Returns the signature format.
*
* @return string
* Name of the filter format.
*/
public function getSignatureFormat();
/**
* Returns the creation time of the user as a UNIX timestamp.
*
* @return int
* Timestamp of the creation date.
*/
public function getCreatedTime();
/**
* The timestamp when the user last accessed the site.
*
* A value of 0 means the user has never accessed the site.
*
* @return int
* Timestamp of the last access.
*/
public function getLastAccessedTime();
/**
* Sets the UNIX timestamp when the user last accessed the site..
*
* @param int $timestamp
* Timestamp of the last access.
*/
public function setLastAccessTime($timestamp);
/**
* Returns the UNIX timestamp when the user last logged in.
*
* @return int
* Timestamp of the last login time.
*/
public function getLastLoginTime();
/**
* Sets the UNIX timestamp when the user last logged in.
*
* @param int $timestamp
* Timestamp of the last login time.
*/
public function setLastLoginTime($timestamp);
/**
* Returns TRUE if the user is active.
*
* @return bool
* TRUE if the user is active, false otherwise.
*/
public function isActive();
/**
* Returns TRUE if the user is blocked.
*
* @return bool
* TRUE if the user is blocked, false otherwise.
*/
public function isBlocked();
/**
* Activates the user.
*
* @return \Drupal\user\UserInterface
* The called user entity.
*/
public function activate();
/**
* Blocks the user.
*
* @return \Drupal\user\UserInterface
* The called user entity.
*/
public function block();
/**
* Returns the timezone of the user.
*
* @return string
* Name of the timezone.
*/
public function getTimeZone();
/**
* Returns the e-mail that was used when the user was registered.
*
* @return string
* Initial e-mail address of the user.
*/
public function getInitialEmail();
}

View File

@ -159,7 +159,7 @@ function user_uri($user) {
* @see user_format_name()
*/
function user_label($entity_type, $entity) {
return user_format_name($entity->getBCEntity());
return $entity->getUsername();
}
/**
@ -462,11 +462,8 @@ function user_access($string, AccountInterface $account = NULL) {
$account = Drupal::request()->attributes->get('account') ?: $user;
}
// Make sure we are working with the BC decorator.
$account = $account instanceof User ? $account->getBCEntity() : $account;
// User #1 has all privileges:
if ($account->uid == 1) {
if ($account->id() == 1) {
return TRUE;
}
@ -478,14 +475,14 @@ function user_access($string, AccountInterface $account = NULL) {
$drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
}
$perm = &$drupal_static_fast['perm'];
if (!isset($perm[$account->uid])) {
$perm[$account->uid] = array();
if (!isset($perm[$account->id()])) {
$perm[$account->id()] = array();
foreach (user_role_permissions($account->getRoles()) as $role_permissions) {
$perm[$account->uid] += array_fill_keys($role_permissions, TRUE);
$perm[$account->id()] += array_fill_keys($role_permissions, TRUE);
}
}
return isset($perm[$account->uid][$string]);
return isset($perm[$account->id()][$string]);
}
/**
@ -586,10 +583,10 @@ function user_search_execute($keys = NULL, $conditions = NULL) {
foreach ($accounts as $account) {
$result = array(
'title' => user_format_name($account),
'link' => url('user/' . $account->uid, array('absolute' => TRUE)),
'link' => url('user/' . $account->id(), array('absolute' => TRUE)),
);
if (user_access('administer users')) {
$result['title'] .= ' (' . $account->mail . ')';
$result['title'] .= ' (' . $account->getEmail() . ')';
}
$results[] = $result;
}
@ -666,25 +663,18 @@ function user_preprocess_block(&$variables) {
/**
* Format a username.
*
* By default, the passed-in object's 'name' property is used if it exists, or
* else, the site-defined value for the 'anonymous' variable. However, a module
* may override this by implementing
* hook_user_format_name_alter(&$name, $account).
*
* @see hook_user_format_name_alter()
*
* @param $account
* @param \Drupal\Core\Session\Interface $account
* The account object for the user whose name is to be formatted.
*
* @return
* An unsanitized string with the username to display. The code receiving
* this result must ensure that check_plain() is called on it before it is
* printed to the page.
*
* @deprecated Use \Drupal\Core\Session\Interface::getUsername() instead.
*/
function user_format_name($account) {
$name = !empty($account->name) ? $account->name : config('user.settings')->get('anonymous');
drupal_alter('user_format_name', $name, $account);
return $name;
function user_format_name(AccountInterface $account) {
return $account->getUsername();
}
/**
@ -707,7 +697,7 @@ function user_template_preprocess_default_variables_alter(&$variables) {
unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
$variables['is_admin'] = user_access('access administration pages');
$variables['logged_in'] = ($user->uid > 0);
$variables['logged_in'] = $user->isAuthenticated();
}
/**
@ -720,20 +710,14 @@ function user_template_preprocess_default_variables_alter(&$variables) {
* @see template_process_username()
*/
function template_preprocess_username(&$variables) {
$account = $variables['account'];
if ($account instanceof User) {
$account = $account->getBCEntity();
}
$account = $variables['account'] ?: drupal_anonymous_user();
$variables['extra'] = '';
if (empty($account->uid)) {
$variables['uid'] = 0;
if (theme_get_setting('features.comment_user_verification')) {
$variables['extra'] = ' (' . t('not verified') . ')';
}
}
else {
$variables['uid'] = (int) $account->uid;
$variables['uid'] = $account->id();
if (empty($variables['uid'])) {
if (theme_get_setting('features.comment_user_verification')) {
$variables['extra'] = ' (' . t('not verified') . ')';
}
}
// Set the name to a formatted name that is safe for printing and
@ -741,7 +725,7 @@ function template_preprocess_username(&$variables) {
// unsanitized version, in case other preprocess functions want to implement
// their own shortening logic or add markup. If they do so, they must ensure
// that $variables['name'] is safe for printing.
$name = $variables['name_raw'] = user_format_name($account);
$name = $variables['name_raw'] = $account->getUsername();
if (drupal_strlen($name) > 20) {
$name = drupal_substr($name, 0, 15) . '...';
}
@ -810,7 +794,7 @@ function theme_username($variables) {
*/
function user_is_anonymous() {
// Menu administrators can see items for anonymous when administering.
return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
return $GLOBALS['user']->isAnonymous() || !empty($GLOBALS['menu_admin']);
}
/**
@ -818,9 +802,11 @@ function user_is_anonymous() {
*
* @return bool
* TRUE if the user is logged in, FALSE if the user is anonymous.
*
* @deprecated Use \Drupal\Core\Session\UserSession::isAuthenticated().
*/
function user_is_logged_in() {
return (bool) $GLOBALS['user']->uid;
return $GLOBALS['user']->isAuthenticated();
}
/**
@ -1043,7 +1029,7 @@ function user_menu_breadcrumb_alter(&$active_trail, $item) {
function user_menu_link_load($menu_links) {
// Hide the "User account" link for anonymous users.
foreach ($menu_links as $link) {
if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->uid) {
if ($link['link_path'] == 'user' && $link['module'] == 'system' && !$GLOBALS['user']->id()) {
$link['hidden'] = 1;
}
}
@ -1089,7 +1075,7 @@ function user_uid_only_optional_to_arg($arg) {
*/
function user_uid_optional_load($uid = NULL) {
if (!isset($uid)) {
$uid = $GLOBALS['user']->uid;
$uid = $GLOBALS['user']->id();
}
return user_load($uid);
}
@ -1103,7 +1089,7 @@ function user_uid_optional_to_arg($arg) {
// Give back the current user uid when called from eg. tracker, aka.
// with an empty arg. Also use the current user uid when called from
// the menu with a % for the current account link.
return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
return empty($arg) || $arg == '%' ? $GLOBALS['user']->id() : $arg;
}
/**
@ -1113,7 +1099,7 @@ function user_uid_optional_to_arg($arg) {
* authenticated users are expected to see "My account".
*/
function user_menu_title() {
if (!user_is_logged_in()) {
if ($GLOBALS['user']->isAnonymous()) {
switch (current_path()) {
case 'user' :
case 'user/login' :
@ -1134,8 +1120,8 @@ function user_menu_title() {
/**
* Menu item title callback - use the user name.
*/
function user_page_title($account) {
return is_object($account) ? user_format_name($account) : '';
function user_page_title(UserInterface $account = NULL) {
return $account ? $account->getUsername() : '';
}
/**
@ -1178,11 +1164,11 @@ function user_authenticate($name, $password) {
$password_hasher = drupal_container()->get('password');
if ($password_hasher->check($password, $account)) {
// Successful authentication.
$uid = $account->uid;
$uid = $account->id();
// Update user to new password scheme if needed.
if ($password_hasher->userNeedsNewHash($account)) {
$account->pass = $password;
$account->setPassword($password);
$account->save();
}
}
@ -1200,21 +1186,21 @@ function user_authenticate($name, $password) {
*
* The global $user object is replaced with the passed in account.
*
* @param \Drupal\Core\Session\AccountInterface $account
* @param \Drupal\user\UserInterface $account
* The account to log in.
*
* @see hook_user_login()
*/
function user_login_finalize(AccountInterface $account) {
function user_login_finalize(UserInterface $account) {
global $user;
$user = $account;
watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
watchdog('user', 'Session opened for %name.', array('%name' => $user->getUsername()));
// Update the user table timestamp noting user has logged in.
// This is also used to invalidate one-time login links.
$user->login = REQUEST_TIME;
$account->setLastLoginTime(REQUEST_TIME);
db_update('users')
->fields(array('login' => $user->login))
->condition('uid', $user->uid)
->fields(array('login' => $user->getLastLoginTime()))
->condition('uid', $user->id())
->execute();
// Regenerate the session ID to prevent against session fixation attacks.
@ -1262,9 +1248,9 @@ function user_user_logout($account) {
*/
function user_pass_reset_url($account, $options = array()) {
$timestamp = REQUEST_TIME;
$langcode = isset($options['langcode']) ? $options['langcode'] : user_preferred_langcode($account);
$langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
$url_options = array('absolute' => TRUE, 'language' => language_load($langcode));
return url("user/reset/$account->uid/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), $url_options);
return url("user/reset/" . $account->id() . "/$timestamp/" . user_pass_rehash($account->getPassword(), $timestamp, $account->getLastLoginTime()), $url_options);
}
/**
@ -1290,9 +1276,9 @@ function user_pass_reset_url($account, $options = array()) {
*/
function user_cancel_url($account, $options = array()) {
$timestamp = REQUEST_TIME;
$langcode = isset($options['langcode']) ? $options['langcode'] : user_preferred_langcode($account);
$langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
$url_options = array('absolute' => TRUE, 'language' => language_load($langcode));
return url("user/$account->uid/cancel/confirm/$timestamp/" . user_pass_rehash($account->pass, $timestamp, $account->login), $url_options);
return url("user/" . $account->id() . "/cancel/confirm/$timestamp/" . user_pass_rehash($account->getPassword(), $timestamp, $account->login), $url_options);
}
/**
@ -1371,7 +1357,7 @@ function user_cancel($edit, $uid, $method) {
);
// After cancelling account, ensure that user is logged out.
if ($account->uid == $user->uid) {
if ($account->id() == $user->id()) {
// Batch API stores data in the session, so use the finished operation to
// manipulate the current user's session id.
$batch['finished'] = '_user_cancel_session_regenerate';
@ -1414,7 +1400,7 @@ function _user_cancel($edit, $account, $method) {
if (!empty($edit['user_cancel_notify'])) {
_user_mail_notify('status_canceled', $account);
}
user_delete($account->uid);
$account->delete();
drupal_set_message(t('%name has been deleted.', array('%name' => $account->name)));
watchdog('user', 'Deleted user: %name %email.', array('%name' => $account->name, '%email' => '<' . $account->mail . '>'), WATCHDOG_NOTICE);
break;
@ -1424,7 +1410,7 @@ function _user_cancel($edit, $account, $method) {
// their session though, as we might have information in it, and we can't
// regenerate it because batch API uses the session ID, we will regenerate it
// in _user_cancel_session_regenerate().
if ($account->uid == $user->uid) {
if ($account->id() == $user->id()) {
$user = drupal_anonymous_user();
}
@ -1808,7 +1794,7 @@ function user_role_revoke_permissions($rid, array $permissions = array()) {
function user_multiple_cancel_confirm($form, &$form_state) {
// Retrieve the accounts to be canceled from the temp store.
$accounts = Drupal::service('user.tempstore')->get('user_user_operations_cancel')->get($GLOBALS['user']->uid);
$accounts = Drupal::service('user.tempstore')->get('user_user_operations_cancel')->get($GLOBALS['user']->id());
$form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
foreach ($accounts as $account) {
$uid = $account->id();
@ -1876,7 +1862,7 @@ function user_multiple_cancel_confirm_submit($form, &$form_state) {
global $user;
// Clear out the accounts from the temp store.
Drupal::service('user.tempstore')->get('user_user_operations_cancel')->delete($user->uid);
Drupal::service('user.tempstore')->get('user_user_operations_cancel')->delete($user->id());
if ($form_state['values']['confirm']) {
foreach ($form_state['values']['accounts'] as $uid => $value) {
// Prevent programmatic form submissions from cancelling user 1.
@ -1884,12 +1870,12 @@ function user_multiple_cancel_confirm_submit($form, &$form_state) {
continue;
}
// Prevent user administrators from deleting themselves without confirmation.
if ($uid == $user->uid) {
if ($uid == $user->id()) {
$admin_form_state = $form_state;
unset($admin_form_state['values']['user_cancel_confirm']);
// The $user global is not a complete user entity, so load the full
// entity.
$admin_form_state['values']['_account'] = user_load($user->uid);
$admin_form_state['values']['_account'] = user_load($user->id());
user_cancel_confirm_form_submit(array(), $admin_form_state);
}
else {
@ -1923,40 +1909,6 @@ function theme_user_signature($variables) {
return $output;
}
/**
* Get the language object preferred by the user. This user preference can
* be set on the user account editing page, and is only available if there
* are more than one languages enabled on the site. If the user did not
* choose a preferred language, or is the anonymous user, the $default
* value, or if it is not set, the site default language will be returned.
*
* @param $account
* User account to look up language for.
* @param $type
* Optional string to define which preferred langcode should be used.
* Default to 'preferred_langcode' property.
* If set 'preferred_$type_langcode' is used.
* @param $default
* Optional default language code to return if the account
* has no valid language.
*/
function user_preferred_langcode($account, $type = NULL, $default = NULL) {
$language_list = language_list();
$account = $account->getBCEntity();
if (isset($type)) {
$preferred_langcode = $account->{'preferred_' . $type . '_langcode'};
}
else {
$preferred_langcode = $account->preferred_langcode;
}
if (!empty($preferred_langcode) && isset($language_list[$preferred_langcode])) {
return $language_list[$preferred_langcode]->id;
}
else {
return $default ? $default : language_default()->id;
}
}
/**
* Conditionally create and send a notification email when a certain
* operation happens on the given user account.
@ -1993,7 +1945,7 @@ function _user_mail_notify($op, $account, $langcode = NULL) {
$notify = config('user.settings')->get('notify.' . $op);
if ($notify || ($op != 'status_canceled' && $op != 'status_blocked')) {
$params['account'] = $account;
$langcode = $langcode ? $langcode : user_preferred_langcode($account);
$langcode = $langcode ? $langcode : $account->getPreferredLangcode();
// Get the custom site notification email to use as the from email address
// if it has been set.
$site_mail = config('system.site')->get('mail_notification');
@ -2157,7 +2109,7 @@ function user_toolbar() {
global $user;
// Add logout & user account links or login link.
if ($user->uid) {
if ($user->isAuthenticated()) {
$links = array(
'account' => array(
'title' => t('View profile'),
@ -2169,7 +2121,7 @@ function user_toolbar() {
),
'account_edit' => array(
'title' => t('Edit profile'),
'href' => 'user/' . $user->uid . '/edit',
'href' => 'user/' . $user->id() . '/edit',
'html' => TRUE,
'attributes' => array(
'title' => t('Edit user account'),
@ -2194,7 +2146,7 @@ function user_toolbar() {
'#type' => 'toolbar_item',
'tab' => array(
'#type' => 'link',
'#title' => user_format_name($user),
'#title' => $user->getUsername(),
'#href' => 'user',
'#options' => array(
'attributes' => array(