Projet

Général

Profil

Paste
Télécharger (20,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / plugins / FeedsUserProcessor.inc @ b5aa1857

1
<?php
2

    
3
/**
4
 * @file
5
 * Contains FeedsUserProcessor.
6
 */
7

    
8
/**
9
 * Option to block users not found in the feed.
10
 *
11
 * @var string
12
 */
13
define('FEEDS_BLOCK_NON_EXISTENT', 'block');
14

    
15
/**
16
 * Feeds processor plugin. Create users from feed items.
17
 */
18
class FeedsUserProcessor extends FeedsProcessor {
19
  /**
20
   * Search by role name.
21
   */
22
  const ROLE_SEARCH_NAME = 'name';
23

    
24
  /**
25
   * Search by role id.
26
   */
27
  const ROLE_SEARCH_RID = 'rid';
28

    
29
  /**
30
   * Unencrypted password.
31
   */
32
  const PASS_UNENCRYPTED = 'none';
33

    
34
  /**
35
   * MD5 encrypted password.
36
   */
37
  const PASS_MD5 = 'md5';
38

    
39
  /**
40
   * SHA512 encrypted password.
41
   */
42
  const PASS_SHA512 = 'sha512';
43

    
44
  /**
45
   * Define entity type.
46
   */
47
  public function entityType() {
48
    return 'user';
49
  }
50

    
51
  /**
52
   * Implements parent::entityInfo().
53
   */
54
  protected function entityInfo() {
55
    $info = parent::entityInfo();
56
    $info['label plural'] = t('Users');
57
    return $info;
58
  }
59

    
60
  /**
61
   * Creates a new user account in memory and returns it.
62
   */
63
  protected function newEntity(FeedsSource $source) {
64
    $account = parent::newEntity($source);
65
    $account->uid = 0;
66
    $account->roles = array_filter($this->config['roles']);
67
    $account->status = $this->config['status'];
68
    $account->is_new = TRUE;
69

    
70
    return $account;
71
  }
72

    
73
  /**
74
   * Loads an existing user.
75
   */
76
  protected function entityLoad(FeedsSource $source, $uid) {
77
    $user = parent::entityLoad($source, $uid);
78

    
79
    // Copy the password so that we can compare it again at save.
80
    $user->feeds_original_pass = $user->pass;
81

    
82
    // Reset roles and status when an user is replaced.
83
    if ($this->config['update_existing'] == FEEDS_REPLACE_EXISTING) {
84
      $user->roles = array_filter($this->config['roles']);
85
      $user->status = $this->config['status'];
86

    
87
      // Unserialize user data if it is still serialized.
88
      if (!empty($user->data) && @unserialize($user->data)) {
89
        $user->data = unserialize($user->data);
90
      }
91
      else {
92
        $user->data = array();
93
      }
94
    }
95

    
96
    return $user;
97
  }
98

    
99
  /**
100
   * Validates a user account.
101
   */
102
  protected function entityValidate($account) {
103
    parent::entityValidate($account);
104

    
105
    if (empty($account->name) || empty($account->mail) || !valid_email_address($account->mail)) {
106
      throw new FeedsValidationException(t('User name missing or email not valid.'));
107
    }
108

    
109
    // Check when an user ID gets set or changed during processing if that user
110
    // ID is not already in use.
111
    if (!empty($account->uid)) {
112
      $is_new = !empty($account->feeds_item->is_new);
113
      $different = !empty($account->feeds_item->entity_id) && $account->feeds_item->entity_id != $account->uid;
114
      if ($is_new || $different) {
115
        $exists = entity_load_unchanged('user', $account->uid);
116
        if ($exists) {
117
          throw new FeedsValidationException(t('Could not update user ID to @uid since that ID is already in use.', array(
118
            '@uid' => $account->uid,
119
          )));
120
        }
121
      }
122
    }
123

    
124
    // Timezone validation.
125
    if (!empty($account->timezone) && !array_key_exists($account->timezone, system_time_zones())) {
126
      throw new FeedsValidationException(t("Failed importing '@name'. User's timezone is not valid.", array('@name' => $account->name)));
127
    }
128
  }
129

    
130
  /**
131
   * Save a user account.
132
   */
133
  protected function entitySave($account) {
134
    if ($this->config['defuse_mail']) {
135
      $account->mail = $account->mail . '_test';
136
    }
137

    
138
    $edit = (array) $account;
139

    
140
    // Remove pass from $edit if the password is unchanged.
141
    if (isset($account->feeds_original_pass) && $account->pass == $account->feeds_original_pass) {
142
      unset($edit['pass']);
143
    }
144

    
145
    // Check if the user ID changed when updating users.
146
    if (!empty($account->feeds_item->entity_id) && $account->feeds_item->entity_id != $account->uid) {
147
      // The user ID of the existing user is different. Try to update the user ID.
148
      db_update('users')
149
        ->fields(array(
150
          'uid' => $account->uid,
151
        ))
152
        ->condition('uid', $account->feeds_item->entity_id)
153
        ->execute();
154
    }
155

    
156
    user_save($account, $edit);
157

    
158
    // If an encrypted password was given, directly set this in the database.
159
    if ($account->uid && !empty($account->pass_crypted)) {
160
      db_update('users')
161
        ->fields(array('pass' => $account->pass_crypted))
162
        ->condition('uid', $account->uid)
163
        ->execute();
164
    }
165

    
166
    if ($account->uid && !empty($account->openid)) {
167
      $authmap = array(
168
        'uid' => $account->uid,
169
        'module' => 'openid',
170
        'authname' => $account->openid,
171
      );
172
      if (SAVED_UPDATED != drupal_write_record('authmap', $authmap, array('uid', 'module'))) {
173
        drupal_write_record('authmap', $authmap);
174
      }
175
    }
176
  }
177

    
178
  /**
179
   * Delete multiple user accounts.
180
   */
181
  protected function entityDeleteMultiple($uids) {
182
    // Prevent user 1 from being deleted.
183
    if (in_array(1, $uids)) {
184
      $uids = array_diff($uids, array(1));
185

    
186
      // But do delete the associated feeds item.
187
      db_delete('feeds_item')
188
        ->condition('entity_type', $this->entityType())
189
        ->condition('entity_id', 1)
190
        ->execute();
191
    }
192
    user_delete_multiple($uids);
193
  }
194

    
195
  /**
196
   * Override parent::configDefaults().
197
   */
198
  public function configDefaults() {
199
    return array(
200
      'roles' => array(),
201
      'status' => 1,
202
      'defuse_mail' => FALSE,
203
    ) + parent::configDefaults();
204
  }
205

    
206
  /**
207
   * Override parent::configForm().
208
   */
209
  public function configForm(&$form_state) {
210
    $form = parent::configForm($form_state);
211
    $form['status'] = array(
212
      '#type' => 'radios',
213
      '#title' => t('Status'),
214
      '#description' => t('Select whether users should be imported active or blocked.'),
215
      '#options' => array(0 => t('Blocked'), 1 => t('Active')),
216
      '#default_value' => $this->config['status'],
217
    );
218

    
219
    $roles = user_roles(TRUE);
220
    unset($roles[2]);
221
    if (count($roles)) {
222
      $form['roles'] = array(
223
        '#type' => 'checkboxes',
224
        '#title' => t('Additional roles'),
225
        '#description' => t('Every user is assigned the "authenticated user" role. Select additional roles here.'),
226
        '#default_value' => $this->config['roles'],
227
        '#options' => $roles,
228
      );
229
    }
230
    $form['defuse_mail'] = array(
231
      '#type' => 'checkbox',
232
      '#title' => t('Defuse e-mail addresses'),
233
      '#description' => t('This appends _test to all imported e-mail addresses to ensure they cannot be used as recipients.'),
234
      '#default_value' => $this->config['defuse_mail'],
235
    );
236
    $form['update_non_existent']['#options'][FEEDS_BLOCK_NON_EXISTENT] = t('Block non-existent users');
237
    return $form;
238
  }
239

    
240
  /**
241
   * Overrides FeedsProcessor::map().
242
   *
243
   * Ensures that the user is assigned additional roles that are configured on
244
   * the settings. The roles could have been revoked when there was mapped to
245
   * the "roles_list" target.
246
   */
247
  protected function map(FeedsSource $source, FeedsParserResult $result, $target_item = NULL) {
248
    $target_item = parent::map($source, $result, $target_item);
249

    
250
    // Assign additional roles as configured.
251
    $roles = array_filter($this->config['roles']);
252
    foreach ($roles as $rid) {
253
      $target_item->roles[$rid] = $rid;
254
    }
255

    
256
    return $target_item;
257
  }
258

    
259
  /**
260
   * Overrides setTargetElement() to operate on a target item that is an user.
261
   */
262
  public function setTargetElement(FeedsSource $source, $target_user, $target_element, $value, array $mapping = array()) {
263
    switch ($target_element) {
264
      case 'pass':
265
        $this->setPassTarget($source, $target_user, $target_element, $value, $mapping);
266
        break;
267

    
268
      case 'created':
269
        $target_user->created = feeds_to_unixtime($value, REQUEST_TIME);
270
        break;
271

    
272
      case 'language':
273
        $target_user->language = strtolower($value);
274
        break;
275

    
276
      case 'roles_list':
277
        // Ensure that the role list is an array.
278
        $value = (array) $value;
279
        $this->rolesListSetTarget($source, $target_user, $target_element, $value, $mapping);
280
        break;
281

    
282
      case 'timezone':
283
        $target_user->timezone = $value;
284
        break;
285

    
286
      default:
287
        parent::setTargetElement($source, $target_user, $target_element, $value);
288
        break;
289
    }
290
  }
291

    
292
  /**
293
   * Return available mapping targets.
294
   */
295
  public function getMappingTargets() {
296
    $targets = parent::getMappingTargets();
297
    $targets += array(
298
      'uid' => array(
299
        'name' => t('User ID'),
300
        'description' => t('The uid of the user. NOTE: use this feature with care, user ids are usually assigned by Drupal.'),
301
        'optional_unique' => TRUE,
302
      ),
303
      'name' => array(
304
        'name' => t('User name'),
305
        'description' => t('Name of the user.'),
306
        'optional_unique' => TRUE,
307
      ),
308
      'mail' => array(
309
        'name' => t('Email address'),
310
        'description' => t('Email address of the user.'),
311
        'optional_unique' => TRUE,
312
      ),
313
      'created' => array(
314
        'name' => t('Created date'),
315
        'description' => t('The created (e. g. joined) data of the user.'),
316
      ),
317
      'pass' => array(
318
        'name' => t('Password'),
319
        'description' => t('The user password.'),
320
        'summary_callbacks' => array(array($this, 'passSummaryCallback')),
321
        'form_callbacks' => array(array($this, 'passFormCallback')),
322
      ),
323
      'status' => array(
324
        'name' => t('Account status'),
325
        'description' => t('Whether a user is active or not. 1 stands for active, 0 for blocked.'),
326
      ),
327
      'language' => array(
328
        'name' => t('User language'),
329
        'description' => t('Default language for the user.'),
330
      ),
331
      'timezone' => array(
332
        'name' => t('Timezone'),
333
        'description' => t('The timezone identifier, like UTC or Europe/Lisbon.'),
334
      ),
335
      'roles_list' => array(
336
        'name' => t('User roles'),
337
        'description' => t('User roles provided as role names in comma separated list.'),
338
        'summary_callbacks' => array(array($this, 'rolesListSummaryCallback')),
339
        'form_callbacks' => array(array($this, 'rolesListFormCallback')),
340
      ),
341
    );
342
    if (module_exists('openid')) {
343
      $targets['openid'] = array(
344
        'name' => t('OpenID identifier'),
345
        '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.'),
346
        'optional_unique' => TRUE,
347
      );
348
    }
349

    
350
    $this->getHookTargets($targets);
351

    
352
    return $targets;
353
  }
354

    
355
  /**
356
   * Get id of an existing feed item term if available.
357
   */
358
  protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {
359
    if ($uid = parent::existingEntityId($source, $result)) {
360
      return $uid;
361
    }
362

    
363
    // Iterate through all unique targets and try to find a user for the
364
    // target's value.
365
    foreach ($this->uniqueTargets($source, $result) as $target => $value) {
366
      switch ($target) {
367
        case 'uid':
368
          $uid = db_query("SELECT uid FROM {users} WHERE uid = :uid", array(':uid' => $value))->fetchField();
369
          break;
370

    
371
        case 'name':
372
          $uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $value))->fetchField();
373
          break;
374

    
375
        case 'mail':
376
          $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(':mail' => $value))->fetchField();
377
          break;
378

    
379
        case 'openid':
380
          $uid = db_query("SELECT uid FROM {authmap} WHERE authname = :authname AND module = 'openid'", array(':authname' => $value))->fetchField();
381
          break;
382
      }
383
      if ($uid) {
384
        // Return with the first nid found.
385
        return $uid;
386
      }
387
    }
388
    return 0;
389
  }
390

    
391
  /**
392
   * Overrides FeedsProcessor::initEntitiesToBeRemoved().
393
   *
394
   * Removes user 1 from the list of entities to be removed.
395
   */
396
  protected function initEntitiesToBeRemoved(FeedsSource $source, FeedsState $state) {
397
    parent::initEntitiesToBeRemoved($source, $state);
398

    
399
    // Prevent user 1 from being deleted.
400
    unset($state->removeList[1]);
401
  }
402

    
403
  /**
404
   * Overrides FeedsProcessor::clean().
405
   *
406
   * Block users instead of deleting them.
407
   *
408
   * @param FeedsState $state
409
   *   The FeedsState object for the given stage.
410
   */
411
  protected function clean(FeedsState $state) {
412
    // Delegate to parent if not blocking or option not set.
413
    if (!isset($this->config['update_non_existent']) || $this->config['update_non_existent'] !== FEEDS_BLOCK_NON_EXISTENT) {
414
      return parent::clean($state);
415
    }
416

    
417
    if (!empty($state->removeList)) {
418
      // @see user_user_operations_block().
419
      // The following foreach is copied from above function but with an added
420
      // counter to count blocked users.
421
      foreach (user_load_multiple($state->removeList) as $account) {
422
        $this->loadItemInfo($account);
423
        $account->feeds_item->hash = $this->config['update_non_existent'];
424
        // For efficiency manually save the original account before applying any
425
        // changes.
426
        $account->original = clone $account;
427
        user_save($account, array('status' => 0));
428
        $state->blocked++;
429
      }
430
    }
431
  }
432

    
433
  /**
434
   * Returns default values for mapper "roles_list".
435
   */
436
  public function rolesListDefaults() {
437
    $roles = user_roles(TRUE);
438
    unset($roles[DRUPAL_AUTHENTICATED_RID]);
439
    $rids = array_keys($roles);
440
    $rids = array_combine($rids, $rids);
441
    return array(
442
      'role_search' => self::ROLE_SEARCH_NAME,
443
      'allowed_roles' => $rids,
444
      'autocreate' => 0,
445
      'revoke_roles' => 1,
446
    );
447
  }
448

    
449
  /**
450
   * Mapping configuration summary callback for target "roles_list".
451
   */
452
  public function rolesListSummaryCallback(array $mapping, $target, array $form, array $form_state) {
453
    $options = array();
454

    
455
    // Add in defaults.
456
    $defaults = $this->rolesListDefaults();
457
    $mapping += $defaults;
458
    $mapping['allowed_roles'] += $defaults['allowed_roles'];
459

    
460
    // Role search.
461
    $role_search_options = $this->rolesListRoleSearchOptions();
462
    $options[] = t('Search roles by: <strong>@search</strong>', array('@search' => $role_search_options[$mapping['role_search']]));
463

    
464
    // Allowed roles.
465
    $role_names = array();
466
    $roles = user_roles(TRUE);
467
    foreach (array_filter($mapping['allowed_roles']) as $rid => $enabled) {
468
      $role_names[] = $roles[$rid];
469
    }
470

    
471
    if (empty($role_names)) {
472
      $role_names = array('<' . t('none') . '>');
473
    }
474
    $options[] = t('Allowed roles: %roles', array('%roles' => implode(', ', $role_names)));
475

    
476
    // Autocreate.
477
    if ($mapping['autocreate']) {
478
      $options[] = t('Automatically create roles');
479
    }
480
    else {
481
      $options[] = t('Only assign existing roles');
482
    }
483

    
484
    // Revoke roles.
485
    if ($mapping['revoke_roles']) {
486
      $options[] = t('Revoke roles: yes');
487
    }
488
    else {
489
      $options[] = t('Revoke roles: no');
490
    }
491

    
492
    return implode('<br />', $options);
493
  }
494

    
495
  /**
496
   * Mapping configuration form callback for target "roles_list".
497
   */
498
  public function rolesListFormCallback(array $mapping, $target, array $form, array $form_state) {
499
    // Add in defaults.
500
    $defaults = $this->rolesListDefaults();
501
    $mapping += $defaults;
502
    $mapping['allowed_roles'] += $defaults['allowed_roles'];
503

    
504
    $allowed_roles_options = user_roles(TRUE);
505
    unset($allowed_roles_options[DRUPAL_AUTHENTICATED_RID]);
506

    
507
    return array(
508
      'role_search' => array(
509
        '#type' => 'select',
510
        '#title' => t('Search roles by'),
511
        '#options' => $this->rolesListRoleSearchOptions(),
512
        '#default_value' => $mapping['role_search'],
513
      ),
514
      'allowed_roles' => array(
515
        '#type' => 'checkboxes',
516
        '#title' => t('Allowed roles'),
517
        '#options' => $allowed_roles_options,
518
        '#default_value' => $mapping['allowed_roles'],
519
        '#description' => t('Select the roles to accept from the feed.<br />Any other roles will be ignored.')
520
      ),
521
      'autocreate' => array(
522
        '#type' => 'checkbox',
523
        '#title' => t('Auto create'),
524
        '#description' => t("Create the role if it doesn't exist."),
525
        '#default_value' => $mapping['autocreate'],
526
      ),
527
      'revoke_roles' => array(
528
        '#type' => 'checkbox',
529
        '#title' => t('Revoke roles'),
530
        '#description' => t('If enabled, roles that are not provided by the feed will be revoked for the user. This affects only the "Allowed roles" as configured above.'),
531
        '#default_value' => $mapping['revoke_roles'],
532
      ),
533
    );
534
  }
535

    
536
  /**
537
   * Returns role list options.
538
   */
539
  public function rolesListRoleSearchOptions() {
540
    return array(
541
      self::ROLE_SEARCH_NAME => t('Role name'),
542
      self::ROLE_SEARCH_RID => t('Role ID'),
543
    );
544
  }
545

    
546
  /**
547
   * Sets role target on the user entity.
548
   */
549
  public function rolesListSetTarget(FeedsSource $source, $entity, $target, array $values, array $mapping) {
550
    // Add in defaults.
551
    $defaults = $this->rolesListDefaults();
552
    $mapping += $defaults;
553
    $mapping['allowed_roles'] += $defaults['allowed_roles'];
554

    
555
    // Eventually revoke roles. Do not touch roles that are not allowed to set
556
    // by the source.
557
    if ($mapping['revoke_roles']) {
558
      foreach ($mapping['allowed_roles'] as $rid) {
559
        unset($entity->roles[$rid]);
560
      }
561
    }
562

    
563
    foreach ($values as $value) {
564
      $role = NULL;
565

    
566
      $value = trim($value);
567
      if (strlen($value) < 1) {
568
        // No role provided. Continue to the next role.
569
        continue;
570
      }
571

    
572
      switch ($mapping['role_search']) {
573
        case self::ROLE_SEARCH_NAME:
574
          $role = user_role_load_by_name($value);
575
          if (!$role && !empty($mapping['autocreate'])) {
576
            // Create new role if role doesn't exist.
577
            $role = new stdClass();
578
            $role->name = $value;
579
            user_role_save($role);
580
            $role = user_role_load_by_name($role->name);
581
          }
582
          break;
583

    
584
        case self::ROLE_SEARCH_RID:
585
          $role = user_role_load($value);
586
          break;
587
      }
588

    
589
      if ($role) {
590
        // Check if the role may be assigned.
591
        if (isset($mapping['allowed_roles'][$role->rid]) && !$mapping['allowed_roles'][$role->rid]) {
592
          // This role may *not* be assiged.
593
          continue;
594
        }
595
        $entity->roles[$role->rid] = $role->name;
596
      }
597
    }
598
  }
599

    
600
  /**
601
   * Mapping configuration summary callback for target "pass".
602
   */
603
  public function passSummaryCallback($mapping, $target, $form, $form_state) {
604
    $options = $this->passSummaryCallbackOptions();
605
    if (!isset($mapping['pass_encryption'])) {
606
      $mapping['pass_encryption'] = self::PASS_UNENCRYPTED;
607
    }
608
    return t('Password encryption: <strong>@encryption</strong>', array('@encryption' => $options[$mapping['pass_encryption']]));
609
  }
610

    
611
  /**
612
   * Returns the list of available password encryption methods.
613
   *
614
   * Used by ::passSummaryCallback().
615
   *
616
   * @return array
617
   *    An array of password encryption option titles.
618
   *
619
   * @see passSummaryCallback()
620
   */
621
  protected function passSummaryCallbackOptions() {
622
    return array(
623
      self::PASS_UNENCRYPTED => t('None'),
624
      self::PASS_MD5 => t('MD5'),
625
      self::PASS_SHA512 => t('SHA512'),
626
    );
627
  }
628

    
629
  /**
630
   * Mapping configuration form callback for target "pass".
631
   */
632
  public function passFormCallback($mapping, $target, $form, $form_state) {
633
    return array(
634
      'pass_encryption' => array(
635
        '#type' => 'select',
636
        '#title' => t('Password encryption'),
637
        '#options' => $this->passFormCallbackOptions(),
638
        '#default_value' => !empty($mapping['pass_encryption']) ? $mapping['pass_encryption'] : self::PASS_UNENCRYPTED,
639
      ),
640
    );
641
  }
642

    
643
  /**
644
   * Returns the list of available password encryption methods.
645
   *
646
   * Used by ::passFormCallback().
647
   *
648
   * @return array
649
   *    An array of password encryption option titles.
650
   *
651
   * @see passFormCallback()
652
   */
653
  protected function passFormCallbackOptions() {
654
    return array(
655
      self::PASS_UNENCRYPTED => t('Unencrypted'),
656
      self::PASS_MD5 => t('MD5 (used in older versions of Drupal)'),
657
      self::PASS_SHA512 => t('SHA512 (default in Drupal 7)'),
658
    );
659
  }
660

    
661
  /**
662
   * Sets the password on the user target.
663
   *
664
   * @see setTargetElement()
665
   */
666
  protected function setPassTarget($source, $target_user, $target_element, $value, $mapping) {
667
    if (empty($value)) {
668
      return;
669
    }
670
    if (!isset($mapping['pass_encryption'])) {
671
      $mapping['pass_encryption'] = self::PASS_UNENCRYPTED;
672
    }
673

    
674
    switch ($mapping['pass_encryption']) {
675
      case self::PASS_MD5:
676
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
677
        $new_hash = user_hash_password($value);
678
        if ($new_hash) {
679
          // Indicate an updated password.
680
          $new_hash = 'U' . $new_hash;
681
          $target_user->pass = $target_user->pass_crypted = $new_hash;
682
        }
683
        break;
684

    
685
      case self::PASS_SHA512:
686
        $target_user->pass = $target_user->pass_crypted = $value;
687
        break;
688

    
689
      default:
690
        $target_user->pass = $value;
691
        break;
692
    }
693
  }
694
}