Skip to content
Snippets Groups Projects
Unverified Commit 635e50bc authored by weaver299's avatar weaver299 Committed by GitHub
Browse files

Merge pull request #397 from ASCWebServices/canini-2

Removing drupal/realname (1.0.0-rc2)
parents 2bf3b254 1cfe7e0d
No related merge requests found
Showing with 0 additions and 559 deletions
realname.admin_settings_form:
path: '/admin/config/people/realname'
defaults:
_form: 'Drupal\realname\Form\RealnameAdminSettingsForm'
_title: 'Real name'
requirements:
_permission: 'administer realname'
services:
realname.config_cache_tag:
class: Drupal\realname\EventSubscriber\ConfigCacheTag
arguments: ['@cache_tags.invalidator']
tags:
- { name: event_subscriber }
realname.route.subscriber:
class: Drupal\realname\Routing\RealnameRouteSubscriber
tags:
- { name: event_subscriber }
<?php
/**
* @file
* Views integration for the realname module.
*/
/**
* Implements hook_views_data().
*/
function realname_views_data() {
$data['realname']['table']['group'] = t('Realname');
$data['realname']['table']['join'] = [
'users' => [
'left_field' => 'uid',
'field' => 'uid',
],
];
$data['realname']['realname'] = [
'title' => t('Real name'),
'help' => t("The user's real name."),
'field' => [
'handler' => 'views_handler_field_user',
'click sortable' => TRUE,
],
'sort' => [
'handler' => 'views_handler_sort',
],
'argument' => [
'handler' => 'views_handler_argument_string',
],
'filter' => [
'handler' => 'views_handler_filter_string',
'title' => t('Name'),
'help' => t("The user's real name. This filter does not check if the user exists and allows partial matching. Does not utilize autocomplete."),
],
];
return $data;
}
<?php
namespace Drupal\realname\Controller;
use Drupal\system\Controller\EntityAutocompleteController;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Tags;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Site\Settings;
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
* Defines a route controller for entity autocomplete form elements.
*/
class RealnameAutocompleteController extends EntityAutocompleteController {
/**
* {@inheritdoc}
*/
public function handleAutocomplete(Request $request, $target_type, $selection_handler, $selection_settings_key) {
if ($target_type != 'user') {
return parent::handleAutocomplete($request, $target_type, $selection_handler, $selection_settings_key);
}
$matches = [];
if ($input = $request->query->get('q')) {
$typed_string = Tags::explode($input);
$typed_string = Unicode::strtolower(array_pop($typed_string));
$selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
if ($selection_settings !== FALSE) {
$selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
if ($selection_settings_hash !== $selection_settings_key) {
throw new AccessDeniedHttpException('Invalid selection settings key.');
}
}
else {
throw new AccessDeniedHttpException();
}
$matches = $this->getMatches($selection_settings, $typed_string);
}
return new JsonResponse($matches);
}
/**
* Gets matched labels based on a given search string.
*
* @param array $selection_settings
* An array of settings that will be passed to the selection handler.
* @param string $string
* (optional) The label of the entity to query by.
*
* @return array
* An array of matched entity labels, in the format required by the AJAX
* autocomplete API (e.g. array('value' => $value, 'label' => $label)).
*
* @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
* Thrown when the current user doesn't have access to the specified entity.
*/
protected function getMatches($selection_settings, $string = '') {
$matches = [];
if (isset($string)) {
// Get an array of matching entities.
$match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
$include_anonymous = isset($selection_settings['include_anonymous']) ? $selection_settings['include_anonymous'] : TRUE;
$connection = \Drupal::database();
$query = $connection->select('users_field_data', 'u');
$query->fields('u', ['uid']);
$query->leftJoin('realname', 'rn', 'u.uid = rn.uid');
if ($match_operator == 'CONTAINS') {
$query->condition((new Condition('OR'))
->condition('rn.realname', '%' . $connection->escapeLike($string) . '%', 'LIKE')
->condition('u.name', '%' . $connection->escapeLike($string) . '%', 'LIKE')
);
}
else {
$query->condition((new Condition('OR'))
->condition('rn.realname', $connection->escapeLike($string) . '%', 'LIKE')
->condition('u.name', $connection->escapeLike($string) . '%', 'LIKE')
);
}
if ($include_anonymous == FALSE) {
$query->condition('u.uid', 0, '>');
}
$query->range(0, 10);
$uids = $query->execute()->fetchCol();
$accounts = User::loadMultiple($uids);
/* @var $account User */
foreach ($accounts as $account) {
$matches[] = [
'value' => t('@realname (@id)', ['@realname' => $account->getDisplayName(), '@id' => $account->id()]),
'label' => t('@realname (@username)', ['@realname' => $account->getDisplayName(), '@username' => $account->getAccountName()]),
];
}
}
return $matches;
}
}
<?php
namespace Drupal\realname\EventSubscriber;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* A subscriber invalidating cache tags when realname config objects are saved.
*/
class ConfigCacheTag implements EventSubscriberInterface {
/**
* The cache tags invalidator.
*
* @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
*/
protected $cacheTagsInvalidator;
/**
* Constructs a RealnameCacheTag object.
*
* @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
* The cache tags invalidator.
*/
public function __construct(CacheTagsInvalidatorInterface $cache_tags_invalidator) {
$this->cacheTagsInvalidator = $cache_tags_invalidator;
}
/**
* Invalidate cache tags when particular realname config objects are saved.
*
* @param \Drupal\Core\Config\ConfigCrudEvent $event
* The Event to process.
*/
public function onSave(ConfigCrudEvent $event) {
// Check if realname settings object has been changed.
if ($event->getConfig()->getName() === 'realname.settings') {
// Clear the realname cache if the pattern was changed.
realname_delete_all();
// A change to the display-name pattern must invalidate the render cache
// since the display-name could be used anywhere.
$this->cacheTagsInvalidator->invalidateTags(['rendered']);
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[ConfigEvents::SAVE][] = ['onSave'];
return $events;
}
}
<?php
namespace Drupal\realname\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configure Realname settings for this site.
*/
class RealnameAdminSettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'realname_admin_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['realname.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('realname.settings');
$form['general'] = [
'#type' => 'fieldset',
'#title' => $this->t('General settings'),
];
$note = '<div>';
$note .= $this->t('Note that if it is changed, all current Realnames will be deleted and the list in the database will be rebuilt as needed.');
$note .= '</div>';
$form['general']['realname_pattern'] = [
'#type' => 'textfield',
'#title' => $this->t('Realname pattern'),
'#default_value' => $config->get('pattern'),
'#element_validate' => ['token_element_validate'],
'#token_types' => ['user'],
'#min_tokens' => 1,
'#required' => TRUE,
'#maxlength' => 256,
'#description' => $this->t('This pattern will be used to construct Realnames for all users.') . $note,
];
// Add the token tree UI.
$form['general']['token_help'] = [
'#theme' => 'token_tree_link',
'#token_types' => ['user'],
'#global_types' => FALSE,
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$pattern = $form_state->getValue('realname_pattern');
// Tokens that will cause recursion.
$tokens = [
'[user:name]',
];
foreach ($tokens as $token) {
if (strpos($pattern, $token) !== FALSE) {
$form_state->setErrorByName('realname_pattern', $this->t('The %token token cannot be used as it will cause recursion.', ['%token' => $token]));
}
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('realname.settings');
if ($form['general']['realname_pattern']['#default_value'] != $form_state->getValue('realname_pattern')) {
$config->set('pattern', $form_state->getValue('realname_pattern'))->save();
}
parent::submitForm($form, $form_state);
}
}
<?php
namespace Drupal\realname\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
/**
* Update user real name.
*
* @Action(
* id = "realname_update_realname_action",
* label = @Translation("Update real name"),
* type = "user"
* )
*/
class RealnameUpdateRealname extends ActionBase {
/**
* {@inheritdoc}
*/
public function execute($account = NULL) {
realname_update($account);
}
/**
* {@inheritdoc}
*/
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
/** @var \Drupal\user\UserInterface $object */
$access = $object->status->access('edit', $account, TRUE)
->andIf($object->access('update', $account, TRUE));
return $return_as_object ? $access : $access->isAllowed();
}
}
<?php
namespace Drupal\realname\Plugin\migrate\process;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
/**
* If the source evaluates to empty, we skip the current row.
*
* @MigrateProcessPlugin(
* id = "realname_replace_token",
* handle_multiples = TRUE
* )
*/
class RealnameReplaceToken extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($realname_pattern) = $value;
// Previous D7 realname token need to be replaced by D8 core token.
//
// At least two tokens may exists:
// - [user:name-raw]
// - [current-user:name-raw]
return str_ireplace(':name-raw]', ':account-name]', $realname_pattern);
}
}
<?php
namespace Drupal\realname\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscriber for routes.
*/
class RealnameRouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('system.entity_autocomplete')) {
$route->setDefault('_controller', '\Drupal\realname\Controller\RealnameAutocompleteController::handleAutocomplete');
}
}
}
<?php
namespace Drupal\realname\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\user\Entity\User;
/**
* Test basic functionality of Realname module.
*
* @group Realname
*/
class RealnameBasicTest extends WebTestBase {
/**
* {@inheritdoc}
*/
public static $modules = [
'realname',
'field_ui',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$permissions = [
'access administration pages',
'administer modules',
'administer realname',
'administer site configuration',
'administer user fields',
'administer user form display',
'administer user display',
'administer users',
];
// User to set up realname.
$this->admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->admin_user);
}
/**
* Test realname configuration.
*/
public function testRealnameConfiguration() {
// Check if Configure link is available on 'Modules' page.
// Requires 'administer modules' permission.
$this->drupalGet('admin/modules');
$this->assertRaw('admin/config/people/realname', '[testRealnameConfiguration]: Configure link from Modules page to Realname settings page exists.');
// Check for setting page's presence.
$this->drupalGet('admin/config/people/realname');
$this->assertRaw(t('Realname pattern'), '[testRealnameConfiguration]: Settings page displayed.');
// Save form with allowed token.
$edit['realname_pattern'] = '[user:account-name]';
$this->drupalPostForm('admin/config/people/realname', $edit, t('Save configuration'));
$this->assertRaw(t('The configuration options have been saved.'), '[testRealnameConfiguration]: Settings form has been saved.');
// Check token recursion protection.
$edit['realname_pattern'] = '[user:name]';
$this->drupalPostForm('admin/config/people/realname', $edit, t('Save configuration'));
$this->assertRaw(t('The %token token cannot be used as it will cause recursion.', ['%token' => '[user:name]']), '[testRealnameConfiguration]: Invalid token found.');
}
/**
* Test realname alter functions.
*/
public function testRealnameUsernameAlter() {
// Add a test string and see if core username has been replaced by realname.
$edit['realname_pattern'] = '[user:account-name] (UID: [user:uid])';
$this->drupalPostForm('admin/config/people/realname', $edit, t('Save configuration'));
$this->drupalGet('user/' . $this->admin_user->id());
// @ @FIXME: Needs patch https://www.drupal.org/node/2629286
// $this->assertRaw($this->admin_user->getDisplayName(), '[testRealnameUsernameAlter]: Real name shown on user page.');
$this->drupalGet('user/' . $this->admin_user->id() . '/edit');
// @FIXME: Needs patch https://www.drupal.org/node/2629286
// $this->assertRaw($this->admin_user->getDisplayName(), '[testRealnameUsernameAlter]: Real name shown on user edit page.');
/** @var \Drupal\user\entity\User $user_account */
$user_account = $this->admin_user;
$username_before = $user_account->getAccountName();
$user_account->save();
$username_after = $user_account->getAccountName();
$this->assertEqual($username_before, $username_after, 'Username did not change after save');
}
/**
* Test realname display configuration.
*/
public function testRealnameManageDisplay() {
$edit['realname_pattern'] = '[user:account-name]';
$this->drupalPostForm('admin/config/people/realname', $edit, t('Save configuration'));
$this->drupalGet('admin/config/people/accounts/fields');
$this->assertTitle('Manage fields | Drupal');
$this->assertNoRaw('Real name', '[testRealnameManageDisplay]: Real name field not shown in manage fields list.');
$this->drupalGet('admin/config/people/accounts/form-display');
$this->assertTitle('Manage form display | Drupal');
$this->assertNoRaw('Real name', '[testRealnameManageDisplay]: Real name field not shown in manage form display list.');
$this->drupalGet('admin/config/people/accounts/display');
$this->assertTitle('Manage display | Drupal');
$this->assertRaw('Real name', '[testRealnameManageDisplay]: Real name field shown in manage display.');
// By default the realname field is not visible.
$this->drupalGet('user/' . $this->admin_user->id());
$this->assertNoText('Real name', '[testRealnameManageDisplay]: Real name field not visible on user page.');
// Make realname field visible on user page.
$this->drupalGet('admin/config/people/accounts/display');
$edit = ['fields[realname][region]' => 'content'];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertResponse(200);
$this->drupalGet('user/' . $this->admin_user->id());
$this->assertText('Real name', '[testRealnameManageDisplay]: Real name field visible on user page.');
}
/**
* Test realname user update.
*/
public function testRealnameUserUpdate() {
$edit['realname_pattern'] = '[user:account-name]';
$this->drupalPostForm('admin/config/people/realname', $edit, t('Save configuration'));
$user1 = User::load($this->admin_user->id());
$realname1 = $user1->realname;
// Update user name.
$user1->name = $this->randomMachineName();
$user1->save();
// Reload the user.
$user2 = User::load($this->admin_user->id());
$realname2 = $user2->realname;
// Check if realname changed.
$this->assertTrue($realname1);
$this->assertTrue($realname2);
$this->assertNotEqual($realname1, $realname2, '[testRealnameUserUpdate]: Real name changed.');
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment