FieldPluginBase.php 57.8 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\views\Plugin\views\field\FieldPluginBase.
merlinofchaos's avatar
merlinofchaos committed
6 7
 */

8
namespace Drupal\views\Plugin\views\field;
9

10
use Drupal\views\Plugin\views\HandlerBase;
11
use Drupal\views\Plugin\views\display\DisplayPluginBase;
12
use Drupal\views\ViewExecutable;
13

merlinofchaos's avatar
merlinofchaos committed
14 15 16 17 18 19 20 21
/**
 * @defgroup views_field_handlers Views field handlers
 * @{
 * Handlers to tell Views how to build and display fields.
 *
 */

/**
22
 * Indicator of the renderText() method for rendering a single item.
merlinofchaos's avatar
merlinofchaos committed
23 24 25 26 27
 * (If no render_item() is present).
 */
define('VIEWS_HANDLER_RENDER_TEXT_PHASE_SINGLE_ITEM', 0);

/**
28
 * Indicator of the renderText() method for rendering the whole element.
merlinofchaos's avatar
merlinofchaos committed
29 30 31 32 33
 * (if no render_item() method is available).
 */
define('VIEWS_HANDLER_RENDER_TEXT_PHASE_COMPLETELY', 1);

/**
34
 * Indicator of the renderText() method for rendering the empty text.
merlinofchaos's avatar
merlinofchaos committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
 */
define('VIEWS_HANDLER_RENDER_TEXT_PHASE_EMPTY', 2);

/**
 * Base field handler that has no options and renders an unformatted field.
 *
 * Definition terms:
 * - additional fields: An array of fields that should be added to the query
 *                      for some purpose. The array is in the form of:
 *                      array('identifier' => array('table' => tablename,
 *                      'field' => fieldname); as many fields as are necessary
 *                      may be in this array.
 * - click sortable: If TRUE, this field may be click sorted.
 *
 * @ingroup views_field_handlers
 */
51
abstract class FieldPluginBase extends HandlerBase {
52

merlinofchaos's avatar
merlinofchaos committed
53 54 55
  var $field_alias = 'unknown';
  var $aliases = array();

56 57 58 59 60 61 62
  /**
   * The field value prior to any rewriting.
   *
   * @var mixed
   */
  public $original_value = NULL;

merlinofchaos's avatar
merlinofchaos committed
63 64 65 66 67 68 69 70
  /**
   * @var array
   * Stores additional fields which get's added to the query.
   * The generated aliases are stored in $aliases.
   */
  var $additional_fields = array();

  /**
71
   * Overrides Drupal\views\Plugin\views\HandlerBase::init().
merlinofchaos's avatar
merlinofchaos committed
72
   */
73 74
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
merlinofchaos's avatar
merlinofchaos committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    $this->additional_fields = array();
    if (!empty($this->definition['additional fields'])) {
      $this->additional_fields = $this->definition['additional fields'];
    }

    if (!isset($this->options['exclude'])) {
      $this->options['exclude'] = '';
    }
  }

  /**
   * Determine if this field can allow advanced rendering.
   *
   * Fields can set this to FALSE if they do not wish to allow
   * token based rewriting or link-making.
   */
92
  protected function allowAdvancedRender() {
merlinofchaos's avatar
merlinofchaos committed
93 94 95 96 97 98
    return TRUE;
  }

  /**
   * Called to add the field to a query.
   */
99
  public function query() {
100
    $this->ensureMyTable();
merlinofchaos's avatar
merlinofchaos committed
101 102
    // Add the field.
    $params = $this->options['group_type'] != 'group' ? array('function' => $this->options['group_type']) : array();
103
    $this->field_alias = $this->query->add_field($this->tableAlias, $this->realField, NULL, $params);
merlinofchaos's avatar
merlinofchaos committed
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

    $this->add_additional_fields();
  }

  /**
   * Add 'additional' fields to the query.
   *
   * @param $fields
   * An array of fields. The key is an identifier used to later find the
   * field alias used. The value is either a string in which case it's
   * assumed to be a field on this handler's table; or it's an array in the
   * form of
   * @code array('table' => $tablename, 'field' => $fieldname) @endcode
   */
  function add_additional_fields($fields = NULL) {
    if (!isset($fields)) {
      // notice check
      if (empty($this->additional_fields)) {
        return;
      }
      $fields = $this->additional_fields;
    }

    $group_params = array();
    if ($this->options['group_type'] != 'group') {
      $group_params = array(
        'function' => $this->options['group_type'],
      );
    }

    if (!empty($fields) && is_array($fields)) {
      foreach ($fields as $identifier => $info) {
        if (is_array($info)) {
          if (isset($info['table'])) {
            $table_alias = $this->query->ensure_table($info['table'], $this->relationship);
          }
          else {
141
            $table_alias = $this->tableAlias;
merlinofchaos's avatar
merlinofchaos committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
          }

          if (empty($table_alias)) {
            debug(t('Handler @handler tried to add additional_field @identifier but @table could not be added!', array('@handler' => $this->definition['handler'], '@identifier' => $identifier, '@table' => $info['table'])));
            $this->aliases[$identifier] = 'broken';
            continue;
          }

          $params = array();
          if (!empty($info['params'])) {
            $params = $info['params'];
          }

          $params += $group_params;
          $this->aliases[$identifier] = $this->query->add_field($table_alias, $info['field'], NULL, $params);
        }
        else {
159
          $this->aliases[$info] = $this->query->add_field($this->tableAlias, $info, NULL, $group_params);
merlinofchaos's avatar
merlinofchaos committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        }
      }
    }
  }

  /**
   * Called to determine what to tell the clicksorter.
   */
  function click_sort($order) {
    if (isset($this->field_alias)) {
      // Since fields should always have themselves already added, just
      // add a sort on the field.
      $params = $this->options['group_type'] != 'group' ? array('function' => $this->options['group_type']) : array();
      $this->query->add_orderby(NULL, NULL, $order, $this->field_alias, $params);
    }
  }

  /**
   * Determine if this field is click sortable.
179 180 181 182
   *
   * @return bool
   *   The value of 'click sortable' from the plugin definition, this defaults
   *   to TRUE if not set.
merlinofchaos's avatar
merlinofchaos committed
183 184
   */
  function click_sortable() {
185
    return isset($this->definition['click sortable']) ? $this->definition['click sortable'] : TRUE;
merlinofchaos's avatar
merlinofchaos committed
186 187 188 189 190
  }

  /**
   * Get this field's label.
   */
191
  public function label() {
merlinofchaos's avatar
merlinofchaos committed
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
    if (!isset($this->options['label'])) {
      return '';
    }
    return $this->options['label'];
  }

  /**
   * Return an HTML element based upon the field's element type.
   */
  function element_type($none_supported = FALSE, $default_empty = FALSE, $inline = FALSE) {
    if ($none_supported) {
      if ($this->options['element_type'] === '0') {
        return '';
      }
    }
    if ($this->options['element_type']) {
      return check_plain($this->options['element_type']);
    }

    if ($default_empty) {
      return '';
    }

    if ($inline) {
      return 'span';
    }

    if (isset($this->definition['element type'])) {
      return $this->definition['element type'];
    }

    return 'span';
  }

  /**
   * Return an HTML element for the label based upon the field's element type.
   */
  function element_label_type($none_supported = FALSE, $default_empty = FALSE) {
    if ($none_supported) {
      if ($this->options['element_label_type'] === '0') {
        return '';
      }
    }
    if ($this->options['element_label_type']) {
      return check_plain($this->options['element_label_type']);
    }

    if ($default_empty) {
      return '';
    }

    return 'span';
  }

  /**
   * Return an HTML element for the wrapper based upon the field's element type.
   */
249
  public function elementWrapperType($none_supported = FALSE, $default_empty = FALSE) {
merlinofchaos's avatar
merlinofchaos committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    if ($none_supported) {
      if ($this->options['element_wrapper_type'] === '0') {
        return 0;
      }
    }
    if ($this->options['element_wrapper_type']) {
      return check_plain($this->options['element_wrapper_type']);
    }

    if ($default_empty) {
      return '';
    }

    return 'div';
  }

  /**
   * Provide a list of elements valid for field HTML.
   *
   * This function can be overridden by fields that want more or fewer
   * elements available, though this seems like it would be an incredibly
   * rare occurence.
   */
273
  public function getElements() {
merlinofchaos's avatar
merlinofchaos committed
274 275
    static $elements = NULL;
    if (!isset($elements)) {
276
      // @todo Add possible html5 elements.
277 278 279 280 281
      $elements = array(
        '' => t(' - Use default -'),
        '0' => t('- None -')
      );
      $elements += config('views.settings')->get('field_rewrite_elements');
merlinofchaos's avatar
merlinofchaos committed
282 283 284 285 286 287 288 289 290 291 292 293
    }

    return $elements;
  }

  /**
   * Return the class of the field.
   */
  function element_classes($row_index = NULL) {
    $classes = explode(' ', $this->options['element_class']);
    foreach ($classes as &$class) {
      $class = $this->tokenize_value($class, $row_index);
294
      $class = drupal_clean_css_identifier($class);
merlinofchaos's avatar
merlinofchaos committed
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
    }
    return implode(' ', $classes);
  }

  /**
   * Replace a value with tokens from the last field.
   *
   * This function actually figures out which field was last and uses its
   * tokens so they will all be available.
   */
  function tokenize_value($value, $row_index = NULL) {
    if (strpos($value, '[') !== FALSE || strpos($value, '!') !== FALSE || strpos($value, '%') !== FALSE) {
      $fake_item = array(
        'alter_text' => TRUE,
        'text' => $value,
      );

      // Use isset() because empty() will trigger on 0 and 0 is
      // the first row.
      if (isset($row_index) && isset($this->view->style_plugin->render_tokens[$row_index])) {
        $tokens = $this->view->style_plugin->render_tokens[$row_index];
      }
      else {
        // Get tokens from the last field.
        $last_field = end($this->view->field);
        if (isset($last_field->last_tokens)) {
          $tokens = $last_field->last_tokens;
        }
        else {
324
          $tokens = $last_field->getRenderTokens($fake_item);
merlinofchaos's avatar
merlinofchaos committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
        }
      }

      $value = strip_tags($this->render_altered($fake_item, $tokens));
      if (!empty($this->options['alter']['trim_whitespace'])) {
        $value = trim($value);
      }
    }

    return $value;
  }

  /**
   * Return the class of the field's label.
   */
340
  public function elementLabelClasses($row_index = NULL) {
merlinofchaos's avatar
merlinofchaos committed
341 342 343
    $classes = explode(' ', $this->options['element_label_class']);
    foreach ($classes as &$class) {
      $class = $this->tokenize_value($class, $row_index);
344
      $class = drupal_clean_css_identifier($class);
merlinofchaos's avatar
merlinofchaos committed
345 346 347 348 349 350 351
    }
    return implode(' ', $classes);
  }

  /**
   * Return the class of the field's wrapper.
   */
352
  public function elementWrapperClasses($row_index = NULL) {
merlinofchaos's avatar
merlinofchaos committed
353 354 355
    $classes = explode(' ', $this->options['element_wrapper_class']);
    foreach ($classes as &$class) {
      $class = $this->tokenize_value($class, $row_index);
356
      $class = drupal_clean_css_identifier($class);
merlinofchaos's avatar
merlinofchaos committed
357 358 359 360
    }
    return implode(' ', $classes);
  }

361
  /**
362
   * Gets the entity matching the current row and relationship.
363
   *
364
   * @param \stdClass $values
365
   *   An object containing all retrieved values.
366 367 368
   *
   * @return \Drupal\Core\Entity\EntityInterface
   *   Returns the entity matching the values.
369
   */
370
  public function get_entity(\stdClass $values) {
371 372 373 374 375 376 377 378 379
    $relationship_id = $this->options['relationship'];
    if ($relationship_id == 'none') {
      return $values->_entity;
    }
    else {
      return $values->_relationship_entities[$relationship_id];
    }
  }

merlinofchaos's avatar
merlinofchaos committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  /**
   * Get the value that's supposed to be rendered.
   *
   * This api exists so that other modules can easy set the values of the field
   * without having the need to change the render method as well.
   *
   * @param $values
   *   An object containing all retrieved values.
   * @param $field
   *   Optional name of the field where the value is stored.
   */
  function get_value($values, $field = NULL) {
    $alias = isset($field) ? $this->aliases[$field] : $this->field_alias;
    if (isset($values->{$alias})) {
      return $values->{$alias};
    }
  }

398 399 400 401 402 403 404
  /**
   * Determines if this field will be available as an option to group the result
   * by in the style settings.
   *
   * @return bool
   *  TRUE if this field handler is groupable, otherwise FALSE.
   */
405
  public function useStringGroupBy() {
406 407 408
    return TRUE;
  }

409 410
  protected function defineOptions() {
    $options = parent::defineOptions();
merlinofchaos's avatar
merlinofchaos committed
411 412 413 414 415 416 417 418

    $options['label'] = array('default' => $this->definition['title'], 'translatable' => TRUE);
    $options['exclude'] = array('default' => FALSE, 'bool' => TRUE);
    $options['alter'] = array(
      'contains' => array(
        'alter_text' => array('default' => FALSE, 'bool' => TRUE),
        'text' => array('default' => '', 'translatable' => TRUE),
        'make_link' => array('default' => FALSE, 'bool' => TRUE),
419
        'path' => array('default' => ''),
merlinofchaos's avatar
merlinofchaos committed
420 421 422 423 424 425 426 427 428 429
        'absolute' => array('default' => FALSE, 'bool' => TRUE),
        'external' => array('default' => FALSE, 'bool' => TRUE),
        'replace_spaces' => array('default' => FALSE, 'bool' => TRUE),
        'path_case' => array('default' => 'none', 'translatable' => FALSE),
        'trim_whitespace' => array('default' => FALSE, 'bool' => TRUE),
        'alt' => array('default' => '', 'translatable' => TRUE),
        'rel' => array('default' => ''),
        'link_class' => array('default' => ''),
        'prefix' => array('default' => '', 'translatable' => TRUE),
        'suffix' => array('default' => '', 'translatable' => TRUE),
430
        'target' => array('default' => ''),
merlinofchaos's avatar
merlinofchaos committed
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
        'nl2br' => array('default' => FALSE, 'bool' => TRUE),
        'max_length' => array('default' => ''),
        'word_boundary' => array('default' => TRUE, 'bool' => TRUE),
        'ellipsis' => array('default' => TRUE, 'bool' => TRUE),
        'more_link' => array('default' => FALSE, 'bool' => TRUE),
        'more_link_text' => array('default' => '', 'translatable' => TRUE),
        'more_link_path' => array('default' => ''),
        'strip_tags' => array('default' => FALSE, 'bool' => TRUE),
        'trim' => array('default' => FALSE, 'bool' => TRUE),
        'preserve_tags' => array('default' => ''),
        'html' => array('default' => FALSE, 'bool' => TRUE),
      ),
    );
    $options['element_type'] = array('default' => '');
    $options['element_class'] = array('default' => '');

    $options['element_label_type'] = array('default' => '');
    $options['element_label_class'] = array('default' => '');
    $options['element_label_colon'] = array('default' => TRUE, 'bool' => TRUE);

    $options['element_wrapper_type'] = array('default' => '');
    $options['element_wrapper_class'] = array('default' => '');

    $options['element_default_classes'] = array('default' => TRUE, 'bool' => TRUE);

    $options['empty'] = array('default' => '', 'translatable' => TRUE);
    $options['hide_empty'] = array('default' => FALSE, 'bool' => TRUE);
    $options['empty_zero'] = array('default' => FALSE, 'bool' => TRUE);
    $options['hide_alter_empty'] = array('default' => TRUE, 'bool' => TRUE);

    return $options;
  }

  /**
   * Performs some cleanup tasks on the options array before saving it.
   */
467
  public function submitOptionsForm(&$form, &$form_state) {
merlinofchaos's avatar
merlinofchaos committed
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
    $options = &$form_state['values']['options'];
    $types = array('element_type', 'element_label_type', 'element_wrapper_type');
    $classes = array_combine(array('element_class', 'element_label_class', 'element_wrapper_class'), $types);

    foreach ($types as $type) {
      if (!$options[$type . '_enable']) {
        $options[$type] = '';
      }
    }

    foreach ($classes as $class => $type) {
      if (!$options[$class . '_enable'] || !$options[$type . '_enable']) {
        $options[$class] = '';
      }
    }

    if (empty($options['custom_label'])) {
      $options['label'] = '';
      $options['element_label_colon'] = FALSE;
    }
  }

  /**
   * Default options form that provides the label widget that all fields
   * should have.
   */
494 495
  public function buildOptionsForm(&$form, &$form_state) {
    parent::buildOptionsForm($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
496 497 498 499 500 501 502 503 504 505 506 507

    $label = $this->label();
    $form['custom_label'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create a label'),
      '#default_value' => $label !== '',
      '#weight' => -103,
    );
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => t('Label'),
      '#default_value' => $label,
508 509 510 511
      '#states' => array(
        'visible' => array(
          ':input[name="options[custom_label]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
512 513 514 515 516 517 518
      ),
      '#weight' => -102,
    );
    $form['element_label_colon'] = array(
      '#type' => 'checkbox',
      '#title' => t('Place a colon after the label'),
      '#default_value' => $this->options['element_label_colon'],
519 520 521 522
      '#states' => array(
        'visible' => array(
          ':input[name="options[custom_label]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
523 524 525 526 527 528 529 530 531 532 533 534 535
      ),
      '#weight' => -101,
    );

    $form['exclude'] = array(
      '#type' => 'checkbox',
      '#title' => t('Exclude from display'),
      '#default_value' => $this->options['exclude'],
      '#description' => t('Enable to load this field as hidden. Often used to group fields, or to use as token in another field.'),
      '#weight' => -100,
    );

    $form['style_settings'] = array(
536
      '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
537 538 539 540 541 542 543 544 545 546 547 548
      '#title' => t('Style settings'),
      '#weight' => 99,
    );

    $form['element_type_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Customize field HTML'),
      '#default_value' => !empty($this->options['element_type']) || (string) $this->options['element_type'] == '0' || !empty($this->options['element_class']) || (string) $this->options['element_class'] == '0',
      '#fieldset' => 'style_settings',
    );
    $form['element_type'] = array(
      '#title' => t('HTML element'),
549
      '#options' => $this->getElements(),
merlinofchaos's avatar
merlinofchaos committed
550 551 552
      '#type' => 'select',
      '#default_value' => $this->options['element_type'],
      '#description' => t('Choose the HTML element to wrap around this field, e.g. H1, H2, etc.'),
553 554 555 556
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
557 558 559 560 561 562 563
      ),
      '#fieldset' => 'style_settings',
    );

    $form['element_class_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create a CSS class'),
564 565 566 567
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
568 569 570 571 572 573 574 575 576
      ),
      '#default_value' => !empty($this->options['element_class']) || (string) $this->options['element_class'] == '0',
      '#fieldset' => 'style_settings',
    );
    $form['element_class'] = array(
      '#title' => t('CSS class'),
      '#description' => t('You may use token substitutions from the rewriting section in this class.'),
      '#type' => 'textfield',
      '#default_value' => $this->options['element_class'],
577 578 579 580 581
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_type_enable]"]' => array('checked' => TRUE),
          ':input[name="options[element_class_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
582 583 584 585 586 587 588 589 590 591 592 593
      ),
      '#fieldset' => 'style_settings',
    );

    $form['element_label_type_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Customize label HTML'),
      '#default_value' => !empty($this->options['element_label_type']) || (string) $this->options['element_label_type'] == '0' || !empty($this->options['element_label_class']) || (string) $this->options['element_label_class'] == '0',
      '#fieldset' => 'style_settings',
    );
    $form['element_label_type'] = array(
      '#title' => t('Label HTML element'),
594
      '#options' => $this->getElements(FALSE),
merlinofchaos's avatar
merlinofchaos committed
595 596 597
      '#type' => 'select',
      '#default_value' => $this->options['element_label_type'],
      '#description' => t('Choose the HTML element to wrap around this label, e.g. H1, H2, etc.'),
598 599 600 601
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_label_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
602 603 604 605 606 607
      ),
      '#fieldset' => 'style_settings',
    );
    $form['element_label_class_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create a CSS class'),
608 609 610 611
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_label_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
612 613 614 615 616 617 618 619 620
      ),
      '#default_value' => !empty($this->options['element_label_class']) || (string) $this->options['element_label_class'] == '0',
      '#fieldset' => 'style_settings',
    );
    $form['element_label_class'] = array(
      '#title' => t('CSS class'),
      '#description' => t('You may use token substitutions from the rewriting section in this class.'),
      '#type' => 'textfield',
      '#default_value' => $this->options['element_label_class'],
621 622 623 624 625
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_label_type_enable]"]' => array('checked' => TRUE),
          ':input[name="options[element_label_class_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
626 627 628 629 630 631 632 633 634 635 636 637
      ),
      '#fieldset' => 'style_settings',
    );

    $form['element_wrapper_type_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Customize field and label wrapper HTML'),
      '#default_value' => !empty($this->options['element_wrapper_type']) || (string) $this->options['element_wrapper_type'] == '0' || !empty($this->options['element_wrapper_class']) || (string) $this->options['element_wrapper_class'] == '0',
      '#fieldset' => 'style_settings',
    );
    $form['element_wrapper_type'] = array(
      '#title' => t('Wrapper HTML element'),
638
      '#options' => $this->getElements(FALSE),
merlinofchaos's avatar
merlinofchaos committed
639 640 641
      '#type' => 'select',
      '#default_value' => $this->options['element_wrapper_type'],
      '#description' => t('Choose the HTML element to wrap around this field and label, e.g. H1, H2, etc. This may not be used if the field and label are not rendered together, such as with a table.'),
642 643 644 645
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_wrapper_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
646 647 648 649 650 651 652
      ),
      '#fieldset' => 'style_settings',
    );

    $form['element_wrapper_class_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Create a CSS class'),
653 654 655 656
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_wrapper_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
657 658 659 660 661 662 663 664 665
      ),
      '#default_value' => !empty($this->options['element_wrapper_class']) || (string) $this->options['element_wrapper_class'] == '0',
      '#fieldset' => 'style_settings',
    );
    $form['element_wrapper_class'] = array(
      '#title' => t('CSS class'),
      '#description' => t('You may use token substitutions from the rewriting section in this class.'),
      '#type' => 'textfield',
      '#default_value' => $this->options['element_wrapper_class'],
666 667 668 669 670
      '#states' => array(
        'visible' => array(
          ':input[name="options[element_wrapper_class_enable]"]' => array('checked' => TRUE),
          ':input[name="options[element_wrapper_type_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684
      ),
      '#fieldset' => 'style_settings',
    );

    $form['element_default_classes'] = array(
      '#type' => 'checkbox',
      '#title' => t('Add default classes'),
      '#default_value' => $this->options['element_default_classes'],
      '#description' => t('Use default Views classes to identify the field, field label and field content.'),
      '#fieldset' => 'style_settings',
    );

    $form['alter'] = array(
      '#title' => t('Rewrite results'),
685
      '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
686 687 688
      '#weight' => 100,
    );

689
    if ($this->allowAdvancedRender()) {
merlinofchaos's avatar
merlinofchaos committed
690 691 692
      $form['alter']['#tree'] = TRUE;
      $form['alter']['alter_text'] = array(
        '#type' => 'checkbox',
693
        '#title' => t('Override the output of this field with custom text'),
merlinofchaos's avatar
merlinofchaos committed
694 695 696 697 698 699 700 701
        '#default_value' => $this->options['alter']['alter_text'],
      );

      $form['alter']['text'] = array(
        '#title' => t('Text'),
        '#type' => 'textarea',
        '#default_value' => $this->options['alter']['text'],
        '#description' => t('The text to display for this field. You may include HTML. You may enter data from this view as per the "Replacement patterns" below.'),
702 703 704 705
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][alter_text]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
706 707 708 709 710
        ),
      );

      $form['alter']['make_link'] = array(
        '#type' => 'checkbox',
711
        '#title' => t('Output this field as a custom link'),
merlinofchaos's avatar
merlinofchaos committed
712 713 714 715 716 717 718
        '#default_value' => $this->options['alter']['make_link'],
      );
      $form['alter']['path'] = array(
        '#title' => t('Link path'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['path'],
        '#description' => t('The Drupal path or absolute URL for this link. You may enter data from this view as per the "Replacement patterns" below.'),
719 720 721 722
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
723 724 725 726 727 728 729
        ),
        '#maxlength' => 255,
      );
      $form['alter']['absolute'] = array(
        '#type' => 'checkbox',
        '#title' => t('Use absolute path'),
        '#default_value' => $this->options['alter']['absolute'],
730 731 732 733
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
734 735 736 737 738 739
        ),
      );
      $form['alter']['replace_spaces'] = array(
        '#type' => 'checkbox',
        '#title' => t('Replace spaces with dashes'),
        '#default_value' => $this->options['alter']['replace_spaces'],
740 741 742 743
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
744 745 746 747 748 749 750
        ),
      );
      $form['alter']['external'] = array(
        '#type' => 'checkbox',
        '#title' => t('External server URL'),
        '#default_value' => $this->options['alter']['external'],
        '#description' => t("Links to an external server using a full URL: e.g. 'http://www.example.com' or 'www.example.com'."),
751 752 753 754
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
755 756 757 758 759 760
        ),
      );
      $form['alter']['path_case'] = array(
        '#type' => 'select',
        '#title' => t('Transform the case'),
        '#description' => t('When printing url paths, how to transform the case of the filter value.'),
761 762 763 764
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        ),
       '#options' => array(
          'none' => t('No transform'),
          'upper' => t('Upper case'),
          'lower' => t('Lower case'),
          'ucfirst' => t('Capitalize first letter'),
          'ucwords' => t('Capitalize each word'),
        ),
        '#default_value' => $this->options['alter']['path_case'],
      );
      $form['alter']['link_class'] = array(
        '#title' => t('Link class'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['link_class'],
        '#description' => t('The CSS class to apply to the link.'),
780 781 782 783
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
784 785 786 787 788 789 790
        ),
      );
      $form['alter']['alt'] = array(
        '#title' => t('Title text'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['alt'],
        '#description' => t('Text to place as "title" text which most browsers display as a tooltip when hovering over the link.'),
791 792 793 794
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
795 796 797 798 799 800 801
        ),
      );
      $form['alter']['rel'] = array(
        '#title' => t('Rel Text'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['rel'],
        '#description' => t('Include Rel attribute for use in lightbox2 or other javascript utility.'),
802 803 804 805
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
806 807 808 809 810 811 812
        ),
      );
      $form['alter']['prefix'] = array(
        '#title' => t('Prefix text'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['prefix'],
        '#description' => t('Any text to display before this link. You may include HTML.'),
813 814 815 816
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
817 818 819 820 821 822 823
        ),
      );
      $form['alter']['suffix'] = array(
        '#title' => t('Suffix text'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['suffix'],
        '#description' => t('Any text to display after this link. You may include HTML.'),
824 825 826 827
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
828 829 830 831 832 833 834
        ),
      );
      $form['alter']['target'] = array(
        '#title' => t('Target'),
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['target'],
        '#description' => t("Target of the link, such as _blank, _parent or an iframe's name. This field is rarely used."),
835 836 837 838
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
839 840 841 842 843
        ),
      );


      // Get a list of the available fields and arguments for token replacement.
844 845 846 847 848

      // Setup the tokens for fields.
      $previous = $this->getPreviousFieldLabels();
      foreach ($previous as $id => $label) {
        $options[t('Fields')]["[$id]"] = $label;
merlinofchaos's avatar
merlinofchaos committed
849
      }
850

merlinofchaos's avatar
merlinofchaos committed
851
      $count = 0; // This lets us prepare the key as we want it printed.
852
      foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
853 854
        $options[t('Arguments')]['%' . ++$count] = t('@argument title', array('@argument' => $handler->adminLabel()));
        $options[t('Arguments')]['!' . $count] = t('@argument input', array('@argument' => $handler->adminLabel()));
merlinofchaos's avatar
merlinofchaos committed
855 856 857 858 859 860 861 862 863
      }

      $this->document_self_tokens($options[t('Fields')]);

      // Default text.
      $output = t('<p>You must add some additional fields to this display before using this field. These fields may be marked as <em>Exclude from display</em> if you prefer. Note that due to rendering order, you cannot use fields that come after this field; if you need a field not listed here, rearrange your fields.</p>');
      // We have some options, so make a list.
      if (!empty($options)) {
        $output = t('<p>The following tokens are available for this field. Note that due to rendering order, you cannot use fields that come after this field; if you need a field not listed here, rearrange your fields.
864
If you would like to have the characters \'[\' and \']\' use the html entity codes \'%5B\' or  \'%5D\' or they will get replaced with empty space.</p>');
merlinofchaos's avatar
merlinofchaos committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        foreach (array_keys($options) as $type) {
          if (!empty($options[$type])) {
            $items = array();
            foreach ($options[$type] as $key => $value) {
              $items[] = $key . ' == ' . $value;
            }
            $output .= theme('item_list',
              array(
                'items' => $items,
                'type' => $type
              ));
          }
        }
      }
      // This construct uses 'hidden' and not markup because process doesn't
      // run. It also has an extra div because the dependency wants to hide
      // the parent in situations like this, so we need a second div to
      // make this work.
      $form['alter']['help'] = array(
884
        '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
885 886
        '#title' => t('Replacement patterns'),
        '#value' => $output,
887 888 889 890 891 892 893 894 895 896 897 898
        '#states' => array(
          'visible' => array(
            array(
              ':input[name="options[alter][make_link]"]' => array('checked' => TRUE),
            ),
            array(
              ':input[name="options[alter][alter_text]"]' => array('checked' => TRUE),
            ),
            array(
              ':input[name="options[alter][more_link]"]' => array('checked' => TRUE),
            ),
          ),
merlinofchaos's avatar
merlinofchaos committed
899 900 901 902 903
        ),
      );

      $form['alter']['trim'] = array(
        '#type' => 'checkbox',
904
        '#title' => t('Trim this field to a maximum number of characters'),
merlinofchaos's avatar
merlinofchaos committed
905 906 907 908
        '#default_value' => $this->options['alter']['trim'],
      );

      $form['alter']['max_length'] = array(
909
        '#title' => t('Maximum number of characters'),
merlinofchaos's avatar
merlinofchaos committed
910 911
        '#type' => 'textfield',
        '#default_value' => $this->options['alter']['max_length'],
912 913 914 915
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
916 917 918 919 920 921 922 923
        ),
      );

      $form['alter']['word_boundary'] = array(
        '#type' => 'checkbox',
        '#title' => t('Trim only on a word boundary'),
        '#description' => t('If checked, this field be trimmed only on a word boundary. This is guaranteed to be the maximum characters stated or less. If there are no word boundaries this could trim a field to nothing.'),
        '#default_value' => $this->options['alter']['word_boundary'],
924 925 926 927
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
928 929 930 931 932
        ),
      );

      $form['alter']['ellipsis'] = array(
        '#type' => 'checkbox',
933
        '#title' => t('Add "..." at the end of trimmed text'),
merlinofchaos's avatar
merlinofchaos committed
934
        '#default_value' => $this->options['alter']['ellipsis'],
935 936 937 938
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
939 940 941 942 943 944 945
        ),
      );

      $form['alter']['more_link'] = array(
        '#type' => 'checkbox',
        '#title' => t('Add a read-more link if output is trimmed.'),
        '#default_value' => $this->options['alter']['more_link'],
946 947 948 949
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
950 951 952 953 954
        ),
      );

      $form['alter']['more_link_text'] = array(
        '#type' => 'textfield',
955
        '#title' => t('More link label'),
merlinofchaos's avatar
merlinofchaos committed
956
        '#default_value' => $this->options['alter']['more_link_text'],
957
        '#description' => t('You may use the "Replacement patterns" above.'),
958 959 960 961 962
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
            ':input[name="options[alter][more_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
963 964 965 966 967 968
        ),
      );
      $form['alter']['more_link_path'] = array(
        '#type' => 'textfield',
        '#title' => t('More link path'),
        '#default_value' => $this->options['alter']['more_link_path'],
969
        '#description' => t('This can be an internal Drupal path such as node/add or an external URL such as "http://drupal.org". You may use the "Replacement patterns" above.'),
970 971 972 973 974
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
            ':input[name="options[alter][more_link]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
975 976 977 978 979 980
        ),
      );

      $form['alter']['html'] = array(
        '#type' => 'checkbox',
        '#title' => t('Field can contain HTML'),
981
        '#description' => t('An HTML corrector will be run to ensure HTML tags are properly closed after trimming.'),
merlinofchaos's avatar
merlinofchaos committed
982
        '#default_value' => $this->options['alter']['html'],
983 984 985 986
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][trim]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
987 988 989 990 991 992 993 994 995 996 997 998 999 1000
        ),
      );

      $form['alter']['strip_tags'] = array(
        '#type' => 'checkbox',
        '#title' => t('Strip HTML tags'),
        '#default_value' => $this->options['alter']['strip_tags'],
      );

      $form['alter']['preserve_tags'] = array(
        '#type' => 'textfield',
        '#title' => t('Preserve certain tags'),
        '#description' => t('List the tags that need to be preserved during the stripping process. example &quot;&lt;p&gt; &lt;br&gt;&quot; which will preserve all p and br elements'),
        '#default_value' => $this->options['alter']['preserve_tags'],
1001 1002 1003 1004
        '#states' => array(
          'visible' => array(
            ':input[name="options[alter][strip_tags]"]' => array('checked' => TRUE),
          ),
merlinofchaos's avatar
merlinofchaos committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        ),
      );

      $form['alter']['trim_whitespace'] = array(
        '#type' => 'checkbox',
        '#title' => t('Remove whitespace'),
        '#default_value' => $this->options['alter']['trim_whitespace'],
      );

      $form['alter']['nl2br'] = array(
        '#type' => 'checkbox',
        '#title' => t('Convert newlines to HTML &lt;br&gt; tags'),
        '#default_value' => $this->options['alter']['nl2br'],
      );
    }

    $form['empty_field_behavior'] = array(
1022
      '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
1023 1024 1025 1026 1027 1028 1029 1030
      '#title' => t('No results behavior'),
      '#weight' => 100,
    );

    $form['empty'] = array(
      '#type' => 'textarea',
      '#title' => t('No results text'),
      '#default_value' => $this->options['empty'],
1031
      '#description' => t('Provide text to display if this field contains an empty result. You may include HTML. You may enter data from this view as per the "Replacement patterns" in the "Rewrite Results" section below.'),
merlinofchaos's avatar
merlinofchaos committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      '#fieldset' => 'empty_field_behavior',
    );

    $form['empty_zero'] = array(
      '#type' => 'checkbox',
      '#title' => t('Count the number 0 as empty'),
      '#default_value' => $this->options['empty_zero'],
      '#description' => t('Enable to display the "no results text" if the field contains the number 0.'),
      '#fieldset' => 'empty_field_behavior',
    );

    $form['hide_empty'] = array(
      '#type' => 'checkbox',
      '#title' => t('Hide if empty'),
      '#default_value' => $this->options['hide_empty'],
      '#description' => t('Enable to hide this field if it is empty. Note that the field label or rewritten output may still be displayed. To hide labels, check the style or row style settings for empty fields. To hide rewritten content, check the "Hide rewriting if empty" checkbox.'),
      '#fieldset' => 'empty_field_behavior',
    );

    $form['hide_alter_empty'] = array(
      '#type' => 'checkbox',
      '#title' => t('Hide rewriting if empty'),
      '#default_value' => $this->options['hide_alter_empty'],
      '#description' => t('Do not display rewritten content if this field is empty.'),
      '#fieldset' => 'empty_field_behavior',
    );
  }

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  /**
   * Returns all field lables of fields before this field.
   *
   * @return array
   *   An array of field labels keyed by their field IDs.
   */
  protected function getPreviousFieldLabels() {
    $all_fields = $this->view->display_handler->getFieldLabels();
    $field_options = array_slice($all_fields, 0, array_search($this->options['id'], array_keys($all_fields)));
    return $field_options;
  }

merlinofchaos's avatar
merlinofchaos committed
1072 1073 1074
  /**
   * Provide extra data to the administration form
   */
1075
  public function adminSummary() {
merlinofchaos's avatar
merlinofchaos committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    return $this->label();
  }

  /**
   * Run before any fields are rendered.
   *
   * This gives the handlers some time to set up before any handler has
   * been rendered.
   *
   * @param $values
   *   An array of all objects returned from the query.
   */
  function pre_render(&$values) { }

  /**
   * Render the field.
   *
   * @param $values
   *   The values retrieved from the database.
   */
  function render($values) {
    $value = $this->get_value($values);
1098
    return $this->sanitizeValue($value);
merlinofchaos's avatar
merlinofchaos committed
1099 1100 1101 1102 1103 1104 1105 1106 1107
  }

  /**
   * Render a field using advanced settings.
   *
   * This renders a field normally, then decides if render-as-link and
   * text-replacement rendering is necessary.
   */
  function advanced_render($values) {
1108
    if ($this->allowAdvancedRender() && method_exists($this, 'render_item')) {
merlinofchaos's avatar
merlinofchaos committed
1109
      $raw_items = $this->get_items($values);
1110 1111 1112 1113
      // If there are no items, set the original value to NULL.
      if (empty($raw_items)) {
        $this->original_value = NULL;
      }
merlinofchaos's avatar
merlinofchaos committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    }
    else {
      $value = $this->render($values);
      if (is_array($value)) {
        $value = drupal_render($value);
      }
      $this->last_render = $value;
      $this->original_value = $value;
    }

1124
    if ($this->allowAdvancedRender()) {
merlinofchaos's avatar
merlinofchaos committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
      $tokens = NULL;
      if (method_exists($this, 'render_item')) {
        $items = array();
        foreach ($raw_items as $count => $item) {
          $value = $this->render_item($count, $item);
          if (is_array($value)) {
            $value = drupal_render($value);
          }
          $this->last_render = $value;
          $this->original_value = $this->last_render;

          $alter = $item + $this->options['alter'];
          $alter['phase'] = VIEWS_HANDLER_RENDER_TEXT_PHASE_SINGLE_ITEM;
1138
          $items[] = $this->renderText($alter);
merlinofchaos's avatar
merlinofchaos committed
1139 1140 1141 1142 1143 1144
        }

        $value = $this->render_items($items);
      }
      else {
        $alter = array('phase' => VIEWS_HANDLER_RENDER_TEXT_PHASE_COMPLETELY) + $this->options['alter'];
1145
        $value = $this->renderText($alter);
merlinofchaos's avatar
merlinofchaos committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
      }

      if (is_array($value)) {
        $value = drupal_render($value);
      }
      // This happens here so that render_as_link can get the unaltered value of
      // this field as a token rather than the altered value.
      $this->last_render = $value;
    }

    if (empty($this->last_render)) {
      if ($this->is_value_empty($this->last_render, $this->options['empty_zero'], FALSE)) {
        $alter = $this->options['alter'];
        $alter['alter_text'] = 1;
        $alter['text'] = $this->options['empty'];
        $alter['phase'] = VIEWS_HANDLER_RENDER_TEXT_PHASE_EMPTY;
1162
        $this->last_render = $this->renderText($alter);
merlinofchaos's avatar
merlinofchaos committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
      }
    }

    return $this->last_render;
  }

  /**
   * Checks if a field value is empty.
   *
   * @param $value
   *   The field value.
   * @param bool $empty_zero
   *   Whether or not this field is configured to consider 0 as empty.
   * @param bool $no_skip_empty
   *   Whether or not to use empty() to check the value.
   *
   * @return bool
   * TRUE if the value is considered empty, FALSE otherwise.
   */
  function is_value_empty($value, $empty_zero, $no_skip_empty = TRUE) {
    if (!isset($value)) {
      $empty = TRUE;
    }
    else {
      $empty = ($empty_zero || ($value !== 0 && $value !== '0'));
    }

    if ($no_skip_empty) {
      $empty = empty($value) && $empty;
    }
    return $empty;
  }

  /**
   * Perform an advanced text render for the item.
   *
   * This is separated out as some fields may render lists, and this allows
   * each item to be handled individually.
   */
1202
  public function renderText($alter) {
merlinofchaos's avatar
merlinofchaos committed
1203 1204 1205
    $value = $this->last_render;

    if (!empty($alter['alter_text']) && $alter['text'] !== '') {
1206
      $tokens = $this->getRenderTokens($alter);
merlinofchaos's avatar
merlinofchaos committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
      $value = $this->render_altered($alter, $tokens);
    }

    if (!empty($this->options['alter']['trim_whitespace'])) {
      $value = trim($value);
    }

    // Check if there should be no further rewrite for empty values.
    $no_rewrite_for_empty = $this->options['hide_alter_empty'] && $this->is_value_empty($this->original_value, $this->options['empty_zero']);

    // Check whether the value is empty and return nothing, so the field isn't rendered.
    // First check whether the field should be hidden if the value(hide_alter_empty = TRUE) /the rewrite is empty (hide_alter_empty = FALSE).
    // For numeric values you can specify whether "0"/0 should be empty.
    if ((($this->options['hide_empty'] && empty($value))
        || ($alter['phase'] != VIEWS_HANDLER_RENDER_TEXT_PHASE_EMPTY && $no_rewrite_for_empty))
      && $this->is_value_empty($value, $this->options['empty_zero'], FALSE)) {
      return '';
    }
    // Only in empty phase.
    if ($alter['phase'] == VIEWS_HANDLER_RENDER_TEXT_PHASE_EMPTY && $no_rewrite_for_empty) {
      // If we got here then $alter contains the value of "No results text"
      // and so there is nothing left to do.
      return $value;
    }

    if (!empty($alter['strip_tags'])) {
      $value = strip_tags($value, $alter['preserve_tags']);
    }

    $suffix = '';
    if (!empty($alter['trim']) && !empty($alter['max_length'])) {
      $length = strlen($value);
      $value = $this->render_trim_text($alter, $value);
      if ($this->options['alter']['more_link'] && strlen($value) < $length) {
1241
        $tokens = $this->getRenderTokens($alter);
merlinofchaos's avatar
merlinofchaos committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
        $more_link_text = $this->options['alter']['more_link_text'] ? $this->options['alter']['more_link_text'] : t('more');
        $more_link_text = strtr(filter_xss_admin($more_link_text), $tokens);
        $more_link_path = $this->options['alter']['more_link_path'];
        $more_link_path = strip_tags(decode_entities(strtr($more_link_path, $tokens)));

        // Take sure that paths which was runned through url() does work as well.
        $base_path = base_path();
        // Checks whether the path starts with the base_path.
        if (strpos($more_link_path, $base_path) === 0) {
          $more_link_path = drupal_substr($more_link_path, drupal_strlen($base_path));
        }

1254
        $more_link = l($more_link_text, $more_link_path, array('attributes' => array('class' => array('views-more-link'))));
merlinofchaos's avatar
merlinofchaos committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266

        $suffix .= " " . $more_link;
      }
    }

    if (!empty($alter['nl2br'])) {
      $value = nl2br($value);
    }
    $this->last_render_text = $value;

    if (!empty($alter['make_link']) && !empty($alter['path'])) {
      if (!isset($tokens)) {
1267
        $tokens = $this->getRenderTokens($alter);
merlinofchaos's avatar
merlinofchaos committed
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
      }
      $value = $this->render_as_link($alter, $value, $tokens);
    }

    return $value . $suffix;
  }

  /**
   * Render this field as altered text, from a fieldset set by the user.
   */
  function render_altered($alter, $tokens) {
    // Filter this right away as our substitutions are already sanitized.
    $value = filter_xss_admin($alter['text']);
    $value = strtr($value, $tokens);

    return $value;
  }

  /**
   * Trim the field down to the specified length.
   */
  function render_trim_text($alter, $value) {
    if (!empty($alter['strip_tags'])) {
      // NOTE: It's possible that some external fields might override the
1292
      // element type.
merlinofchaos's avatar
merlinofchaos committed
1293 1294
      $this->definition['element type'] = 'span';
    }
1295
    return static::trimText($alter, $value);
merlinofchaos's avatar
merlinofchaos committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
  }

  /**
   * Render this field as a link, with the info from a fieldset set by
   * the user.
   */
  function render_as_link($alter, $text, $tokens) {
    $value = '';

    if (!empty($alter['prefix'])) {
      $value .= filter_xss_admin(strtr($alter['prefix'], $tokens));
    }

    $options = array(
      'html' => TRUE,
      'absolute' => !empty($alter['absolute']) ? TRUE : FALSE,
    );

    // $path will be run through check_url() by l() so we do not need to
    // sanitize it ourselves.
    $path = $alter['path'];

    // strip_tags() removes <front>, so check whether its different to front.
    if ($path != '<front>') {
      // Use strip tags as there should never be HTML in the path.
      // However, we need to preserve special characters like " that
      // were removed by check_plain().
      $path = strip_tags(decode_entities(strtr($path, $tokens)));

      if (!empty($alter['path_case']) && $alter['path_case'] != 'none') {
1326
        $path = $this->caseTransform($path, $this->options['alter']['path_case']);
merlinofchaos's avatar
merlinofchaos committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
      }

      if (!empty($alter['replace_spaces'])) {
        $path = str_replace(' ', '-', $path);
      }
    }

    // Parse the URL and move any query and fragment parameters out of the path.
    $url = parse_url($path);

    // Seriously malformed URLs may return FALSE or empty arrays.
    if (empty($url)) {
      return $text;
    }

    // If the path is empty do not build a link around the given text and return
    // it as is.
    // http://www.example.com URLs will not have a $url['path'], so check host as well.
    if (empty($url['path']) && empty($url['host']) && empty($url['fragment'])) {
      return $text;
    }

    // If no scheme is provided in the $path, assign the default 'http://'.
    // This allows a url of 'www.example.com' to be converted to 'http://www.example.com'.
    // Only do this on for external URLs.
1352
    if ($alter['external']) {
merlinofchaos's avatar
merlinofchaos committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
      if (!isset($url['scheme'])) {
        // There is no scheme, add the default 'http://' to the $path.
        $path = "http://$path";
        // Reset the $url array to include the new scheme.
        $url = parse_url($path);
      }
    }

    if (isset($url['query'])) {
      $path = strtr($path, array('?' . $url['query'] => ''));
      $query = drupal_get_query_array($url['query']);
      // Remove query parameters that were assigned a query string replacement
      // token for which there is no value available.
      foreach ($query as $param => $val) {
        if ($val == '%' . $param) {
          unset($query[$param]);
        }
      }
      $options['query'] = $query;
    }
    if (isset($url['fragment'])) {
      $path = strtr($path, array('#' . $url['fragment'] => ''));
      // If the path is empty we want to have a fragment for the current site.
      if ($path == '') {
        $options['external'] = TRUE;
      }
      $options['fragment'] = $url['fragment'];
    }

    $alt = strtr($alter['alt'], $tokens);
    // Set the title attribute of the link only if it improves accessibility
    if ($alt && $alt != $text) {
      $options['attributes']['title'] = decode_entities($alt);
    }

    $class = strtr($alter['link_class'], $tokens);
    if ($class) {
      $options['attributes']['class'] = array($class);
    }

    if (!empty($alter['rel']) && $rel = strtr($alter['rel'], $tokens)) {
      $options['attributes']['rel'] = $rel;
    }

1397
    $target = check_plain(trim(strtr($alter['target'], $tokens)));
merlinofchaos's avatar
merlinofchaos committed
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    if (!empty($target)) {
      $options['attributes']['target'] = $target;
    }

    // Allow the addition of arbitrary attributes to links. Additional attributes
    // currently can only be altered in preprocessors and not within the UI.
    if (isset($alter['link_attributes']) && is_array($alter['link_attributes'])) {
      foreach ($alter['link_attributes'] as $key => $attribute) {
        if (!isset($options['attributes'][$key])) {
          $options['attributes'][$key] = strtr($attribute, $tokens);
        }
      }
    }

    // If the query and fragment were programatically assigned overwrite any
    // parsed values.
    if (isset($alter['query'])) {
      // Convert the query to a string, perform token replacement, and then
      // convert back to an array form for l().
      $options['query'] = drupal_http_build_query($alter['query']);
      $options['query'] = strtr($options['query'], $tokens);
      $options['query'] = drupal_get_query_array($options['query']);
    }
    if (isset($alter['alias'])) {
      // Alias is a boolean field, so no token.
      $options['alias'] = $alter['alias'];
    }
    if (isset($alter['fragment'])) {
      $options['fragment'] = strtr($alter['fragment'], $tokens);
    }
    if (isset($alter['language'])) {
      $options['language'] = $alter['language'];
    }

    // If the url came from entity_uri(), pass along the required options.
    if (isset($alter['entity'])) {
      $options['entity'] = $alter['entity'];
    }
    if (isset($alter['entity_type'])) {
      $options['entity_type'] = $alter['entity_type'];
    }

    $value .= l($text, $path, $options);

    if (!empty($alter['suffix'])) {
      $value .= filter_xss_admin(strtr($alter['suffix'], $tokens));
    }

    return $value;
  }

  /**
   * Get the 'render' tokens to use for advanced rendering.
   *
   * This runs through all of the fields and arguments that
   * are available and gets their values. This will then be
   * used in one giant str_replace().
   */
1456
  public function getRenderTokens($item) {
merlinofchaos's avatar
merlinofchaos committed
1457 1458 1459 1460 1461
    $tokens = array();
    if (!empty($this->view->build_info['substitutions'])) {
      $tokens = $this->view->build_info['substitutions'];
    }
    $count = 0;
1462
    foreach ($this->view->display_handler->getHandlers('argument') as $arg => $handler) {
merlinofchaos's avatar
merlinofchaos committed
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
      $token = '%' . ++$count;
      if (!isset($tokens[$token])) {
        $tokens[$token] = '';
      }

      // Use strip tags as there should never be HTML in the path.
      // However, we need to preserve special characters like " that
      // were removed by check_plain().
      $tokens['!' . $count] = isset($this->view->args[$count - 1]) ? strip_tags(decode_entities($this->view->args[$count - 1])) : '';
    }

1474
    // Get flattened set of tokens for any array depth in $_GET parameters.
1475
    $tokens += $this->getTokenValuesRecursive(drupal_container()->get('request')->query->all());
merlinofchaos's avatar
merlinofchaos committed
1476 1477

    // Now add replacements for our fields.
1478
    foreach ($this->view->display_handler->getHandlers('field') as $field => $handler) {
merlinofchaos's avatar
merlinofchaos committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
      if (isset($handler->last_render)) {
        $tokens["[$field]"] = $handler->last_render;
      }
      else {
        $tokens["[$field]"] = '';
      }

      // We only use fields up to (and including) this one.
      if ($field == $this->options['id']) {
        break;
      }
    }

    // Store the tokens for the row so we can reference them later if necessary.
    $this->view->style_plugin->render_tokens[$this->view->row_index] = $tokens;
    $this->last_tokens = $tokens;
1495
    if (!empty($item)) {
1496
      $this->addSelfTokens($tokens, $item);
1497
    }
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

    return $tokens;
  }

  /**
   * Recursive function to add replacements for nested query string parameters.
   *
   * E.g. if you pass in the following array:
   *   array(
   *     'foo' => array(
   *       'a' => 'value',
   *       'b' => 'value',
   *     ),
   *     'bar' => array(
   *       'a' => 'value',
   *       'b' => array(
   *         'c' => value,
   *       ),
   *     ),
   *   );
   *
   * Would yield the following array of tokens:
   *   array(
   *     '%foo_a' => 'value'
   *     '%foo_b' => 'value'
   *     '%bar_a' => 'value'
   *     '%bar_b_c' => 'value'
   *   );
   *
   * @param $array
   *   An array of values.
   *
   * @param $parent_keys
   *   An array of parent keys. This will represent the array depth.
   *
   * @return
   *   An array of available tokens, with nested keys representative of the array structure.
   */
1536
  protected function getTokenValuesRecursive(array $array, array $parent_keys = array()) {
1537 1538 1539 1540
    $tokens = array();

    foreach ($array as $param => $val) {
      if (is_array($val)) {
1541 1542 1543 1544 1545
        // Copy parent_keys array, so we don't affect other elements of this
        // iteration.
        $child_parent_keys = $parent_keys;
        $child_parent_keys[] = $param;
        // Get the child tokens.
1546
        $child_tokens = $this->getTokenValuesRecursive($val, $child_parent_keys);
1547 1548
        // Add them to the current tokens array.
        $tokens += $child_tokens;
1549 1550 1551 1552 1553 1554 1555 1556
      }
      else {
        // Create a token key based on array element structure.
        $token_string = !empty($parent_keys) ? implode('_', $parent_keys) . '_' . $param : $param;
        $tokens['%' . $token_string] = strip_tags(decode_entities($val));
      }
    }

merlinofchaos's avatar
merlinofchaos committed
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
    return $tokens;
  }

  /**
   * Add any special tokens this field might use for itself.
   *
   * This method is intended to be overridden by items that generate
   * fields as a list. For example, the field that displays all terms
   * on a node might have tokens for the tid and the term.
   *
   * By convention, tokens should follow the format of [token-subtoken]
   * where token is the field ID and subtoken is the field. If the
   * field ID is terms, then the tokens might be [terms-tid] and [terms-name].
   */
1571
  protected function addSelfTokens(&$tokens, $item) { }
merlinofchaos's avatar
merlinofchaos committed
1572 1573 1574 1575

  /**
   * Document any special tokens this field might use for itself.
   *
alexpott's avatar