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

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

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

10
use Drupal\views\Plugin\views\PluginBase;
11
use Drupal\views\Plugin\views\display\DisplayPluginBase;
12
use Drupal\views\ViewExecutable;
13
use Drupal\views\Plugin\views\HandlerBase;
14
use Drupal\views\Views;
15

merlinofchaos's avatar
merlinofchaos committed
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
/**
 * @defgroup views_argument_handlers Views argument handlers
 * Handlers to tell Views how to contextually filter queries.
 * @{
 */

/**
 * Base class for arguments.
 *
 * The basic argument works for very simple arguments such as nid and uid
 *
 * Definition terms for this handler:
 * - name field: The field to use for the name to use in the summary, which is
 *               the displayed output. For example, for the node: nid argument,
 *               the argument itself is the nid, but node.title is displayed.
 * - name table: The table to use for the name, should it not be in the same
 *               table as the argument.
 * - empty field name: For arguments that can have no value, such as taxonomy
 *                     which can have "no term", this is the string which
 *                     will be displayed for this lack of value. Be sure to use
 *                     t().
 * - validate type: A little used string to allow an argument to restrict
 *                  which validator is available to just one. Use the
 *                  validator ID. This probably should not be used at all,
 *                  and may disappear or change.
 * - numeric: If set to TRUE this field is numeric and will use %d instead of
 *            %s in queries.
 *
 * @ingroup views_argument_handlers
 */
46
abstract class ArgumentPluginBase extends HandlerBase {
47

merlinofchaos's avatar
merlinofchaos committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  var $validator = NULL;
  var $argument = NULL;
  var $value = NULL;

  /**
   * The table to use for the name, should it not be in the same table as the argument.
   * @var string
   */
  var $name_table;

  /**
   * The field to use for the name to use in the summary, which is
   * the displayed output. For example, for the node: nid argument,
   * the argument itself is the nid, but node.title is displayed.
   * @var string
   */
  var $name_field;

  /**
67
   * Overrides Drupal\views\Plugin\views\HandlerBase:init().
merlinofchaos's avatar
merlinofchaos committed
68
   */
69 70
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
merlinofchaos's avatar
merlinofchaos committed
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

    if (!empty($this->definition['name field'])) {
      $this->name_field = $this->definition['name field'];
    }
    if (!empty($this->definition['name table'])) {
      $this->name_table = $this->definition['name table'];
    }
  }

  /**
   * Give an argument the opportunity to modify the breadcrumb, if it wants.
   * This only gets called on displays where a breadcrumb is actually used.
   *
   * The breadcrumb will be in the form of an array, with the keys being
   * the path and the value being the already sanitized title of the path.
   */
  function set_breadcrumb(&$breadcrumb) { }

  /**
   * Determine if the argument can generate a breadcrumb
   *
   * @return TRUE/FALSE
   */
  function uses_breadcrumb() {
    $info = $this->default_actions($this->options['default_action']);
    return !empty($info['breadcrumb']);
  }

  function is_exception($arg = NULL) {
    if (!isset($arg)) {
      $arg = isset($this->argument) ? $this->argument : NULL;
    }
    return !empty($this->options['exception']['value']) && $this->options['exception']['value'] === $arg;
  }

  function exception_title() {
    // If title overriding is off for the exception, return the normal title.
    if (empty($this->options['exception']['title_enable'])) {
109
      return $this->getTitle();
merlinofchaos's avatar
merlinofchaos committed
110 111 112 113 114 115 116 117 118
    }
    return $this->options['exception']['title'];
  }

  /**
   * Determine if the argument needs a style plugin.
   *
   * @return TRUE/FALSE
   */
119
  public function needsStylePlugin() {
merlinofchaos's avatar
merlinofchaos committed
120 121 122 123 124
    $info = $this->default_actions($this->options['default_action']);
    $validate_info = $this->default_actions($this->options['validate']['fail']);
    return !empty($info['style plugin']) || !empty($validate_info['style plugin']);
  }

125 126
  protected function defineOptions() {
    $options = parent::defineOptions();
merlinofchaos's avatar
merlinofchaos committed
127 128 129 130 131 132

    $options['default_action'] = array('default' => 'ignore');
    $options['exception'] = array(
      'contains' => array(
        'value' => array('default' => 'all'),
        'title_enable' => array('default' => FALSE, 'bool' => TRUE),
133
        'title' => array('default' => 'All', 'translatable' => TRUE),
merlinofchaos's avatar
merlinofchaos committed
134 135 136 137 138 139
      ),
    );
    $options['title_enable'] = array('default' => FALSE, 'bool' => TRUE);
    $options['title'] = array('default' => '', 'translatable' => TRUE);
    $options['breadcrumb_enable'] = array('default' => FALSE, 'bool' => TRUE);
    $options['breadcrumb'] = array('default' => '', 'translatable' => TRUE);
140 141
    $options['default_argument_type'] = array('default' => 'fixed');
    $options['default_argument_options'] = array('default' => array());
merlinofchaos's avatar
merlinofchaos committed
142
    $options['default_argument_skip_url'] = array('default' => FALSE, 'bool' => TRUE);
143
    $options['summary_options'] = array('default' => array());
merlinofchaos's avatar
merlinofchaos committed
144 145 146 147
    $options['summary'] = array(
      'contains' => array(
        'sort_order' => array('default' => 'asc'),
        'number_of_records' => array('default' => 0),
148
        'format' => array('default' => 'default_summary'),
merlinofchaos's avatar
merlinofchaos committed
149 150 151 152 153
      ),
    );
    $options['specify_validation'] = array('default' => FALSE, 'bool' => TRUE);
    $options['validate'] = array(
      'contains' => array(
154
        'type' => array('default' => 'none'),
merlinofchaos's avatar
merlinofchaos committed
155 156 157
        'fail' => array('default' => 'not found'),
      ),
    );
158
    $options['validate_options'] = array('default' => array());
merlinofchaos's avatar
merlinofchaos committed
159 160 161 162

    return $options;
  }

163 164
  public function buildOptionsForm(&$form, &$form_state) {
    parent::buildOptionsForm($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
165

166
    $argument_text = $this->view->display_handler->getArgumentText();
merlinofchaos's avatar
merlinofchaos committed
167 168 169 170 171 172 173 174 175 176

    $form['#pre_render'][] = 'views_ui_pre_render_move_argument_options';

    $form['description'] = array(
      '#markup' => $argument_text['description'],
      '#theme_wrappers' => array('container'),
      '#attributes' => array('class' => array('description')),
    );

    $form['no_argument'] = array(
177
      '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
178 179
      '#title' => $argument_text['filter value not present'],
    );
180
    // Everything in the details is floated, so the last element needs to
merlinofchaos's avatar
merlinofchaos committed
181 182 183 184 185 186 187
    // clear those floats.
    $form['no_argument']['clearfix'] = array(
      '#weight' => 1000,
      '#markup' => '<div class="clearfix"></div>',
    );
    $form['default_action'] = array(
      '#type' => 'radios',
188
      '#process' => array(array($this, 'processContainerRadios')),
merlinofchaos's avatar
merlinofchaos committed
189 190 191 192 193
      '#default_value' => $this->options['default_action'],
      '#fieldset' => 'no_argument',
    );

    $form['exception'] = array(
194
      '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
      '#title' => t('Exceptions'),
      '#collapsed' => TRUE,
      '#fieldset' => 'no_argument',
    );
    $form['exception']['value'] = array(
      '#type' => 'textfield',
      '#title' => t('Exception value'),
      '#size' => 20,
      '#default_value' => $this->options['exception']['value'],
      '#description' => t('If this value is received, the filter will be ignored; i.e, "all values"'),
    );
    $form['exception']['title_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Override title'),
      '#default_value' => $this->options['exception']['title_enable'],
    );
    $form['exception']['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Override title'),
      '#title_display' => 'invisible',
      '#size' => 20,
      '#default_value' => $this->options['exception']['title'],
      '#description' => t('Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc.'),
218 219 220 221
      '#states' => array(
        'visible' => array(
          ':input[name="options[exception][title_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      ),
    );

    $options = array();
    $defaults = $this->default_actions();
    $validate_options = array();
    foreach ($defaults as $id => $info) {
      $options[$id] = $info['title'];
      if (empty($info['default only'])) {
        $validate_options[$id] = $info['title'];
      }
      if (!empty($info['form method'])) {
        $this->{$info['form method']}($form, $form_state);
      }
    }
    $form['default_action']['#options'] = $options;

    $form['argument_present'] = array(
240
      '#type' => 'details',
merlinofchaos's avatar
merlinofchaos committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254
      '#title' => $argument_text['filter value present'],
    );
    $form['title_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Override title'),
      '#default_value' => $this->options['title_enable'],
      '#fieldset' => 'argument_present',
    );
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Provide title'),
      '#title_display' => 'invisible',
      '#default_value' => $this->options['title'],
      '#description' => t('Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc.'),
255 256 257 258
      '#states' => array(
        'visible' => array(
          ':input[name="options[title_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
      ),
      '#fieldset' => 'argument_present',
    );

    $form['breadcrumb_enable'] = array(
      '#type' => 'checkbox',
      '#title' => t('Override breadcrumb'),
      '#default_value' => $this->options['breadcrumb_enable'],
      '#fieldset' => 'argument_present',
    );
    $form['breadcrumb'] = array(
      '#type' => 'textfield',
      '#title' => t('Provide breadcrumb'),
      '#title_display' => 'invisible',
      '#default_value' => $this->options['breadcrumb'],
      '#description' => t('Enter a breadcrumb name you would like to use. See "Title" for percent substitutions.'),
275 276 277 278
      '#states' => array(
        'visible' => array(
          ':input[name="options[breadcrumb_enable]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
      ),
      '#fieldset' => 'argument_present',
    );

    $form['specify_validation'] = array(
      '#type' => 'checkbox',
      '#title' => t('Specify validation criteria'),
      '#default_value' => $this->options['specify_validation'],
      '#fieldset' => 'argument_present',
    );

    $form['validate'] = array(
      '#type' => 'container',
      '#fieldset' => 'argument_present',
    );
    $form['validate']['type'] = array(
      '#type' => 'select',
      '#title' => t('Validator'),
      '#default_value' => $this->options['validate']['type'],
298 299 300 301
      '#states' => array(
        'visible' => array(
          ':input[name="options[specify_validation]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
302 303 304
      ),
    );

305
    $plugins = Views::pluginManager('argument_validator')->getDefinitions();
merlinofchaos's avatar
merlinofchaos committed
306
    foreach ($plugins as $id => $info) {
307
      if (!empty($info['no_ui'])) {
merlinofchaos's avatar
merlinofchaos committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        continue;
      }

      $valid = TRUE;
      if (!empty($info['type'])) {
        $valid = FALSE;
        if (empty($this->definition['validate type'])) {
          continue;
        }
        foreach ((array) $info['type'] as $type) {
          if ($type == $this->definition['validate type']) {
            $valid = TRUE;
            break;
          }
        }
      }

      // If we decide this validator is ok, add it to the list.
      if ($valid) {
327
        $plugin = $this->getPlugin('argument_validator', $id);
merlinofchaos's avatar
merlinofchaos committed
328 329 330 331 332 333 334 335
        if ($plugin) {
          if ($plugin->access() || $this->options['validate']['type'] == $id) {
            $form['validate']['options'][$id] = array(
              '#prefix' => '<div id="edit-options-validate-options-' . $id . '-wrapper">',
              '#suffix' => '</div>',
              '#type' => 'item',
              // Even if the plugin has no options add the key to the form_state.
              '#input' => TRUE, // trick it into checking input to make #process run
336 337 338 339 340
              '#states' => array(
                'visible' => array(
                  ':input[name="options[specify_validation]"]' => array('checked' => TRUE),
                  ':input[name="options[validate][type]"]' => array('value' => $id),
                ),
merlinofchaos's avatar
merlinofchaos committed
341 342
              ),
              '#id' => 'edit-options-validate-options-' . $id,
343
              '#default_value' => array(),
merlinofchaos's avatar
merlinofchaos committed
344
            );
345
            $plugin->buildOptionsForm($form['validate']['options'][$id], $form_state);
merlinofchaos's avatar
merlinofchaos committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359
            $validate_types[$id] = $info['title'];
          }
        }
      }
    }

    asort($validate_types);
    $form['validate']['type']['#options'] = $validate_types;

    $form['validate']['fail'] = array(
      '#type' => 'select',
      '#title' => t('Action to take if filter value does not validate'),
      '#default_value' => $this->options['validate']['fail'],
      '#options' => $validate_options,
360 361 362 363
      '#states' => array(
        'visible' => array(
          ':input[name="options[specify_validation]"]' => array('checked' => TRUE),
        ),
merlinofchaos's avatar
merlinofchaos committed
364 365 366 367 368
      ),
      '#fieldset' => 'argument_present',
    );
  }

369
  public function validateOptionsForm(&$form, &$form_state) {
merlinofchaos's avatar
merlinofchaos committed
370 371 372 373 374 375
    if (empty($form_state['values']['options'])) {
      return;
    }

    // Let the plugins do validation.
    $default_id = $form_state['values']['options']['default_argument_type'];
376
    $plugin = $this->getPlugin('argument_default', $default_id);
merlinofchaos's avatar
merlinofchaos committed
377
    if ($plugin) {
378
      $plugin->validateOptionsForm($form['argument_default'][$default_id], $form_state, $form_state['values']['options']['argument_default'][$default_id]);
merlinofchaos's avatar
merlinofchaos committed
379 380 381 382
    }

    // summary plugin
    $summary_id = $form_state['values']['options']['summary']['format'];
383
    $plugin = $this->getPlugin('style', $summary_id);
merlinofchaos's avatar
merlinofchaos committed
384
    if ($plugin) {
385
      $plugin->validateOptionsForm($form['summary']['options'][$summary_id], $form_state, $form_state['values']['options']['summary']['options'][$summary_id]);
merlinofchaos's avatar
merlinofchaos committed
386 387 388
    }

    $validate_id = $form_state['values']['options']['validate']['type'];
389
    $plugin = $this->getPlugin('argument_validator', $validate_id);
merlinofchaos's avatar
merlinofchaos committed
390
    if ($plugin) {
391
      $plugin->validateOptionsForm($form['validate']['options'][$default_id], $form_state, $form_state['values']['options']['validate']['options'][$validate_id]);
merlinofchaos's avatar
merlinofchaos committed
392 393 394 395
    }

  }

396
  public function submitOptionsForm(&$form, &$form_state) {
merlinofchaos's avatar
merlinofchaos committed
397 398 399 400 401 402
    if (empty($form_state['values']['options'])) {
      return;
    }

    // Let the plugins make submit modifications if necessary.
    $default_id = $form_state['values']['options']['default_argument_type'];
403
    $plugin = $this->getPlugin('argument_default', $default_id);
merlinofchaos's avatar
merlinofchaos committed
404 405
    if ($plugin) {
      $options = &$form_state['values']['options']['argument_default'][$default_id];
406
      $plugin->submitOptionsForm($form['argument_default'][$default_id], $form_state, $options);
merlinofchaos's avatar
merlinofchaos committed
407 408 409 410 411 412
      // Copy the now submitted options to their final resting place so they get saved.
      $form_state['values']['options']['default_argument_options'] = $options;
    }

    // summary plugin
    $summary_id = $form_state['values']['options']['summary']['format'];
413
    $plugin = $this->getPlugin('style', $summary_id);
merlinofchaos's avatar
merlinofchaos committed
414 415
    if ($plugin) {
      $options = &$form_state['values']['options']['summary']['options'][$summary_id];
416
      $plugin->submitOptionsForm($form['summary']['options'][$summary_id], $form_state, $options);
merlinofchaos's avatar
merlinofchaos committed
417 418 419 420 421
      // Copy the now submitted options to their final resting place so they get saved.
      $form_state['values']['options']['summary_options'] = $options;
    }

    $validate_id = $form_state['values']['options']['validate']['type'];
422
    $plugin = $this->getPlugin('argument_validator', $validate_id);
merlinofchaos's avatar
merlinofchaos committed
423 424
    if ($plugin) {
      $options = &$form_state['values']['options']['validate']['options'][$validate_id];
425
      $plugin->submitOptionsForm($form['validate']['options'][$validate_id], $form_state, $options);
merlinofchaos's avatar
merlinofchaos committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
      // Copy the now submitted options to their final resting place so they get saved.
      $form_state['values']['options']['validate_options'] = $options;
    }

    // Clear out the content of title if it's not enabled.
    $options =& $form_state['values']['options'];
    if (empty($options['title_enable'])) {
      $options['title'] = '';
    }
  }

  /**
   * Provide a list of default behaviors for this argument if the argument
   * is not present.
   *
   * Override this method to provide additional (or fewer) default behaviors.
   */
  function default_actions($which = NULL) {
    $defaults = array(
      'ignore' => array(
        'title' => t('Display all results for the specified field'),
447
        'method' => 'defaultIgnore',
merlinofchaos's avatar
merlinofchaos committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        'breadcrumb' => TRUE, // generate a breadcrumb to here
      ),
      'default' => array(
        'title' => t('Provide default value'),
        'method' => 'default_default',
        'form method' => 'default_argument_form',
        'has default argument' => TRUE,
        'default only' => TRUE, // this can only be used for missing argument, not validation failure
        'breadcrumb' => TRUE, // generate a breadcrumb to here
      ),
      'not found' => array(
        'title' => t('Hide view'),
        'method' => 'default_not_found',
        'hard fail' => TRUE, // This is a hard fail condition
      ),
      'summary' => array(
        'title' => t('Display a summary'),
        'method' => 'default_summary',
466
        'form method' => 'defaultSummaryForm',
merlinofchaos's avatar
merlinofchaos committed
467 468 469 470 471
        'style plugin' => TRUE,
        'breadcrumb' => TRUE, // generate a breadcrumb to here
      ),
      'empty' => array(
        'title' => t('Display contents of "No results found"'),
472
        'method' => 'defaultEmpty',
merlinofchaos's avatar
merlinofchaos committed
473 474 475 476
        'breadcrumb' => TRUE, // generate a breadcrumb to here
      ),
      'access denied' => array(
        'title' => t('Display "Access Denied"'),
477
        'method' => 'defaultAccessDenied',
merlinofchaos's avatar
merlinofchaos committed
478 479 480 481
        'breadcrumb' => FALSE, // generate a breadcrumb to here
      ),
    );

482
    if ($this->view->display_handler->hasPath()) {
merlinofchaos's avatar
merlinofchaos committed
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
      $defaults['not found']['title'] = t('Show "Page not found"');
    }

    if ($which) {
      if (!empty($defaults[$which])) {
        return $defaults[$which];
      }
    }
    else {
      return $defaults;
    }
  }

  /**
   * Provide a form for selecting the default argument when the
   * default action is set to provide default argument.
   */
  function default_argument_form(&$form, &$form_state) {
501
    $plugins = Views::pluginManager('argument_default')->getDefinitions();
merlinofchaos's avatar
merlinofchaos committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    $options = array();

    $form['default_argument_skip_url'] = array(
      '#type' => 'checkbox',
      '#title' => t('Skip default argument for view URL'),
      '#default_value' => $this->options['default_argument_skip_url'],
      '#description' => t('Select whether to include this default argument when constructing the URL for this view. Skipping default arguments is useful e.g. in the case of feeds.')
    );

    $form['default_argument_type'] = array(
      '#prefix' => '<div id="edit-options-default-argument-type-wrapper">',
      '#suffix' => '</div>',
      '#type' => 'select',
      '#id' => 'edit-options-default-argument-type',
      '#title' => t('Type'),
      '#default_value' => $this->options['default_argument_type'],
518 519 520 521 522
      '#states' => array(
        'visible' => array(
          ':input[name="options[default_action]"]' => array('value' => 'default'),
        ),
      ),
merlinofchaos's avatar
merlinofchaos committed
523 524 525 526 527 528
      // Views custom key, moves this element to the appropriate container
      // under the radio button.
      '#argument_option' => 'default',
    );

    foreach ($plugins as $id => $info) {
529
      if (!empty($info['no_ui'])) {
merlinofchaos's avatar
merlinofchaos committed
530 531
        continue;
      }
532
      $plugin = $this->getPlugin('argument_default', $id);
merlinofchaos's avatar
merlinofchaos committed
533 534 535 536 537 538 539 540 541 542
      if ($plugin) {
        if ($plugin->access() || $this->options['default_argument_type'] == $id) {
          $form['argument_default']['#argument_option'] = 'default';
          $form['argument_default'][$id] = array(
            '#prefix' => '<div id="edit-options-argument-default-options-' . $id . '-wrapper">',
            '#suffix' => '</div>',
            '#id' => 'edit-options-argument-default-options-' . $id,
            '#type' => 'item',
            // Even if the plugin has no options add the key to the form_state.
            '#input' => TRUE,
543 544 545 546 547
            '#states' => array(
              'visible' => array(
                ':input[name="options[default_action]"]' => array('value' => 'default'),
                ':input[name="options[default_argument_type]"]' => array('value' => $id),
              ),
merlinofchaos's avatar
merlinofchaos committed
548
            ),
549
            '#default_value' => array(),
merlinofchaos's avatar
merlinofchaos committed
550 551
          );
          $options[$id] = $info['title'];
552
          $plugin->buildOptionsForm($form['argument_default'][$id], $form_state);
merlinofchaos's avatar
merlinofchaos committed
553 554 555 556 557 558 559 560 561 562 563 564
        }
      }
    }

    asort($options);
    $form['default_argument_type']['#options'] = $options;
  }

  /**
   * Provide a form for selecting further summary options when the
   * default action is set to display one.
   */
565
  public function defaultSummaryForm(&$form, &$form_state) {
566
    $style_plugins = Views::pluginManager('style')->getDefinitions();
merlinofchaos's avatar
merlinofchaos committed
567 568 569
    $summary_plugins = array();
    $format_options = array();
    foreach ($style_plugins as $key => $plugin) {
570
      if (isset($plugin['display_types']) && in_array('summary', $plugin['display_types'])) {
merlinofchaos's avatar
merlinofchaos committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
        $summary_plugins[$key] = $plugin;
        $format_options[$key] = $plugin['title'];
      }
    }

    $form['summary'] = array(
      // Views custom key, moves this element to the appropriate container
      // under the radio button.
      '#argument_option' => 'summary',
    );
    $form['summary']['sort_order'] = array(
      '#type' => 'radios',
      '#title' => t('Sort order'),
      '#options' => array('asc' => t('Ascending'), 'desc' => t('Descending')),
      '#default_value' => $this->options['summary']['sort_order'],
586 587 588 589 590
      '#states' => array(
        'visible' => array(
          ':input[name="options[default_action]"]' => array('value' => 'summary'),
        ),
      ),
merlinofchaos's avatar
merlinofchaos committed
591 592 593 594 595 596
    );
    $form['summary']['number_of_records'] = array(
      '#type' => 'radios',
      '#title' => t('Sort by'),
      '#default_value' => $this->options['summary']['number_of_records'],
      '#options' => array(
597
        0 => $this->getSortName(),
merlinofchaos's avatar
merlinofchaos committed
598 599
        1 => t('Number of records')
      ),
600 601 602 603 604
      '#states' => array(
        'visible' => array(
          ':input[name="options[default_action]"]' => array('value' => 'summary'),
        ),
      ),
merlinofchaos's avatar
merlinofchaos committed
605 606 607 608 609 610 611
    );

    $form['summary']['format'] = array(
      '#type' => 'radios',
      '#title' => t('Format'),
      '#options' => $format_options,
      '#default_value' => $this->options['summary']['format'],
612 613 614 615 616
      '#states' => array(
        'visible' => array(
          ':input[name="options[default_action]"]' => array('value' => 'summary'),
        ),
      ),
merlinofchaos's avatar
merlinofchaos committed
617 618 619
    );

    foreach ($summary_plugins as $id => $info) {
620
      $plugin = $this->getPlugin('style', $id);
621
      if (!$plugin->usesOptions()) {
merlinofchaos's avatar
merlinofchaos committed
622 623 624 625 626 627 628 629 630
        continue;
      }
      if ($plugin) {
        $form['summary']['options'][$id] = array(
          '#prefix' => '<div id="edit-options-summary-options-' . $id . '-wrapper">',
          '#suffix' => '</div>',
          '#id' => 'edit-options-summary-options-' . $id,
          '#type' => 'item',
          '#input' => TRUE, // trick it into checking input to make #process run
631 632 633 634 635
          '#states' => array(
            'visible' => array(
              ':input[name="options[default_action]"]' => array('value' => 'summary'),
              ':input[name="options[summary][format]"]' => array('value' => $id),
            ),
merlinofchaos's avatar
merlinofchaos committed
636
          ),
637
          '#default_value' => array(),
merlinofchaos's avatar
merlinofchaos committed
638 639
        );
        $options[$id] = $info['title'];
640
        $plugin->buildOptionsForm($form['summary']['options'][$id], $form_state);
merlinofchaos's avatar
merlinofchaos committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
      }
    }
  }

  /**
   * Handle the default action, which means our argument wasn't present.
   *
   * Override this method only with extreme care.
   *
   * @return
   *   A boolean value; if TRUE, continue building this view. If FALSE,
   *   building the view will be aborted here.
   */
  function default_action($info = NULL) {
    if (!isset($info)) {
      $info = $this->default_actions($this->options['default_action']);
    }

    if (!$info) {
      return FALSE;
    }

    if (!empty($info['method args'])) {
      return call_user_func_array(array(&$this, $info['method']), $info['method args']);
    }
    else {
      return $this->{$info['method']}();
    }
  }

  /**
   * How to act if validation failes
   */
674
  public function validateFail() {
merlinofchaos's avatar
merlinofchaos committed
675 676 677 678 679 680 681 682 683
    $info = $this->default_actions($this->options['validate']['fail']);
    return $this->default_action($info);
  }
  /**
   * Default action: ignore.
   *
   * If an argument was expected and was not given, in this case, simply
   * ignore the argument entirely.
   */
684
  public function defaultIgnore() {
merlinofchaos's avatar
merlinofchaos committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    return TRUE;
  }

  /**
   * Default action: not found.
   *
   * If an argument was expected and was not given, in this case, report
   * the view as 'not found' or hide it.
   */
  function default_not_found() {
    // Set a failure condition and let the display manager handle it.
    $this->view->build_info['fail'] = TRUE;
    return FALSE;
  }

  /**
   * Default action: access denied.
   *
   * If an argument was expected and was not given, in this case, report
   * the view as 'access denied'.
   */
706
  public function defaultAccessDenied() {
merlinofchaos's avatar
merlinofchaos committed
707 708 709 710 711 712 713 714 715 716
    $this->view->build_info['denied'] = TRUE;
    return FALSE;
  }

  /**
   * Default action: empty
   *
   * If an argument was expected and was not given, in this case, display
   * the view's empty text
   */
717
  public function defaultEmpty() {
merlinofchaos's avatar
merlinofchaos committed
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
    // We return with no query; this will force the empty text.
    $this->view->built = TRUE;
    $this->view->executed = TRUE;
    $this->view->result = array();
    return FALSE;
  }

  /**
   * This just returns true. The view argument builder will know where
   * to find the argument from.
   */
  function default_default() {
    return TRUE;
  }

  /**
   * Determine if the argument is set to provide a default argument.
   */
736
  function hasDefaultArgument() {
merlinofchaos's avatar
merlinofchaos committed
737 738 739 740 741 742 743 744
    $info = $this->default_actions($this->options['default_action']);
    return !empty($info['has default argument']);
  }

  /**
   * Get a default argument, if available.
   */
  function get_default_argument() {
745
    $plugin = $this->getPlugin('argument_default');
merlinofchaos's avatar
merlinofchaos committed
746 747 748 749 750 751 752 753 754 755 756 757 758
    if ($plugin) {
      return $plugin->get_argument();
    }
  }

  /**
   * Process the summary arguments for display.
   *
   * For example, the validation plugin may want to alter an argument for use in
   * the URL.
   */
  function process_summary_arguments(&$args) {
    if ($this->options['validate']['type'] != 'none') {
759
      if (isset($this->validator) || $this->validator = $this->getPlugin('argument_validator')) {
merlinofchaos's avatar
merlinofchaos committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
        $this->validator->process_summary_arguments($args);
      }
    }
  }

  /**
   * Default action: summary.
   *
   * If an argument was expected and was not given, in this case, display
   * a summary query.
   */
  function default_summary() {
    $this->view->build_info['summary'] = TRUE;
    $this->view->build_info['summary_level'] = $this->options['id'];

    // Change the display style to the summary style for this
    // argument.
777 778
    $this->view->style_plugin = Views::pluginManager("style")->createInstance($this->options['summary']['format']);
    $this->view->style_plugin->init($this->view, $this->displayHandler, $this->options['summary_options']);
merlinofchaos's avatar
merlinofchaos committed
779 780 781 782 783 784 785

    // Clear out the normal primary field and whatever else may have
    // been added and let the summary do the work.
    $this->query->clear_fields();
    $this->summary_query();

    $by = $this->options['summary']['number_of_records'] ? 'num_records' : NULL;
786
    $this->summarySort($this->options['summary']['sort_order'], $by);
merlinofchaos's avatar
merlinofchaos committed
787 788 789

    // Summaries have their own sorting and fields, so tell the View not
    // to build these.
790
    $this->view->build_sort = FALSE;
merlinofchaos's avatar
merlinofchaos committed
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    return TRUE;
  }

  /**
   * Build the info for the summary query.
   *
   * This must:
   * - add_groupby: group on this field in order to create summaries.
   * - add_field: add a 'num_nodes' field for the count. Usually it will
   *   be a count on $view->base_field
   * - set_count_field: Reset the count field so we get the right paging.
   *
   * @return
   *   The alias used to get the number of records (count) for this entry.
   */
  function summary_query() {
807
    $this->ensureMyTable();
merlinofchaos's avatar
merlinofchaos committed
808
    // Add the field.
809
    $this->base_alias = $this->query->add_field($this->tableAlias, $this->realField);
merlinofchaos's avatar
merlinofchaos committed
810 811

    $this->summary_name_field();
812
    return $this->summaryBasics();
merlinofchaos's avatar
merlinofchaos committed
813 814 815 816 817 818 819 820 821 822 823 824 825
  }

  /**
   * Add the name field, which is the field displayed in summary queries.
   * This is often used when the argument is numeric.
   */
  function summary_name_field() {
    // Add the 'name' field. For example, if this is a uid argument, the
    // name field would be 'name' (i.e, the username).

    if (isset($this->name_table)) {
      // if the alias is different then we're probably added, not ensured,
      // so look up the join and add it instead.
826
      if ($this->tableAlias != $this->name_table) {
827
        $j = HandlerBase::getTableJoin($this->name_table, $this->table);
merlinofchaos's avatar
merlinofchaos committed
828 829
        if ($j) {
          $join = clone $j;
830
          $join->leftTable = $this->tableAlias;
merlinofchaos's avatar
merlinofchaos committed
831 832 833 834 835 836 837 838
          $this->name_table_alias = $this->query->add_table($this->name_table, $this->relationship, $join);
        }
      }
      else {
        $this->name_table_alias = $this->query->ensure_table($this->name_table, $this->relationship);
      }
    }
    else {
839
      $this->name_table_alias = $this->tableAlias;
merlinofchaos's avatar
merlinofchaos committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853
    }

    if (isset($this->name_field)) {
      $this->name_alias = $this->query->add_field($this->name_table_alias, $this->name_field);
    }
    else {
      $this->name_alias = $this->base_alias;
    }
  }

  /**
   * Some basic summary behavior that doesn't need to be repeated as much as
   * code that goes into summary_query()
   */
854
  public function summaryBasics($count_field = TRUE) {
merlinofchaos's avatar
merlinofchaos committed
855
    // Add the number of nodes counter
856
    $distinct = ($this->view->display_handler->getOption('distinct') && empty($this->query->no_distinct));
merlinofchaos's avatar
merlinofchaos committed
857

858
    $count_alias = $this->query->add_field($this->view->storage->get('base_table'), $this->view->storage->get('base_field'), 'num_records', array('count' => TRUE, 'distinct' => $distinct));
merlinofchaos's avatar
merlinofchaos committed
859 860 861
    $this->query->add_groupby($this->name_alias);

    if ($count_field) {
862
      $this->query->set_count_field($this->tableAlias, $this->realField);
merlinofchaos's avatar
merlinofchaos committed
863 864 865 866 867 868 869 870 871 872 873 874
    }

    $this->count_alias = $count_alias;
  }

  /**
   * Sorts the summary based upon the user's selection. The base variant of
   * this is usually adequte.
   *
   * @param $order
   *   The order selected in the UI.
   */
875
  public function summarySort($order, $by = NULL) {
merlinofchaos's avatar
merlinofchaos committed
876 877 878 879 880 881
    $this->query->add_orderby(NULL, NULL, $order, (!empty($by) ? $by : $this->name_alias));
  }

  /**
   * Provide the argument to use to link from the summary to the next level;
   * this will be called once per row of a summary, and used as part of
882
   * $view->getUrl().
merlinofchaos's avatar
merlinofchaos committed
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
   *
   * @param $data
   *   The query results for the row.
   */
  function summary_argument($data) {
    return $data->{$this->base_alias};
  }

  /**
   * Provides the name to use for the summary. By default this is just
   * the name field.
   *
   * @param $data
   *   The query results for the row.
   */
  function summary_name($data) {
    $value = $data->{$this->name_alias};
    if (empty($value) && !empty($this->definition['empty field name'])) {
      $value = $this->definition['empty field name'];
    }
    return check_plain($value);
  }

  /**
   * Set up the query for this argument.
   *
   * The argument sent may be found at $this->argument.
   */
911
  public function query($group_by = FALSE) {
912
    $this->ensureMyTable();
913
    $this->query->add_where(0, "$this->tableAlias.$this->realField", $this->argument);
merlinofchaos's avatar
merlinofchaos committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
  }

  /**
   * Get the title this argument will assign the view, given the argument.
   *
   * This usually needs to be overridden to provide a proper title.
   */
  function title() {
    return check_plain($this->argument);
  }

  /**
   * Called by the view object to get the title. This may be set by a
   * validator so we don't necessarily call through to title().
   */
929
  public function getTitle() {
merlinofchaos's avatar
merlinofchaos committed
930 931 932 933 934 935 936 937 938 939 940
    if (isset($this->validated_title)) {
      return $this->validated_title;
    }
    else {
      return $this->title();
    }
  }

  /**
   * Validate that this argument works. By default, all arguments are valid.
   */
941
  public function validateArgument($arg) {
merlinofchaos's avatar
merlinofchaos committed
942 943 944 945 946 947 948 949 950 951
    // By using % in URLs, arguments could be validated twice; this eases
    // that pain.
    if (isset($this->argument_validated)) {
      return $this->argument_validated;
    }

    if ($this->is_exception($arg)) {
      return $this->argument_validated = TRUE;
    }

952
    $plugin = $this->getPlugin('argument_validator');
953
    return $this->argument_validated = $plugin->validate_argument($arg);
merlinofchaos's avatar
merlinofchaos committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
  }

  /**
   * Called by the menu system to validate an argument.
   *
   * This checks to see if this is a 'soft fail', which means that if the
   * argument fails to validate, but there is an action to take anyway,
   * then validation cannot actually fail.
   */
  function validate_argument($arg) {
    $validate_info = $this->default_actions($this->options['validate']['fail']);
    if (empty($validate_info['hard fail'])) {
      return TRUE;
    }

969
    $rc = $this->validateArgument($arg);
merlinofchaos's avatar
merlinofchaos committed
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987

    // If the validator has changed the validate fail condition to a
    // soft fail, deal with that:
    $validate_info = $this->default_actions($this->options['validate']['fail']);
    if (empty($validate_info['hard fail'])) {
      return TRUE;
    }

    return $rc;
  }

  /**
   * Set the input for this argument
   *
   * @return TRUE if it successfully validates; FALSE if it does not.
   */
  function set_argument($arg) {
    $this->argument = $arg;
988
    return $this->validateArgument($arg);
merlinofchaos's avatar
merlinofchaos committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  }

  /**
   * Get the value of this argument.
   */
  function get_value() {
    // If we already processed this argument, we're done.
    if (isset($this->argument)) {
      return $this->argument;
    }

    // Otherwise, we have to pretend to process ourself to find the value.
    $value = NULL;
    // Find the position of this argument within the view.
    $position = 0;
    foreach ($this->view->argument as $id => $argument) {
      if ($id == $this->options['id']) {
        break;
      }
      $position++;
    }

    $arg = isset($this->view->args[$position]) ? $this->view->args[$position] : NULL;
    $this->position = $position;

    // Clone ourselves so that we don't break things when we're really
    // processing the arguments.
    $argument = clone $this;
1017
    if (!isset($arg) && $argument->hasDefaultArgument()) {
merlinofchaos's avatar
merlinofchaos committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
      $arg = $argument->get_default_argument();

      // remember that this argument was computed, not passed on the URL.
      $this->is_default = TRUE;
    }
    // Set the argument, which will also validate that the argument can be set.
    if ($argument->set_argument($arg)) {
      $value = $argument->argument;
    }
    unset($argument);
    return $value;
  }

  /**
   * Get the display or row plugin, if it exists.
   */
1034
  public function getPlugin($type = 'argument_default', $name = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1035 1036
    $options = array();
    switch ($type) {
1037
      case 'argument_default':
merlinofchaos's avatar
merlinofchaos committed
1038 1039 1040
        $plugin_name = $this->options['default_argument_type'];
        $options_name = 'default_argument_options';
        break;
1041
      case 'argument_validator':
merlinofchaos's avatar
merlinofchaos committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
        $plugin_name = $this->options['validate']['type'];
        $options_name = 'validate_options';
        break;
      case 'style':
        $plugin_name = $this->options['summary']['format'];
        $options_name = 'summary_options';
    }

    if (!$name) {
      $name = $plugin_name;
    }

    // we only fetch the options if we're fetching the plugin actually
    // in use.
    if ($name == $plugin_name) {
      $options = $this->options[$options_name];
    }

1060
    $plugin = Views::pluginManager($type)->createInstance($name);
merlinofchaos's avatar
merlinofchaos committed
1061
    if ($plugin) {
1062 1063 1064 1065 1066
      $plugin->init($this->view, $this->displayHandler, $options);

      if ($type !== 'style') {
        // It's an argument_default/argument_validate plugin, so set the argument.
        $plugin->setArgument($this);
merlinofchaos's avatar
merlinofchaos committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
      }
      return $plugin;
    }
  }

  /**
   * Return a description of how the argument would normally be sorted.
   *
   * Subclasses should override this to specify what the default sort order of
   * their argument is (e.g. alphabetical, numeric, date).
   */
1078
  public function getSortName() {
merlinofchaos's avatar
merlinofchaos committed
1079 1080
    return t('Default sort', array(), array('context' => 'Sort order'));
  }
1081

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
  /**
   * Custom form radios process function.
   *
   * Roll out a single radios element to a list of radios, using the options
   * array as index. While doing that, create a container element underneath
   * each option, which contains the settings related to that option.
   *
   * @see form_process_radios()
   */
  public static function processContainerRadios($element) {
    if (count($element['#options']) > 0) {
      foreach ($element['#options'] as $key => $choice) {
        $element += array($key => array());
        // Generate the parents as the autogenerator does, so we will have a
        // unique id for each radio button.
        $parents_for_id = array_merge($element['#parents'], array($key));

        $element[$key] += array(
          '#type' => 'radio',
          '#title' => $choice,
          // The key is sanitized in drupal_attributes() during output from the
          // theme function.
          '#return_value' => $key,
          '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
          '#attributes' => $element['#attributes'],
          '#parents' => $element['#parents'],
          '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
          '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
        );
        $element[$key . '_options'] = array(
          '#type' => 'container',
          '#attributes' => array('class' => array('views-admin-dependent')),
        );
      }
    }
    return $element;
  }

merlinofchaos's avatar
merlinofchaos committed
1120 1121 1122 1123 1124
}

/**
 * @}
 */