Newer
Older
Alex Barth
committed
<?php
// $Id$
/**
* @file
* Definition of FeedsDataProcessor.
*/
/**
* Creates simple table records from feed items. Uses Data module.
*/
class FeedsDataProcessor extends FeedsProcessor {
/**
* Implementation of FeedsProcessor::process().
*/
public function process(FeedsImportBatch $batch, FeedsSource $source) {
Alex Barth
committed
// Count number of created and updated nodes.
$inserted = $updated = 0;
while ($item = $batch->shiftItem()) {
Alex Barth
committed
if (!($id = $this->existingItemId($item, $source)) || $this->config['update_existing']) {
// Map item to a data record, feed_nid and timestamp are mandatory.
$data = array();
$data['feed_nid'] = $source->feed_nid;
$data['timestamp'] = FEEDS_REQUEST_TIME;
$data = $this->map($item, $data);
// Save data.
if ($id) {
$data['id'] = $id;
$this->handler()->update($data, 'id');
$updated++;
}
else {
$this->handler()->insert($data);
$inserted++;
}
}
}
// Set messages.
if ($inserted) {
drupal_set_message(t('Created !number items.', array('!number' => $inserted)));
Alex Barth
committed
}
elseif ($updated) {
drupal_set_message(t('Updated !number items.', array('!number' => $updated)));
Alex Barth
committed
}
else {
Alex Barth
committed
}
Alex Barth
committed
}
/**
* Implementation of FeedsProcessor::clear().
*
* Delete all data records for feed_nid in this table.
*/
public function clear(FeedsBatch $batch, FeedsSource $source) {
Alex Barth
committed
$clause = array(
'feed_nid' => $source->feed_nid,
);
$num = $this->handler()->delete($clause);
drupal_set_message(t('Deleted !number items.', array('!number' => $num)));
Alex Barth
committed
}
/**
* Implement expire().
*/
public function expire($time = NULL) {
if ($time === NULL) {
$time = $this->expiryTime();
}
if ($time == FEEDS_EXPIRE_NEVER) {
Alex Barth
committed
}
$clause = array(
'timestamp' => array(
'<',
FEEDS_REQUEST_TIME - $time,
),
);
$num = $this->handler()->delete($clause);
drupal_set_message(t('Expired !number records from !table.', array('!number' => $num, '!table' => $this->tableName())));
Alex Barth
committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
}
/**
* Return expiry time.
*/
public function expiryTime() {
return $this->config['expire'];
}
/**
* Override parent::addMapping() and create a new field for new mapping
* targets.
*
* @see getMappingTargets().
*/
public function addMapping($source, $target, $unique = FALSE) {
if (empty($source) || empty($target)) {
return;
}
// Create a new field with targets that start with "new:"
@list($new, $type) = explode(':', $target);
if ($new == 'new') {
// Build a field name from the source key.
$field_name = data_safe_name($source);
// Get the full schema spec from data.
$type = data_get_field_definition($type);
// Add the field to the table.
$schema = $this->table()->get('table_schema');
if (!isset($schema['fields'][$field_name])) {
$target = $this->table()->addField($field_name, $type);
// Let the user know.
drupal_set_message(t('Created new field "!name".', array('!name' => $field_name)));
}
else {
throw new Exception(t('Field !field_name already exists as a mapping target. Remove it from mapping if you would like to map another source to it. Remove it from !data_table table if you would like to change its definition.', array('!field_name' => $field_name, '!data_table' => l($this->table()->get('name'), 'admin/content/data'))));
}
}
// Let parent populate the mapping configuration.
parent::addMapping($source, $target, $unique);
}
/**
* Return available mapping targets.
*/
public function getMappingTargets() {
$schema = $this->table()->get('table_schema');
$meta = $this->table()->get('meta');
// Collect all existing fields except id and field_nid and offer them as
// mapping targets.
$existing_fields = $new_fields = array();
if (isset($schema['fields'])) {
foreach ($schema['fields'] as $field_name => $field) {
if (!in_array($field_name, array('id', 'feed_nid'))) {
// Any existing field can be optionally unique.
// @todo Push this reverse mapping of spec to short name into data
// module.
$type = $field['type'];
if ($type == 'int' && $field['unsigned']) {
$type = 'unsigned int';
}
Alex Barth
committed
$existing_fields[$field_name] = array(
'name' => empty($meta['fields'][$field_name]['label']) ? $field_name : $meta['fields'][$field_name]['label'],
'description' => t('Field of type !type.', array('!type' => $type)),
Alex Barth
committed
'optional_unique' => TRUE,
);
}
}
}
// Do the same for every joined table.
foreach ($this->handler()->joined_tables as $table) {
$schema = data_get_table($table)->get('table_schema');
if (isset($schema['fields'])) {
foreach ($schema['fields'] as $field_name => $field) {
if (!in_array($field_name, array('id', 'feed_nid'))) {
// Fields in joined tables can't be unique.
$type = $field['type'];
if ($type == 'int' && $field['unsigned']) {
$type = 'unsigned int';
}
Alex Barth
committed
$existing_fields["$table.$field_name"] = array(
'name' => $table .'.'. (empty($meta['fields'][$field_name]['label']) ? $field_name : $meta['fields'][$field_name]['label']),
'description' => t('Joined field of type !type.', array('!type' => $type)),
Alex Barth
committed
'optional_unique' => FALSE,
);
}
}
}
}
// Now add data field types as mapping targets.
$field_types = drupal_map_assoc(array_keys(data_get_field_definitions()));
foreach ($field_types as $k => $v) {
$new_fields['new:'. $k] = array(
'name' => t('[new] !type', array('!type' => $v)),
'description' => t('Creates a new column of type !type.', array('!type' => $v)),
);
Alex Barth
committed
}
$fields = $new_fields + $existing_fields;
drupal_alter('feeds_data_processor_targets', $fields, $this->table()->get('name'));
return $fields;
Alex Barth
committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
}
/**
* Set target element, bring element in a FeedsDataHandler format.
*/
public function setTargetElement(&$target_item, $target_element, $value) {
if (strpos($target_element, '.')) {
/**
Add field in FeedsDataHandler format.
This is the tricky part, FeedsDataHandler expects an *array* of records
at #[joined_table_name]. We need to iterate over the $value that has
been mapped to this element and create a record array from each of
them.
*/
list($table, $field) = explode('.', $target_element);
$values = array();
$value = is_array($value) ? $value : array($value);
foreach ($value as $v) {
// Create a record array.
$values[] = array(
$field => $v,
);
}
$target_item['#'. $table] = $values;
}
else {
$target_item[$target_element] = $value;
}
}
/**
* Iterate through unique targets and try to load existing records.
* Return id for the first match.
*/
protected function existingItemId($source_item, FeedsSource $source) {
foreach ($this->uniqueTargets($source_item) as $target => $value) {
if ($records = $this->handler()->load(array('feed_nid' => $source->feed_nid, $target => $value))) {
Alex Barth
committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
return $records[0]['id'];
}
}
return 0;
}
/**
* Override parent::configDefaults().
*/
public function configDefaults() {
return array(
'update_existing' => 0,
'expire' => FEEDS_EXPIRE_NEVER, // Don't expire items by default.
'mappings' => array(),
);
}
/**
* Override parent::configForm().
*/
public function configForm(&$form_state) {
$form['update_existing'] = array(
'#type' => 'checkbox',
'#title' => t('Update existing items'),
'#description' => t('Check if existing items should be updated from the feed.'),
'#default_value' => $this->config['update_existing'],
);
$period = drupal_map_assoc(array(FEEDS_EXPIRE_NEVER, 3600, 10800, 21600, 43200, 86400, 259200, 604800, 604800 * 4, 604800 * 12, 604800 * 24, 31536000), 'feeds_format_expire');
$form['expire'] = array(
'#type' => 'select',
'#title' => t('Expire items'),
'#options' => $period,
'#description' => t('Select after how much time data records should be deleted. The timestamp target value will be used for determining the item\'s age, see Mapping settings.'),
'#default_value' => $this->config['expire'],
);
return $form;
}
/**
* Return the data table name for this feed.
*/
protected function tableName() {
return variable_get('feeds_data_'. $this->id, 'feeds_data_'. $this->id);
Alex Barth
committed
}
/**
* Return the data table for this feed.
*
* @throws Exception $e
* Throws this exception if a table cannot be found and cannot be created.
*
* @todo Make *Data module* throw exception when table can't be found or
Alex Barth
committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
* can't be created.
*/
protected function table() {
if ($table = data_get_table($this->tableName())) {
return $table;
}
else {
if ($table = data_create_table($this->tableName(), $this->baseSchema(), feeds_importer($this->id)->config['name'])) {
return $table;
}
}
throw new Exception(t('Could not create data table.'));
}
/**
* Return a data handler for this table.
*
* Avoids a call to table() to not unnecessarily instantiate DataTable.
*/
protected function handler() {
data_include('DataHandler');
feeds_include('FeedsDataHandler');
return FeedsDataHandler::instance($this->tableName(), 'id');
}
/**
* Every Feeds data table must have these elements.
*/
protected function baseSchema() {
return array(
'fields' => array(
'feed_nid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'id' => array(
'type' => 'serial',
'size' => 'normal',
'unsigned' => TRUE,
'not null' => TRUE,
),
'timestamp' => array(
'description' => 'The Unix timestamp for the data.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => FALSE,
),
),
'indexes' => array(
'feed_nid' => array('feed_nid'),
'id' => array('id'),
'timestamp' => array('timestamp'),
),
'primary key' => array(
'0' => 'id',
),
);
}
}