admin.inc 84.5 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Provides the Views' administrative interface.
 */

8
use Drupal\Core\Database\Database;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Drupal\views_ui\ViewUI;
11
use Drupal\views_ui\ViewFormControllerBase;
12
use Drupal\views\Analyzer;
13
use Drupal\views\ViewExecutable;
14
use Drupal\views\Plugin\views\wizard\WizardException;
15

merlinofchaos's avatar
merlinofchaos committed
16 17 18
/**
 * Returns the results of the live preview.
 */
19 20 21 22
function views_ui_preview(ViewUI $view, $display_id) {
  // Pass along any other arguments.
  $args = func_get_args();
  unset($args[0], $args[1]);
23
  return $view->renderPreview($display_id, $args);
merlinofchaos's avatar
merlinofchaos committed
24 25 26 27 28 29 30
}

/**
 * Page callback to add a new view.
 */
function views_ui_add_page() {
  drupal_set_title(t('Add new view'));
31 32
  $view = entity_create('view', array());
  return entity_get_form($view, 'add');
merlinofchaos's avatar
merlinofchaos committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
}

/**
 * Converts a form element in the add view wizard to be AJAX-enabled.
 *
 * This function takes a form element and adds AJAX behaviors to it such that
 * changing it triggers another part of the form to update automatically. It
 * also adds a submit button to the form that appears next to the triggering
 * element and that duplicates its functionality for users who do not have
 * JavaScript enabled (the button is automatically hidden for users who do have
 * JavaScript).
 *
 * To use this function, call it directly from your form builder function
 * immediately after you have defined the form element that will serve as the
 * JavaScript trigger. Calling it elsewhere (such as in hook_form_alter()) may
 * mean that the non-JavaScript fallback button does not appear in the correct
 * place in the form.
 *
 * @param $wrapping_element
 *   The element whose child will server as the AJAX trigger. For example, if
 *   $form['some_wrapper']['triggering_element'] represents the element which
 *   will trigger the AJAX behavior, you would pass $form['some_wrapper'] for
 *   this parameter.
 * @param $trigger_key
 *   The key within the wrapping element that identifies which of its children
 *   serves as the AJAX trigger. In the above example, you would pass
 *   'triggering_element' for this parameter.
 * @param $refresh_parents
 *   An array of parent keys that point to the part of the form that will be
 *   refreshed by AJAX. For example, if triggering the AJAX behavior should
 *   cause $form['dynamic_content']['section'] to be refreshed, you would pass
 *   array('dynamic_content', 'section') for this parameter.
 */
function views_ui_add_ajax_trigger(&$wrapping_element, $trigger_key, $refresh_parents) {
  $seen_ids = &drupal_static(__FUNCTION__ . ':seen_ids', array());
  $seen_buttons = &drupal_static(__FUNCTION__ . ':seen_buttons', array());

  // Add the AJAX behavior to the triggering element.
  $triggering_element = &$wrapping_element[$trigger_key];
  $triggering_element['#ajax']['callback'] = 'views_ui_ajax_update_form';
  // We do not use drupal_html_id() to get an ID for the AJAX wrapper, because
  // it remembers IDs across AJAX requests (and won't reuse them), but in our
  // case we need to use the same ID from request to request so that the
  // wrapper can be recognized by the AJAX system and its content can be
  // dynamically updated. So instead, we will keep track of duplicate IDs
  // (within a single request) on our own, later in this function.
  $triggering_element['#ajax']['wrapper'] = 'edit-view-' . implode('-', $refresh_parents) . '-wrapper';

  // Add a submit button for users who do not have JavaScript enabled. It
  // should be displayed next to the triggering element on the form.
  $button_key = $trigger_key . '_trigger_update';
  $wrapping_element[$button_key] = array(
    '#type' => 'submit',
    // Hide this button when JavaScript is enabled.
    '#attributes' => array('class' => array('js-hide')),
    '#submit' => array('views_ui_nojs_submit'),
    // Add a process function to limit this button's validation errors to the
    // triggering element only. We have to do this in #process since until the
    // form API has added the #parents property to the triggering element for
    // us, we don't have any (easy) way to find out where its submitted values
    // will eventually appear in $form_state['values'].
    '#process' => array_merge(array('views_ui_add_limited_validation'), element_info_property('submit', '#process', array())),
    // Add an after-build function that inserts a wrapper around the region of
    // the form that needs to be refreshed by AJAX (so that the AJAX system can
    // detect and dynamically update it). This is done in #after_build because
    // it's a convenient place where we have automatic access to the complete
    // form array, but also to minimize the chance that the HTML we add will
    // get clobbered by code that runs after we have added it.
    '#after_build' => array_merge(element_info_property('submit', '#after_build', array()), array('views_ui_add_ajax_wrapper')),
  );
  // Copy #weight and #access from the triggering element to the button, so
  // that the two elements will be displayed together.
  foreach (array('#weight', '#access') as $property) {
    if (isset($triggering_element[$property])) {
      $wrapping_element[$button_key][$property] = $triggering_element[$property];
    }
  }
  // For easiest integration with the form API and the testing framework, we
  // always give the button a unique #value, rather than playing around with
  // #name.
  $button_title = !empty($triggering_element['#title']) ? $triggering_element['#title'] : $trigger_key;
  if (empty($seen_buttons[$button_title])) {
    $wrapping_element[$button_key]['#value'] = t('Update "@title" choice', array(
      '@title' => $button_title,
    ));
    $seen_buttons[$button_title] = 1;
  }
  else {
    $wrapping_element[$button_key]['#value'] = t('Update "@title" choice (@number)', array(
      '@title' => $button_title,
      '@number' => ++$seen_buttons[$button_title],
124
    ));
merlinofchaos's avatar
merlinofchaos committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  }

  // Attach custom data to the triggering element and submit button, so we can
  // use it in both the process function and AJAX callback.
  $ajax_data = array(
    'wrapper' => $triggering_element['#ajax']['wrapper'],
    'trigger_key' => $trigger_key,
    'refresh_parents' => $refresh_parents,
    // Keep track of duplicate wrappers so we don't add the same wrapper to the
    // page more than once.
    'duplicate_wrapper' => !empty($seen_ids[$triggering_element['#ajax']['wrapper']]),
  );
  $seen_ids[$triggering_element['#ajax']['wrapper']] = TRUE;
  $triggering_element['#views_ui_ajax_data'] = $ajax_data;
  $wrapping_element[$button_key]['#views_ui_ajax_data'] = $ajax_data;
}

/**
 * Processes a non-JavaScript fallback submit button to limit its validation errors.
 */
function views_ui_add_limited_validation($element, &$form_state) {
  // Retrieve the AJAX triggering element so we can determine its parents. (We
  // know it's at the same level of the complete form array as the submit
  // button, so all we have to do to find it is swap out the submit button's
  // last array parent.)
  $array_parents = $element['#array_parents'];
  array_pop($array_parents);
  $array_parents[] = $element['#views_ui_ajax_data']['trigger_key'];
153
  $ajax_triggering_element = drupal_array_get_nested_value($form_state['complete_form'], $array_parents);
merlinofchaos's avatar
merlinofchaos committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

  // Limit this button's validation to the AJAX triggering element, so it can
  // update the form for that change without requiring that the rest of the
  // form be filled out properly yet.
  $element['#limit_validation_errors'] = array($ajax_triggering_element['#parents']);

  // If we are in the process of a form submission and this is the button that
  // was clicked, the form API workflow in form_builder() will have already
  // copied it to $form_state['triggering_element'] before our #process
  // function is run. So we need to make the same modifications in $form_state
  // as we did to the element itself, to ensure that #limit_validation_errors
  // will actually be set in the correct place.
  if (!empty($form_state['triggering_element'])) {
    $clicked_button = &$form_state['triggering_element'];
    if ($clicked_button['#name'] == $element['#name'] && $clicked_button['#value'] == $element['#value']) {
      $clicked_button['#limit_validation_errors'] = $element['#limit_validation_errors'];
    }
  }

  return $element;
}

/**
 * After-build function that adds a wrapper to a form region (for AJAX refreshes).
 *
 * This function inserts a wrapper around the region of the form that needs to
 * be refreshed by AJAX, based on information stored in the corresponding
 * submit button form element.
 */
function views_ui_add_ajax_wrapper($element, &$form_state) {
  // Don't add the wrapper <div> if the same one was already inserted on this
  // form.
  if (empty($element['#views_ui_ajax_data']['duplicate_wrapper'])) {
    // Find the region of the complete form that needs to be refreshed by AJAX.
    // This was earlier stored in a property on the element.
189
    $complete_form = &$form_state['complete_form'];
merlinofchaos's avatar
merlinofchaos committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    $refresh_parents = $element['#views_ui_ajax_data']['refresh_parents'];
    $refresh_element = drupal_array_get_nested_value($complete_form, $refresh_parents);

    // The HTML ID that AJAX expects was also stored in a property on the
    // element, so use that information to insert the wrapper <div> here.
    $id = $element['#views_ui_ajax_data']['wrapper'];
    $refresh_element += array(
      '#prefix' => '',
      '#suffix' => '',
    );
    $refresh_element['#prefix'] = '<div id="' . $id . '" class="views-ui-ajax-wrapper">' . $refresh_element['#prefix'];
    $refresh_element['#suffix'] .= '</div>';

    // Copy the element that needs to be refreshed back into the form, with our
    // modifications to it.
    drupal_array_set_nested_value($complete_form, $refresh_parents, $refresh_element);
  }

  return $element;
}

/**
 * Updates a part of the add view form via AJAX.
 *
 * @return
 *   The part of the form that has changed.
 */
function views_ui_ajax_update_form($form, $form_state) {
  // The region that needs to be updated was stored in a property of the
  // triggering element by views_ui_add_ajax_trigger(), so all we have to do is
  // retrieve that here.
  return drupal_array_get_nested_value($form, $form_state['triggering_element']['#views_ui_ajax_data']['refresh_parents']);
}

/**
 * Non-Javascript fallback for updating the add view form.
 */
function views_ui_nojs_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

/**
 * Form element validation handler for a taxonomy autocomplete field.
 *
 * This allows a taxonomy autocomplete field to be validated outside the
 * standard Field API workflow, without passing in a complete field widget.
 * Instead, all that is required is that $element['#field_name'] contain the
 * name of the taxonomy autocomplete field that is being validated.
 *
 * This function is currently not used for validation directly, although it
 * could be. Instead, it is only used to store the term IDs and vocabulary name
 * in the element value, based on the tags that the user typed in.
 *
 * @see taxonomy_autocomplete_validate()
 */
function views_ui_taxonomy_autocomplete_validate($element, &$form_state) {
  $value = array();
  if ($tags = $element['#value']) {
    // Get the machine names of the vocabularies we will search, keyed by the
    // vocabulary IDs.
    $field = field_info_field($element['#field_name']);
    $vocabularies = array();
    if (!empty($field['settings']['allowed_values'])) {
      foreach ($field['settings']['allowed_values'] as $tree) {
        if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
          $vocabularies[$vocabulary->vid] = $tree['vocabulary'];
        }
      }
    }
    // Store the term ID of each (valid) tag that the user typed.
    $typed_terms = drupal_explode_tags($tags);
    foreach ($typed_terms as $typed_term) {
262
      if ($terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
merlinofchaos's avatar
merlinofchaos committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        $term = array_pop($terms);
        $value['tids'][] = $term->tid;
      }
    }
    // Store the term IDs along with the name of the vocabulary. Currently
    // Views (as well as the Field UI) assumes that there will only be one
    // vocabulary, although technically the API allows there to be more than
    // one.
    if (!empty($value['tids'])) {
      $value['tids'] = array_unique($value['tids']);
      $value['vocabulary'] = array_pop($vocabularies);
    }
  }
  form_set_value($element, $value, $form_state);
}

/**
 * Page to delete a view.
 */
282
function views_ui_break_lock_confirm($form, &$form_state, ViewUI $view) {
merlinofchaos's avatar
merlinofchaos committed
283 284 285 286
  $form_state['view'] = &$view;
  $form = array();

  if (empty($view->locked)) {
287
    $form['message']['#markup'] = t('There is no lock on view %name to break.', array('%name' => $view->get('name')));
merlinofchaos's avatar
merlinofchaos committed
288 289 290
    return $form;
  }

291 292
  $cancel = drupal_container()->get('request')->query->get('cancel');
  if (empty($cancel)) {
293
    $cancel = 'admin/structure/views/view/' . $view->get('name') . '/edit';
merlinofchaos's avatar
merlinofchaos committed
294 295
  }

296
  $account = user_load($view->locked->owner);
297
  $form = confirm_form($form,
298
                  t('Do you want to break the lock on view %name?',
299
                  array('%name' => $view->get('name'))),
merlinofchaos's avatar
merlinofchaos committed
300
                  $cancel,
301
                  t('By breaking this lock, any unsaved changes made by !user will be lost.', array('!user' => theme('username', array('account' => $account)))),
merlinofchaos's avatar
merlinofchaos committed
302 303
                  t('Break lock'),
                  t('Cancel'));
304 305
  $form['actions']['submit']['#submit'][] = array($view, 'submitBreakLock');
  return $form;
merlinofchaos's avatar
merlinofchaos committed
306 307 308 309 310
}

/**
 * Page callback for the Edit View page.
 */
311
function views_ui_edit_page(ViewUI $view, $display_id = NULL) {
312 313 314
  $view->displayID = $display_id;
  $build['edit'] = entity_get_form($view, 'edit');
  $build['preview'] = entity_get_form($view, 'preview');
merlinofchaos's avatar
merlinofchaos committed
315 316 317
  return $build;
}

318 319 320 321 322 323 324 325 326 327 328 329
/**
 * Page callback for rendering the preview form and the preview of the view.
 *
 * @param \Drupal\views_ui\ViewUI $view
 *   The view UI object to preview.
 * @param string $display_id
 *   The display ID to preview.
 *
 * @return array
 *   The form array of the full preview form.
 */
function views_ui_build_preview(ViewUI $view, $display_id) {
330 331
  $view->displayID = $display_id;
  return entity_get_form($view, 'preview');
332
}
333

334
/**
335
 * Move form elements into details for presentation purposes.
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
 *
 * Many views forms use #tree = TRUE to keep their values in a hierarchy for
 * easier storage. Moving the form elements into fieldsets during form building
 * would break up that hierarchy. Therefore, we wait until the pre_render stage,
 * where any changes we make affect presentation only and aren't reflected in
 * $form_state['values'].
 */
function views_ui_pre_render_add_fieldset_markup($form) {
  foreach (element_children($form) as $key) {
    $element = $form[$key];
    // In our form builder functions, we added an arbitrary #fieldset property
    // to any element that belongs in a fieldset. If this form element has that
    // property, move it into its fieldset.
    if (isset($element['#fieldset']) && isset($form[$element['#fieldset']])) {
      $form[$element['#fieldset']][$key] = $element;
      // Remove the original element this duplicates.
      unset($form[$key]);
merlinofchaos's avatar
merlinofchaos committed
353 354 355 356 357 358 359
    }
  }

  return $form;
}

/**
360 361 362 363 364 365
 * Flattens the structure of an element containing the #flatten property.
 *
 * If a form element has #flatten = TRUE, then all of it's children
 * get moved to the same level as the element itself.
 * So $form['to_be_flattened'][$key] becomes $form[$key], and
 * $form['to_be_flattened'] gets unset.
merlinofchaos's avatar
merlinofchaos committed
366
 */
367
function views_ui_pre_render_flatten_data($form) {
merlinofchaos's avatar
merlinofchaos committed
368 369
  foreach (element_children($form) as $key) {
    $element = $form[$key];
370 371 372 373 374 375 376
    if (!empty($element['#flatten'])) {
      foreach (element_children($element) as $child_key) {
        $form[$child_key] = $form[$key][$child_key];
      }
      // All done, remove the now-empty parent.
      unset($form[$key]);
    }
merlinofchaos's avatar
merlinofchaos committed
377 378
  }

379
  return $form;
merlinofchaos's avatar
merlinofchaos committed
380 381 382
}

/**
383
 * Moves argument options into their place.
merlinofchaos's avatar
merlinofchaos committed
384
 *
385 386 387 388 389 390 391
 * When configuring the default argument behavior, almost each of the radio
 * buttons has its own fieldset shown bellow it when the radio button is
 * clicked. That fieldset is created through a custom form process callback.
 * Each element that has #argument_option defined and pointing to a default
 * behavior gets moved to the appropriate fieldset.
 * So if #argument_option is specified as 'default', the element is moved
 * to the 'default_options' fieldset.
merlinofchaos's avatar
merlinofchaos committed
392
 */
393 394 395 396 397 398 399 400 401 402
function views_ui_pre_render_move_argument_options($form) {
  foreach (element_children($form) as $key) {
    $element = $form[$key];
    if (!empty($element['#argument_option'])) {
      $container_name = $element['#argument_option'] . '_options';
      if (isset($form['no_argument']['default_action'][$container_name])) {
        $form['no_argument']['default_action'][$container_name][$key] = $element;
      }
      // Remove the original element this duplicates.
      unset($form[$key]);
merlinofchaos's avatar
merlinofchaos committed
403 404
    }
  }
405
  return $form;
merlinofchaos's avatar
merlinofchaos committed
406 407 408 409 410 411 412 413 414 415
}

/**
 * Add a <select> dropdown for a given section, allowing the user to
 * change whether this info is stored on the default display or on
 * the current display.
 */
function views_ui_standard_display_dropdown(&$form, &$form_state, $section) {
  $view = &$form_state['view'];
  $display_id = $form_state['display_id'];
416 417 418
  $executable = $view->get('executable');
  $displays = $executable->displayHandlers;
  $current_display = $executable->display_handler;
merlinofchaos's avatar
merlinofchaos committed
419 420 421 422

  // Add the "2 of 3" progress indicator.
  // @TODO: Move this to a separate function if it's needed on any forms that
  // don't have the display dropdown.
423
  if ($form_progress = $view->getFormProgress()) {
merlinofchaos's avatar
merlinofchaos committed
424 425 426 427
    $form['progress']['#markup'] = '<div id="views-progress-indicator">' . t('@current of @total', array('@current' => $form_progress['current'], '@total' => $form_progress['total'])) . '</div>';
    $form['progress']['#weight'] = -1001;
  }

428
  if ($current_display->isDefaultDisplay()) {
merlinofchaos's avatar
merlinofchaos committed
429 430 431 432 433
    return;
  }

  // Determine whether any other displays have overrides for this section.
  $section_overrides = FALSE;
434
  $section_defaulted = $current_display->isDefaulted($section);
merlinofchaos's avatar
merlinofchaos committed
435 436 437 438
  foreach ($displays as $id => $display) {
    if ($id === 'default' || $id === $display_id) {
      continue;
    }
439
    if ($display && !$display->isDefaulted($section)) {
merlinofchaos's avatar
merlinofchaos committed
440 441 442 443 444
      $section_overrides = TRUE;
    }
  }

  $display_dropdown['default'] = ($section_overrides ? t('All displays (except overridden)') : t('All displays'));
445
  $display_dropdown[$display_id] = t('This @display_type (override)', array('@display_type' => $current_display->getPluginId()));
merlinofchaos's avatar
merlinofchaos committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  // Only display the revert option if we are in a overridden section.
  if (!$section_defaulted) {
    $display_dropdown['default_revert'] = t('Revert to default');
  }

  $form['override'] = array(
    '#prefix' => '<div class="views-override clearfix container-inline">',
    '#suffix' => '</div>',
    '#weight' => -1000,
    '#tree' => TRUE,
  );
  $form['override']['dropdown'] = array(
    '#type' => 'select',
    '#title' => t('For'), // @TODO: Translators may need more context than this.
    '#options' => $display_dropdown,
  );
462
  if ($current_display->isDefaulted($section)) {
merlinofchaos's avatar
merlinofchaos committed
463 464 465 466 467 468 469 470 471
    $form['override']['dropdown']['#default_value'] = 'defaults';
  }
  else {
    $form['override']['dropdown']['#default_value'] = $display_id;
  }

}


472 473 474 475 476 477 478
/**
 * Returns information about subforms for editing the pieces of a view.
 *
 * @param string|null $key
 *   The form for which to retrieve data. If NULL, the list of all forms is
 *   returned.
 */
merlinofchaos's avatar
merlinofchaos committed
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
function views_ui_ajax_forms($key = NULL) {
  $forms = array(
    'display' => array(
      'form_id' => 'views_ui_edit_display_form',
      'args' => array('section'),
    ),
    'remove-display' => array(
      'form_id' => 'views_ui_remove_display_form',
      'args' => array(),
    ),
    'rearrange' => array(
      'form_id' => 'views_ui_rearrange_form',
      'args' => array('type'),
    ),
    'rearrange-filter' => array(
      'form_id' => 'views_ui_rearrange_filter_form',
      'args' => array('type'),
    ),
    'reorder-displays' => array(
      'form_id' => 'views_ui_reorder_displays_form',
      'args' => array(),
500
      'callback' => 'buildDisplaysReorderForm',
merlinofchaos's avatar
merlinofchaos committed
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    ),
    'add-item' => array(
      'form_id' => 'views_ui_add_item_form',
      'args' => array('type'),
    ),
    'config-item' => array(
      'form_id' => 'views_ui_config_item_form',
      'args' => array('type', 'id'),
    ),
    'config-item-extra' => array(
      'form_id' => 'views_ui_config_item_extra_form',
      'args' => array('type', 'id'),
    ),
    'config-item-group' => array(
      'form_id' => 'views_ui_config_item_group_form',
      'args' => array('type', 'id'),
    ),
    'edit-details' => array(
      'form_id' => 'views_ui_edit_details_form',
      'args' => array(),
    ),
    'analyze' => array(
      'form_id' => 'views_ui_analyze_view_form',
      'args' => array(),
    ),
  );

  if ($key) {
    return !empty($forms[$key]) ? $forms[$key] : NULL;
  }

  return $forms;
}

/**
 * Create the URL for one of our standard AJAX forms based upon known
 * information about the form.
 */
function views_ui_build_form_url($form_state) {
  $form = views_ui_ajax_forms($form_state['form_key']);
  $ajax = empty($form_state['ajax']) ? 'nojs' : 'ajax';
542
  $name = $form_state['view']->get('name');
merlinofchaos's avatar
merlinofchaos committed
543 544 545 546 547 548 549 550 551 552 553 554 555
  $url = "admin/structure/views/$ajax/$form_state[form_key]/$name/$form_state[display_id]";
  foreach ($form['args'] as $arg) {
    $url .= '/' . $form_state[$arg];
  }
  return $url;
}

/**
 * Generic entry point to handle forms.
 *
 * We do this for consistency and to make it easy to chain forms
 * together.
 */
556
function views_ui_ajax_form($js, $key, ViewUI $view, $display_id = '') {
557 558 559 560 561 562
  // Reset the cache of IDs. Drupal rather aggressively prevents ID
  // duplication but this causes it to remember IDs that are no longer even
  // being used.
  $seen_ids_init = &drupal_static('drupal_html_id:init');
  $seen_ids_init = array();

merlinofchaos's avatar
merlinofchaos committed
563 564 565 566 567 568 569 570 571 572
  $form = views_ui_ajax_forms($key);
  if (empty($form)) {
    return MENU_NOT_FOUND;
  }

  views_include('ajax');
  $args = func_get_args();
  // Remove the known args
  array_splice($args, 0, 4);

573
  $form_state = $view->buildFormState($js, $key, $display_id, $args);
merlinofchaos's avatar
merlinofchaos committed
574 575 576 577
  // check to see if this is the top form of the stack. If it is, pop
  // it off; if it isn't, the user clicked somewhere else and the stack is
  // now irrelevant.
  if (!empty($view->stack)) {
578
    $identifier = $view->buildIdentifier($key, $display_id, $args);
merlinofchaos's avatar
merlinofchaos committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    // Retrieve the first form from the stack without changing the integer keys,
    // as they're being used for the "2 of 3" progress indicator.
    reset($view->stack);
    list($key, $top) = each($view->stack);
    unset($view->stack[$key]);

    if (array_shift($top) != $identifier) {
      $view->stack = array();
    }
  }

  // Automatically remove the form cache if it is set and the key does
  // not match. This way navigating away from the form without hitting
  // update will work.
  if (isset($view->form_cache) && $view->form_cache['key'] != $key) {
    unset($view->form_cache);
  }

  // With the below logic, we may end up rendering a form twice (or two forms
  // each sharing the same element ids), potentially resulting in
  // drupal_add_js() being called twice to add the same setting. drupal_get_js()
  // is ok with that, but until ajax_render() is (http://drupal.org/node/208611),
  // reset the drupal_add_js() static before rendering the second time.
  $drupal_add_js_original = drupal_add_js();
  $drupal_add_js = &drupal_static('drupal_add_js');
  $output = views_ajax_form_wrapper($form_state['form_id'], $form_state);
  if ($form_state['submitted'] && empty($form_state['rerender'])) {
    // Sometimes we need to re-generate the form for multi-step type operations.
    $object = NULL;
    if (!empty($view->stack)) {
      $drupal_add_js = $drupal_add_js_original;
      $stack = $view->stack;
      $top = array_shift($stack);
      $top[0] = $js;
613
      $form_state = call_user_func_array(array($view, 'buildFormState'), $top);
merlinofchaos's avatar
merlinofchaos committed
614 615 616 617 618 619 620 621 622
      $form_state['input'] = array();
      $form_state['url'] = url(views_ui_build_form_url($form_state));
      if (!$js) {
        return drupal_goto(views_ui_build_form_url($form_state));
      }
      $output = views_ajax_form_wrapper($form_state['form_id'], $form_state);
    }
    elseif (!$js) {
      // if nothing on the stack, non-js forms just go back to the main view editor.
623
      return drupal_goto("admin/structure/views/view/{$view->get('name')}/edit");
merlinofchaos's avatar
merlinofchaos committed
624 625 626 627 628 629 630 631 632 633 634 635 636
    }
    else {
      $output = array();
      $output[] = views_ajax_command_dismiss_form();
      $output[] = views_ajax_command_show_buttons();
      $output[] = views_ajax_command_trigger_preview();
      if (!empty($form_state['#page_title'])) {
        $output[] = views_ajax_command_replace_title($form_state['#page_title']);
      }
    }
    // If this form was for view-wide changes, there's no need to regenerate
    // the display section of the form.
    if ($display_id !== '') {
637
      entity_form_controller('view', 'edit')->rebuildCurrentTab($view, $output, $display_id);
merlinofchaos's avatar
merlinofchaos committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
    }
  }

  return $js ? array('#type' => 'ajax', '#commands' => $output) : $output;
}

/**
 * Form constructor callback to display analysis information on a view
 */
function views_ui_analyze_view_form($form, &$form_state) {
  $view = &$form_state['view'];

  $form['#title'] = t('View analysis');
  $form['#section'] = 'analyze';

653
  $analyzer = new Analyzer($view->get('executable'));
654
  $messages = $analyzer->getMessages();
merlinofchaos's avatar
merlinofchaos committed
655 656 657 658

  $form['analysis'] = array(
    '#prefix' => '<div class="form-item">',
    '#suffix' => '</div>',
659
    '#markup' => $analyzer->formatMessages($messages),
merlinofchaos's avatar
merlinofchaos committed
660 661 662 663
  );

  // Inform the standard button function that we want an OK button.
  $form_state['ok_button'] = TRUE;
664
  $view->getStandardButtons($form, $form_state, 'views_ui_analyze_view_form');
merlinofchaos's avatar
merlinofchaos committed
665 666 667 668 669 670 671
  return $form;
}

/**
 * Submit handler for views_ui_analyze_view_form
 */
function views_ui_analyze_view_form_submit($form, &$form_state) {
672
  $form_state['redirect'] = 'admin/structure/views/view/' . $form_state['view']->get('name') . '/edit';
merlinofchaos's avatar
merlinofchaos committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
}

/**
 * Form builder to edit details of a view.
 */
function views_ui_edit_details_form($form, &$form_state) {
  $view = &$form_state['view'];

  $form['#title'] = t('View name and description');
  $form['#section'] = 'details';

  $form['details'] = array(
    '#theme_wrappers' => array('container'),
    '#attributes' => array('class' => array('scroll')),
  );
  $form['details']['human_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Human-readable name'),
    '#description' => t('A descriptive human-readable name for this view. Spaces are allowed'),
692
    '#default_value' => $view->getHumanName(),
merlinofchaos's avatar
merlinofchaos committed
693 694 695 696 697
  );
  $form['details']['tag'] = array(
    '#type' => 'textfield',
    '#title' => t('View tag'),
    '#description' => t('Optionally, enter a comma delimited list of tags for this view to use in filtering and sorting views on the administrative page.'),
698
    '#default_value' => $view->get('tag'),
merlinofchaos's avatar
merlinofchaos committed
699 700 701 702 703 704
    '#autocomplete_path' => 'admin/views/ajax/autocomplete/tag',
  );
  $form['details']['description'] = array(
    '#type' => 'textfield',
    '#title' => t('View description'),
    '#description' => t('This description will appear on the Views administrative UI to tell you what the view is about.'),
705
    '#default_value' => $view->get('description'),
merlinofchaos's avatar
merlinofchaos committed
706 707
  );

708
  $view->getStandardButtons($form, $form_state, 'views_ui_edit_details_form');
merlinofchaos's avatar
merlinofchaos committed
709 710 711 712 713 714 715 716 717 718 719 720
  return $form;
}

/**
 * Submit handler for views_ui_edit_details_form.
 */
function views_ui_edit_details_form_submit($form, &$form_state) {
  $view = $form_state['view'];
  foreach ($form_state['values'] as $key => $value) {
    // Only save values onto the view if they're actual view properties
    // (as opposed to 'op' or 'form_build_id').
    if (isset($form['details'][$key])) {
721
      $view->set($key, $value);
merlinofchaos's avatar
merlinofchaos committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735
    }
  }
  $form_state['#page_title'] = views_ui_edit_page_title($view);
  views_ui_cache_set($view);
}

/**
 * Form constructor callback to edit display of a view
 */
function views_ui_edit_display_form($form, &$form_state) {
  $view = &$form_state['view'];
  $display_id = $form_state['display_id'];
  $section = $form_state['section'];

736 737
  $executable = $view->get('executable');
  if (!$executable->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
738 739
    views_ajax_error(t('Invalid display id @display', array('@display' => $display_id)));
  }
740
  $display = &$executable->display[$display_id];
merlinofchaos's avatar
merlinofchaos committed
741 742 743 744 745 746

  // Get form from the handler.
  $form['options'] = array(
    '#theme_wrappers' => array('container'),
    '#attributes' => array('class' => array('scroll')),
  );
747
  $executable->display_handler->buildOptionsForm($form['options'], $form_state);
merlinofchaos's avatar
merlinofchaos committed
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764

  // The handler options form sets $form['#title'], which we need on the entire
  // $form instead of just the ['options'] section.
  $form['#title'] = $form['options']['#title'];
  unset($form['options']['#title']);

  // Move the override dropdown out of the scrollable section of the form.
  if (isset($form['options']['override'])) {
    $form['override'] = $form['options']['override'];
    unset($form['options']['override']);
  }

  $name = NULL;
  if (isset($form_state['update_name'])) {
    $name = $form_state['update_name'];
  }

765
  $view->getStandardButtons($form, $form_state, 'views_ui_edit_display_form', $name);
merlinofchaos's avatar
merlinofchaos committed
766 767 768 769 770 771 772
  return $form;
}

/**
 * Validate handler for views_ui_edit_display_form
 */
function views_ui_edit_display_form_validate($form, &$form_state) {
773
  $form_state['view']->get('executable')->displayHandlers[$form_state['display_id']]->validateOptionsForm($form['options'], $form_state);
merlinofchaos's avatar
merlinofchaos committed
774 775 776 777 778 779 780 781 782 783

  if (form_get_errors()) {
    $form_state['rerender'] = TRUE;
  }
}

/**
 * Submit handler for views_ui_edit_display_form
 */
function views_ui_edit_display_form_submit($form, &$form_state) {
784
  $form_state['view']->get('executable')->displayHandlers[$form_state['display_id']]->submitOptionsForm($form['options'], $form_state);
merlinofchaos's avatar
merlinofchaos committed
785 786 787 788 789 790 791 792 793 794

  views_ui_cache_set($form_state['view']);
}

/**
 * Override handler for views_ui_edit_display_form
 *
 * @TODO: Not currently used. Remove unless we implement an override toggle.
 */
function views_ui_edit_display_form_override($form, &$form_state) {
795
  $form_state['view']->get('executable')->displayHandlers[$form_state['display_id']]->optionsOverride($form['options'], $form_state);
merlinofchaos's avatar
merlinofchaos committed
796 797 798 799 800 801 802 803 804 805 806 807 808 809

  views_ui_cache_set($form_state['view']);
  $form_state['rerender'] = TRUE;
  $form_state['rebuild'] = TRUE;
}

/**
 * Form to rearrange items in the views UI.
 */
function views_ui_rearrange_form($form, &$form_state) {
  $view = &$form_state['view'];
  $display_id = $form_state['display_id'];
  $type = $form_state['type'];

810 811 812
  $types = ViewExecutable::viewsHandlerTypes();
  $executable = $view->get('executable');
  if (!$executable->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
813 814
    views_ajax_error(t('Invalid display id @display', array('@display' => $display_id)));
  }
815
  $display = &$executable->displayHandlers[$display_id];
merlinofchaos's avatar
merlinofchaos committed
816 817 818
  $form['#title'] = t('Rearrange @type', array('@type' => $types[$type]['ltitle']));
  $form['#section'] = $display_id . 'rearrange-item';

819
  if ($display->defaultableSections($types[$type]['plural'])) {
merlinofchaos's avatar
merlinofchaos committed
820 821 822 823 824 825 826 827
    $form_state['section'] = $types[$type]['plural'];
    views_ui_standard_display_dropdown($form, $form_state, $form_state['section']);
  }

  $count = 0;

  // Get relationship labels
  $relationships = array();
828
  foreach ($display->getHandlers('relationship') as $id => $handler) {
merlinofchaos's avatar
merlinofchaos committed
829 830 831 832 833 834 835
    $relationships[$id] = $handler->label();
  }

  // Filters can now be grouped so we do a little bit extra:
  $groups = array();
  $grouping = FALSE;
  if ($type == 'filter') {
836
    $group_info = $executable->display_handler->getOption('filter_groups');
merlinofchaos's avatar
merlinofchaos committed
837 838 839 840 841 842
    if (!empty($group_info['groups']) && count($group_info['groups']) > 1) {
      $grouping = TRUE;
      $groups = array(0 => array());
    }
  }

843
  foreach ($display->getOption($types[$type]['plural']) as $id => $field) {
merlinofchaos's avatar
merlinofchaos committed
844 845 846 847 848
    $form['fields'][$id] = array('#tree' => TRUE);
    $form['fields'][$id]['weight'] = array(
      '#type' => 'textfield',
      '#default_value' => ++$count,
    );
849
    $handler = $display->getHandler($type, $id);
merlinofchaos's avatar
merlinofchaos committed
850
    if ($handler) {
851
      $name = $handler->adminLabel() . ' ' . $handler->adminSummary();
merlinofchaos's avatar
merlinofchaos committed
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
      if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
        $name = '(' . $relationships[$field['relationship']] . ') ' . $name;
      }

      $form['fields'][$id]['name'] = array(
        '#markup' => $name,
      );
    }
    else {
      $form['fields'][$id]['name'] = array('#markup' => t('Broken field @id', array('@id' => $id)));
    }
    $form['fields'][$id]['removed'] = array(
      '#type' => 'checkbox',
      '#id' => 'views-removed-' . $id,
      '#attributes' => array('class' => array('views-remove-checkbox')),
      '#default_value' => 0,
    );
  }

  // Add javascript settings that will be added via $.extend for tabledragging
  $form['#js']['tableDrag']['arrange']['weight'][0] = array(
    'target' => 'weight',
    'source' => NULL,
    'relationship' => 'sibling',
    'action' => 'order',
    'hidden' => TRUE,
    'limit' => 0,
  );

  $name = NULL;
  if (isset($form_state['update_name'])) {
    $name = $form_state['update_name'];
  }

886
  $view->getStandardButtons($form, $form_state, 'views_ui_rearrange_form');
merlinofchaos's avatar
merlinofchaos committed
887 888 889
  return $form;
}

890 891
/**
 * Submit handler for rearranging form.
merlinofchaos's avatar
merlinofchaos committed
892 893
 */
function views_ui_rearrange_form_submit($form, &$form_state) {
894 895
  $types = ViewExecutable::viewsHandlerTypes();
  $display = &$form_state['view']->get('executable')->displayHandlers[$form_state['display_id']];
merlinofchaos's avatar
merlinofchaos committed
896

897
  $old_fields = $display->getOption($types[$form_state['type']]['plural']);
merlinofchaos's avatar
merlinofchaos committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
  $new_fields = $order = array();

  // Make an array with the weights
  foreach ($form_state['values'] as $field => $info) {
    // add each value that is a field with a weight to our list, but only if
    // it has had its 'removed' checkbox checked.
    if (is_array($info) && isset($info['weight']) && empty($info['removed'])) {
      $order[$field] = $info['weight'];
    }
  }

  // Sort the array
  asort($order);

  // Create a new list of fields in the new order.
  foreach (array_keys($order) as $field) {
    $new_fields[$field] = $old_fields[$field];
  }
916
  $display->setOption($types[$form_state['type']]['plural'], $new_fields);
merlinofchaos's avatar
merlinofchaos committed
917 918 919 920 921 922 923 924 925 926 927 928 929

  // Store in cache
  views_ui_cache_set($form_state['view']);
}

/**
 * Form to rearrange items in the views UI.
 */
function views_ui_rearrange_filter_form($form, &$form_state) {
  $view = &$form_state['view'];
  $display_id = $form_state['display_id'];
  $type = $form_state['type'];

930 931 932
  $types = ViewExecutable::viewsHandlerTypes();
  $executable = $view->get('executable');
  if (!$executable->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
933 934
    views_ajax_render(t('Invalid display id @display', array('@display' => $display_id)));
  }
935
  $display = $executable->displayHandlers[$display_id];
936
  $form['#title'] = check_plain($display->display['display_title']) . ': ';
merlinofchaos's avatar
merlinofchaos committed
937 938 939
  $form['#title'] .= t('Rearrange @type', array('@type' => $types[$type]['ltitle']));
  $form['#section'] = $display_id . 'rearrange-item';

940
  if ($display->defaultableSections($types[$type]['plural'])) {
merlinofchaos's avatar
merlinofchaos committed
941 942 943 944 945 946 947 948 949
    $form_state['section'] = $types[$type]['plural'];
    views_ui_standard_display_dropdown($form, $form_state, $form_state['section']);
  }

  if (!empty($view->form_cache)) {
    $groups = $view->form_cache['groups'];
    $handlers = $view->form_cache['handlers'];
  }
  else {
950 951
    $groups = $display->getOption('filter_groups');
    $handlers = $display->getOption($types[$type]['plural']);
merlinofchaos's avatar
merlinofchaos committed
952 953 954 955 956
  }
  $count = 0;

  // Get relationship labels
  $relationships = array();
957
  foreach ($display->getHandlers('relationship') as $id => $handler) {
merlinofchaos's avatar
merlinofchaos committed
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    $relationships[$id] = $handler->label();
  }

  $group_options = array();

  /**
   * Filter groups is an array that contains:
   * array(
   *   'operator' => 'and' || 'or',
   *   'groups' => array(
   *     $group_id => 'and' || 'or',
   *   ),
   * );
   */

  $grouping = count(array_keys($groups['groups'])) > 1;

  $form['filter_groups']['#tree'] = TRUE;
  $form['filter_groups']['operator'] = array(
    '#type' => 'select',
978
    '#options' => array(
merlinofchaos's avatar
merlinofchaos committed
979 980 981 982 983 984 985 986 987 988 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 1017 1018 1019 1020 1021 1022 1023 1024
      'AND' => t('And'),
      'OR' => t('Or'),
    ),
    '#default_value' => $groups['operator'],
    '#attributes' => array(
      'class' => array('warning-on-change'),
    ),
    '#title' => t('Operator to use on all groups'),
    '#description' => t('Either "group 0 AND group 1 AND group 2" or "group 0 OR group 1 OR group 2", etc'),
    '#access' => $grouping,
  );

  $form['remove_groups']['#tree'] = TRUE;

  foreach ($groups['groups'] as $id => $group) {
    $form['filter_groups']['groups'][$id] = array(
      '#title' => t('Operator'),
      '#type' => 'select',
      '#options' => array(
        'AND' => t('And'),
        'OR' => t('Or'),
      ),
      '#default_value' => $group,
      '#attributes' => array(
        'class' => array('warning-on-change'),
      ),
    );

    $form['remove_groups'][$id] = array(); // to prevent a notice
    if ($id != 1) {
      $form['remove_groups'][$id] = array(
        '#type' => 'submit',
        '#value' => t('Remove group @group', array('@group' => $id)),
        '#id' => "views-remove-group-$id",
        '#attributes' => array(
          'class' => array('views-remove-group'),
        ),
        '#group' => $id,
      );
    }
    $group_options[$id] = $id == 1 ? t('Default group') : t('Group @group', array('@group' => $id));
    $form['#group_renders'][$id] = array();
  }

  $form['#group_options'] = $group_options;
  $form['#groups'] = $groups;
1025
  // We don't use getHandlers() because we want items without handlers to
merlinofchaos's avatar
merlinofchaos committed
1026 1027 1028 1029 1030 1031 1032 1033
  // appear and show up as 'broken' so that the user can see them.
  $form['filters'] = array('#tree' => TRUE);
  foreach ($handlers as $id => $field) {
    // If the group does not exist, move the filters to the default group.
    if (empty($field['group']) || empty($groups['groups'][$field['group']])) {
      $field['group'] = 1;
    }

1034
    $handler = $display->getHandler($type, $id);
merlinofchaos's avatar
merlinofchaos committed
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 1060 1061 1062 1063 1064
    if ($grouping && $handler && !$handler->can_group()) {
      $field['group'] = 'ungroupable';
    }

    // If not grouping and the handler is set ungroupable, move it back to
    // the default group to prevent weird errors from having it be in its
    // own group:
    if (!$grouping && $field['group'] == 'ungroupable') {
      $field['group'] = 1;
    }

    // Place this item into the proper group for rendering.
    $form['#group_renders'][$field['group']][] = $id;

    $form['filters'][$id]['weight'] = array(
      '#type' => 'textfield',
      '#default_value' => ++$count,
      '#size' => 8,
    );
    $form['filters'][$id]['group'] = array(
      '#type' => 'select',
      '#options' => $group_options,
      '#default_value' => $field['group'],
      '#attributes' => array(
        'class' => array('views-region-select', 'views-region-' . $id),
      ),
      '#access' => $field['group'] !== 'ungroupable',
    );

    if ($handler) {
1065
      $name = $handler->adminLabel() . ' ' . $handler->adminSummary();
merlinofchaos's avatar
merlinofchaos committed
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
      if (!empty($field['relationship']) && !empty($relationships[$field['relationship']])) {
        $name = '(' . $relationships[$field['relationship']] . ') ' . $name;
      }

      $form['filters'][$id]['name'] = array(
        '#markup' => $name,
      );
    }
    else {
      $form['filters'][$id]['name'] = array('#markup' => t('Broken field @id', array('@id' => $id)));
    }
    $form['filters'][$id]['removed'] = array(
      '#type' => 'checkbox',
      '#id' => 'views-removed-' . $id,
      '#attributes' => array('class' => array('views-remove-checkbox')),
      '#default_value' => 0,
    );
  }

  if (isset($form_state['update_name'])) {
    $name = $form_state['update_name'];
  }

1089
  $view->getStandardButtons($form, $form_state, 'views_ui_rearrange_filter_form');
merlinofchaos's avatar
merlinofchaos committed
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
  $form['buttons']['add_group'] = array(
    '#type' => 'submit',
    '#value' => t('Create new filter group'),
    '#id' => 'views-add-group',
    '#group' => 'add',
  );

  return $form;
}

/**
 * Submit handler for rearranging form
 */
function views_ui_rearrange_filter_form_submit($form, &$form_state) {
1104 1105
  $types = ViewExecutable::viewsHandlerTypes();
  $display = &$form_state['view']->get('executable')->displayHandlers[$form_state['display_id']];
merlinofchaos's avatar
merlinofchaos committed
1106 1107 1108 1109 1110 1111
  $remember_groups = array();

  if (!empty($form_state['view']->form_cache)) {
    $old_fields = $form_state['view']->form_cache['handlers'];
  }
  else {
1112
    $old_fields = $display->getOption($types[$form_state['type']]['plural']);
merlinofchaos's avatar
merlinofchaos committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
  }
  $count = 0;

  $groups = $form_state['values']['filter_groups'];
  // Whatever button was clicked, re-calculate field information.
  $new_fields = $order = array();

  // Make an array with the weights
  foreach ($form_state['values']['filters'] as $field => $info) {
    // add each value that is a field with a weight to our list, but only if
    // it has had its 'removed' checkbox checked.
    if (is_array($info) && empty($info['removed'])) {
      if (isset($info['weight'])) {
        $order[$field] = $info['weight'];
      }

      if (isset($info['group'])) {
        $old_fields[$field]['group'] = $info['group'];
        $remember_groups[$info['group']][] = $field;
      }
    }
  }

  // Sort the array
  asort($order);

  // Create a new list of fields in the new order.
  foreach (array_keys($order) as $field) {
    $new_fields[$field] = $old_fields[$field];
  }

  // If the #group property is set on the clicked button, that means we are
  // either adding or removing a group, not actually updating the filters.
  if (!empty($form_state['clicked_button']['#group'])) {
    if ($form_state['clicked_button']['#group'] == 'add') {
      // Add a new group
      $groups['groups'][] = 'AND';
    }
    else {
      // Renumber groups above the removed one down.
      foreach (array_keys($groups['groups']) as $group_id) {
        if ($group_id >= $form_state['clicked_button']['#group']) {
          $old_group = $group_id + 1;
          if (isset($groups['groups'][$old_group])) {
            $groups['groups'][$group_id] = $groups['groups'][$old_group];
            if (isset($remember_groups[$old_group])) {
              foreach ($remember_groups[$old_group] as $id) {
                $new_fields[$id]['group'] = $group_id;
              }
            }
          }
          else {
            // If this is the last one, just unset it.
            unset($groups['groups'][$group_id]);
          }
        }
      }
    }
    // Update our cache with values so that cancel still works the way
    // people expect.
    $form_state['view']->form_cache = array(
      'key' => 'rearrange-filter',
      'groups' => $groups,
      'handlers' => $new_fields,
    );

    // Return to this form except on actual Update.
1180
    $form_state['view']->addFormToStack('rearrange-filter', $form_state['display_id'], array($form_state['type']));
merlinofchaos's avatar
merlinofchaos committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  }
  else {
    // The actual update button was clicked. Remove the empty groups, and
    // renumber them sequentially.
    ksort($remember_groups);
    $groups['groups'] = views_array_key_plus(array_values(array_intersect_key($groups['groups'], $remember_groups)));
    // Change the 'group' key on each field to match. Here, $mapping is an
    // array whose keys are the old group numbers and whose values are the new
    // (sequentially numbered) ones.
    $mapping = array_flip(views_array_key_plus(array_keys($remember_groups)));
    foreach ($new_fields as &$new_field) {
      $new_field['group'] = $mapping[$new_field['group']];
    }

    // Write the changed handler values.
1196 1197
    $display->setOption($types[$form_state['type']]['plural'], $new_fields);
    $display->setOption('filter_groups', $groups);
merlinofchaos's avatar
merlinofchaos committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    if (isset($form_state['view']->form_cache)) {
      unset($form_state['view']->form_cache);
    }
  }

  // Store in cache.
  views_ui_cache_set($form_state['view']);
}

/**
 * Form to add_item items in the views UI.
 */
function views_ui_add_item_form($form, &$form_state) {
  $view = &$form_state['view'];
  $display_id = $form_state['display_id'];
  $type = $form_state['type'];

  $form = array(
    'options' => array(
      '#theme_wrappers' => array('container'),
      '#attributes' => array('class' => array('scroll')),
    ),
  );

1222 1223
  $executable = $view->get('executable');
  if (!$executable->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
1224 1225
    views_ajax_error(t('Invalid display id @display', array('@display' => $display_id)));
  }
1226
  $display = &$executable->displayHandlers[$display_id];
merlinofchaos's avatar
merlinofchaos committed
1227

1228
  $types = ViewExecutable::viewsHandlerTypes();
merlinofchaos's avatar
merlinofchaos committed
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
  $ltitle = $types[$type]['ltitle'];
  $section = $types[$type]['plural'];

  if (!empty($types[$type]['type'])) {
    $type = $types[$type]['type'];
  }

  $form['#title'] = t('Add @type', array('@type' => $ltitle));
  $form['#section'] = $display_id . 'add-item';

  // Add the display override dropdown.
  views_ui_standard_display_dropdown($form, $form_state, $section);

  // Figure out all the base tables allowed based upon what the relationships provide.
1243
  $base_tables = $executable->getBaseTables();
1244
  $options = views_fetch_fields(array_keys($base_tables), $type, $display->useGroupBy(), $form_state['type']);
merlinofchaos's avatar
merlinofchaos committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270

  if (!empty($options)) {
    $form['options']['controls'] = array(
      '#theme_wrappers' => array('container'),
      '#id' => 'views-filterable-options-controls',
      '#attributes' => array('class' => array('container-inline')),
    );
    $form['options']['controls']['options_search'] = array(
      '#type' => 'textfield',
      '#title' => t('Search'),
    );

    $groups = array('all' => t('- All -'));
    $form['options']['controls']['group'] = array(
      '#type' => 'select',
      '#title' => t('Filter'),
      '#options' => array(),
    );

    $form['options']['name'] = array(
      '#prefix' => '<div class="views-radio-box form-checkboxes views-filterable-options">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
      '#default_value' => 'all',
    );

1271
    // Group options first to simplify the usage of #states.
merlinofchaos's avatar
merlinofchaos committed
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    $grouped_options = array();
    foreach ($options as $key => $option) {
      $group = preg_replace('/[^a-z0-9]/', '-', strtolower($option['group']));
      $groups[$group] = $option['group'];
      $grouped_options[$group][$key] = $option;
      if (!empty($option['aliases']) && is_array($option['aliases'])) {
        foreach ($option['aliases'] as $id => $alias) {
          if (empty($alias['base']) || !empty($base_tables[$alias['base']])) {
            $copy = $option;
            $copy['group'] = $alias['group'];
            $copy['title'] = $alias['title'];
            if (isset($alias['help'])) {
              $copy['help'] = $alias['help'];
            }

            $group = preg_replace('/[^a-z0-9]/', '-', strtolower($copy['group']));
            $groups[$group] = $copy['group'];
            $grouped_options[$group][$key . '$' . $id] = $copy;
          }
        }
      }
    }

    foreach ($grouped_options as $group => $group_options) {
      $zebra = 0;
      foreach ($group_options as $key => $option) {
        $zebra_class = ($zebra % 2) ? 'odd' : 'even';
        $form['options']['name'][$key] = array(
          '#type' => 'checkbox',
          '#title' => t('!group: !field', array('!group' => $option['group'], '!field' => $option['title'])),
          '#description' => $option['help'],
          '#return_value' => $key,
          '#prefix' => "<div class='$zebra_class filterable-option'>",
          '#suffix' => '</div>',
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
          '#states' => array(
            'visible' => array(
              array(
                ':input[name="group"]' => array('value' => 'all'),
              ),
              array(
                ':input[name="group"]' => array('value' => $group),
              ),
            )
          )
merlinofchaos's avatar
merlinofchaos committed
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
        );
        $zebra++;
      }
    }

    $form['options']['controls']['group']['#options'] = $groups;
  }
  else {
    $form['options']['markup'] = array(
      '#markup' => '<div class="form-item">' . t('There are no @types available to add.', array('@types' =>  $ltitle)) . '</div>',
    );
  }
  // Add a div to show the selected items
  $form['selected'] = array(
    '#type' => 'item',
    '#markup' => '<div class="views-selected-options"></div>',
    '#title' => t('Selected') . ':',
1333
    '#theme_wrappers' => array('form_element', 'views_ui_container'),
merlinofchaos's avatar
merlinofchaos committed
1334 1335
    '#attributes' => array('class' => array('container-inline', 'views-add-form-selected')),
  );
1336
  $view->getStandardButtons($form, $form_state, 'views_ui_add_item_form', t('Add and configure @types', array('@types' => $ltitle)));
merlinofchaos's avatar
merlinofchaos committed
1337 1338

  // Remove the default submit function.
1339 1340
  $form['buttons']['submit']['#submit'] = array_diff($form['buttons']['submit']['#submit'], array(array($view, 'standardSubmit')));
  $form['buttons']['submit']['#submit'][] = array($view, 'submitItemAdd');
merlinofchaos's avatar
merlinofchaos committed
1341 1342 1343 1344

  return $form;
}

1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
/**
 * Override handler for views_ui_edit_display_form
 */
function views_ui_config_item_form_build_group($form, &$form_state) {
  $item = &$form_state['handler']->options;
  // flip. If the filter was a group, set back to a standard filter.
  $item['is_grouped'] = empty($item['is_grouped']);

  // If necessary, set new defaults:
  if ($item['is_grouped']) {
    $form_state['handler']->build_group_options();
  }

1358
  $form_state['view']->get('executable')->setItem($form_state['display_id'], $form_state['type'], $form_state['id'], $item);
1359

1360
  $form_state['view']->addFormToStack($form_state['form_key'], $form_state['display_id'], array($form_state['type'], $form_state['id']), TRUE, TRUE);
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

  views_ui_cache_set($form_state['view']);
  $form_state['rerender'] = TRUE;
  $form_state['rebuild'] = TRUE;
  $form_state['force_build_group_options'] = TRUE;
}

/**
 * Add a new group to the exposed filter groups.
 */
function views_ui_config_item_form_add_group($form, &$form_state) {
  $item =& $form_state['handler']->options;

  // Add a new row.
  $item['group_info']['group_items'][] = array();

1377
  $form_state['view']->get('executable')->setItem($form_state['display_id'], $form_state['type'], $form_state['id'], $item);
1378 1379 1380 1381 1382 1383

  views_ui_cache_set($form_state['view']);
  $form_state['rerender'] = TRUE;
  $form_state['rebuild'] = TRUE;
  $form_state['force_build_group_options'] = TRUE;
}
merlinofchaos's avatar
merlinofchaos committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400

/**
 * Form to config_item items in the views UI.
 */
function views_ui_config_item_form($form, &$form_state) {
  $view = &$form_state['view'];
  $display_id = $form_state['display_id'];
  $type = $form_state['type'];
  $id = $form_state['id'];

  $form = array(
    'options' => array(
      '#tree' => TRUE,
      '#theme_wrappers' => array('container'),
      '#attributes' => array('class' => array('scroll')),
    ),
  );
1401 1402
  $executable = $view->get('executable');
  if (!$executable->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
1403 1404
    views_ajax_error(t('Invalid display id @display', array('@display' => $display_id)));
  }
1405
  $item = $executable->getItem($display_id, $type, $id);
merlinofchaos's avatar
merlinofchaos committed
1406 1407

  if ($item) {
1408
    $handler = $executable->display_handler->getHandler($type, $id);
merlinofchaos's avatar
merlinofchaos committed
1409 1410 1411 1412
    if (empty($handler)) {
      $form['markup'] = array('#markup' => t("Error: handler for @table > @field doesn't exist!", array('@table' => $item['table'], '@field' => $item['field'])));
    }
    else {
1413
      $types = ViewExecutable::viewsHandlerTypes();
merlinofchaos's avatar
merlinofchaos committed
1414 1415 1416

      // If this item can come from the default display, show a dropdown
      // that lets the user choose which display the changes should apply to.
1417
      if ($executable->display_handler->defaultableSections($types[$type]['plural'])) {
merlinofchaos's avatar
merlinofchaos committed
1418 1419 1420 1421 1422 1423
        $form_state['section'] = $types[$type]['plural'];
        views_ui_standard_display_dropdown($form, $form_state, $form_state['section']);
      }

      // A whole bunch of code to figure out what relationships are valid for
      // this item.
1424
      $relationships = $executable->display_handler->getOption('relationships');
merlinofchaos's avatar
merlinofchaos committed
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
      $relationship_options = array();

      foreach ($relationships as $relationship) {
        // relationships can't link back to self. But also, due to ordering,
        // relationships can only link to prior relationships.
        if ($type == 'relationship' && $id == $relationship['id']) {
          break;
        }
        $relationship_handler = views_get_handler($relationship['table'], $relationship['field'], 'relationship');
        // ignore invalid/broken relationships.
        if (empty($relationship_handler)) {
          continue;
        }

        // If this relationship is valid for this type, add it to the list.
        $data = views_fetch_data($relationship['table']);
        $base = $data[$relationship['field']]['relationship']['base'];
1442
        $base_fields = views_fetch_fields($base, $form_state['type'], $executable->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1443
        if (isset($base_fields[$item['table'] . '.' . $item['field']])) {
1444
          $relationship_handler->init($executable, $relationship);
merlinofchaos's avatar
merlinofchaos committed
1445 1446 1447 1448 1449 1450 1451
          $relationship_options[$relationship['id']] = $relationship_handler->label();
        }
      }

      if (!empty($relationship_options)) {
        // Make sure the existing relationship is even valid. If not, force
        // it to none.
1452
        $base_fields = views_fetch_fields($view->get('base_table'), $form_state['type'], $executable->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1453 1454 1455 1456 1457 1458 1459 1460 1461
        if (isset($base_fields[$item['table'] . '.' . $item['field']])) {
          $relationship_options = array_merge(array('none' => t('Do not use a relationship')), $relationship_options);
        }
        $rel = empty($item['relationship']) ? 'none' : $item['relationship'];
        if (empty($relationship_options[$rel])) {
          // Pick the first relationship.
          $rel = key($relationship_options);
          // We want this relationship option to get saved even if the user
          // skips submitting the form.
1462
          $executable->setItemOption($display_id, $type, $id, 'relationship', $rel);
1463
          $temp_view = $view->cloneView();
merlinofchaos's avatar
merlinofchaos committed
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
          views_ui_cache_set($temp_view);
        }

        $form['options']['relationship'] = array(
          '#type' => 'select',
          '#title' => t('Relationship'),
          '#options' => $relationship_options,
          '#default_value' => $rel,
          '#weight' => -500,
        );
      }
      else {
        $form['options']['relationship'] = array(
          '#type' => 'value',
          '#value' => 'none',
        );
      }

1482
      $form['#title'] = t('Configure @type: @item', array('@type' => $types[$type]['lstitle'], '@item' => $handler->adminLabel()));
merlinofchaos's avatar
merlinofchaos committed
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495

      if (!empty($handler->definition['help'])) {
        $form['options']['form_description'] = array(
          '#markup' => $handler->definition['help'],
          '#theme_wrappers' => array('container'),
          '#attributes' => array('class' => array('form-item description')),
          '#weight' => -1000,
        );
      }

      $form['#section'] = $display_id . '-' . $type . '-' . $id;

      // Get form from the handler.
1496
      $handler->buildOptionsForm($form['options'], $form_state);
merlinofchaos's avatar
merlinofchaos committed
1497 1498 1499 1500 1501 1502 1503 1504
      $form_state['handler'] = &$handler;
    }

    $name = NULL;
    if (isset($form_state['update_name'])) {
      $name = $form_state['update_name'];
    }

1505
    $view->getStandardButtons($form, $form_state, 'views_ui_config_item_form', $name, t('Remove'), 'remove');
merlinofchaos's avatar
merlinofchaos committed
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
    // Only validate the override values, because this values are required for
    // the override selection.
    $form['buttons']['remove']['#limit_validation_errors'] = array(array('override'));
  }

  return $form;
}

/**
 * Submit handler for configing new item(s) to a view.
 */
function views_ui_config_item_form_validate($form, &$form_state) {
1518
  $form_state['handler']->validateOptionsForm($form['options'], $form_state);
merlinofchaos's avatar
merlinofchaos committed
1519 1520 1521 1522