View source
<?php
class RulesPHPEvaluator extends RulesDataInputEvaluator {
public function editAccess() {
return parent::editAccess() && (user_access('use PHP for settings') || drupal_is_cli());
}
public static function getUsedVars($text, $var_info) {
if (strpos($text, '<?') !== FALSE) {
$used_vars = array();
foreach ($var_info as $name => $info) {
if (strpos($text, '$' . $name) !== FALSE) {
$used_vars[] = $name;
}
}
return $used_vars;
}
}
public function prepare($text, $var_info) {
$this->setting = self::getUsedVars($text, $var_info);
}
public function evaluate($text, $options, RulesState $state) {
$vars['eval_options'] = $options;
foreach ($this->setting as $key => $var_name) {
$vars[$var_name] = $state
->get($var_name);
}
return rules_php_eval($text, rules_unwrap_data($vars));
}
public static function help($var_info) {
module_load_include('inc', 'rules', 'rules/modules/php.rules');
$render = array(
'#type' => 'fieldset',
'#title' => t('PHP Evaluation'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
) + rules_php_evaluator_help($var_info);
return $render;
}
}
class RulesPHPDataProcessor extends RulesDataProcessor {
protected static function form($settings, $var_info) {
$settings += array(
'code' => '',
);
$form = array(
'#type' => 'fieldset',
'#title' => t('PHP evaluation'),
'#collapsible' => TRUE,
'#collapsed' => empty($settings['code']),
'#description' => t('Enter PHP code to process the selected argument value.'),
);
$form['code'] = array(
'#type' => 'textarea',
'#title' => t('Code'),
'#description' => t('Enter PHP code without <?php ?> delimiters that returns the processed value. The selected value is available in the variable $value. Example: %code', array(
'%code' => 'return $value + 1;',
)),
'#default_value' => $settings['code'],
'#weight' => 5,
);
return $form;
}
public function editAccess() {
return parent::editAccess() && (user_access('use PHP for settings') || drupal_is_cli());
}
public function process($value, $info, RulesState $state, RulesPlugin $element) {
$value = isset($this->processor) ? $this->processor
->process($value, $info, $state, $element) : $value;
return rules_php_eval_return($this->setting['code'], array(
'value' => $value,
));
}
}
function rules_execute_php_eval($code, $settings, $state, $element) {
$data = array();
if (!empty($settings['used_vars'])) {
foreach ($settings['used_vars'] as $key => $var_name) {
$data[$var_name] = $state
->get($var_name);
}
}
return rules_php_eval_return($code, rules_unwrap_data($data));
}
function rules_php_eval($code, $arguments = array()) {
extract($arguments);
ob_start();
print eval('?>' . $code);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
function rules_php_eval_return($code, $arguments = array()) {
extract($arguments);
return eval($code);
}