Merging in all changes from GitHub between
[project/feeds.git] / mappers / file.inc
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * On behalf implementation of Feeds mapping API for file.module and
7 * image.module.
8 *
9 * Does actually not include mappers for field types defined in fields module
10 * (because there aren't any) but mappers for all fields that contain their
11 * value simply in $entity->fieldname['und'][$i]['value'].
12 */
13
14 /**
15 * Implements hook_feeds_processor_targets_alter().
16 *
17 * @see FeedsNodeProcessor::getMappingTargets().
18 */
19 function file_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
20 foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
21 $info = field_info_field($name);
22
23 if (in_array($info['type'], array('file', 'image'))) {
24 $targets[$name] = array(
25 'name' => $instance['label'],
26 'callback' => 'file_feeds_set_target',
27 'description' => t('The @label field of the node.', array('@label' => $instance['label'])),
28 );
29 }
30 }
31 }
32
33 /**
34 * Callback for mapping. Here is where the actual mapping happens.
35 *
36 * When the callback is invoked, $target contains the name of the field the
37 * user has decided to map to and $value contains the value of the feed item
38 * element the user has picked as a source.
39 */
40 function file_feeds_set_target($entity, $target, $value) {
41 if (empty($value)) {
42 return;
43 }
44 module_load_include('inc', 'file');
45
46 // Make sure $value is an array of objects of type FeedsEnclosure.
47 if (!is_array($value)) {
48 $value = array($value);
49 }
50 foreach ($value as $k => $v) {
51 if (!($v instanceof FeedsEnclosure)) {
52 if (is_string($v)) {
53 $value[$k] = new FeedsEnclosure($v, 'application/octet-stream');
54 }
55 else {
56 unset($value[$k]);
57 }
58 }
59 }
60 if (empty($value)) {
61 return;
62 }
63
64 // Determine file destination.
65 // @todo This needs review and debugging.
66 $info = field_info_field($target);
67 $bundle_name = $entity->entity_type == 'node' ? $entity->type : $entity->entity_type;
68 $instance_info = field_info_instance($entity->entity_type, $target, $bundle_name);
69 $account = !empty($entity->uid) ? user_load($entity->uid) : NULL;
70 $destination = file_field_widget_uri($info, $instance_info, $account);
71
72 // Populate entity.
73 $i = 0;
74 $field = isset($entity->$target) ? $entity->$target : array();
75 foreach ($value as $v) {
76 if ($file = $v->getFile($destination)) {
77 $field['und'][$i] = (array)$file;
78 $field['und'][$i]['display'] = 1; // @todo: Figure out how to properly populate this field.
79 if ($info['cardinality'] == 1) {
80 break;
81 }
82 $i++;
83 }
84 }
85 $entity->{$target} = $field;
86 }