You are here

class clients_connection_drupal_services in Web Service Clients 7

Same name and namespace in other branches
  1. 6.2 connections/clients_drupal/clients_drupal.inc \clients_connection_drupal_services
  2. 7.3 connections/clients_drupal/clients_drupal.inc \clients_connection_drupal_services
  3. 7.2 connections/clients_drupal/clients_drupal.inc \clients_connection_drupal_services

General Drupal client class.

This should connect to Drupal 7 services. Which are still at the RC stage... so it's largely an abstract class for the moment.

Hierarchy

Expanded class hierarchy of clients_connection_drupal_services

File

backends/clients_drupal/clients_drupal.inc, line 14
Defines methods and calls to Drupal services

View source
class clients_connection_drupal_services extends clients_connection_base {

  // ============================================ Connection form methods.

  /**
   * Form builder for adding or editing connections of this class.
   *
   * Static function, call without an object.
   *
   * This (so far) is common to all versions of Drupal Services.
   *
   * @param $type
   *  The type of the connection.
   * @param $cid
   * (optional) The id of the connection, if this is an edit.
   *
   * @return
   *  A FormAPI form array. This will be merged in with basic data and the
   *  submit button added.
   *
   * @see clients_connection_add()
   * @see clients_connection_edit()
   */
  static function connectionSettingsForm(&$form_state, $type, $cid = NULL) {
    $form = array();
    if (is_null($cid)) {
      $new = TRUE;
      $connection_types = clients_get_connection_types();
      drupal_set_title(t('Add @type connection', array(
        '@type' => $connection_types[$type]['label'],
      )));
    }
    else {
      $connection = clients_connection_load((int) $cid);
      $form['cid'] = array(
        '#type' => 'value',
        '#value' => $cid,
      );
    }
    $form['type'] = array(
      '#type' => 'value',
      '#value' => $type,
    );
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Connection name'),
      '#default_value' => $cid ? $connection->name : '',
      '#size' => 50,
      '#maxlength' => 100,
      '#description' => t('Must be unique, any characters allowed'),
      '#required' => TRUE,
    );
    $form['endpoint'] = array(
      '#type' => 'textfield',
      '#title' => t('Connection endpoint'),
      '#default_value' => $cid ? $connection->endpoint : '',
      '#size' => 50,
      '#maxlength' => 100,
      '#description' => t('Remote service URL e.g. http://mysite.com/services/xmlrpc'),
      '#required' => TRUE,
    );
    $form['configuration'] = array(
      '#type' => 'fieldset',
      '#title' => t('Configuration'),
      '#collapsible' => FALSE,
      '#tree' => TRUE,
    );
    $form['configuration']['domain'] = array(
      '#type' => 'textfield',
      '#title' => t('Domain'),
      '#default_value' => $cid ? $connection->configuration['domain'] : '',
      '#size' => 50,
      '#maxlength' => 100,
      '#description' => t('This should be same as the \'Domain\' field used by the Services authentication key on the server you are connecting to.'),
      '#required' => TRUE,
    );
    $form['configuration']['servicekey'] = array(
      '#type' => 'textfield',
      '#title' => t('Service key'),
      '#default_value' => $cid ? $connection->configuration['servicekey'] : '',
      '#size' => 50,
      '#maxlength' => 40,
      '#attributes' => array(
        'autocomplete' => 'off',
      ),
      '#description' => t('This should be same as the \'Key\' field used by the Services authentication key on the server you are connecting to.'),
      '#required' => TRUE,
    );
    $form['configuration']['username'] = array(
      '#type' => 'textfield',
      '#title' => t('Service username'),
      '#default_value' => $cid ? $connection->configuration['username'] : '',
      '#size' => 30,
      '#maxlength' => 60,
      '#attributes' => array(
        'autocomplete' => 'off',
      ),
      '#description' => t('This should be same as the username on the server you are connecting to.'),
      '#required' => TRUE,
    );
    $password_desc = $cid ? t('This should be same as the password on the server you are connecting to. Leave blank unless you need to change this.') : 'This should be same as the password on the server you are connecting to.';
    $form['configuration']['password'] = array(
      '#type' => 'password',
      '#title' => t('Service password'),
      '#size' => 30,
      '#maxlength' => 60,
      '#attributes' => array(
        'autocomplete' => 'off',
      ),
      '#description' => $password_desc,
      '#required' => $new,
    );
    $form['configuration']['methods_enabled'] = array(
      '#type' => 'textarea',
      '#title' => t('Services'),
      '#default_value' => $cid ? $connection->configuration['methods_enabled'] : '',
      '#description' => t('List of Drupal services on remote servers that you want to enable here (e.g. views.service). Resources can select from this list. One per line.'),
    );
    $form['configuration']['views_enabled'] = array(
      '#type' => 'textarea',
      '#title' => t('Views'),
      '#default_value' => $cid ? $connection->configuration['views_enabled'] : '',
      '#description' => t('List of Drupal views on remote servers. Resources can select from this list. One per line.'),
    );
    return $form;
  }

  /**
   * Submit handler for saving/updating connections of this class.
   *
   * @see clients_connection_form_submit().
   */
  static function connectionSettingsForm_submit($form, &$form_state) {

    // Presence of the cid tells us whether we're editing or adding a new connection.
    $new = !isset($form_state['values']['cid']);
    if ($new) {
      $form_state['values']['configuration']['password'] = clients_drupal_encrypt($form_state['values']['configuration']['password']);
    }
    else {

      // Prepare password for serialized storage
      if (empty($form_state['values']['configuration']['password'])) {

        // Need to load connection and set password to original if blank
        $original = clients_connection_load((int) $form_state['values']['cid']);
        $form_state['values']['configuration']['password'] = $original->configuration['password'];
      }
      $form_state['values']['configuration']['password'] = clients_drupal_encrypt($form_state['values']['configuration']['password']);
    }
  }

  // ============================================ Constructor.

  /**
   * Constructor method.
   *
   * @param $connection_data
   *  An object containing connection data, as returned from clients_connection_load().
   */
  function __construct($connection_data) {

    // Call the base class to set the connection properties.
    parent::__construct($connection_data);

    // Decrypt the password.
    $this->configuration['password'] = clients_drupal_decrypt($this->configuration['password']);
  }

  // ============================================ Connection API.

  /**
   * Call a remote method.
   *
   * @param $method
   *  The name of the remote method to call.
   * @param
   *  All other parameters are passed to the remote method.
   *  Note that the D5 version of Services does not seem to respect optional parameters; you
   *  should pass in defaults (eg an empty string or 0) instead of omitting a parameter.
   *
   * @return
   *  Whatever is returned from the remote site.
   */
  function callMethod($method) {

    // TODO: Needs to be written for Services D7.

    //dsm($method);
  }

  // ===================================== old static stuff

  /**
   * Use for testing
   */
  public static function connect($connection) {
    $session = xmlrpc($connection->endpoint, 'system.connect');
    if ($session === FALSE) {
      return xmlrpc_error();

      // null for services 2...
    }
    return $session;
  }

  /**
   * Prepares a hashed token for the service, based on current time,
   * the required service and config values; serviceKey and serviceDomain
   *t
   * @param $connection
   *   stdClass: A service connection as returned by Clients::load()
   * @param $serviceMethod
   *   string: Name of service method to access
   *
   * @return
   *   array a valid token
   */
  public static function getToken($connection, $serviceMethod) {
    $timestamp = (string) time();
    $nonce = uniqid();
    $hashParameters = array(
      $timestamp,
      $connection->configuration['domain'],
      $nonce,
      $serviceMethod,
    );
    $hash = hash_hmac("sha256", implode(';', $hashParameters), $connection->configuration['servicekey']);
    return array(
      'hash' => $hash,
      'domain' => $connection->configuration['domain'],
      'timestamp' => $timestamp,
      'nonce' => $nonce,
    );
  }

  /**
   * Connects to Drupal Services and logs in the user provided in the config.
   * Returns a session for the user.
   * @todo needs error catching in case service is down
   *
   * @return
   *   array
   */
  public static function getUser($connection) {
    $session = self::connect($connection);
    if ($session->is_error == TRUE) {
      drupal_set_message('There was an error connecting to the service.');
      return;
    }
    $userToken = self::getToken($connection, 'user.login');
    $user = xmlrpc($connection->endpoint, 'user.login', $userToken['hash'], $userToken['domain'], $userToken['timestamp'], $userToken['nonce'], $session['sessid'], $connection->configuration['username'], $connection->configuration['password']);
    if ($user === FALSE) {
      return xmlrpc_error();
    }
    return $user;
  }

  /**
   * Gets raw data from service call
   */
  protected static function fetch($connection, $resource, $user) {
    $cacheid = md5($connection->name . implode($resource->configuration['options']));

    // user is stdClass if xmlrpc_error()...
    if (!is_array($user) || !isset($user['sessid'])) {

      // @todo watchdog
      drupal_set_message($user->message, 'error');
      return;
    }
    $token = self::getToken($connection, $resource->configuration['options']['method']);

    // catch empty arguments
    $arguments = array_values($resource->configuration['options']['arguments']);
    $arguments = trim($arguments[0]) != '' ? $arguments : array();
    $result = parent::doCall('xmlrpc', $cacheid, $connection->endpoint, $resource->configuration['options']['method'], $token['hash'], $token['domain'], $token['timestamp'], $token['nonce'], $user['sessid'], $resource->configuration['options']['view'], NULL, $arguments, (int) $resource->configuration['options']['offset'], (int) $resource->configuration['options']['limit']);
    return $result;
  }

  /**
   * Executes call and processes data
   */
  public static function call($connection, $resource) {
    if ($resource->configuration['options']['method'] == 'views.get') {
      $user = self::getUser($connection);

      // gets raw result
      $result = self::fetch($connection, $resource, $user);

      // needs some post-processing
      $processed_result = new stdClass();
      $processed_result->created = $result->created;
      $processed_result->data = array();
      foreach ($result->data as $item) {
        foreach ($item as $k => $v) {

          // handle CCK field data structure
          if (strpos($k, 'field_') !== FALSE) {
            $item[$k] = $v[0]['value'];
          }
        }

        // nid will interfere with local nids in client
        $item['remote_nid'] = $item['nid'];
        unset($item['nid']);

        // remote taxonomy is not understood locally so flatten to RSS-style bag of tags (TODO: develop this to preserve vocabs)
        $tags = array();
        if (isset($item['taxonomy'])) {
          foreach ((array) $item['taxonomy'] as $term) {
            $tags = $term['name'];
          }
          unset($item['taxonomy']);
        }
        $item['tags'] = $tags;
        $processed_result->data[] = $item;
      }
      return $processed_result;
    }

    // else method not supported yet
  }

}

Members

Namesort descending Modifiers Type Description Overrides
clients_connection_base::$cid public property
clients_connection_base::$configuration public property
clients_connection_base::$endpoint public property
clients_connection_base::$name public property
clients_connection_base::doCall protected static function Takes variable number of params after cacheid.
clients_connection_base::getTestOperations function Provide buttons for the connection testing page. 1
clients_connection_drupal_services::call public static function Executes call and processes data Overrides clients_connection_base::call
clients_connection_drupal_services::callMethod function Call a remote method. 1
clients_connection_drupal_services::connect public static function Use for testing
clients_connection_drupal_services::connectionSettingsForm static function Form builder for adding or editing connections of this class.
clients_connection_drupal_services::connectionSettingsForm_submit static function Submit handler for saving/updating connections of this class. Overrides clients_connection_base::connectionSettingsForm_submit
clients_connection_drupal_services::fetch protected static function Gets raw data from service call
clients_connection_drupal_services::getToken public static function Prepares a hashed token for the service, based on current time, the required service and config values; serviceKey and serviceDomain t
clients_connection_drupal_services::getUser public static function Connects to Drupal Services and logs in the user provided in the config. Returns a session for the user. @todo needs error catching in case service is down
clients_connection_drupal_services::__construct function Constructor method. Overrides clients_connection_base::__construct