ui.data.inc 20.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 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 235 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 278 279 280 281 282 283 284 285 286 287 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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
<?php

/**
 * @file Contains data type related forms.
 */


/**
 * Interface for data types providing a direct input form.
 */
interface RulesDataDirectInputFormInterface {

  /**
   * Constructs the direct input form.
   *
   * @return Array
   *  The direct input form.
   */
  public static function inputForm($name, $info, $settings, RulesPlugin $element);

  /**
   * Render the configured value.
   *
   * @return Array
   *   A renderable array.
   */
  public static function render($value);

}

/**
 * Interface for data UI classes providing an options list.
 */
interface RulesDataInputOptionsListInterface extends RulesDataDirectInputFormInterface {

  /**
   * Returns the options list for the data type.
   *
   * @param RulesPlugin $element
   *   The rules element to get the options for.
   * @param string $name
   *   The name of the parameter for which to get options.
   *
   * For retrieving information about the used data type and parameter, the
   * helper RulesDataUI::getTypeInfo() may be used as following:
   * @code
   *   list($type, $parameter_info) = RulesDataUI::getTypeInfo($element, $name);
   * @endcode
   *
   * @return
   *   An array of options as used by hook_options_list().
   */
  public static function optionsList(RulesPlugin $element, $name);
}

/**
 * Default UI related class for data types.
 */
class RulesDataUI {

  /**
   * Specifies the default input mode per data type.
   */
  public static function getDefaultMode() {
    return 'selector';
  }

  /**
   * Provides the selection form for a parameter.
   */
  public static function selectionForm($name, $info, $settings, RulesPlugin $element) {
    if (!isset($settings[$name . ':select'])) {
      $settings[$name . ':select'] = '';
      $vars = $element->availableVariables();
      // Default to variables with the same name as the parameter.
      if (isset($vars[$name])) {
        $settings[$name . ':select'] = $name;
      }
      // If there is only one match, use it by default.
      elseif (count($matches = RulesData::matchingDataSelector($vars, $info, '', 1, FALSE)) == 1) {
        $settings[$name . ':select'] = rules_array_key($matches);
      }
    }
    $form[$name . ':select'] = array(
      '#type' => 'rules_data_selection',
      '#title' => t('Data selector'),
      '#default_value' => $settings[$name . ':select'],
      '#required' => empty($info['optional']),
      '#autocomplete_path' => RulesPluginUI::path($element->root()->name, 'autocomplete' . '/' . $name),
      // Make the autocomplete textfield big enough so that it can display
      // descriptions without word wraps.
      '#size' => 75,
      '#description' => t("The data selector helps you drill down into the data available to Rules. <em>To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').</em> More useful tips about data selection is available in <a href='@url'>the online documentation</a>.",
        array('@url' => rules_external_help('data-selection'))),
    );

    $cache = rules_get_cache();
    $form['types_help'] = array(
      '#theme' => 'rules_settings_help',
      '#heading' => t('Data types'),
    );
    if ($info['type'] == '*') {
      $type_labels[] = t('any');
    }
    else {
      $types = is_array($info['type']) ? $info['type'] : array($info['type']);
      $type_labels = array();
      foreach ($types as $type) {
        $type_labels[] = drupal_ucfirst(isset($cache['data_info'][$type]['label']) ? $cache['data_info'][$type]['label'] : $type);
      }
    }
    $form['types_help']['#text'] = format_plural(count($type_labels), 'Select data of the type %types.', 'Select data of the types %types.', array('%types' => implode(', ', $type_labels)));

    if (!empty($info['translatable'])) {
      if (empty($info['custom translation language'])) {
        $text = t('If a multilingual data source (i.e. a translatable field) is given, the argument is translated to the current interface language.');
      }
      else {
        $text = t('If a multilingual data source (i.e. a translatable field) is given, the argument is translated to the configured language.');
      }
      $form['translation'] = array(
        '#theme' => 'rules_settings_help',
        '#text' => $text,
        '#heading' => t('Translation'),
      );
    }
    $form['help'] = array(
      '#theme' => 'rules_data_selector_help',
      '#variables' => $element->availableVariables(),
      '#parameter' => $info,
    );

    // Add data processor.
    $settings += array($name . ':process' => array());
    $form[$name . ':process'] = array();
    RulesDataProcessor::attachForm($form[$name . ':process'], $settings[$name . ':process'], $info, $element->availableVariables());
    return $form;
  }

  /**
   * Renders the value by making use of the label if an options list is available.
   *
   * Used for data UI classes implementing the
   * RulesDataDirectInputFormInterface.
   *
   * In case an options list is available, the the usual render() method won't
   * be invoked, instead the selected entry is rendered via this method.
   *
   * @todo for Drupal 8: Refactor to avoid implementations have to care about
   * option lists when generating the form, but not when rendering values.
   */
  public static function renderOptionsLabel($value, $name, $info, RulesPlugin $element) {
    if (!empty($info['options list'])) {
      $element->call('loadBasicInclude');
      $options = entity_property_options_flatten(call_user_func($info['options list'], $element, $name));
      if (!is_array($value) && isset($options[$value])) {
        $value = $options[$value];
      }
      elseif (is_array($value)) {
        foreach ($value as $key => $single_value) {
          if (isset($options[$single_value])) {
            $value[$key] = $options[$single_value];
          }
        }
        $value = implode(', ', $value);
      }
      return array(
        'content' => array('#markup' => check_plain($value)),
        '#attributes' => array('class' => array('rules-parameter-options-entry')),
      );
    }
  }

  /**
   * Returns the data type and parameter information for the given arguments.
   *
   * This helper may be used by options list callbacks operation at data-type
   * level, see RulesDataInputOptionsListInterface.
   */
  public static function getTypeInfo(RulesPlugin $element, $name) {
    $parameters = $element->pluginParameterInfo();
    return array($parameters[$name]['type'], $parameters[$name]);
  }
}

/**
 * UI for textual data.
 */
class RulesDataUIText extends RulesDataUI implements RulesDataDirectInputFormInterface {

  public static function getDefaultMode() {
    return 'input';
  }

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    if (!empty($info['options list'])) {
      // Make sure the .rules.inc of the providing module is included as the
      // options list callback may reside there.
      $element->call('loadBasicInclude');
      $form[$name] = array(
        '#type' => 'select',
        '#options' => call_user_func($info['options list'], $element, $name),
      );
    }
    else {
      $form[$name] = array(
        '#type' => 'textarea',
      );
      RulesDataInputEvaluator::attachForm($form, $settings, $info, $element->availableVariables());
    }
    $settings += array($name => isset($info['default value']) ? $info['default value'] : NULL);
    $form[$name] += array(
      '#title' => t('Value'),
      '#default_value' => $settings[$name],
      '#required' => empty($info['optional']),
      '#after_build' => array('rules_ui_element_fix_empty_after_build'),
      '#rows' => 3,
    );
    return $form;
  }

  public static function render($value) {
    return array(
      'content' => array('#markup' => check_plain($value)),
      '#attributes' => array('class' => array('rules-parameter-text')),
    );
  }
}

/**
 * UI for text tokens.
 */
class RulesDataUITextToken extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    if ($form[$name]['#type'] == 'textarea') {
      $form[$name]['#element_validate'][] = 'rules_ui_element_token_validate';
      $form[$name]['#description'] = t('May only contain lowercase letters, numbers, and underscores and has to start with a letter.');
      $form[$name]['#rows'] = 1;
    }
    return $form;
  }
}

/**
 * UI for formatted text.
 */
class RulesDataUITextFormatted extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    $settings += array($name => isset($info['default value']) ? $info['default value'] : array('value' => NULL, 'format' => NULL));

    $form[$name]['#type'] = 'text_format';
    $form[$name]['#base_type'] = 'textarea';
    $form[$name]['#default_value'] = $settings[$name]['value'];
    $form[$name]['#format'] = $settings[$name]['format'];
    return $form;
  }

  public static function render($value) {
    return array(
      'content' => array('#markup' => check_plain($value['value'])),
      '#attributes' => array('class' => array('rules-parameter-text-formatted')),
    );
  }
}



/**
 * UI for decimal data.
 */
class RulesDataUIDecimal extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    if (empty($info['options list'])) {
      $form[$name]['#type'] = 'textfield';
    }
    $form[$name]['#element_validate'][] = 'rules_ui_element_decimal_validate';
    $form[$name]['#rows'] = 1;
    return $form;
  }
}

/**
 * UI for integers.
 */
class RulesDataUIInteger extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    if (empty($info['options list'])) {
      $form[$name]['#type'] = 'textfield';
    }
    $form[$name]['#element_validate'][] = 'rules_ui_element_integer_validate';
    return $form;
  }
}

/**
 * UI for IP addresses.
 */
class RulesDataUIIPAddress extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    if (empty($info['options list'])) {
      $form[$name]['#type'] = 'textfield';
      $form[$name]['#description'] = t('If not provided, the IP address of the current user will be used.');
    }
    $form[$name]['#element_validate'][] = 'rules_ui_element_ip_address_validate';
    $form[$name]['#rows'] = 1;
    return $form;
  }
}

/**
 * UI for boolean data.
 */
class RulesDataUIBoolean extends RulesDataUI implements RulesDataDirectInputFormInterface {

  public static function getDefaultMode() {
    return 'input';
  }

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $settings += array($name => isset($info['default value']) ? $info['default value'] : NULL);
    // Note: Due to the checkbox even optional parameter always receive a value.
    $form[$name] = array(
      '#type' => 'checkbox',
      '#title' => check_plain($info['label']),
      '#default_value' => $settings[$name],
    );
    return $form;
  }

  public static function render($value) {
    return array(
      'content' => array('#markup' => !empty($value) ? t('true') : t('false')),
      '#attributes' => array('class' => array('rules-parameter-boolean')),
    );
  }
}

/**
 * UI for dates.
 */
class RulesDataUIDate extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $settings += array($name => isset($info['default value']) ? $info['default value'] : (empty($info['optional']) ? gmdate('Y-m-d H:i:s', time()) : NULL));

    // Convert any configured timestamp into a readable format.
    if (is_numeric($settings[$name])) {
      $settings[$name] = gmdate('Y-m-d H:i:s', $settings[$name]);
    }
    $form = parent::inputForm($name, $info, $settings, $element);
    $form[$name]['#type'] = 'textfield';
    $form[$name]['#element_validate'][] = 'rules_ui_element_date_validate';
    // Note that the date input evaluator takes care for parsing dates using
    // strtotime() into a timestamp, which is the internal date format.
    $form[$name]['#description'] = t('The date in GMT. You may enter a fixed time (like %format) or any other values in GMT known by the PHP !strtotime function (like "+1 day"). Relative dates like "+1 day" or "now" relate to the evaluation time.',
      array('%format' => gmdate('Y-m-d H:i:s', time() + 86400),
            '!strtotime' => l('strtotime()', 'http://php.net/strtotime')));

    //TODO: Leverage the jquery datepicker+timepicker once a module providing
    //the timpeicker is available.
    return $form;
  }

  public static function render($value) {
    $value = is_numeric($value) ? format_date($value, 'short') : check_plain($value);
    return array(
      'content' => array('#markup' => $value),
      '#attributes' => array('class' => array('rules-parameter-date')),
    );
  }
}

/**
 * UI for duration type parameter.
 */
class RulesDataUIDuration extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    $form[$name]['#type'] = 'rules_duration';
    $form[$name]['#after_build'][] = 'rules_ui_element_duration_after_build';
    return $form;
  }

  public static function render($value) {
    $value = is_numeric($value) ? format_interval($value) : check_plain($value);
    return array(
      'content' => array('#markup' => $value),
      '#attributes' => array('class' => array('rules-parameter-duration')),
    );
  }
}

/**
 * UI for the URI type parameter.
 */
class RulesDataUIURI extends RulesDataUIText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    $form[$name]['#rows'] = 1;
    $form[$name]['#description'] = t('You may enter relative URLs like %url as well as absolute URLs like %absolute-url.', array('%url' => 'user/login?destination=node', '%absolute-url' => 'http://drupal.org'));
    return $form;
  }
}

/**
 * UI for lists of textual data.
 */
class RulesDataUIListText extends RulesDataUIText {

  public static function getDefaultMode() {
    return 'input';
  }

  /**
   * @todo This does not work for inputting textual values including "\n".
   */
  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $settings += array($name => isset($info['default value']) ? $info['default value'] : NULL);
    $form = parent::inputForm($name, $info, $settings, $element);

    if ($form[$name]['#type'] == 'textarea') {
      // Fix up the value to be an array during after build.
      $form[$name]['#delimiter'] = "\n";
      $form[$name]['#after_build'][] = 'rules_ui_list_textarea_after_build';
      $form[$name]['#pre_render'][] = 'rules_ui_list_textarea_pre_render';
      $form[$name]['#default_value'] = !empty($settings[$name]) ? implode("\n", $settings[$name]) : NULL;
      $form[$name]['#description'] = t('A list of values, one on each line.');
    }
    else {
      $form[$name]['#multiple'] = TRUE;
    }
    return $form;
  }

  public static function render($value) {
    return array(
      'content' => array('#markup' => check_plain(implode(', ', $value))),
      '#attributes' => array('class' => array('rules-parameter-list')),
    );
  }
}

/**
 * UI for lists of integers.
 */
class RulesDataUIListInteger extends RulesDataUIListText {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $settings += array($name => isset($info['default value']) ? $info['default value'] : NULL);
    $form = parent::inputForm($name, $info, $settings, $element);

    if ($form[$name]['#type'] == 'textarea') {
      $form[$name]['#description'] = t('A list of integers, separated by commas. E.g. enter "1, 2, 3".');
      $form[$name]['#delimiter'] = ',';
      $form[$name]['#default_value'] = !empty($settings[$name]) ? implode(", ", $settings[$name]) : NULL;
      $form[$name]['#element_validate'][] = 'rules_ui_element_integer_list_validate';
      $form[$name]['#rows'] = 1;
    }
    return $form;
  }
}

/**
 * UI for lists of tokens.
 */
class RulesDataUIListToken extends RulesDataUIListInteger {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);

    if ($form[$name]['#type'] == 'textarea') {
      $form[$name]['#description'] = t('A list of text tokens, separated by commas. E.g. enter "one, two, three".');
      $form[$name]['#element_validate'] = array('rules_ui_element_token_list_validate');
    }
    return $form;
  }
}

/**
 * UI for entity-based data types.
 */
class RulesDataUIEntity extends RulesDataUIText {

  public static function getDefaultMode() {
    return 'selector';
  }

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    if (empty($info['options list'])) {
      $form[$name]['#type'] = 'textfield';

      $entity_info = entity_get_info($info['type']);
      if (empty($entity_info['entity keys']['name'])) {
        $form[$name]['#element_validate'][] = 'rules_ui_element_integer_validate';
      }
      $form[$name]['#title'] = t('@entity identifier', array('@entity' => $entity_info['label']));
      $entity_label = strtolower($entity_info['label'][0]) . substr($entity_info['label'], 1);
      $form[$name]['#description'] = t('Specify an identifier of a @entity.', array('@entity' => $entity_label));
    }
    return $form;
  }
}

/**
 * UI for exportable entity-based data types.
 */
class RulesDataUIEntityExportable extends RulesDataUIEntity {

  public static function getDefaultMode() {
    return 'input';
  }
}

/**
 * Data UI variant displaying a select list of available bundle entities.
 *
 * This is used for "bundle entities" implemented via the 'bundle of' feature
 * of entity.module.
 */
class RulesDataUIBundleEntity extends RulesDataUIEntity implements RulesDataInputOptionsListInterface {

  public static function getDefaultMode() {
    return 'input';
  }

  /**
   * Implements RulesDataInputOptionsListInterface::optionsList().
   */
  public static function optionsList(RulesPlugin $element, $name) {
    list($data_type, $parameter_info) = RulesDataUI::getTypeInfo($element, $name);
    $bundles = array();
    $entity_info = entity_get_info();
    $bundle_of_type = $entity_info[$data_type]['bundle of'];
    if (isset($entity_info[$bundle_of_type]['bundles'])) {
      foreach ($entity_info[$bundle_of_type]['bundles'] as $bundle_name => $bundle_info) {
        $bundles[$bundle_name] = $bundle_info['label'];
      }
    }
    return $bundles;
  }
}

/**
 * UI for taxonomy vocabularies.
 *
 * @see RulesTaxonomyVocabularyWrapper
 */
class RulesDataUITaxonomyVocabulary extends RulesDataUIEntity implements RulesDataInputOptionsListInterface {

  public static function getDefaultMode() {
    return 'input';
  }

  /**
   * Implements RulesDataInputOptionsListInterface::optionsList().
   */
  public static function optionsList(RulesPlugin $element, $name) {
    $options = array();
    foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocab) {
      $options[$machine_name] = $vocab->name;
    }
    return $options;
  }
}

/**
 * UI for lists of entity-based data types.
 */
class RulesDataUIListEntity extends RulesDataUIListInteger {

  public static function inputForm($name, $info, $settings, RulesPlugin $element) {
    $form = parent::inputForm($name, $info, $settings, $element);
    if (empty($info['options list'])) {

      $entity_info = entity_get_info(entity_property_list_extract_type($info['type']));
      if (!empty($entity_info['entity keys']['name'])) {
        $form[$name]['#element_validate'] = array('rules_ui_element_token_list_validate');
      }
      $form[$name]['#title'] = t('@entity identifiers', array('@entity' => $entity_info['label']));
      $entity_label = strtolower($entity_info['label'][0]) . substr($entity_info['label'], 1);
      $form[$name]['#description'] = t('Specify a comma-separated list of identifiers of @entity entities.', array('@entity' => $entity_label));
    }
    return $form;
  }
}