Context:
Currently there is an Issue, with a patch, to incorporate a PHP plugin for use with Drush for the Drupal 6 version of Feeds Tamper. #951336: Php compute patch to use with Drush

Request:
I need a regular plugin for the Drupal 7 version of Feeds Tamper, that will allow me to use PHP.
I'd say that's enough difference for a new issue on the matter. (if I'm wrong please let me know)

Comments

djalloway’s picture

StatusFileSize
new1.47 KB

First attempt, patch provided.

djalloway’s picture

Status: Active » Needs review

used this on my current project, tested and confirmed working.

twistor’s picture

Status: Needs review » Needs work

I'm still reluctant to include any kind of eval based plugins for three reasons:

  1. It's dead simple to write plugins.
  2. eval() is slow and this could potentially be running thousands of times per import.
  3. Nasty security implications.

As far as the code, wouldn't it make more sense to offer the replacement patterns as $variables inside the eval?

djalloway’s picture

I agree 100% with 1,2 and 3.
Maybe this is better suited right where it is, as an optional plugin.
Providing replacement patterns as variables is a great idea. Honestly, I was over deadline on this and just threw it together to accomplish what I needed, the thought process ending right there.

Any improvements are welcomed, I might even revamp this a bit, as it saves time on a lot of Data Migration use-cases.

foopang’s picture

How do you use replacement patterns?
I tried to insert them into php code, but it's not working.

djalloway’s picture

@beansboxchrispang In my migration project, I need to lookup/return the User ID using the Email address in my imported data, here is my code snippet.

  return db_query("SELECT uid FROM {users} WHERE mail = :mail", array(':mail' => '[author]'))->fetchField();

You can see where I use the [author] replacement field to replace the :mail token value in my query, then return the resulting field.

_cosmos_’s picture

I try this plugin and get error

Возникла AJAX HTTP ошибка. Полученный код HTTP: 500 Следует отладочная информация. Путь: /batch?id=1416&op=do СтатусТекст: Internal Server Error ResponseText:

this code i set to eval php textarea

<?php
return strtolower([cat1_description]);

?>

What i doing wrong?

djalloway’s picture

did you apply the patch in #1 correctly to the 7.x.1.x-dev version of the Feeds Tamper module?

_cosmos_’s picture

it works for me

<?
/**
 * Измененная версия от Сбоев К.М. <sboevkm@gmail.com>
 * Плагин для feeds_tamper добавляет обработку поля
 * произвольным php кодом
 *  
*/
$plugin = array(
  'form' => 'feeds_tamper_php_code_form',
  'callback' => 'feeds_tamper_php_code_callback',
  'name' => 'PHP Code',
  'multi' => 'skip',
  'category' => 'Other',
);

function feeds_tamper_php_code_form($importer, $element_key, $settings) {
  $form = array();
  $mappings = $importer->processor->config['mappings'];

  $replace = array();
  foreach ($mappings as $mapping) {
    $replace[] = '[' . $mapping['source'] . ']';
  }

  $form['text'] = array(
    '#type' => 'textarea',
    '#title' => t('Replacement pattern'),
    '#default_value' => isset($settings['text']) ? $settings['text'] : '',
    '#description' => t('Execute any PHP code. Be sure to include the &lt;?php and ?&gt; tags.'),
  );
  $form['help'] = array(
    '#type' => 'fieldset',
    '#title' => t('Available Replacement Patterns'),
    '#collapsed' => TRUE,
    '#collapsible' => TRUE,
    '#value' => theme('item_list', array('items' => $replace)),
  );
  return $form;
}

function feeds_tamper_php_code_callback($result, $item_key, $element_key, &$field, $settings) {
  $trans = array();
  $item = $result->items[$item_key];
  foreach ($item as $key => $value) {
    $trans[ $key] = $value;
  }
  

  //$field = php_eval(strtr($settings['text'], $trans));
  extract($trans, EXTR_OVERWRITE); //, 'value');
  ob_start();
  eval($settings['text']);
  $field = ob_get_contents();
  ob_end_clean();

}

пример кода в текстовом поле feeds_tamper

print str_replace('bad','ok',$source_field_name);

спасибо за плагин товарищам

mrfelton’s picture

This doesn't quite work for my user case. In my case, I have an existing node that is being updated by feeds. The node has a multivalue field with a couple of values already set. When the feed runs I want to append any new values from the feed file to the multivalue field on the existing node, as additional values.

To do that, I need a way of accessing the node that is being updated and/or the field that is being updated so that I can grab the existing values, and merge them with the values in the feed.

mrfelton’s picture

Status: Needs work » Needs review
StatusFileSize
new1.49 KB

I actually have this working now, with the following code in the php tamper rule, and then an explode rule after it. I had to make one modification to the code to get it to work with cvs imports, which was to run the replacement patterns through strtolower. same issue as in #1263718: Rewrite plugin fails when tokens contain upper case letters

<?php
$skus = array();

// Load the node based on title
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'optics_frame_product_display')
  ->propertyCondition('title', '[Frame Description]')
  ->execute();

if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
  $node = current($nodes);
  foreach ($node->field_product['und'] as $key => $val) {
    $product = commerce_product_load($node->field_product['und'][$key]['product_id']);
    $skus[] = $product->sku;
  }
}
$skus[] = '[Crown SKU]';
$skus = array_unique($skus);
watchdog('test', print_r($skus, 1));
return implode(',', $skus);
?>
dooug’s picture

Status: Needs review » Needs work

I applied this patch to feeds_tamper. It seems to work for executing isolated php code, but in my case I need to modify the value of that mapper element. Like mentioned above, I tried using the replacement patterns provided, but they don't seem to be replaced. I also tried dpm(get_defined_vars()); with the devel module, but only some global configuration variables are available.

I think this patch needs work to be able to execute code on the mapper element value. Correct me if I missing how to do this, please!

kenorb’s picture

I think for this, we should add some access control e.g.:

$access = user_access('use PHP for settings');

As it would be security risk for roles which has give the access to manage feeds.

quardz’s picture

twistor’s picture

Status: Needs work » Fixed

This has a module now, so marking as fixed.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.