You are here

class UserSaveHandler in Services Client 7.2

Hierarchy

Expanded class hierarchy of UserSaveHandler

2 string references to 'UserSaveHandler'
services_client_migrate_hook in ./services_client.legacy.inc
Migrate old hook with mapping to new system.
services_client_services_client_event_handler in ./services_client.plugins.inc
List availalable event handler plugins.

File

include/event.inc, line 1262

View source
class UserSaveHandler extends EntitySaveHandler {
  public function getDefaultConfiguration() {
    $config = parent::getDefaultConfiguration();
    $config += array(
      'user_map_roles' => 0,
      'user_sync_by_name' => 0,
      'user_map_roles_map' => array(),
    );
    return $config;
  }

  /**
   * Config form.
   */
  public function configForm(&$form, &$form_state) {
    parent::configForm($form, $form_state);
    $form['user_config'] = array(
      '#prefix' => '<div id="user-config-wrapper">',
      '#suffix' => '</div>',
      '#type' => 'fieldset',
      '#title' => t('User configuration'),
      '#tree' => FALSE,
    );
    $form['user_config']['user_sync_by_name'] = array(
      '#type' => 'checkbox',
      '#title' => t('Sync by names'),
      '#description' => t('Check if users should be synced by names rather by UUID.'),
      '#default_value' => $this->config['user_sync_by_name'],
    );
    $form['user_config']['user_map_roles'] = array(
      '#type' => 'checkbox',
      '#title' => t('Map user roles'),
      '#description' => t('Check if user roles should be mapped from local site to remote'),
      '#default_value' => $this->config['user_map_roles'],
    );
    $form['user_config']['user_map_roles_widget'] = array(
      '#type' => 'fieldset',
      '#title' => t('Roles mapping'),
      '#tree' => TRUE,
    );

    // Calculate how many rows
    $rows = !empty($form_state['user_roles_count']) ? $form_state['user_roles_count'] : count($this->config['user_map_roles_map']) + 1;
    if (empty($form_state['user_roles_count'])) {
      $form_state['user_roles_count'] = $rows;
    }
    $form['user_config']['user_map_roles_widget']['#theme'] = 'services_client_mapping_rows';
    $local_roles = array(
      '' => '< ' . t('none') . ' >',
    ) + user_roles(TRUE);
    $remote_roles = $this
      ->getRemoteRoles();
    for ($i = 0; $i < $rows; $i++) {
      $form['user_config']['user_map_roles_widget'][$i]['local'] = array(
        '#type' => 'select',
        '#title' => t('Local'),
        '#default_value' => isset($this->config['user_map_roles_map'][$i]['local']) ? $this->config['user_map_roles_map'][$i]['local'] : '',
        '#options' => $local_roles,
      );
      if (empty($remote_roles)) {
        $form['user_config']['user_map_roles_widget'][$i]['remote'] = array(
          '#type' => 'textfield',
          '#title' => t('Remote'),
          '#default_value' => isset($this->config['user_map_roles_map'][$i]['remote']) ? $this->config['user_map_roles_map'][$i]['remote'] : '',
        );
      }
      else {
        $form['user_config']['user_map_roles_widget'][$i]['remote'] = array(
          '#type' => 'select',
          '#title' => t('Remote'),
          '#default_value' => isset($this->config['user_map_roles_map'][$i]['remote']) ? $this->config['user_map_roles_map'][$i]['remote'] : '',
          '#options' => array(
            '' => '< ' . t('none') . ' >',
          ) + drupal_map_assoc(array_values($remote_roles)),
        );
      }
      $form['user_config']['user_map_roles_widget']['add_row'] = array(
        '#type' => 'submit',
        '#value' => t('Add row'),
        '#submit' => array(
          'services_client_plugin_mapping_role_add_row',
        ),
        '#ajax' => array(
          'callback' => 'services_client_plugin_mapping_role_ajax',
          'wrapper' => 'user-config-wrapper',
        ),
        '#weight' => 100,
      );
    }
    $form['user_config']['user_map_roles_remote'] = array(
      '#markup' => '<p>' . t('Available roles') . '</p><pre>' . check_plain($this
        ->debugObject($remote_roles)) . '</pre>',
    );
    $form['user_config']['user_map_roles_remote_refresh'] = array(
      '#type' => 'submit',
      '#value' => t('Refresh roles'),
      '#submit' => array(
        'services_client_plugin_mapping_roles_refresh',
      ),
      '#ajax' => array(
        'callback' => 'services_client_plugin_mapping_role_ajax',
        'wrapper' => 'user-config-wrapper',
      ),
      '#weight' => 100,
    );
  }

  /**
   * Override get remote id. This allows to sync users by name.
   *
   * @throws ServicesClientConnectionResponseException
   */
  public function getRemoteEntityId() {
    if (!empty($this->config['user_sync_by_name'])) {
      $entity = $this
        ->getEntity();
      $name = isset($entity->original->name) ? $entity->original->name : $entity->name;
      $result = $this
        ->getConnection()
        ->index('user', 'uid,name', array(
        'name' => $name,
      ));
      if (!empty($result[0]['uid'])) {
        return $result[0]['uid'];
      }
    }
    else {
      return parent::getRemoteEntityId();
    }
  }

  /**
   * Form submit.
   */
  public function configFormSubmit(&$form, &$form_state) {
    parent::configFormSubmit($form, $form_state);
    $this->config['user_map_roles'] = $form_state['values']['user_map_roles'];
    $this->config['user_sync_by_name'] = $form_state['values']['user_sync_by_name'];

    // Store role mapping
    $this->config['user_map_roles_map'] = array();
    $i = 0;
    foreach (array_keys($form_state['values']['user_map_roles_widget']) as $key) {
      if ($key !== 'add_row') {
        $local = $form_state['values']['user_map_roles_widget'][$key]['local'];
        $remote = $form_state['values']['user_map_roles_widget'][$key]['remote'];
        if (!empty($local) && !empty($remote)) {
          $this->config['user_map_roles_map'][$i++] = array(
            'local' => $local,
            'remote' => $remote,
          );
        }
      }
    }
  }

  /**
   * Add role mapping.
   */
  public function beforeSync($object) {
    if (!empty($this->config['user_map_roles'])) {
      $account = $this
        ->getEntity();

      // Build map of role to format [local_role_id] => [remote_role_name]
      $map = array();
      foreach ($this->config['user_map_roles_map'] as $id => $row) {
        $map[$row['local']] = $row['remote'];
      }

      // Load remote roles in format [remote_role_name] => [remote_role_id]
      $remote_roles = array_flip($this
        ->getRemoteRoles());

      // Build list of roles that will be attached to object
      $roles = array();

      // First we need to make sure that we have roles to map and also remote_roles
      // list isn't empty.
      if (!empty($map) && !empty($remote_roles)) {
        foreach ($map as $local_rid => $remote_role) {

          // Foreach local role, check if role is attached to local user account
          // and if we have remote role.
          if (isset($account->roles[$local_rid]) && isset($remote_roles[$remote_role])) {
            $roles[$remote_roles[$remote_role]] = $remote_role;
          }
        }
      }

      // If some mapping was created, attach roles.
      if (!empty($roles)) {
        $object->roles = $roles;
      }
    }
  }

  /**
   * Get list of remote roles.
   *
   * @return array
   *   Remote connection roles.
   */
  protected function getRemoteRoles() {
    $cid = 'services_client:remote_roles:' . $this->event->connection;
    $roles = array();
    if ($cache = cache_get($cid)) {
      $roles = $cache->data;
    }
    else {
      try {
        $roles = $this
          ->getConnection()
          ->action('user', 'list_roles');
        cache_set($cid, $roles, 'cache', time() + 60 * 60);
      } catch (ServicesClientConnectionResponseException $e) {
        $e
          ->log();
        $roles = array();
      }
    }
    return $roles;
  }

  /**
   * Force refreshing list of remote roles.
   */
  public function refreshRemoteRoles() {
    cache_clear_all('services_client:remote_roles:' . $this->event->connection, 'cache');
    return $this
      ->getRemoteRoles();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
EntitySaveHandler::doSync protected function Execute sync action. Overrides EventHandler::doSync
EntitySaveHandler::execute public function Execute event and send event to remove endpoint. Overrides EventHandler::execute
EntitySaveHandler::getMappedObject protected function Retrieve object that should be send to remote site.
EventHandler::$connection protected property Holds connection to remote server.
EventHandler::$entity protected property Processed drupal entity in event.
EventHandler::$plugin_instances protected property Initialized plugin classes.
EventHandler::$tags protected property Stores tags assigned to event.
EventHandler::addPlugin public function Add configuration plugin.
EventHandler::addTag public function Add event tag.
EventHandler::afterSync protected function Allow plugin to react on before sync event.
EventHandler::breakEditLock public function Break any edit lock for current event.
EventHandler::clearObjectCache public function Clear current object cache.
EventHandler::debugObject protected function Retrieve printed version of any variable. Should be used for logging.
EventHandler::enqueue public function Enqueue item if should be queue.
EventHandler::enqueueEntity protected function Put current entity to queue.
EventHandler::generateUuid protected function Generates a UUID v4 using PHP code.
EventHandler::getBaseUrl public function Retrieve UI base url for event.
EventHandler::getConnection protected function Retrieves event connection to remote site.
EventHandler::getConnectionId protected function Retrieve remote connection id.
EventHandler::getControlData protected function Retrieve controll data for current entity.
EventHandler::getEditLock public function Retrieve edit lock if exists (other user is editing same event).
EventHandler::getEntity public function Retrieve current event entity.
EventHandler::getEntityId public function Retrieve entity ID.
EventHandler::getEvent public function Retrieve event definition.
EventHandler::getObjectCache public function Retrieve object cached version of event.
EventHandler::getObjectCacheOrCache public function Retrieve current object from cache. If not currently in object cache adds object to object cache.
EventHandler::getPlugin public function Retrieve existing plugin.
EventHandler::getPluginInstance protected function Retrieve plugin instance by name and configuration.
EventHandler::getRemoteIdByUUID protected function Load remote ID by UUID based on remote UUID configuration.
EventHandler::getUrl public function Get path prefixed with event specific URL.
EventHandler::hasTag public function Check if event has specific tag.
EventHandler::isAutoTriggered public function Determine weather event should be fired automatically on drupal object action like node_save or node_delete.
EventHandler::isChanged public function Determine weather object has been changed by editing configuration and not which isn't stored in permanent storage.
EventHandler::isMatching public function Determine wheather entity is matching event conditions.
EventHandler::log protected function Log messages to Drupal watchdog.
EventHandler::logErrorResult protected function Log error result from services client operation.
EventHandler::objectCached public function Retrieve instance of object initialized with object cache.
EventHandler::removePlugin public function Remove existing plugin from configuration. This does is not saved to DB until save() method is called.
EventHandler::removeTag public function Remove tag from event.
EventHandler::save public function Save current event configuration to database.
EventHandler::setConnection public function Set new connection to remote site.
EventHandler::setEntity public function Set entity for current event.
EventHandler::setObjectCache public function Store current object state to object cache.
EventHandler::setPluginConfig public function Update plugin configuration. This does is not saved to DB until save() method is called.
EventHandler::skipAutosync public function Return TRUE if this entity shouldn't be send automatically to all connections.
EventHandler::__construct public function Constructor. Overrides ServicesClientPlugin::__construct
ServicesClientPlugin::$config protected property Plugin specific configuration
ServicesClientPlugin::$event protected property Event definition
ServicesClientPlugin::configFormValidate public function Validate configuration form. Overrides ServicesClientConfigurableInterface::configFormValidate 1
ServicesClientPlugin::getConfiguration public function Retrieve current plugin configuration. Overrides ServicesClientConfigurableInterface::getConfiguration
ServicesClientPlugin::setConfiguration public function Set configuration of plugin. Overrides ServicesClientConfigurableInterface::setConfiguration
UserSaveHandler::beforeSync public function Add role mapping. Overrides EventHandler::beforeSync
UserSaveHandler::configForm public function Config form. Overrides EntitySaveHandler::configForm
UserSaveHandler::configFormSubmit public function Form submit. Overrides EventHandler::configFormSubmit
UserSaveHandler::getDefaultConfiguration public function Retrieve default event configuration. Overrides EntitySaveHandler::getDefaultConfiguration
UserSaveHandler::getRemoteEntityId public function Override get remote id. This allows to sync users by name. Overrides EventHandler::getRemoteEntityId
UserSaveHandler::getRemoteRoles protected function Get list of remote roles.
UserSaveHandler::refreshRemoteRoles public function Force refreshing list of remote roles.