Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -79,7 +79,7 @@ class CancelUser extends ActionBase implements ContainerFactoryPluginInterface {
* {@inheritdoc}
*/
public function execute($object = NULL) {
$this->executeMultiple(array($object));
$this->executeMultiple([$object]);
}
/**

View file

@ -49,9 +49,9 @@ abstract class ChangeUserRoleBase extends ConfigurableActionBase implements Cont
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array(
return [
'rid' => '',
);
];
}
/**
@ -60,13 +60,13 @@ abstract class ChangeUserRoleBase extends ConfigurableActionBase implements Cont
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$roles = user_role_names(TRUE);
unset($roles[RoleInterface::AUTHENTICATED_ID]);
$form['rid'] = array(
$form['rid'] = [
'#type' => 'radios',
'#title' => t('Role'),
'#options' => $roles,
'#default_value' => $this->configuration['rid'],
'#required' => TRUE,
);
];
return $form;
}

View file

@ -72,7 +72,7 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
*/
protected function blockAccess(AccountInterface $account) {
$route_name = $this->routeMatch->getRouteName();
if ($account->isAnonymous() && !in_array($route_name, array('user.login', 'user.logout'))) {
if ($account->isAnonymous() && !in_array($route_name, ['user.login', 'user.logout'])) {
return AccessResult::allowed()
->addCacheContexts(['route.name', 'user.roles:anonymous']);
}
@ -96,28 +96,36 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
$form['pass']['#size'] = 15;
$form['#action'] = $this->url('<current>', [], ['query' => $this->getDestinationArray(), 'external' => FALSE]);
// Build action links.
$items = array();
$items = [];
if (\Drupal::config('user.settings')->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
$items['create_account'] = \Drupal::l($this->t('Create new account'), new Url('user.register', array(), array(
'attributes' => array(
'title' => $this->t('Create a new user account.'),
'class' => array('create-account-link'),
),
)));
$items['create_account'] = [
'#type' => 'link',
'#title' => $this->t('Create new account'),
'#url' => Url::fromRoute('user.register', [], [
'attributes' => [
'title' => $this->t('Create a new user account.'),
'class' => ['create-account-link'],
],
]),
];
}
$items['request_password'] = \Drupal::l($this->t('Reset your password'), new Url('user.pass', array(), array(
'attributes' => array(
'title' => $this->t('Send password reset instructions via email.'),
'class' => array('request-password-link'),
),
)));
return array(
$items['request_password'] = [
'#type' => 'link',
'#title' => $this->t('Reset your password'),
'#url' => Url::fromRoute('user.pass', [], [
'attributes' => [
'title' => $this->t('Send password reset instructions via email.'),
'class' => ['request-password-link'],
],
]),
];
return [
'user_login_form' => $form,
'user_links' => array(
'user_links' => [
'#theme' => 'item_list',
'#items' => $items,
),
);
],
];
}
}

View file

@ -22,13 +22,13 @@ class UserRole extends ConditionPluginBase {
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['roles'] = array(
$form['roles'] = [
'#type' => 'checkboxes',
'#title' => $this->t('When the user has the following roles'),
'#default_value' => $this->configuration['roles'],
'#options' => array_map('\Drupal\Component\Utility\Html::escape', user_role_names()),
'#description' => $this->t('If you select no roles, the condition will evaluate to TRUE for all users.'),
);
];
return parent::buildConfigurationForm($form, $form_state);
}
@ -36,9 +36,9 @@ class UserRole extends ConditionPluginBase {
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array(
'roles' => array(),
) + parent::defaultConfiguration();
return [
'roles' => [],
] + parent::defaultConfiguration();
}
/**
@ -62,10 +62,10 @@ class UserRole extends ConditionPluginBase {
$roles = reset($roles);
}
if (!empty($this->configuration['negate'])) {
return $this->t('The user is not a member of @roles', array('@roles' => $roles));
return $this->t('The user is not a member of @roles', ['@roles' => $roles]);
}
else {
return $this->t('The user is a member of @roles', array('@roles' => $roles));
return $this->t('The user is a member of @roles', ['@roles' => $roles]);
}
}

View file

@ -86,51 +86,51 @@ class UserSelection extends DefaultSelection {
$selection_handler_settings = $this->configuration['handler_settings'];
// Merge in default values.
$selection_handler_settings += array(
'filter' => array(
$selection_handler_settings += [
'filter' => [
'type' => '_none',
),
],
'include_anonymous' => TRUE,
);
];
$form['include_anonymous'] = array(
$form['include_anonymous'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include the anonymous user.'),
'#default_value' => $selection_handler_settings['include_anonymous'],
);
];
// Add user specific filter options.
$form['filter']['type'] = array(
$form['filter']['type'] = [
'#type' => 'select',
'#title' => $this->t('Filter by'),
'#options' => array(
'#options' => [
'_none' => $this->t('- None -'),
'role' => $this->t('User role'),
),
],
'#ajax' => TRUE,
'#limit_validation_errors' => array(),
'#limit_validation_errors' => [],
'#default_value' => $selection_handler_settings['filter']['type'],
);
];
$form['filter']['settings'] = array(
$form['filter']['settings'] = [
'#type' => 'container',
'#attributes' => array('class' => array('entity_reference-settings')),
'#process' => array(array('\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem', 'formProcessMergeParent')),
);
'#attributes' => ['class' => ['entity_reference-settings']],
'#process' => [['\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem', 'formProcessMergeParent']],
];
if ($selection_handler_settings['filter']['type'] == 'role') {
// Merge in default values.
$selection_handler_settings['filter'] += array(
$selection_handler_settings['filter'] += [
'role' => NULL,
);
];
$form['filter']['settings']['role'] = array(
$form['filter']['settings']['role'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Restrict to the selected roles'),
'#required' => TRUE,
'#options' => array_diff_key(user_role_names(TRUE), array(RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID)),
'#options' => array_diff_key(user_role_names(TRUE), [RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID]),
'#default_value' => $selection_handler_settings['filter']['role'],
);
];
}
$form += parent::buildConfigurationForm($form, $form_state);
@ -239,7 +239,7 @@ class UserSelection extends DefaultSelection {
$value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
$value_part->compile($this->connection, $query);
$or->condition(db_and()
->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => \Drupal::config('user.settings')->get('anonymous')))
->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + [':anonymous_name' => \Drupal::config('user.settings')->get('anonymous')])
->condition('base_table.uid', 0)
);
$query->condition($or);

View file

@ -2,7 +2,6 @@
namespace Drupal\user\Plugin\Field\FieldFormatter;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
@ -26,18 +25,18 @@ class AuthorFormatter extends EntityReferenceFormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
/** @var $referenced_user \Drupal\user\UserInterface */
$elements[$delta] = array(
$elements[$delta] = [
'#theme' => 'username',
'#account' => $entity,
'#link_options' => array('attributes' => array('rel' => 'author')),
'#cache' => array(
'#link_options' => ['attributes' => ['rel' => 'author']],
'#cache' => [
'tags' => $entity->getCacheTags(),
),
);
],
];
}
return $elements;
@ -54,9 +53,7 @@ class AuthorFormatter extends EntityReferenceFormatterBase {
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity) {
// Always allow an entity author's username to be read, even if the current
// user does not have permission to view the entity author's profile.
return AccessResult::allowed();
return $entity->access('view label', NULL, TRUE);
}
}

View file

@ -104,7 +104,7 @@ class UserSearch extends SearchPluginBase implements AccessibleInterface {
* {@inheritdoc}
*/
public function execute() {
$results = array();
$results = [];
if (!$this->isSearchExecutable()) {
return $results;
}
@ -120,12 +120,12 @@ class UserSearch extends SearchPluginBase implements AccessibleInterface {
$query = $this->database
->select('users_field_data', 'users')
->extend('Drupal\Core\Database\Query\PagerSelectExtender');
$query->fields('users', array('uid'));
$query->fields('users', ['uid']);
$query->condition('default_langcode', 1);
if ($this->currentUser->hasPermission('administer users')) {
// Administrators can also search in the otherwise private email field,
// and they don't need to be restricted to only active users.
$query->fields('users', array('mail'));
$query->fields('users', ['mail']);
$query->condition($query->orConditionGroup()
->condition('name', '%' . $keys . '%', 'LIKE')
->condition('mail', '%' . $keys . '%', 'LIKE')
@ -144,10 +144,10 @@ class UserSearch extends SearchPluginBase implements AccessibleInterface {
$accounts = $this->entityManager->getStorage('user')->loadMultiple($uids);
foreach ($accounts as $account) {
$result = array(
$result = [
'title' => $account->getDisplayName(),
'link' => $account->url('canonical', array('absolute' => TRUE)),
);
'link' => $account->url('canonical', ['absolute' => TRUE]),
];
if ($this->currentUser->hasPermission('administer users')) {
$result['title'] .= ' (' . $account->getEmail() . ')';
}
@ -162,13 +162,13 @@ class UserSearch extends SearchPluginBase implements AccessibleInterface {
* {@inheritdoc}
*/
public function getHelp() {
$help = array('list' => array(
$help = ['list' => [
'#theme' => 'item_list',
'#items' => array(
'#items' => [
$this->t('User search looks for user names and partial user names. Example: mar would match usernames mar, delmar, and maryjane.'),
$this->t('You can use * as a wildcard within your keyword. Example: m*r would match user names mar, delmar, and elementary.'),
),
));
],
]];
return $help;
}

View file

@ -86,7 +86,7 @@ class ProtectedUserFieldConstraintValidator extends ConstraintValidator implemen
$changed = $items->getValue() != $account_unchanged->get($field->getName())->getValue();
}
if ($changed && (!$account->checkExistingPassword($account_unchanged))) {
$this->context->addViolation($constraint->message, array('%name' => $field->getLabel()));
$this->context->addViolation($constraint->message, ['%name' => $field->getLabel()]);
}
}
}

View file

@ -3,8 +3,6 @@
namespace Drupal\user\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* Checks if the user's email address is provided if required.
@ -18,7 +16,7 @@ use Symfony\Component\Validator\ExecutionContextInterface;
* label = @Translation("User email required", context = "Validation")
* )
*/
class UserMailRequired extends Constraint implements ConstraintValidatorInterface {
class UserMailRequired extends Constraint {
/**
* Violation message. Use the same message as FormValidator.
@ -30,45 +28,4 @@ class UserMailRequired extends Constraint implements ConstraintValidatorInterfac
*/
public $message = '@name field is required.';
/**
* @var \Symfony\Component\Validator\ExecutionContextInterface
*/
protected $context;
/**
* {@inheritdoc}
*/
public function initialize(ExecutionContextInterface $context) {
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function validatedBy() {
return get_class($this);
}
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
/** @var \Drupal\user\UserInterface $account */
$account = $items->getEntity();
$existing_value = NULL;
if ($account->id()) {
$account_unchanged = \Drupal::entityManager()
->getStorage('user')
->loadUnchanged($account->id());
$existing_value = $account_unchanged->getEmail();
}
$required = !(!$existing_value && \Drupal::currentUser()->hasPermission('administer users'));
if ($required && (!isset($items) || $items->isEmpty())) {
$this->context->addViolation($this->message, ['@name' => $account->getFieldDefinition('mail')->getLabel()]);
}
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace Drupal\user\Plugin\Validation\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
/**
* Checks if the user's email address is provided if required.
*
* The user mail field is NOT required if account originally had no mail set
* and the user performing the edit has 'administer users' permission.
* This allows users without email address to be edited and deleted.
*/
class UserMailRequiredValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
/** @var \Drupal\user\UserInterface $account */
$account = $items->getEntity();
$existing_value = NULL;
if ($account->id()) {
$account_unchanged = \Drupal::entityManager()
->getStorage('user')
->loadUnchanged($account->id());
$existing_value = $account_unchanged->getEmail();
}
$required = !(!$existing_value && \Drupal::currentUser()->hasPermission('administer users'));
if ($required && (!isset($items) || $items->isEmpty())) {
$this->context->addViolation($constraint->message, ['@name' => $account->getFieldDefinition('mail')->getLabel()]);
}
}
}

View file

@ -54,7 +54,7 @@ class UserNameConstraintValidator extends ConstraintValidator {
$this->context->addViolation($constraint->illegalMessage);
}
if (Unicode::strlen($name) > USERNAME_MAX_LENGTH) {
$this->context->addViolation($constraint->tooLongMessage, array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
$this->context->addViolation($constraint->tooLongMessage, ['%name' => $name, '%max' => USERNAME_MAX_LENGTH]);
}
}

View file

@ -77,7 +77,7 @@ class EntityUser extends EntityContentBase {
* {@inheritdoc}
* @throws \Drupal\migrate\MigrateException
*/
public function import(Row $row, array $old_destination_id_values = array()) {
public function import(Row $row, array $old_destination_id_values = []) {
// Do not overwrite the root account password.
if ($row->getDestinationProperty('uid') == 1) {
$row->removeDestinationProperty('pass');
@ -88,7 +88,7 @@ class EntityUser extends EntityContentBase {
/**
* {@inheritdoc}
*/
protected function save(ContentEntityInterface $entity, array $old_destination_id_values = array()) {
protected function save(ContentEntityInterface $entity, array $old_destination_id_values = []) {
// Do not overwrite the root account password.
if ($entity->id() != 1) {
// Set the pre_hashed password so that the PasswordItem field does not hash

View file

@ -56,7 +56,7 @@ class UserData extends DestinationBase implements ContainerFactoryPluginInterfac
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = array()) {
public function import(Row $row, array $old_destination_id_values = []) {
$uid = $row->getDestinationProperty('uid');
$module = $row->getDestinationProperty('module');
$key = $row->getDestinationProperty('key');

View file

@ -21,7 +21,7 @@ class ConvertTokens extends ProcessPluginBase {
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$tokens = array(
$tokens = [
'!site' => '[site:name]',
'!username' => '[user:name]',
'!mailto' => '[user:mail]',
@ -32,7 +32,7 @@ class ConvertTokens extends ProcessPluginBase {
'!uri' => '[site:url]',
'!date' => '[date:medium]',
'!password' => '',
);
];
// Given that our source is a database column that could hold a NULL
// value, sometimes that filters down to here. str_replace() cannot

View file

@ -17,7 +17,7 @@ class ProfileFieldSettings extends ProcessPluginBase {
* {@inheritdoc}
*/
public function transform($type, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$settings = array();
$settings = [];
switch ($type) {
case 'date':
$settings['datetime_type'] = 'date';

View file

@ -22,10 +22,10 @@ class UserUpdate8002 extends ProcessPluginBase {
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$rid = $row->getSourceProperty('rid');
$map = array(
$map = [
1 => 'anonymous',
2 => 'authenticated',
);
];
return isset($map[$rid]) ? $map[$rid] : $value;
}

View file

@ -70,7 +70,7 @@ class ProfileField extends DrupalSqlBase {
// D6 profile checkboxes values are always 0 or 1 (with no labels), so we
// need to create two label-less options that will get 0 and 1 for their
// keys.
$row->setSourceProperty('options', array(NULL, NULL));
$row->setSourceProperty('options', [NULL, NULL]);
}
return parent::prepareRow($row);
@ -80,7 +80,7 @@ class ProfileField extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'fid' => $this->t('Primary Key: Unique profile field ID.'),
'title' => $this->t('Title of the field shown to the end user.'),
'name' => $this->t('Internal name of the field used in the form HTML and URLs.'),
@ -94,7 +94,7 @@ class ProfileField extends DrupalSqlBase {
'visibility' => $this->t('The level of visibility for the field. (0 = hidden, 1 = private, 2 = public on profile but not member list pages, 3 = public on profile and list pages)'),
'autocomplete' => $this->t('Whether form auto-completion is enabled. (0 = disabled, 1 = enabled)'),
'options' => $this->t('List of options to be used in a list selection field.'),
);
];
}
/**

View file

@ -22,24 +22,24 @@ class UserPictureInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
public function initializeIterator() {
return new \ArrayIterator(array(
array(
return new \ArrayIterator([
[
'id' => '',
'file_directory' => $this->variableGet('user_picture_path', 'pictures'),
'max_filesize' => $this->variableGet('user_picture_file_size', '30') . 'KB',
'max_resolution' => $this->variableGet('user_picture_dimensions', '85x85'),
)));
]]);
}
/**
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'file_directory' => 'The directory to store images..',
'max_filesize' => 'The maximum allowed file size in KBs.',
'max_resolution' => "The maximum resolution.",
);
];
}
/**

View file

@ -21,7 +21,7 @@ class ProfileFieldValues extends DrupalSqlBase {
public function query() {
$query = $this->select('profile_values', 'pv')
->distinct()
->fields('pv', array('uid'));
->fields('pv', ['uid']);
return $query;
}
@ -32,9 +32,9 @@ class ProfileFieldValues extends DrupalSqlBase {
public function prepareRow(Row $row) {
// Find profile values for this row.
$query = $this->select('profile_values', 'pv')
->fields('pv', array('fid', 'value'));
->fields('pv', ['fid', 'value']);
$query->leftJoin('profile_fields', 'pf', 'pf.fid=pv.fid');
$query->fields('pf', array('name', 'type'));
$query->fields('pf', ['name', 'type']);
$query->condition('uid', $row->getSourceProperty('uid'));
$results = $query->execute();
@ -43,14 +43,14 @@ class ProfileFieldValues extends DrupalSqlBase {
if ($profile_value['type'] == 'date') {
$date = unserialize($profile_value['value']);
$date = date('Y-m-d', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$row->setSourceProperty($profile_value['name'], array('value' => $date));
$row->setSourceProperty($profile_value['name'], ['value' => $date]);
}
elseif ($profile_value['type'] == 'list') {
// Explode by newline and comma.
$row->setSourceProperty($profile_value['name'], preg_split("/[\r\n,]+/", $profile_value['value']));
}
else {
$row->setSourceProperty($profile_value['name'], array($profile_value['value']));
$row->setSourceProperty($profile_value['name'], [$profile_value['value']]);
}
}
@ -61,16 +61,16 @@ class ProfileFieldValues extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
$fields = array(
$fields = [
'fid' => $this->t('Unique profile field ID.'),
'uid' => $this->t('The user Id.'),
'value' => $this->t('The value for this field.'),
);
];
$query = $this->select('profile_values', 'pv')
->fields('pv', array('fid', 'value'));
->fields('pv', ['fid', 'value']);
$query->leftJoin('profile_fields', 'pf', 'pf.fid=pv.fid');
$query->fields('pf', array('name', 'title'));
$query->fields('pf', ['name', 'title']);
$results = $query->execute();
foreach ($results as $profile) {
$fields[$profile['name']] = $this->t($profile['title']);
@ -83,12 +83,12 @@ class ProfileFieldValues extends DrupalSqlBase {
* {@inheritdoc}
*/
public function getIds() {
return array(
'uid' => array(
return [
'uid' => [
'type' => 'integer',
'alias' => 'pv',
),
);
],
];
}
}

View file

@ -19,14 +19,14 @@ class Role extends DrupalSqlBase {
*
* @var array
*/
protected $filterPermissions = array();
protected $filterPermissions = [];
/**
* {@inheritdoc}
*/
public function query() {
$query = $this->select('role', 'r')
->fields('r', array('rid', 'name'))
->fields('r', ['rid', 'name'])
->orderBy('r.rid');
return $query;
}
@ -35,10 +35,10 @@ class Role extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'rid' => $this->t('Role ID.'),
'name' => $this->t('The name of the user role.'),
);
];
}
/**
@ -46,7 +46,7 @@ class Role extends DrupalSqlBase {
*/
protected function initializeIterator() {
$filter_roles = $this->select('filter_formats', 'f')
->fields('f', array('format', 'roles'))
->fields('f', ['format', 'roles'])
->execute()
->fetchAllKeyed();
foreach ($filter_roles as $format => $roles) {
@ -65,7 +65,7 @@ class Role extends DrupalSqlBase {
public function prepareRow(Row $row) {
$rid = $row->getSourceProperty('rid');
$permissions = $this->select('permission', 'p')
->fields('p', array('perm'))
->fields('p', ['perm'])
->condition('rid', $rid)
->execute()
->fetchField();

View file

@ -35,7 +35,7 @@ class User extends DrupalSqlBase {
// Profile fields.
if ($this->moduleExists('profile')) {
$fields += $this->select('profile_fields', 'pf')
->fields('pf', array('name', 'title'))
->fields('pf', ['name', 'title'])
->execute()
->fetchAllKeyed();
}
@ -49,7 +49,7 @@ class User extends DrupalSqlBase {
public function prepareRow(Row $row) {
// User roles.
$roles = $this->select('users_roles', 'ur')
->fields('ur', array('rid'))
->fields('ur', ['rid'])
->condition('ur.uid', $row->getSourceProperty('uid'))
->execute()
->fetchCol();
@ -60,7 +60,7 @@ class User extends DrupalSqlBase {
if ($row->hasSourceProperty('timezone_id') && $row->getSourceProperty('timezone_id')) {
if ($this->getDatabase()->schema()->tableExists('event_timezones')) {
$event_timezone = $this->select('event_timezones', 'e')
->fields('e', array('name'))
->fields('e', ['name'])
->condition('e.timezone', $row->getSourceProperty('timezone_id'))
->execute()
->fetchField();
@ -80,12 +80,12 @@ class User extends DrupalSqlBase {
* {@inheritdoc}
*/
public function getIds() {
return array(
'uid' => array(
return [
'uid' => [
'type' => 'integer',
'alias' => 'u',
),
);
],
];
}
/**
@ -95,7 +95,7 @@ class User extends DrupalSqlBase {
* Associative array having field name as key and description as value.
*/
protected function baseFields() {
$fields = array(
$fields = [
'uid' => $this->t('User ID'),
'name' => $this->t('Username'),
'pass' => $this->t('Password'),
@ -112,7 +112,7 @@ class User extends DrupalSqlBase {
'picture' => $this->t('Picture'),
'init' => $this->t('Init'),
'data' => $this->t('User data'),
);
];
// Possible field added by Date contributed module.
// @see https://api.drupal.org/api/drupal/modules%21user%21user.install/function/user_update_7002/7

View file

@ -21,7 +21,7 @@ class UserPicture extends DrupalSqlBase {
public function query() {
$query = $this->select('users', 'u')
->condition('picture', '', '<>')
->fields('u', array('uid', 'access', 'picture'))
->fields('u', ['uid', 'access', 'picture'])
->orderBy('u.access');
return $query;
}
@ -30,11 +30,11 @@ class UserPicture extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'uid' => 'Primary Key: Unique user ID.',
'access' => 'Timestamp for previous time user accessed the site.',
'picture' => "Path to the user's uploaded picture.",
);
];
}
/**
* {@inheritdoc}

View file

@ -34,7 +34,7 @@ class UserPictureFile extends DrupalSqlBase {
public function query() {
$query = $this->select('users', 'u')
->condition('u.picture', '', '<>')
->fields('u', array('uid', 'picture'));
->fields('u', ['uid', 'picture']);
return $query;
}
@ -62,10 +62,10 @@ class UserPictureFile extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'picture' => "Path to the user's uploaded picture.",
'filename' => 'The picture filename.',
);
];
}
/**
* {@inheritdoc}

View file

@ -25,11 +25,11 @@ class Role extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'rid' => $this->t('Role ID.'),
'name' => $this->t('The name of the user role.'),
'weight' => $this->t('The weight of the role.'),
);
];
}
/**

View file

@ -27,7 +27,7 @@ class User extends FieldableEntity {
* {@inheritdoc}
*/
public function fields() {
$fields = array(
$fields = [
'uid' => $this->t('User ID'),
'name' => $this->t('Username'),
'pass' => $this->t('Password'),
@ -44,12 +44,12 @@ class User extends FieldableEntity {
'init' => $this->t('Init'),
'data' => $this->t('User data'),
'roles' => $this->t('Roles'),
);
];
// Profile fields.
if ($this->moduleExists('profile')) {
$fields += $this->select('profile_fields', 'pf')
->fields('pf', array('name', 'title'))
->fields('pf', ['name', 'title'])
->execute()
->fetchAllKeyed();
}
@ -79,9 +79,9 @@ class User extends FieldableEntity {
// ProfileFieldValues plugin.
if ($this->getDatabase()->schema()->tableExists('profile_value')) {
$query = $this->select('profile_value', 'pv')
->fields('pv', array('fid', 'value'));
->fields('pv', ['fid', 'value']);
$query->leftJoin('profile_field', 'pf', 'pf.fid=pv.fid');
$query->fields('pf', array('name', 'type'));
$query->fields('pf', ['name', 'type']);
$query->condition('uid', $row->getSourceProperty('uid'));
$results = $query->execute();
@ -89,14 +89,14 @@ class User extends FieldableEntity {
if ($profile_value['type'] == 'date') {
$date = unserialize($profile_value['value']);
$date = date('Y-m-d', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$row->setSourceProperty($profile_value['name'], array('value' => $date));
$row->setSourceProperty($profile_value['name'], ['value' => $date]);
}
elseif ($profile_value['type'] == 'list') {
// Explode by newline and comma.
$row->setSourceProperty($profile_value['name'], preg_split("/[\r\n,]+/", $profile_value['value']));
}
else {
$row->setSourceProperty($profile_value['name'], array($profile_value['value']));
$row->setSourceProperty($profile_value['name'], [$profile_value['value']]);
}
}
}
@ -108,12 +108,12 @@ class User extends FieldableEntity {
* {@inheritdoc}
*/
public function getIds() {
return array(
'uid' => array(
return [
'uid' => [
'type' => 'integer',
'alias' => 'u',
),
);
],
];
}
}

View file

@ -0,0 +1,190 @@
<?php
namespace Drupal\user\Plugin\rest\resource;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Session\AccountInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\Plugin\rest\resource\EntityResourceAccessTrait;
use Drupal\rest\Plugin\rest\resource\EntityResourceValidationTrait;
use Drupal\user\UserInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
/**
* Represents user registration as a resource.
*
* @RestResource(
* id = "user_registration",
* label = @Translation("User registration"),
* serialization_class = "Drupal\user\Entity\User",
* uri_paths = {
* "https://www.drupal.org/link-relations/create" = "/user/register",
* },
* )
*/
class UserRegistrationResource extends ResourceBase {
use EntityResourceValidationTrait;
use EntityResourceAccessTrait;
/**
* User settings config instance.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $userSettings;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs a new UserRegistrationResource instance.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param array $serializer_formats
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Config\ImmutableConfig $user_settings
* A user settings config instance.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, ImmutableConfig $user_settings, AccountInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->userSettings = $user_settings;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('rest'),
$container->get('config.factory')->get('user.settings'),
$container->get('current_user')
);
}
/**
* Responds to user registration POST request.
*
* @param \Drupal\user\UserInterface $account
* The user account entity.
*
* @return \Drupal\rest\ModifiedResourceResponse
* The HTTP response object.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function post(UserInterface $account = NULL) {
$this->ensureAccountCanRegister($account);
// Only activate new users if visitors are allowed to register and no email
// verification required.
if ($this->userSettings->get('register') == USER_REGISTER_VISITORS && !$this->userSettings->get('verify_mail')) {
$account->activate();
}
else {
$account->block();
}
$this->checkEditFieldAccess($account);
// Make sure that the user entity is valid (email and name are valid).
$this->validate($account);
// Create the account.
$account->save();
$this->sendEmailNotifications($account);
return new ModifiedResourceResponse($account, 200);
}
/**
* Ensure the account can be registered in this request.
*
* @param \Drupal\user\UserInterface $account
* The user account to register.
*/
protected function ensureAccountCanRegister(UserInterface $account = NULL) {
if ($account === NULL) {
throw new BadRequestHttpException('No user account data for registration received.');
}
// POSTed user accounts must not have an ID set, because we always want to
// create new entities here.
if (!$account->isNew()) {
throw new BadRequestHttpException('An ID has been set and only new user accounts can be registered.');
}
// Only allow anonymous users to register, authenticated users with the
// necessary permissions can POST a new user to the "user" REST resource.
// @see \Drupal\rest\Plugin\rest\resource\EntityResource
if (!$this->currentUser->isAnonymous()) {
throw new AccessDeniedHttpException('Only anonymous users can register a user.');
}
// Verify that the current user can register a user account.
if ($this->userSettings->get('register') == USER_REGISTER_ADMINISTRATORS_ONLY) {
throw new AccessDeniedHttpException('You cannot register a new user account.');
}
if (!$this->userSettings->get('verify_mail')) {
if (empty($account->getPassword())) {
// If no e-mail verification then the user must provide a password.
throw new UnprocessableEntityHttpException('No password provided.');
}
}
else {
if (!empty($account->getPassword())) {
// If e-mail verification required then a password cannot provided.
// The password will be set when the user logs in.
throw new UnprocessableEntityHttpException('A Password cannot be specified. It will be generated on login.');
}
}
}
/**
* Sends email notifications if necessary for user that was registered.
*
* @param \Drupal\user\UserInterface $account
* The user account.
*/
protected function sendEmailNotifications(UserInterface $account) {
$approval_settings = $this->userSettings->get('register');
// No e-mail verification is required. Activating the user.
if ($approval_settings == USER_REGISTER_VISITORS) {
if ($this->userSettings->get('verify_mail')) {
// No administrator approval required.
_user_mail_notify('register_no_approval_required', $account);
}
}
// Administrator approval required.
elseif ($approval_settings == USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL) {
_user_mail_notify('register_pending_approval', $account);
}
}
}

View file

@ -103,7 +103,7 @@ class Permission extends AccessPluginBase implements CacheableDependencyInterfac
protected function defineOptions() {
$options = parent::defineOptions();
$options['perm'] = array('default' => 'access content');
$options['perm'] = ['default' => 'access content'];
return $options;
}
@ -119,13 +119,13 @@ class Permission extends AccessPluginBase implements CacheableDependencyInterfac
$perms[$display_name][$perm] = strip_tags($perm_item['title']);
}
$form['perm'] = array(
$form['perm'] = [
'#type' => 'select',
'#options' => $perms,
'#title' => $this->t('Permission'),
'#default_value' => $this->options['perm'],
'#description' => $this->t('Only users with the selected permission flag will be able to access this display.'),
);
];
}
/**

View file

@ -99,31 +99,31 @@ class Role extends AccessPluginBase implements CacheableDependencyInterface {
protected function defineOptions() {
$options = parent::defineOptions();
$options['role'] = array('default' => array());
$options['role'] = ['default' => []];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['role'] = array(
$form['role'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Role'),
'#default_value' => $this->options['role'],
'#options' => array_map('\Drupal\Component\Utility\Html::escape', user_role_names()),
'#description' => $this->t('Only the checked roles will be able to access this display.'),
);
];
}
public function validateOptionsForm(&$form, FormStateInterface $form_state) {
$role = $form_state->getValue(array('access_options', 'role'));
$role = $form_state->getValue(['access_options', 'role']);
$role = array_filter($role);
if (!$role) {
$form_state->setError($form['role'], $this->t('You must select at least one role if type is "by role"'));
}
$form_state->setValue(array('access_options', 'role'), $role);
$form_state->setValue(['access_options', 'role'], $role);
}
/**

View file

@ -52,7 +52,7 @@ class RolesRid extends ManyToOne {
*/
public function titleQuery() {
$entities = $this->roleStorage->loadMultiple($this->value);
$titles = array();
$titles = [];
foreach ($entities as $entity) {
$titles[] = $entity->label();
}

View file

@ -64,7 +64,7 @@ class User extends ArgumentDefaultPluginBase implements CacheableDependencyInter
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['user'] = array('default' => '');
$options['user'] = ['default' => ''];
return $options;
}
@ -73,11 +73,11 @@ class User extends ArgumentDefaultPluginBase implements CacheableDependencyInter
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['user'] = array(
$form['user'] = [
'#type' => 'checkbox',
'#title' => $this->t('Also look for a node and use the node author'),
'#default_value' => $this->options['user'],
);
];
}
/**

View file

@ -38,8 +38,8 @@ class User extends Entity {
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['restrict_roles'] = array('default' => FALSE);
$options['roles'] = array('default' => array());
$options['restrict_roles'] = ['default' => FALSE];
$options['roles'] = ['default' => []];
return $options;
}
@ -51,30 +51,30 @@ class User extends Entity {
parent::buildOptionsForm($form, $form_state);
$sanitized_id = ArgumentPluginBase::encodeValidatorId($this->definition['id']);
$form['restrict_roles'] = array(
$form['restrict_roles'] = [
'#type' => 'checkbox',
'#title' => $this->t('Restrict user based on role'),
'#default_value' => $this->options['restrict_roles'],
);
];
$form['roles'] = array(
$form['roles'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Restrict to the selected roles'),
'#options' => array_map(array('\Drupal\Component\Utility\Html', 'escape'), user_role_names(TRUE)),
'#options' => array_map(['\Drupal\Component\Utility\Html', 'escape'], user_role_names(TRUE)),
'#default_value' => $this->options['roles'],
'#description' => $this->t('If no roles are selected, users from any role will be allowed.'),
'#states' => array(
'visible' => array(
':input[name="options[validate][options][' . $sanitized_id . '][restrict_roles]"]' => array('checked' => TRUE),
),
),
);
'#states' => [
'visible' => [
':input[name="options[validate][options][' . $sanitized_id . '][restrict_roles]"]' => ['checked' => TRUE],
],
],
];
}
/**
* {@inheritdoc}
*/
public function submitOptionsForm(&$form, FormStateInterface $form_state, &$options = array()) {
public function submitOptionsForm(&$form, FormStateInterface $form_state, &$options = []) {
// filter trash out of the options so we don't store giant unnecessary arrays
$options['roles'] = array_filter($options['roles']);
}

View file

@ -23,10 +23,10 @@ class UserName extends User {
$entity_type = $this->entityManager->getDefinition('user');
$form['multiple']['#options'] = array(
0 => $this->t('Single name', array('%type' => $entity_type->getLabel())),
1 => $this->t('One or more names separated by , or +', array('%type' => $entity_type->getLabel())),
);
$form['multiple']['#options'] = [
0 => $this->t('Single name', ['%type' => $entity_type->getLabel()]),
1 => $this->t('One or more names separated by , or +', ['%type' => $entity_type->getLabel()]),
];
}
/**
@ -39,14 +39,14 @@ class UserName extends User {
$names = array_filter(preg_split('/[,+ ]/', $argument));
}
elseif ($argument) {
$names = array($argument);
$names = [$argument];
}
// No specified argument should be invalid.
else {
return FALSE;
}
$accounts = $this->userStorage->loadByProperties(array('name' => $names));
$accounts = $this->userStorage->loadByProperties(['name' => $names]);
// If there are no accounts, return FALSE now. As we will not enter the
// loop below otherwise.

View file

@ -66,7 +66,7 @@ class Permissions extends PrerenderList {
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$this->additional_fields['uid'] = array('table' => 'users_field_data', 'field' => 'uid');
$this->additional_fields['uid'] = ['table' => 'users_field_data', 'field' => 'uid'];
}
public function query() {
@ -75,12 +75,11 @@ class Permissions extends PrerenderList {
}
public function preRender(&$values) {
$uids = array();
$this->items = array();
$this->items = [];
$permission_names = \Drupal::service('user.permissions')->getPermissions();
$rids = array();
$rids = [];
foreach ($values as $result) {
$user_rids = $this->getEntity($result)->getRoles();
$uid = $this->getValue($result);
@ -100,15 +99,13 @@ class Permissions extends PrerenderList {
}
}
foreach ($uids as $uid) {
if (isset($this->items[$uid])) {
ksort($this->items[$uid]);
}
foreach ($this->items as &$permission) {
ksort($permission);
}
}
}
function render_item($count, $item) {
public function render_item($count, $item) {
return $item['permission'];
}

View file

@ -55,7 +55,7 @@ class Roles extends PrerenderList {
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$this->additional_fields['uid'] = array('table' => 'users_field_data', 'field' => 'uid');
$this->additional_fields['uid'] = ['table' => 'users_field_data', 'field' => 'uid'];
}
public function query() {
@ -64,8 +64,8 @@ class Roles extends PrerenderList {
}
public function preRender(&$values) {
$uids = array();
$this->items = array();
$uids = [];
$this->items = [];
foreach ($values as $result) {
$uids[] = $this->getValue($result);
@ -73,7 +73,7 @@ class Roles extends PrerenderList {
if ($uids) {
$roles = user_roles();
$result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles)));
$result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', [':uids[]' => $uids, ':rids[]' => array_keys($roles)]);
foreach ($result as $role) {
$this->items[$role->uid][$role->rid]['role'] = $roles[$role->rid]->label();
$this->items[$role->uid][$role->rid]['rid'] = $role->rid;
@ -90,7 +90,7 @@ class Roles extends PrerenderList {
}
}
function render_item($count, $item) {
public function render_item($count, $item) {
return $item['role'];
}

View file

@ -25,7 +25,7 @@ class UserBulkForm extends BulkForm {
foreach ($this->view->result as $row_index => $result) {
$account = $result->_entity;
if ($account instanceof UserInterface) {
$form[$this->options['id']][$row_index]['#title'] = $this->t('Update the user %name', array('%name' => $account->label()));
$form[$this->options['id']][$row_index]['#title'] = $this->t('Update the user %name', ['%name' => $account->label()]);
}
}
}

View file

@ -58,8 +58,8 @@ class UserData extends FieldPluginBase {
protected function defineOptions() {
$options = parent::defineOptions();
$options['data_module'] = array('default' => '');
$options['data_name'] = array('default' => '');
$options['data_module'] = ['default' => ''];
$options['data_name'] = ['default' => ''];
return $options;
}
@ -71,25 +71,25 @@ class UserData extends FieldPluginBase {
parent::buildOptionsForm($form, $form_state);
$modules = $this->moduleHandler->getModuleList();
$names = array();
$names = [];
foreach (array_keys($modules) as $name) {
$names[$name] = $this->moduleHandler->getName($name);
}
$form['data_module'] = array(
$form['data_module'] = [
'#title' => $this->t('Module name'),
'#type' => 'select',
'#description' => $this->t('The module which sets this user data.'),
'#default_value' => $this->options['data_module'],
'#options' => $names,
);
];
$form['data_name'] = array(
$form['data_name'] = [
'#title' => $this->t('Name'),
'#type' => 'textfield',
'#description' => $this->t('The name of the data key.'),
'#default_value' => $this->options['data_name'],
);
];
}
/**

View file

@ -19,9 +19,9 @@ class Name extends InOperator {
protected $alwaysMultiple = TRUE;
protected function valueForm(&$form, FormStateInterface $form_state) {
$users = $this->value ? User::loadMultiple($this->value) : array();
$users = $this->value ? User::loadMultiple($this->value) : [];
$default_value = EntityAutocomplete::getEntityLabels($users);
$form['value'] = array(
$form['value'] = [
'#type' => 'entity_autocomplete',
'#title' => $this->t('Usernames'),
'#description' => $this->t('Enter a comma separated list of user names.'),
@ -29,7 +29,7 @@ class Name extends InOperator {
'#tags' => TRUE,
'#default_value' => $default_value,
'#process_default_value' => $this->isExposed(),
);
];
$user_input = $form_state->getUserInput();
if ($form_state->get('exposed') && !isset($user_input[$this->options['expose']['identifier']])) {
@ -40,13 +40,13 @@ class Name extends InOperator {
protected function valueValidate($form, FormStateInterface $form_state) {
$uids = [];
if ($values = $form_state->getValue(array('options', 'value'))) {
if ($values = $form_state->getValue(['options', 'value'])) {
foreach ($values as $value) {
$uids[] = $value['target_id'];
}
sort($uids);
}
$form_state->setValue(array('options', 'value'), $uids);
$form_state->setValue(['options', 'value'], $uids);
}
public function acceptExposedInput($input) {
@ -105,7 +105,7 @@ class Name extends InOperator {
public function adminSummary() {
// set up $this->valueOptions for the parent summary
$this->valueOptions = array();
$this->valueOptions = [];
if ($this->value) {
$result = \Drupal::entityTypeManager()->getStorage('user')

View file

@ -88,7 +88,7 @@ class Permissions extends ManyToOne {
*/
public function query() {
// @todo user_role_names() should maybe support multiple permissions.
$rids = array();
$rids = [];
// Get all role IDs that have the configured permissions.
foreach ($this->value as $permission) {
$roles = user_role_names(FALSE, $permission);

View file

@ -62,7 +62,7 @@ class Roles extends ManyToOne {
/**
* Override empty and not empty operator labels to be clearer for user roles.
*/
function operators() {
public function operators() {
$operators = parent::operators();
$operators['empty']['title'] = $this->t("Only has the 'authenticated user' role");
$operators['not empty']['title'] = $this->t("Has roles in addition to 'authenticated user'");
@ -73,7 +73,7 @@ class Roles extends ManyToOne {
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = array();
$dependencies = [];
foreach ($this->value as $role_id) {
$role = $this->roleStorage->load($role_id);
$dependencies[$role->getConfigDependencyKey()][] = $role->getConfigDependencyName();

View file

@ -27,16 +27,16 @@ class Users extends WizardPluginBase {
/**
* Set default values for the filters.
*/
protected $filters = array(
'status' => array(
protected $filters = [
'status' => [
'value' => TRUE,
'table' => 'users_field_data',
'field' => 'status',
'plugin_id' => 'boolean',
'entity_type' => 'user',
'entity_field' => 'status',
)
);
]
];
/**
* {@inheritdoc}