Projet

Général

Profil

Paste
Télécharger (12,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / plugins / FeedsNodeProcessor.inc @ 41cc1b08

1
<?php
2

    
3
/**
4
 * @file
5
 * Class definition of FeedsNodeProcessor.
6
 */
7

    
8
/**
9
 * Option for handling content in Drupal but not in source data (unpublish
10
 * instead of skip/delete).
11
 */
12
define('FEEDS_UNPUBLISH_NON_EXISTENT', 'unpublish');
13

    
14
/**
15
 * Creates nodes from feed items.
16
 */
17
class FeedsNodeProcessor extends FeedsProcessor {
18

    
19
  /**
20
   * Define entity type.
21
   */
22
  public function entityType() {
23
    return 'node';
24
  }
25

    
26
  /**
27
   * Implements parent::entityInfo().
28
   */
29
  protected function entityInfo() {
30
    $info = parent::entityInfo();
31
    $info['label plural'] = t('Nodes');
32
    return $info;
33
  }
34

    
35
  /**
36
   * Creates a new node in memory and returns it.
37
   */
38
  protected function newEntity(FeedsSource $source) {
39
    $node = new stdClass();
40
    $node->type = $this->bundle();
41
    $node->changed = REQUEST_TIME;
42
    $node->created = REQUEST_TIME;
43
    $node->language = LANGUAGE_NONE;
44
    $node->is_new = TRUE;
45
    node_object_prepare($node);
46
    // Populate properties that are set by node_object_prepare().
47
    $node->log = 'Created by FeedsNodeProcessor';
48
    $node->uid = $this->config['author'];
49
    return $node;
50
  }
51

    
52
  /**
53
   * Loads an existing node.
54
   *
55
   * If the update existing method is not FEEDS_UPDATE_EXISTING, only the node
56
   * table will be loaded, foregoing the node_load API for better performance.
57
   *
58
   * @todo Reevaluate the use of node_object_prepare().
59
   */
60
  protected function entityLoad(FeedsSource $source, $nid) {
61
    $node = parent::entityLoad($source, $nid);
62

    
63
    if ($this->config['update_existing'] != FEEDS_UPDATE_EXISTING) {
64
      $node->uid = $this->config['author'];
65
    }
66

    
67
    node_object_prepare($node);
68

    
69
    // Workaround for issue #1247506. See #1245094 for backstory.
70
    if (!empty($node->menu)) {
71
      // If the node has a menu item(with a valid mlid) it must be flagged
72
      // 'enabled'.
73
      $node->menu['enabled'] = (int) (bool) $node->menu['mlid'];
74
    }
75

    
76
    // Populate properties that are set by node_object_prepare().
77
    if ($this->config['update_existing'] == FEEDS_UPDATE_EXISTING) {
78
      $node->log = 'Updated by FeedsNodeProcessor';
79
    }
80
    else {
81
      $node->log = 'Replaced by FeedsNodeProcessor';
82
    }
83
    return $node;
84
  }
85

    
86
  /**
87
   * Check that the user has permission to save a node.
88
   */
89
  protected function entitySaveAccess($entity) {
90

    
91
    // The check will be skipped for anonymous nodes.
92
    if ($this->config['authorize'] && !empty($entity->uid)) {
93

    
94
      $author = user_load($entity->uid);
95

    
96
      // If the uid was mapped directly, rather than by email or username, it
97
      // could be invalid.
98
      if (!$author) {
99
        $message = 'User %uid is not a valid user.';
100
        throw new FeedsAccessException(t($message, array('%uid' => $entity->uid)));
101
      }
102

    
103
      if (empty($entity->nid) || !empty($entity->is_new)) {
104
        $op = 'create';
105
        $access = node_access($op, $entity->type, $author);
106
      }
107
      else {
108
        $op = 'update';
109
        $access = node_access($op, $entity, $author);
110
      }
111

    
112
      if (!$access) {
113
        $message = t('The user %name is not authorized to %op content of type %content_type. To import this item, either the user "@name" (author of the item) must be given the permission to @op content of type @content_type, or the option "Authorize" on the Node processor settings must be turned off.', array(
114
          '%name' => $author->name,
115
          '%op' => $op,
116
          '%content_type' => $entity->type,
117
          '@name' => $author->name,
118
          '@op' => $op,
119
          '@content_type' => $entity->type,
120
        ));
121
        throw new FeedsAccessException($message);
122
      }
123
    }
124
  }
125

    
126
  /**
127
   * Validates a node.
128
   */
129
  protected function entityValidate($entity) {
130
    if (!isset($entity->uid) || !is_numeric($entity->uid)) {
131
       $entity->uid = $this->config['author'];
132
    }
133
  }
134

    
135
  /**
136
   * Save a node.
137
   */
138
  public function entitySave($entity) {
139
    node_save($entity);
140
  }
141

    
142
  /**
143
   * Delete a series of nodes.
144
   */
145
  protected function entityDeleteMultiple($nids) {
146
    node_delete_multiple($nids);
147
  }
148

    
149
  /**
150
   * Overrides parent::expiryQuery().
151
   */
152
  protected function expiryQuery(FeedsSource $source, $time) {
153
    $select = parent::expiryQuery($source, $time);
154
    $select->condition('e.created', REQUEST_TIME - $time, '<');
155
    return $select;
156
  }
157

    
158
  /**
159
   * Return expiry time.
160
   */
161
  public function expiryTime() {
162
    return $this->config['expire'];
163
  }
164

    
165
  /**
166
   * Override parent::configDefaults().
167
   */
168
  public function configDefaults() {
169
    return array(
170
      'expire' => FEEDS_EXPIRE_NEVER,
171
      'author' => 0,
172
      'authorize' => TRUE,
173
    ) + parent::configDefaults();
174
  }
175

    
176
  /**
177
   * Override parent::configForm().
178
   */
179
  public function configForm(&$form_state) {
180
    $form = parent::configForm($form_state);
181

    
182
    $author = user_load($this->config['author']);
183
    $form['author'] = array(
184
      '#type' => 'textfield',
185
      '#title' => t('Author'),
186
      '#description' => t('Select the author of the nodes to be created - leave empty to assign "anonymous".'),
187
      '#autocomplete_path' => 'user/autocomplete',
188
      '#default_value' => empty($author->name) ?  'anonymous' : check_plain($author->name),
189
    );
190
    $form['authorize'] = array(
191
      '#type' => 'checkbox',
192
      '#title' => t('Authorize'),
193
      '#description' => t('Check that the author has permission to create the node.'),
194
      '#default_value' => $this->config['authorize'],
195
    );
196
    $period = drupal_map_assoc(array(FEEDS_EXPIRE_NEVER, 3600, 10800, 21600, 43200, 86400, 259200, 604800, 2592000, 2592000 * 3, 2592000 * 6, 31536000), 'feeds_format_expire');
197
    $form['expire'] = array(
198
      '#type' => 'select',
199
      '#title' => t('Expire nodes'),
200
      '#options' => $period,
201
      '#description' => t("Select after how much time nodes should be deleted. The node's published date will be used for determining the node's age, see Mapping settings."),
202
      '#default_value' => $this->config['expire'],
203
    );
204
    // Add on the "Unpublish" option for nodes, update wording.
205
    if (isset($form['update_non_existent'])) {
206
      $form['update_non_existent']['#options'][FEEDS_UNPUBLISH_NON_EXISTENT] = t('Unpublish non-existent nodes');
207
    }
208
    return $form;
209
  }
210

    
211
  /**
212
   * Override parent::configFormValidate().
213
   */
214
  public function configFormValidate(&$values) {
215
    if ($author = user_load_by_name($values['author'])) {
216
      $values['author'] = $author->uid;
217
    }
218
    else {
219
      $values['author'] = 0;
220
    }
221
  }
222

    
223
  /**
224
   * Reschedule if expiry time changes.
225
   */
226
  public function configFormSubmit(&$values) {
227
    if ($this->config['expire'] != $values['expire']) {
228
      feeds_reschedule($this->id);
229
    }
230
    parent::configFormSubmit($values);
231
  }
232

    
233
  /**
234
   * Override setTargetElement to operate on a target item that is a node.
235
   */
236
  public function setTargetElement(FeedsSource $source, $target_node, $target_element, $value) {
237
    switch ($target_element) {
238
      case 'created':
239
        $target_node->created = feeds_to_unixtime($value, REQUEST_TIME);
240
        break;
241
      case 'feeds_source':
242
        // Get the class of the feed node importer's fetcher and set the source
243
        // property. See feeds_node_update() how $node->feeds gets stored.
244
        if ($id = feeds_get_importer_id($this->bundle())) {
245
          $class = get_class(feeds_importer($id)->fetcher);
246
          $target_node->feeds[$class]['source'] = $value;
247
          // This effectively suppresses 'import on submission' feature.
248
          // See feeds_node_insert().
249
          $target_node->feeds['suppress_import'] = TRUE;
250
        }
251
        break;
252
      case 'user_name':
253
        if ($user = user_load_by_name($value)) {
254
          $target_node->uid = $user->uid;
255
        }
256
        break;
257
      case 'user_mail':
258
        if ($user = user_load_by_mail($value)) {
259
          $target_node->uid = $user->uid;
260
        }
261
        break;
262
      default:
263
        parent::setTargetElement($source, $target_node, $target_element, $value);
264
        break;
265
    }
266
  }
267

    
268
  /**
269
   * Return available mapping targets.
270
   */
271
  public function getMappingTargets() {
272
    $type = node_type_get_type($this->bundle());
273

    
274
    $targets = parent::getMappingTargets();
275
    if ($type && $type->has_title) {
276
      $targets['title'] = array(
277
        'name' => t('Title'),
278
        'description' => t('The title of the node.'),
279
        'optional_unique' => TRUE,
280
      );
281
    }
282
    $targets['nid'] = array(
283
      'name' => t('Node ID'),
284
      'description' => t('The nid of the node. NOTE: use this feature with care, node ids are usually assigned by Drupal.'),
285
      'optional_unique' => TRUE,
286
    );
287
    $targets['uid'] = array(
288
      'name' => t('User ID'),
289
      'description' => t('The Drupal user ID of the node author.'),
290
    );
291
    $targets['user_name'] = array(
292
      'name' => t('Username'),
293
      'description' => t('The Drupal username of the node author.'),
294
    );
295
    $targets['user_mail'] = array(
296
      'name' => t('User email'),
297
      'description' => t('The email address of the node author.'),
298
    );
299
    $targets['status'] = array(
300
      'name' => t('Published status'),
301
      'description' => t('Whether a node is published or not. 1 stands for published, 0 for not published.'),
302
    );
303
    $targets['created'] = array(
304
      'name' => t('Published date'),
305
      'description' => t('The UNIX time when a node has been published.'),
306
    );
307
    $targets['promote'] = array(
308
      'name' => t('Promoted to front page'),
309
      'description' => t('Boolean value, whether or not node is promoted to front page. (1 = promoted, 0 = not promoted)'),
310
    );
311
    $targets['sticky'] = array(
312
      'name' => t('Sticky'),
313
      'description' => t('Boolean value, whether or not node is sticky at top of lists. (1 = sticky, 0 = not sticky)'),
314
    );
315

    
316
    // Include language field if Locale module is enabled.
317
    if (module_exists('locale')) {
318
      $targets['language'] = array(
319
        'name' => t('Language'),
320
        'description' => t('The two-character language code of the node.'),
321
      );
322
    }
323

    
324
    // Include comment field if Comment module is enabled.
325
    if (module_exists('comment')) {
326
      $targets['comment'] = array(
327
        'name' => t('Comments'),
328
        'description' => t('Whether comments are allowed on this node: 0 = no, 1 = read only, 2 = read/write.'),
329
      );
330
    }
331

    
332
    // If the target content type is a Feed node, expose its source field.
333
    if ($id = feeds_get_importer_id($this->bundle())) {
334
      $name = feeds_importer($id)->config['name'];
335
      $targets['feeds_source'] = array(
336
        'name' => t('Feed source'),
337
        'description' => t('The content type created by this processor is a Feed Node, it represents a source itself. Depending on the fetcher selected on the importer "@importer", this field is expected to be for example a URL or a path to a file.', array('@importer' => $name)),
338
        'optional_unique' => TRUE,
339
      );
340
    }
341

    
342
    $this->getHookTargets($targets);
343

    
344
    return $targets;
345
  }
346

    
347
  /**
348
   * Get nid of an existing feed item node if available.
349
   */
350
  protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {
351
    if ($nid = parent::existingEntityId($source, $result)) {
352
      return $nid;
353
    }
354

    
355
    // Iterate through all unique targets and test whether they do already
356
    // exist in the database.
357
    foreach ($this->uniqueTargets($source, $result) as $target => $value) {
358
      switch ($target) {
359
        case 'nid':
360
          $nid = db_query("SELECT nid FROM {node} WHERE nid = :nid", array(':nid' => $value))->fetchField();
361
          break;
362
        case 'title':
363
          $nid = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(':title' => $value, ':type' => $this->bundle()))->fetchField();
364
          break;
365
        case 'feeds_source':
366
          if ($id = feeds_get_importer_id($this->bundle())) {
367
            $nid = db_query("SELECT fs.feed_nid FROM {node} n JOIN {feeds_source} fs ON n.nid = fs.feed_nid WHERE fs.id = :id AND fs.source = :source", array(':id' => $id, ':source' => $value))->fetchField();
368
          }
369
          break;
370
      }
371
      if ($nid) {
372
        // Return with the first nid found.
373
        return $nid;
374
      }
375
    }
376
    return 0;
377
  }
378

    
379
  /**
380
   * Overrides FeedsProcessor::clean().
381
   *
382
   * Allow unpublish instead of delete.
383
   *
384
   * @param FeedsState $state
385
   *   The FeedsState object for the given stage.
386
   */
387
  protected function clean(FeedsState $state) {
388
    // Delegate to parent if not unpublishing or option not set.
389
    if (!isset($this->config['update_non_existent']) || $this->config['update_non_existent'] != FEEDS_UNPUBLISH_NON_EXISTENT) {
390
      return parent::clean($state);
391
    }
392

    
393
    $total = count($state->removeList);
394
    if ($total) {
395
      $nodes = node_load_multiple($state->removeList);
396
      foreach ($nodes as &$node) {
397
        $this->loadItemInfo($node);
398
        // Update the hash value of the feed item to ensure that the item gets
399
        // updated in case it reappears in the feed.
400
        $node->feeds_item->hash = $this->config['update_non_existent'];
401
        node_unpublish_action($node);
402
        node_save($node);
403
        $state->unpublished++;
404
      }
405
    }
406
  }
407

    
408
}