You are here

class FeedsUserProcessor in Feeds 7

Same name and namespace in other branches
  1. 6 plugins/FeedsUserProcessor.inc \FeedsUserProcessor
  2. 7.2 plugins/FeedsUserProcessor.inc \FeedsUserProcessor

Feeds processor plugin. Create users from feed items.

Hierarchy

Expanded class hierarchy of FeedsUserProcessor

4 string references to 'FeedsUserProcessor'
FeedsCSVtoUsersTest::test in tests/feeds_processor_user.test
Test node creation, refreshing/deleting feeds and feed items.
FeedsMapperProfileTestCase::test in tests/feeds_mapper_profile.test
Basic test loading a doulbe entry CSV file.
feeds_import_feeds_importer_default in feeds_import/feeds_import.feeds_importer_default.inc
Implementation of hook_feeds_importer_default().
_feeds_feeds_plugins in ./feeds.plugins.inc
Break out for feeds_feed_plugins().

File

plugins/FeedsUserProcessor.inc, line 11
FeedsUserProcessor class.

View source
class FeedsUserProcessor extends FeedsProcessor {

  /**
   * Implements FeedsProcessor::process().
   */
  public function process(FeedsImportBatch $batch, FeedsSource $source) {

    // Count number of created and updated nodes.
    $created = $updated = $failed = 0;
    while ($item = $batch
      ->shiftItem()) {
      if (!($uid = $this
        ->existingItemId($batch, $source)) || $this->config['update_existing']) {

        // Map item to a term.
        $account = $this
          ->map($batch);

        // Check if user name and mail are set, otherwise continue.
        if (empty($account->name) || empty($account->mail) || !valid_email_address($account->mail)) {
          $failed++;
          continue;
        }

        // Add term id if available.
        if (!empty($uid)) {
          $account->uid = $uid;
        }

        // Save the user.
        user_save($account, (array) $account);
        if ($account->uid && $account->openid) {
          $authmap = array(
            'uid' => $account->uid,
            'module' => 'openid',
            'authname' => $account->openid,
          );
          if (SAVED_UPDATED != drupal_write_record('authmap', $authmap, array(
            'uid',
            'module',
          ))) {
            drupal_write_record('authmap', $authmap);
          }
        }
        if ($uid) {
          $updated++;
        }
        else {
          $created++;
        }
      }
    }

    // Set messages.
    if ($failed) {
      drupal_set_message(format_plural($failed, 'There was @number user that could not be imported because either their name or their email was empty or not valid. Check import data and mapping settings on User processor.', 'There were @number users that could not be imported because either their name or their email was empty or not valid. Check import data and mapping settings on User processor.', array(
        '@number' => $failed,
      )), 'error');
    }
    if ($created) {
      drupal_set_message(format_plural($created, 'Created @number user.', 'Created @number users.', array(
        '@number' => $created,
      )));
    }
    elseif ($updated) {
      drupal_set_message(format_plural($updated, 'Updated @number user.', 'Updated @number users.', array(
        '@number' => $updated,
      )));
    }
    else {
      drupal_set_message(t('There are no new users.'));
    }
  }

  /**
   * Implements FeedsProcessor::clear().
   */
  public function clear(FeedsBatch $batch, FeedsSource $source) {

    // Do not support deleting users as we have no way of knowing which ones we
    // imported.
    throw new Exception(t('User processor does not support deleting users.'));
  }

  /**
   * Execute mapping on an item.
   */
  protected function map(FeedsImportBatch $batch) {

    // Prepare term object.
    $target_account = new stdClass();
    $target_account->uid = 0;
    $target_account->entity_type = 'user';
    $target_account->roles = array_filter($this->config['roles']);
    $target_account->status = $this->config['status'];

    // Have parent class do the iterating.
    return parent::map($batch, $target_account);
  }

  /**
   * Override parent::configDefaults().
   */
  public function configDefaults() {
    return array(
      'roles' => array(),
      'update_existing' => FALSE,
      'status' => 1,
      'mappings' => array(),
    );
  }

  /**
   * Override parent::configForm().
   */
  public function configForm(&$form_state) {
    $form = array();
    $form['status'] = array(
      '#type' => 'radios',
      '#title' => t('Status'),
      '#description' => t('Select whether users should be imported active or blocked.'),
      '#options' => array(
        0 => t('Blocked'),
        1 => t('Active'),
      ),
      '#default_value' => $this->config['status'],
    );
    $roles = user_roles(TRUE);
    unset($roles[2]);
    if (count($roles)) {
      $form['roles'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Additional roles'),
        '#description' => t('Every user is assigned the "authenticated user" role. Select additional roles here.'),
        '#default_value' => $this->config['roles'],
        '#options' => $roles,
      );
    }

    // @todo Implement true updating.
    $form['update_existing'] = array(
      '#type' => 'checkbox',
      '#title' => t('Replace existing users'),
      '#description' => t('If an existing user is found for an imported user, replace it. Existing users will be determined using mappings that are a "unique target".'),
      '#default_value' => $this->config['update_existing'],
    );
    return $form;
  }

  /**
   * Set target element.
   */
  public function setTargetElement(&$target_item, $target_element, $value) {
    $target_item->{$target_element} = $value;
  }

  /**
   * Return available mapping targets.
   */
  public function getMappingTargets() {
    $targets = array(
      'name' => array(
        'name' => t('User name'),
        'description' => t('Name of the user.'),
        'optional_unique' => TRUE,
      ),
      'mail' => array(
        'name' => t('Email address'),
        'description' => t('Email address of the user.'),
        'optional_unique' => TRUE,
      ),
      'created' => array(
        'name' => t('Created date'),
        'description' => t('The created (e. g. joined) data of the user.'),
      ),
    );
    if (module_exists('openid')) {
      $targets['openid'] = array(
        'name' => t('OpenID identifier'),
        'description' => t('The OpenID identifier of the user. <strong>CAUTION:</strong> Use only for migration purposes, misconfiguration of the OpenID identifier can lead to severe security breaches like users gaining access to accounts other than their own.'),
        'optional_unique' => TRUE,
      );
    }

    // Let other modules expose mapping targets.
    self::loadMappers();
    feeds_alter('feeds_processor_targets', $targets, 'user');
    return $targets;
  }

  /**
   * Get id of an existing feed item term if available.
   */
  protected function existingItemId(FeedsImportBatch $batch, FeedsSource $source) {

    // Iterate through all unique targets and try to find a user for the
    // target's value.
    foreach ($this
      ->uniqueTargets($batch) as $target => $value) {
      switch ($target) {
        case 'name':
          $uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(
            ':name' => $value,
          ))
            ->fetchField();
          break;
        case 'mail':
          $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(
            ':mail' => $value,
          ))
            ->fetchField();
          break;
        case 'openid':
          $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname AND module = 'openid'", array(
            ':authname' => $value,
          ))
            ->fetchField();
          break;
      }
      if ($uid) {

        // Return with the first nid found.
        return $uid;
      }
    }
    return 0;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FeedsConfigurable::$config protected property
FeedsConfigurable::$disabled protected property CTools export enabled status of this object.
FeedsConfigurable::$export_type protected property
FeedsConfigurable::$id protected property
FeedsConfigurable::addConfig public function Similar to setConfig but adds to existing configuration.
FeedsConfigurable::configFormSubmit public function Submission handler for configForm(). 2
FeedsConfigurable::configFormValidate public function Validation handler for configForm(). 3
FeedsConfigurable::copy public function Copy a configuration. 1
FeedsConfigurable::existing public function Determine whether this object is persistent and enabled. I. e. it is defined either in code or in the database and it is enabled. 1
FeedsConfigurable::getConfig public function Implements getConfig(). 1
FeedsConfigurable::instance public static function Instantiate a FeedsConfigurable object. 1
FeedsConfigurable::setConfig public function Set configuration.
FeedsConfigurable::__get public function Override magic method __get(). Make sure that $this->config goes through getConfig()
FeedsPlugin::all public static function Get all available plugins.
FeedsPlugin::byType public static function Gets all available plugins of a particular type.
FeedsPlugin::child public static function Determines whether given plugin is derived from given base plugin.
FeedsPlugin::hasSourceConfig public function Returns TRUE if $this->sourceForm() returns a form. Overrides FeedsSourceInterface::hasSourceConfig
FeedsPlugin::loadMappers protected static function Loads on-behalf implementations from mappers/ directory.
FeedsPlugin::save public function Save changes to the configuration of this object. Delegate saving to parent (= Feed) which will collect information from this object by way of getConfig() and store it. Overrides FeedsConfigurable::save
FeedsPlugin::sourceDefaults public function Implements FeedsSourceInterface::sourceDefaults(). Overrides FeedsSourceInterface::sourceDefaults 1
FeedsPlugin::sourceDelete public function A source is being deleted. Overrides FeedsSourceInterface::sourceDelete 2
FeedsPlugin::sourceForm public function Callback methods, exposes source form. Overrides FeedsSourceInterface::sourceForm 3
FeedsPlugin::sourceFormValidate public function Validation handler for sourceForm. Overrides FeedsSourceInterface::sourceFormValidate 2
FeedsPlugin::sourceSave public function A source is being saved. Overrides FeedsSourceInterface::sourceSave 2
FeedsPlugin::typeOf public static function Determines the type of a plugin.
FeedsPlugin::__construct protected function Constructor. Overrides FeedsConfigurable::__construct
FeedsProcessor::expire public function Delete feed items younger than now - $time. Do not invoke expire on a processor directly, but use FeedsImporter::expire() instead. 1
FeedsProcessor::expiryTime public function Per default, don't support expiry. If processor supports expiry of imported items, return the time after which items should be removed. 1
FeedsProcessor::getMappings public function Get mappings.
FeedsProcessor::uniqueTargets protected function Utility function that iterates over a target array and retrieves all sources that are unique.
FeedsUserProcessor::clear public function Implements FeedsProcessor::clear(). Overrides FeedsProcessor::clear
FeedsUserProcessor::configDefaults public function Override parent::configDefaults(). Overrides FeedsProcessor::configDefaults
FeedsUserProcessor::configForm public function Override parent::configForm(). Overrides FeedsConfigurable::configForm
FeedsUserProcessor::existingItemId protected function Get id of an existing feed item term if available. Overrides FeedsProcessor::existingItemId
FeedsUserProcessor::getMappingTargets public function Return available mapping targets. Overrides FeedsProcessor::getMappingTargets
FeedsUserProcessor::map protected function Execute mapping on an item. Overrides FeedsProcessor::map
FeedsUserProcessor::process public function Implements FeedsProcessor::process(). Overrides FeedsProcessor::process
FeedsUserProcessor::setTargetElement public function Set target element. Overrides FeedsProcessor::setTargetElement