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

/**
 * @file
 * Handles the server side AJAX interactions of Views.
 */

8 9
use Symfony\Component\HttpFoundation\JsonResponse;

merlinofchaos's avatar
merlinofchaos committed
10 11 12 13 14 15 16 17 18 19
/**
 * @defgroup ajax Views AJAX library
 * @{
 * Handles the server side AJAX interactions of Views.
 */

/**
 * Menu callback to load a view via AJAX.
 */
function views_ajax() {
20 21 22 23 24 25 26 27 28 29 30
  $request = drupal_container()->get('request');
  $name = $request->request->get('view_name');
  $display_id = $request->request->get('view_display_id');
  if (isset($name) && isset($display_id)) {
    $args = $request->request->get('view_args');
    $args = isset($args) && $args !== '' ? explode('/', $args) : array();
    $path = $request->request->get('view_path');
    $dom_id = $request->request->get('view_dom_id');
    $dom_id = isset($dom_id) ? preg_replace('/[^a-zA-Z0-9_-]+/', '-', $dom_id) : NULL;
    $pager_element = $request->request->get('pager_element');
    $pager_element = isset($pager_element) ? intval($pager_element) : NULL;
merlinofchaos's avatar
merlinofchaos committed
31 32 33

    $commands = array();

34 35
    // Remove all of this stuff from the query of the request so it doesn't end
    // up in pagers and tablesort URLs.
merlinofchaos's avatar
merlinofchaos committed
36
    foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', 'ajax_html_ids', 'ajax_page_state') as $key) {
37 38
      if ($request->query->has($key)) {
        $request->query->remove($key);
merlinofchaos's avatar
merlinofchaos committed
39
      }
40 41
      if ($request->request->has($key)) {
        $request->request->remove($key);
merlinofchaos's avatar
merlinofchaos committed
42 43 44 45 46 47
      }
    }

    // Load the view.
    $view = views_get_view($name);
    if ($view && $view->access($display_id)) {
48
      // Fix the current path for paging.
merlinofchaos's avatar
merlinofchaos committed
49
      if (!empty($path)) {
50
        _current_path($path);
merlinofchaos's avatar
merlinofchaos committed
51 52 53 54
      }

      // Add all $_POST data, because AJAX is always a post and many things,
      // such as tablesorts, exposed filters and paging assume $_GET.
55 56 57
      $request_all = $request->request->all();
      $query_all = $request->query->all();
      $request->query->replace($request_all + $query_all);
merlinofchaos's avatar
merlinofchaos committed
58 59 60 61

      // Overwrite the destination.
      // @see drupal_get_destination()
      $origin_destination = $path;
62
      $query = drupal_http_build_query($request->query->all());
merlinofchaos's avatar
merlinofchaos committed
63 64 65 66 67 68 69 70 71
      if ($query != '') {
        $origin_destination .= '?' . $query;
      }
      $destination = &drupal_static('drupal_get_destination');
      $destination = array('destination' => $origin_destination);

      // Override the display's pager_element with the one actually used.
      if (isset($pager_element)) {
        $commands[] = views_ajax_command_scroll_top('.view-dom-id-' . $dom_id);
72
        $view->displayHandlers[$display_id]->setOption('pager_element', $pager_element);
merlinofchaos's avatar
merlinofchaos committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
      }
      // Reuse the same DOM id so it matches that in Drupal.settings.
      $view->dom_id = $dom_id;

      $commands[] = ajax_command_replace('.view-dom-id-' . $dom_id, $view->preview($display_id, $args));
    }
    drupal_alter('views_ajax_data', $commands, $view);
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

/**
 * Creates a Drupal AJAX 'viewsSetForm' command.
 *
 * @param $output
 *   The form to display in the modal.
 * @param $title
 *   The title.
 * @param $url
 *   An optional URL.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_set_form($output, $title, $url = NULL) {
  $command = array(
    'command' => 'viewsSetForm',
    'output' => $output,
    'title' => $title,
  );
  if (isset($url)) {
    $command['url'] = $url;
  }
  return $command;
}

/**
 * Creates a Drupal AJAX 'viewsDismissForm' command.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_dismiss_form() {
  $command = array(
    'command' => 'viewsDismissForm',
  );
  return $command;
}

/**
 * Creates a Drupal AJAX 'viewsHilite' command.
 *
 * @param $selector
 *   The selector to highlight
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_hilite($selector) {
  return array(
    'command' => 'viewsHilite',
    'selector' => $selector,
  );
}

/**
 * Creates a Drupal AJAX 'addTab' command.
 *
 * @param $id
 *   The DOM ID.
 * @param $title
 *   The title.
 * @param $body
 *   The body.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_add_tab($id, $title, $body) {
  $command = array(
    'command' => 'viewsAddTab',
    'id' => $id,
    'title' => $title,
    'body' => $body,
  );
  return $command;
}

/**
 * Scroll to top of the current view.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_scroll_top($selector) {
  $command = array(
    'command' => 'viewsScrollTop',
    'selector' => $selector,
  );
  return $command;
}

/**
 * Shows Save and Cancel buttons.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_show_buttons() {
  $command = array(
    'command' => 'viewsShowButtons',
  );
  return $command;
}

/**
 * Trigger the Views live preview.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_trigger_preview() {
  $command = array(
    'command' => 'viewsTriggerPreview',
  );
  return $command;
}

/**
 * Replace the page title.
 *
 * @return
 *   An array suitable for use with the ajax_render() function.
 */
function views_ajax_command_replace_title($title) {
  $command = array(
    'command' => 'viewsReplaceTitle',
    'title' => $title,
211
    'siteName' => config('system.site')->get('name'),
merlinofchaos's avatar
merlinofchaos committed
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
  );
  return $command;
}

/**
 * Return an AJAX error.
 */
function views_ajax_error($message) {
  $commands = array();
  $commands[] = views_ajax_command_set_form($message, t('Error'));
  return $commands;
}

/**
 * Wrapper around drupal_build_form to handle some AJAX stuff automatically.
 * This makes some assumptions about the client.
 */
function views_ajax_form_wrapper($form_id, &$form_state) {
  // This won't override settings already in.
  $form_state += array(
    'rerender' => FALSE,
    'no_redirect' => !empty($form_state['ajax']),
    'no_cache' => TRUE,
    'build_info' => array(
      'args' => array(),
    ),
  );

  $form = drupal_build_form($form_id, $form_state);
  $output = drupal_render($form);

  // These forms have the title built in, so set the title here:
  if (empty($form_state['ajax']) && !empty($form_state['title'])) {
    drupal_set_title($form_state['title']);
    drupal_add_css(drupal_get_path('module', 'views_ui') . '/css/views-admin.css');
  }

  if (!empty($form_state['ajax']) && (empty($form_state['executed']) || !empty($form_state['rerender']))) {
    // If the form didn't execute and we're using ajax, build up a
    // Ajax command list to execute.
    $commands = array();

    $display = '';
    if ($messages = theme('status_messages')) {
      $display = '<div class="views-messages">' . $messages . '</div>';
    }
    $display .= $output;

    $title = empty($form_state['title']) ? '' : $form_state['title'];

262
    $url = empty($form_state['url']) ? url(current_path(), array('absolute' => TRUE)) : $form_state['url'];
merlinofchaos's avatar
merlinofchaos committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

    $commands[] = views_ajax_command_set_form($display, $title, $url);

    if (!empty($form_state['#section'])) {
      $commands[] = views_ajax_command_hilite('.' . drupal_clean_css_identifier($form_state['#section']));
    }

    return $commands;
  }

  // These forms have the title built in, so set the title here:
  if (empty($form_state['ajax']) && !empty($form_state['title'])) {
    drupal_set_title($form_state['title']);
  }

  return $output;
}

/**
282 283 284 285 286 287 288 289
 * Page callback for views user autocomplete.
 *
 * @param string $string
 *   (optional) A comma-separated list of user names entered in the
 *   autocomplete form element. Only the last user is used for autocompletion.
 *   Defaults to '' (an empty string).
 *
 * @return Symfony\Component\HttpFoundation\JsonResponse
merlinofchaos's avatar
merlinofchaos committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
 */
function views_ajax_autocomplete_user($string = '') {
  // The user enters a comma-separated list of user name. We only autocomplete the last name.
  $array = drupal_explode_tags($string);

  // Fetch last name
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string != '') {
    $prefix = count($array) ? implode(', ', $array) . ', ' : '';

    if (strpos('anonymous', strtolower($last_string)) !== FALSE) {
      $matches[$prefix . 'Anonymous'] = 'Anonymous';
    }

    $result = db_select('users', 'u')
      ->fields('u', array('uid', 'name'))
      ->condition('u.name', db_like($last_string) . '%', 'LIKE')
      ->range(0, 10)
      ->execute()
      ->fetchAllKeyed();

    foreach ($result as $account) {
      $n = $account;
      // Commas and quotes in terms are special cases, so encode 'em.
      if (strpos($account, ',') !== FALSE || strpos($account, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $account) . '"';
      }
      $matches[$prefix . $n] = check_plain($account);
    }
  }

322
  return new JsonResponse($matches);
merlinofchaos's avatar
merlinofchaos committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
}

/**
 * Page callback for views taxonomy autocomplete.
 *
 * @param $vid
 *   The vocabulary id of the tags which should be returned.
 *
 * @param $tags_typed
 *   The typed string of the user.
 *
 * @see taxonomy_autocomplete()
 */
function views_ajax_autocomplete_taxonomy($vid, $tags_typed = '') {
  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $tags_typed = drupal_explode_tags($tags_typed);
  $tag_last = drupal_strtolower(array_pop($tags_typed));

  $matches = array();
  if ($tag_last != '') {

    $query = db_select('taxonomy_term_data', 't');
    $query->addTag('translatable');
    $query->addTag('term_access');

    // Do not select already entered terms.
    if (!empty($tags_typed)) {
      $query->condition('t.name', $tags_typed, 'NOT IN');
    }
    // Select rows that match by term name.
    $tags_return = $query
      ->fields('t', array('tid', 'name'))
      ->condition('t.vid', $vid)
      ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
      ->range(0, 10)
      ->execute()
      ->fetchAllKeyed();

    $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';

    $term_matches = array();
    foreach ($tags_return as $tid => $name) {
      $n = $name;
      // Term names containing commas or quotes must be wrapped in quotes.
      if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $name) . '"';
      }
      // Add term name to list of matches.
      $term_matches[$prefix . $n] = check_plain($name);
    }
  }

375
  return new JsonResponse($term_matches);
merlinofchaos's avatar
merlinofchaos committed
376 377 378 379 380
}

/**
 * @}
 */