Projet

Général

Profil

Paste
Télécharger (79,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views / views.module @ b858700c

1
<?php
2

    
3
/**
4
 * @file
5
 * Primarily Drupal hooks and global API functions to manipulate views.
6
 *
7
 * This is the main module file for Views. The main entry points into
8
 * this module are views_page() and views_block(), where it handles
9
 * incoming page and block requests.
10
 */
11

    
12
/**
13
 * Advertise the current views api version
14
 */
15
function views_api_version() {
16
  return '3.0';
17
}
18

    
19
/**
20
 * Implements hook_forms().
21
 *
22
 * To provide distinct form IDs for Views forms, the View name and
23
 * specific display name are appended to the base ID,
24
 * views_form_views_form. When such a form is built or submitted, this
25
 * function will return the proper callback function to use for the given form.
26
 */
27
function views_forms($form_id, $args) {
28
  if (strpos($form_id, 'views_form_') === 0) {
29
    return array(
30
      $form_id => array(
31
        'callback' => 'views_form',
32
      ),
33
    );
34
  }
35
}
36

    
37
/**
38
 * Returns a form ID for a Views form using the name and display of the View.
39
 */
40
function views_form_id($view) {
41
  $parts = array(
42
    'views_form',
43
    $view->name,
44
    $view->current_display,
45
  );
46

    
47
  return implode('_', $parts);
48
}
49

    
50
/**
51
 * Views will not load plugins advertising a version older than this.
52
 */
53
function views_api_minimum_version() {
54
  return '2';
55
}
56

    
57
/**
58
 * Implement hook_theme(). Register views theming functions.
59
 */
60
function views_theme($existing, $type, $theme, $path) {
61
  $path = drupal_get_path('module', 'views');
62
  ctools_include('theme', 'views', 'theme');
63

    
64
  // Some quasi clever array merging here.
65
  $base = array(
66
    'file' => 'theme.inc',
67
    'path' => $path . '/theme',
68
  );
69

    
70
  // Our extra version of pager from pager.inc
71
  $hooks['views_mini_pager'] = $base + array(
72
    'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array()),
73
    'pattern' => 'views_mini_pager__',
74
  );
75

    
76
  $variables = array(
77
    // For displays, we pass in a dummy array as the first parameter, since
78
    // $view is an object but the core contextual_preprocess() function only
79
    // attaches contextual links when the primary theme argument is an array.
80
    'display' => array('view_array' => array(), 'view' => NULL),
81
    'style' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
82
    'row' => array('view' => NULL, 'options' => NULL, 'row' => NULL, 'field_alias' => NULL),
83
    'exposed_form' => array('view' => NULL, 'options' => NULL),
84
    'pager' => array(
85
      'view' => NULL, 'options' => NULL,
86
      'tags' => array(), 'quantity' => 10, 'element' => 0, 'parameters' => array()
87
    ),
88
  );
89

    
90
  // Default view themes
91
  $hooks['views_view_field'] = $base + array(
92
    'pattern' => 'views_view_field__',
93
    'variables' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
94
  );
95
  $hooks['views_view_grouping'] = $base + array(
96
    'pattern' => 'views_view_grouping__',
97
    'variables' => array('view' => NULL, 'grouping' => NULL, 'grouping_level' => NULL, 'rows' => NULL, 'title' => NULL),
98
  );
99

    
100
  $plugins = views_fetch_plugin_data();
101

    
102
  // Register theme functions for all style plugins
103
  foreach ($plugins as $type => $info) {
104
    foreach ($info as $plugin => $def) {
105
      if (isset($def['theme']) && (!isset($def['register theme']) || !empty($def['register theme']))) {
106
        $hooks[$def['theme']] = array(
107
          'pattern' => $def['theme'] . '__',
108
          'file' => $def['theme file'],
109
          'path' => $def['theme path'],
110
          'variables' => $variables[$type],
111
        );
112

    
113
        $include = DRUPAL_ROOT . '/' . $def['theme path'] . '/' . $def['theme file'];
114
        if (file_exists($include)) {
115
          require_once $include;
116
        }
117

    
118
        if (!function_exists('theme_' . $def['theme'])) {
119
          $hooks[$def['theme']]['template'] = drupal_clean_css_identifier($def['theme']);
120
        }
121
      }
122
      if (isset($def['additional themes'])) {
123
        foreach ($def['additional themes'] as $theme => $theme_type) {
124
          if (empty($theme_type)) {
125
            $theme = $theme_type;
126
            $theme_type = $type;
127
          }
128

    
129
          $hooks[$theme] = array(
130
            'pattern' => $theme . '__',
131
            'file' => $def['theme file'],
132
            'path' => $def['theme path'],
133
            'variables' => $variables[$theme_type],
134
          );
135

    
136
          if (!function_exists('theme_' . $theme)) {
137
            $hooks[$theme]['template'] = drupal_clean_css_identifier($theme);
138
          }
139
        }
140
      }
141
    }
142
  }
143

    
144
  $hooks['views_form_views_form'] = $base + array(
145
    'render element' => 'form',
146
  );
147

    
148
  $hooks['views_exposed_form'] = $base + array(
149
    'template' => 'views-exposed-form',
150
    'pattern' => 'views_exposed_form__',
151
    'render element' => 'form',
152
  );
153

    
154
  $hooks['views_more'] = $base + array(
155
    'template' => 'views-more',
156
    'pattern' => 'views_more__',
157
    'variables' => array('more_url' => NULL, 'link_text' => 'more', 'view' => NULL),
158
  );
159

    
160
  // Add theme suggestions which are part of modules.
161
  foreach (views_get_module_apis() as $info) {
162
    if (isset($info['template path'])) {
163
      $hooks += _views_find_module_templates($hooks, $info['template path']);
164
    }
165
  }
166
  return $hooks;
167
}
168

    
169
/**
170
 * Scans a directory of a module for template files.
171
 *
172
 * @param $cache
173
 *   The existing cache of theme hooks to test against.
174
 * @param $path
175
 *   The path to search.
176
 *
177
 * @see drupal_find_theme_templates()
178
 */
179
function _views_find_module_templates($cache, $path) {
180
  $templates = array();
181
  $regex = '/' . '\.tpl\.php' . '$' . '/';
182

    
183
  // Because drupal_system_listing works the way it does, we check for real
184
  // templates separately from checking for patterns.
185
  $files = drupal_system_listing($regex, $path, 'name', 0);
186
  foreach ($files as $template => $file) {
187
    // Chop off the remaining extensions if there are any. $template already
188
    // has the rightmost extension removed, but there might still be more,
189
    // such as with .tpl.php, which still has .tpl in $template at this point.
190
    if (($pos = strpos($template, '.')) !== FALSE) {
191
      $template = substr($template, 0, $pos);
192
    }
193
    // Transform - in filenames to _ to match function naming scheme
194
    // for the purposes of searching.
195
    $hook = strtr($template, '-', '_');
196
    if (isset($cache[$hook])) {
197
      $templates[$hook] = array(
198
        'template' => $template,
199
        'path' => dirname($file->filename),
200
        'includes' => isset($cache[$hook]['includes']) ? $cache[$hook]['includes'] : NULL,
201
      );
202
    }
203
    // Ensure that the pattern is maintained from base themes to its sub-themes.
204
    // Each sub-theme will have their templates scanned so the pattern must be
205
    // held for subsequent runs.
206
    if (isset($cache[$hook]['pattern'])) {
207
      $templates[$hook]['pattern'] = $cache[$hook]['pattern'];
208
    }
209
  }
210

    
211
  $patterns = array_keys($files);
212

    
213
  foreach ($cache as $hook => $info) {
214
    if (!empty($info['pattern'])) {
215
      // Transform _ in pattern to - to match file naming scheme
216
      // for the purposes of searching.
217
      $pattern = strtr($info['pattern'], '_', '-');
218

    
219
      $matches = preg_grep('/^'. $pattern .'/', $patterns);
220
      if ($matches) {
221
        foreach ($matches as $match) {
222
          $file = substr($match, 0, strpos($match, '.'));
223
          // Put the underscores back in for the hook name and register this pattern.
224
          $templates[strtr($file, '-', '_')] = array(
225
            'template' => $file,
226
            'path' => dirname($files[$match]->uri),
227
            'variables' => isset($info['variables']) ? $info['variables'] : NULL,
228
            'render element' => isset($info['render element']) ? $info['render element'] : NULL,
229
            'base hook' => $hook,
230
            'includes' => isset($info['includes']) ? $info['includes'] : NULL,
231
          );
232
        }
233
      }
234
    }
235
  }
236

    
237
  return $templates;
238
}
239

    
240
/**
241
 * Returns a list of plugins and metadata about them.
242
 *
243
 * @return array
244
 *   An array keyed by PLUGIN_TYPE:PLUGIN_NAME, like 'display:page' or
245
 *   'pager:full', containing an array with the following keys:
246
 *   - title: The plugin's title.
247
 *   - type: The plugin type.
248
 *   - module: The module providing the plugin.
249
 *   - views: An array of enabled Views that are currently using this plugin,
250
 *     keyed by machine name.
251
 */
252
function views_plugin_list() {
253
  $plugin_data = views_fetch_plugin_data();
254
  $plugins = array();
255
  foreach (views_get_enabled_views() as $view) {
256
    foreach ($view->display as $display_id => $display) {
257
      foreach ($plugin_data as $type => $info) {
258
        if ($type == 'display' && isset($display->display_plugin)) {
259
          $name = $display->display_plugin;
260
        }
261
        elseif (isset($display->display_options["{$type}_plugin"])) {
262
          $name = $display->display_options["{$type}_plugin"];
263
        }
264
        elseif (isset($display->display_options[$type]['type'])) {
265
          $name = $display->display_options[$type]['type'];
266
        }
267
        else {
268
          continue;
269
        }
270

    
271
        // Key first by the plugin type, then the name.
272
        $key = $type . ':' . $name;
273
        // Add info for this plugin.
274
        if (!isset($plugins[$key])) {
275
          $plugins[$key] = array(
276
            'type' => $type,
277
            'title' => check_plain($info[$name]['title']),
278
            'module' => check_plain($info[$name]['module']),
279
            'views' => array(),
280
          );
281
        }
282

    
283
        // Add this view to the list for this plugin.
284
        $plugins[$key]['views'][$view->name] = $view->name;
285
      }
286
    }
287
  }
288
  return $plugins;
289
}
290

    
291
/**
292
 * A theme preprocess function to automatically allow view-based node
293
 * templates if called from a view.
294
 *
295
 * The 'modules/node.views.inc' file is a better place for this, but
296
 * we haven't got a chance to load that file before Drupal builds the
297
 * node portion of the theme registry.
298
 */
299
function views_preprocess_node(&$vars) {
300
  // The 'view' attribute of the node is added in views_preprocess_node()
301
  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
302
    $vars['view'] = $vars['node']->view;
303
    $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
304
    if (!empty($vars['node']->view->current_display)) {
305
      $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;
306

    
307
      // If a node is being rendered in a view, and the view does not have a path,
308
      // prevent drupal from accidentally setting the $page variable:
309
      if ($vars['page'] && $vars['view_mode'] == 'full' && !$vars['view']->display_handler->has_path()) {
310
        $vars['page'] = FALSE;
311
      }
312
    }
313
  }
314

    
315
  // Allow to alter comments and links based on the settings in the row plugin.
316
  if (!empty($vars['view']->style_plugin->row_plugin) && get_class($vars['view']->style_plugin->row_plugin) == 'views_plugin_row_node_view') {
317
    node_row_node_view_preprocess_node($vars);
318
  }
319
}
320

    
321
/**
322
 * A theme preprocess function to automatically allow view-based node
323
 * templates if called from a view.
324
 */
325
function views_preprocess_comment(&$vars) {
326
  // The 'view' attribute of the node is added in template_preprocess_views_view_row_comment()
327
  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
328
    $vars['view'] = &$vars['node']->view;
329
    $vars['theme_hook_suggestions'][] = 'comment__view__' . $vars['node']->view->name;
330
    if (!empty($vars['node']->view->current_display)) {
331
      $vars['theme_hook_suggestions'][] = 'comment__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;
332
    }
333
  }
334
}
335

    
336
/**
337
 * Implement hook_permission().
338
 */
339
function views_permission() {
340
  return array(
341
    'administer views' => array(
342
      'title' => t('Administer views'),
343
      'description' => t('Access the views administration pages.'),
344
      'restrict access' => TRUE,
345
    ),
346
    'access all views' => array(
347
      'title' => t('Bypass views access control'),
348
      'description' => t('Bypass access control when accessing views.'),
349
      'restrict access' => TRUE,
350
    ),
351
  );
352
}
353

    
354
/**
355
 * Implement hook_menu().
356
 */
357
function views_menu() {
358
  // Any event which causes a menu_rebuild could potentially mean that the
359
  // Views data is updated -- module changes, profile changes, etc.
360
  views_invalidate_cache();
361
  $items = array();
362
  $items['views/ajax'] = array(
363
    'title' => 'Views',
364
    'page callback' => 'views_ajax',
365
    'theme callback' => 'ajax_base_page_theme',
366
    'delivery callback' => 'ajax_deliver',
367
    'access callback' => TRUE,
368
    'description' => 'Ajax callback for view loading.',
369
    'type' => MENU_CALLBACK,
370
    'file' => 'includes/ajax.inc',
371
  );
372
  // Path is not admin/structure/views due to menu complications with the wildcards from
373
  // the generic ajax callback.
374
  $items['admin/views/ajax/autocomplete/user'] = array(
375
    'page callback' => 'views_ajax_autocomplete_user',
376
    'theme callback' => 'ajax_base_page_theme',
377
    'access callback' => 'user_access',
378
    'access arguments' => array('access user profiles'),
379
    'type' => MENU_CALLBACK,
380
    'file' => 'includes/ajax.inc',
381
  );
382
  // Define another taxonomy autocomplete because the default one of drupal
383
  // does not support a vid a argument anymore
384
  $items['admin/views/ajax/autocomplete/taxonomy'] = array(
385
    'page callback' => 'views_ajax_autocomplete_taxonomy',
386
    'theme callback' => 'ajax_base_page_theme',
387
    'access callback' => 'user_access',
388
    'access arguments' => array('access content'),
389
    'type' => MENU_CALLBACK,
390
    'file' => 'includes/ajax.inc',
391
  );
392
  return $items;
393
}
394

    
395
/**
396
 * Implement hook_menu_alter().
397
 */
398
function views_menu_alter(&$callbacks) {
399
  $our_paths = array();
400
  $views = views_get_applicable_views('uses hook menu');
401
  foreach ($views as $data) {
402
    list($view, $display_id) = $data;
403
    $result = $view->execute_hook_menu($display_id, $callbacks);
404
    if (is_array($result)) {
405
      // The menu system doesn't support having two otherwise
406
      // identical paths with different placeholders.  So we
407
      // want to remove the existing items from the menu whose
408
      // paths would conflict with ours.
409

    
410
      // First, we must find any existing menu items that may
411
      // conflict.  We use a regular expression because we don't
412
      // know what placeholders they might use.  Note that we
413
      // first construct the regex itself by replacing %views_arg
414
      // in the display path, then we use this constructed regex
415
      // (which will be something like '#^(foo/%[^/]*/bar)$#') to
416
      // search through the existing paths.
417
      $regex = '#^(' . preg_replace('#%views_arg#', '%[^/]*', implode('|', array_keys($result))) . ')$#';
418
      $matches = preg_grep($regex, array_keys($callbacks));
419

    
420
      // Remove any conflicting items that were found.
421
      foreach ($matches as $path) {
422
        // Don't remove the paths we just added!
423
        if (!isset($our_paths[$path])) {
424
          unset($callbacks[$path]);
425
        }
426
      }
427
      foreach ($result as $path => $item) {
428
        if (!isset($callbacks[$path])) {
429
          // Add a new item, possibly replacing (and thus effectively
430
          // overriding) one that we removed above.
431
          $callbacks[$path] = $item;
432
        }
433
        else {
434
          // This item already exists, so it must be one that we added.
435
          // We change the various callback arguments to pass an array
436
          // of possible display IDs instead of a single ID.
437
          $callbacks[$path]['page arguments'][1] = (array)$callbacks[$path]['page arguments'][1];
438
          $callbacks[$path]['page arguments'][1][] = $display_id;
439
          $callbacks[$path]['access arguments'][] = $item['access arguments'][0];
440
          $callbacks[$path]['load arguments'][1] = (array)$callbacks[$path]['load arguments'][1];
441
          $callbacks[$path]['load arguments'][1][] = $display_id;
442
        }
443
        $our_paths[$path] = TRUE;
444
      }
445
    }
446
  }
447

    
448
  // Save memory: Destroy those views.
449
  foreach ($views as $data) {
450
    list($view, $display_id) = $data;
451
    $view->destroy();
452
  }
453
}
454

    
455
/**
456
 * Helper function for menu loading. This will automatically be
457
 * called in order to 'load' a views argument; primarily it
458
 * will be used to perform validation.
459
 *
460
 * @param $value
461
 *   The actual value passed.
462
 * @param $name
463
 *   The name of the view. This needs to be specified in the 'load function'
464
 *   of the menu entry.
465
 * @param $display_id
466
 *   The display id that will be loaded for this menu item.
467
 * @param $index
468
 *   The menu argument index. This counts from 1.
469
 */
470
function views_arg_load($value, $name, $display_id, $index) {
471
  static $views = array();
472

    
473
  // Make sure we haven't already loaded this views argument for a similar menu
474
  // item elsewhere.
475
  $key = $name . ':' . $display_id . ':' . $value . ':' . $index;
476
  if (isset($views[$key])) {
477
    return $views[$key];
478
  }
479

    
480
  if ($view = views_get_view($name)) {
481
    $view->set_display($display_id);
482
    $view->init_handlers();
483

    
484
    $ids = array_keys($view->argument);
485

    
486
    $indexes = array();
487
    $path = explode('/', $view->get_path());
488

    
489
    foreach ($path as $id => $piece) {
490
      if ($piece == '%' && !empty($ids)) {
491
        $indexes[$id] = array_shift($ids);
492
      }
493
    }
494

    
495
    if (isset($indexes[$index])) {
496
      if (isset($view->argument[$indexes[$index]])) {
497
        $arg = $view->argument[$indexes[$index]]->validate_argument($value) ? $value : FALSE;
498
        $view->destroy();
499

    
500
        // Store the output in case we load this same menu item again.
501
        $views[$key] = $arg;
502
        return $arg;
503
      }
504
    }
505
    $view->destroy();
506
  }
507
}
508

    
509
/**
510
 * Page callback: Displays a page view, given a name and display id.
511
 *
512
 * @param $name
513
 *   The name of a view.
514
 * @param $display_id
515
 *   The display id of a view.
516
 *
517
 * @return
518
 *   Either the HTML of a fully-executed view, or MENU_NOT_FOUND.
519
 */
520
function views_page($name, $display_id) {
521
  $args = func_get_args();
522
  // Remove $name and $display_id from the arguments.
523
  array_shift($args);
524
  array_shift($args);
525

    
526
  // Load the view and render it.
527
  if ($view = views_get_view($name)) {
528
    return $view->execute_display($display_id, $args);
529
  }
530

    
531
  // Fallback; if we get here no view was found or handler was not valid.
532
  return MENU_NOT_FOUND;
533
}
534

    
535
/**
536
 * Implements hook_page_alter().
537
 */
538
function views_page_alter(&$page) {
539
  // If the main content of this page contains a view, attach its contextual
540
  // links to the overall page array. This allows them to be rendered directly
541
  // next to the page title.
542
  $view = views_get_page_view();
543
  if (!empty($view)) {
544
    // If a module is still putting in the display like we used to, catch that.
545
    if (is_subclass_of($view, 'views_plugin_display')) {
546
      $view = $view->view;
547
    }
548

    
549
    views_add_contextual_links($page, 'page', $view, $view->current_display);
550
  }
551
}
552

    
553
/**
554
 * Implements MODULE_preprocess_HOOK().
555
 */
556
function views_preprocess_html(&$variables) {
557
  // If the page contains a view as its main content, contextual links may have
558
  // been attached to the page as a whole; for example, by views_page_alter().
559
  // This allows them to be associated with the page and rendered by default
560
  // next to the page title (which we want). However, it also causes the
561
  // Contextual Links module to treat the wrapper for the entire page (i.e.,
562
  // the <body> tag) as the HTML element that these contextual links are
563
  // associated with. This we don't want; for better visual highlighting, we
564
  // prefer a smaller region to be chosen. The region we prefer differs from
565
  // theme to theme and depends on the details of the theme's markup in
566
  // page.tpl.php, so we can only find it using JavaScript. We therefore remove
567
  // the "contextual-links-region" class from the <body> tag here and add
568
  // JavaScript that will insert it back in the correct place.
569
  if (!empty($variables['page']['#views_contextual_links_info'])) {
570
    $key = array_search('contextual-links-region', $variables['classes_array']);
571
    if ($key !== FALSE) {
572
      unset($variables['classes_array'][$key]);
573
      // Add the JavaScript, with a group and weight such that it will run
574
      // before modules/contextual/contextual.js.
575
      drupal_add_js(drupal_get_path('module', 'views') . '/js/views-contextual.js', array('group' => JS_LIBRARY, 'weight' => -1));
576
    }
577
  }
578
}
579

    
580
/**
581
 * Implements hook_contextual_links_view_alter().
582
 */
583
function views_contextual_links_view_alter(&$element, $items) {
584
  // If we are rendering views-related contextual links attached to the overall
585
  // page array, add a class to the list of contextual links. This will be used
586
  // by the JavaScript added in views_preprocess_html().
587
  if (!empty($element['#element']['#views_contextual_links_info']) && !empty($element['#element']['#type']) && $element['#element']['#type'] == 'page') {
588
    $element['#attributes']['class'][] = 'views-contextual-links-page';
589
  }
590
}
591

    
592
/**
593
 * Implement hook_block_info().
594
 */
595
function views_block_info() {
596
  // Try to avoid instantiating all the views just to get the blocks info.
597
  views_include('cache');
598
  $cache = views_cache_get('views_block_items', TRUE);
599
  if ($cache && is_array($cache->data)) {
600
    return $cache->data;
601
  }
602

    
603
  $items = array();
604
  $views = views_get_all_views();
605
  foreach ($views as $view) {
606
    // disabled views get nothing.
607
    if (!empty($view->disabled)) {
608
      continue;
609
    }
610

    
611
    $view->init_display();
612
    foreach ($view->display as $display_id => $display) {
613

    
614
      if (isset($display->handler) && !empty($display->handler->definition['uses hook block'])) {
615
        $result = $display->handler->execute_hook_block_list();
616
        if (is_array($result)) {
617
          $items = array_merge($items, $result);
618
        }
619
      }
620

    
621
      if (isset($display->handler) && $display->handler->get_option('exposed_block')) {
622
        $result = $display->handler->get_special_blocks();
623
        if (is_array($result)) {
624
          $items = array_merge($items, $result);
625
        }
626
      }
627
    }
628
  }
629

    
630
  // block.module has a delta length limit of 32, but our deltas can
631
  // unfortunately be longer because view names can be 32 and display IDs
632
  // can also be 32. So for very long deltas, change to md5 hashes.
633
  $hashes = array();
634

    
635
  // get the keys because we're modifying the array and we don't want to
636
  // confuse PHP too much.
637
  $keys = array_keys($items);
638
  foreach ($keys as $delta) {
639
    if (strlen($delta) >= 32) {
640
      $hash = md5($delta);
641
      $hashes[$hash] = $delta;
642
      $items[$hash] = $items[$delta];
643
      unset($items[$delta]);
644
    }
645
  }
646

    
647
  // Only save hashes if they have changed.
648
  $old_hashes = variable_get('views_block_hashes', array());
649
  if ($hashes != $old_hashes) {
650
    variable_set('views_block_hashes', $hashes);
651
  }
652
  // Save memory: Destroy those views.
653
  foreach ($views as $view) {
654
    $view->destroy();
655
  }
656

    
657
  views_cache_set('views_block_items', $items, TRUE);
658

    
659
  return $items;
660
}
661

    
662
/**
663
 * Implement hook_block_view().
664
 */
665
function views_block_view($delta) {
666
  $start = microtime(TRUE);
667
  // if this is 32, this should be an md5 hash.
668
  if (strlen($delta) == 32) {
669
    $hashes = variable_get('views_block_hashes', array());
670
    if (!empty($hashes[$delta])) {
671
      $delta = $hashes[$delta];
672
    }
673
  }
674

    
675
  // This indicates it's a special one.
676
  if (substr($delta, 0, 1) == '-') {
677
    list($nothing, $type, $name, $display_id) = explode('-', $delta);
678
    // Put the - back on.
679
    $type = '-' . $type;
680
    if ($view = views_get_view($name)) {
681
      if ($view->access($display_id)) {
682
        $view->set_display($display_id);
683
        if (isset($view->display_handler)) {
684
          $output = $view->display_handler->view_special_blocks($type);
685
          // Before returning the block output, convert it to a renderable
686
          // array with contextual links.
687
          views_add_block_contextual_links($output, $view, $display_id, 'special_block_' . $type);
688
          $view->destroy();
689
          return $output;
690
        }
691
      }
692
      $view->destroy();
693
    }
694
  }
695

    
696
  // If the delta doesn't contain valid data return nothing.
697
  $explode = explode('-', $delta);
698
  if (count($explode) != 2) {
699
    return;
700
  }
701
  list($name, $display_id) = $explode;
702
  // Load the view
703
  if ($view = views_get_view($name)) {
704
    if ($view->access($display_id)) {
705
      $output = $view->execute_display($display_id);
706
      // Before returning the block output, convert it to a renderable array
707
      // with contextual links.
708
      views_add_block_contextual_links($output, $view, $display_id);
709
      $view->destroy();
710
      return $output;
711
    }
712
    $view->destroy();
713
  }
714
}
715

    
716
/**
717
 * Converts Views block content to a renderable array with contextual links.
718
 *
719
 * @param $block
720
 *   An array representing the block, with the same structure as the return
721
 *   value of hook_block_view(). This will be modified so as to force
722
 *   $block['content'] to be a renderable array, containing the optional
723
 *   '#contextual_links' property (if there are any contextual links associated
724
 *   with the block).
725
 * @param $view
726
 *   The view that was used to generate the block content.
727
 * @param $display_id
728
 *   The ID of the display within the view that was used to generate the block
729
 *   content.
730
 * @param $block_type
731
 *   The type of the block. If it's block it's a regular views display,
732
 *   but 'special_block_-exp' exist as well.
733
 */
734
function views_add_block_contextual_links(&$block, $view, $display_id, $block_type = 'block') {
735
  // Do not add contextual links to an empty block.
736
  if (!empty($block['content'])) {
737
    // Contextual links only work on blocks whose content is a renderable
738
    // array, so if the block contains a string of already-rendered markup,
739
    // convert it to an array.
740
    if (is_string($block['content'])) {
741
      $block['content'] = array('#markup' => $block['content']);
742
    }
743
    // Add the contextual links.
744
    views_add_contextual_links($block['content'], $block_type, $view, $display_id);
745
  }
746
}
747

    
748
/**
749
 * Adds contextual links associated with a view display to a renderable array.
750
 *
751
 * This function should be called when a view is being rendered in a particular
752
 * location and you want to attach the appropriate contextual links (e.g.,
753
 * links for editing the view) to it.
754
 *
755
 * The function operates by checking the view's display plugin to see if it has
756
 * defined any contextual links that are intended to be displayed in the
757
 * requested location; if so, it attaches them. The contextual links intended
758
 * for a particular location are defined by the 'contextual links' and
759
 * 'contextual links locations' properties in hook_views_plugins() and
760
 * hook_views_plugins_alter(); as a result, these hook implementations have
761
 * full control over where and how contextual links are rendered for each
762
 * display.
763
 *
764
 * In addition to attaching the contextual links to the passed-in array (via
765
 * the standard #contextual_links property), this function also attaches
766
 * additional information via the #views_contextual_links_info property. This
767
 * stores an array whose keys are the names of each module that provided
768
 * views-related contextual links (same as the keys of the #contextual_links
769
 * array itself) and whose values are themselves arrays whose keys ('location',
770
 * 'view_name', and 'view_display_id') store the location, name of the view,
771
 * and display ID that were passed in to this function. This allows you to
772
 * access information about the contextual links and how they were generated in
773
 * a variety of contexts where you might be manipulating the renderable array
774
 * later on (for example, alter hooks which run later during the same page
775
 * request).
776
 *
777
 * @param $render_element
778
 *   The renderable array to which contextual links will be added. This array
779
 *   should be suitable for passing in to drupal_render() and will normally
780
 *   contain a representation of the view display whose contextual links are
781
 *   being requested.
782
 * @param $location
783
 *   The location in which the calling function intends to render the view and
784
 *   its contextual links. The core system supports three options for this
785
 *   parameter:
786
 *   - 'block': Used when rendering a block which contains a view. This
787
 *     retrieves any contextual links intended to be attached to the block
788
 *     itself.
789
 *   - 'page': Used when rendering the main content of a page which contains a
790
 *     view. This retrieves any contextual links intended to be attached to the
791
 *     page itself (for example, links which are displayed directly next to the
792
 *     page title).
793
 *   - 'view': Used when rendering the view itself, in any context. This
794
 *     retrieves any contextual links intended to be attached directly to the
795
 *     view.
796
 *   If you are rendering a view and its contextual links in another location,
797
 *   you can pass in a different value for this parameter. However, you will
798
 *   also need to use hook_views_plugins() or hook_views_plugins_alter() to
799
 *   declare, via the 'contextual links locations' array key, which view
800
 *   displays support having their contextual links rendered in the location
801
 *   you have defined.
802
 * @param $view
803
 *   The view whose contextual links will be added.
804
 * @param $display_id
805
 *   The ID of the display within $view whose contextual links will be added.
806
 *
807
 * @see hook_views_plugins()
808
 * @see views_block_view()
809
 * @see views_page_alter()
810
 * @see template_preprocess_views_view()
811
 */
812
function views_add_contextual_links(&$render_element, $location, $view, $display_id) {
813
  // Do not do anything if the view is configured to hide its administrative
814
  // links.
815
  if (empty($view->hide_admin_links)) {
816
    // Also do not do anything if the display plugin has not defined any
817
    // contextual links that are intended to be displayed in the requested
818
    // location.
819
    $plugin = views_fetch_plugin_data('display', $view->display[$display_id]->display_plugin);
820
    // If contextual links locations are not set, provide a sane default. (To
821
    // avoid displaying any contextual links at all, a display plugin can still
822
    // set 'contextual links locations' to, e.g., an empty array.)
823
    $plugin += array('contextual links locations' => array('view'));
824
    // On exposed_forms blocks contextual links should always be visible.
825
    $plugin['contextual links locations'][] = 'special_block_-exp';
826
    $has_links = !empty($plugin['contextual links']) && !empty($plugin['contextual links locations']);
827
    if ($has_links && in_array($location, $plugin['contextual links locations'])) {
828
      foreach ($plugin['contextual links'] as $module => $link) {
829
        $args = array();
830
        $valid = TRUE;
831
        if (!empty($link['argument properties'])) {
832
          foreach ($link['argument properties'] as $property) {
833
            // If the plugin is trying to create an invalid contextual link
834
            // (for example, "path/to/{$view->property}", where $view->property
835
            // does not exist), we cannot construct the link, so we skip it.
836
            if (!property_exists($view, $property)) {
837
              $valid = FALSE;
838
              break;
839
            }
840
            else {
841
              $args[] = $view->{$property};
842
            }
843
          }
844
        }
845
        // If the link was valid, attach information about it to the renderable
846
        // array.
847
        if ($valid) {
848
          $render_element['#contextual_links'][$module] = array($link['parent path'], $args);
849
          $render_element['#views_contextual_links_info'][$module] = array(
850
            'location' => $location,
851
            'view' => $view,
852
            'view_name' => $view->name,
853
            'view_display_id' => $display_id,
854
          );
855
        }
856
      }
857
    }
858
  }
859
}
860

    
861
/**
862
 * Returns an array of language names.
863
 *
864
 * This is a one to one copy of locale_language_list because we can't rely on enabled locale module.
865
 *
866
 * @param $field
867
 *   'name' => names in current language, localized
868
 *   'native' => native names
869
 * @param $all
870
 *   Boolean to return all languages or only enabled ones
871
 *
872
 * @see locale_language_list()
873
 */
874
function views_language_list($field = 'name', $all = FALSE) {
875
  if ($all) {
876
    $languages = language_list();
877
  }
878
  else {
879
    $languages = language_list('enabled');
880
    $languages = $languages[1];
881
  }
882
  $list = array();
883
  foreach ($languages as $language) {
884
    $list[$language->language] = ($field == 'name') ? t($language->name) : $language->$field;
885
  }
886
  return $list;
887
}
888

    
889
/**
890
 * Implements hook_flush_caches().
891
 */
892
function views_flush_caches() {
893
  return array('cache_views', 'cache_views_data');
894
}
895

    
896
/**
897
 * Implements hook_field_create_instance.
898
 */
899
function views_field_create_instance($instance) {
900
  cache_clear_all('*', 'cache_views', TRUE);
901
  cache_clear_all('*', 'cache_views_data', TRUE);
902
}
903

    
904
/**
905
 * Implements hook_field_update_instance.
906
 */
907
function views_field_update_instance($instance, $prior_instance) {
908
  cache_clear_all('*', 'cache_views', TRUE);
909
  cache_clear_all('*', 'cache_views_data', TRUE);
910
}
911

    
912
/**
913
 * Implements hook_field_delete_instance.
914
 */
915
function views_field_delete_instance($instance) {
916
  cache_clear_all('*', 'cache_views', TRUE);
917
  cache_clear_all('*', 'cache_views_data', TRUE);
918
}
919

    
920
/**
921
 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
922
 */
923
function views_invalidate_cache() {
924
  // Clear the views cache.
925
  cache_clear_all('*', 'cache_views', TRUE);
926

    
927
  // Clear the page and block cache.
928
  cache_clear_all();
929

    
930
  // Set the menu as needed to be rebuilt.
931
  variable_set('menu_rebuild_needed', TRUE);
932

    
933
  // Allow modules to respond to the Views cache being cleared.
934
  module_invoke_all('views_invalidate_cache');
935
}
936

    
937
/**
938
 * Access callback to determine if the user can import Views.
939
 *
940
 * View imports require an additional access check because they are PHP
941
 * code and PHP is more locked down than administer views.
942
 */
943
function views_import_access() {
944
  return user_access('administer views') && user_access('use PHP for settings');
945
}
946

    
947
/**
948
 * Determine if the logged in user has access to a view.
949
 *
950
 * This function should only be called from a menu hook or some other
951
 * embedded source. Each argument is the result of a call to
952
 * views_plugin_access::get_access_callback() which is then used
953
 * to determine if that display is accessible. If *any* argument
954
 * is accessible, then the view is accessible.
955
 */
956
function views_access() {
957
  $args = func_get_args();
958
  foreach ($args as $arg) {
959
    if ($arg === TRUE) {
960
      return TRUE;
961
    }
962

    
963
    if (!is_array($arg)) {
964
      continue;
965
    }
966

    
967
    list($callback, $arguments) = $arg;
968
    $arguments = $arguments ? $arguments : array();
969
    // Bring dynamic arguments to the access callback.
970
    foreach ($arguments as $key => $value) {
971
      if (is_int($value) && isset($args[$value])) {
972
        $arguments[$key] = $args[$value];
973
      }
974
    }
975
    if (function_exists($callback) && call_user_func_array($callback, $arguments)) {
976
      return TRUE;
977
    }
978
  }
979

    
980
  return FALSE;
981
}
982

    
983
/**
984
 * Access callback for the views_plugin_access_perm access plugin.
985
 *
986
 * Determine if the specified user has access to a view on the basis of
987
 * permissions. If the $account argument is omitted, the current user
988
 * is used.
989
 */
990
function views_check_perm($perm, $account = NULL) {
991
  return user_access($perm, $account) || user_access('access all views', $account);
992
}
993

    
994
/**
995
 * Access callback for the views_plugin_access_role access plugin.
996

    
997
 * Determine if the specified user has access to a view on the basis of any of
998
 * the requested roles. If the $account argument is omitted, the current user
999
 * is used.
1000
 */
1001
function views_check_roles($rids, $account = NULL) {
1002
  global $user;
1003
  $account = isset($account) ? $account : $user;
1004
  $roles = array_keys($account->roles);
1005
  $roles[] = $account->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
1006
  return user_access('access all views', $account) || array_intersect(array_filter($rids), $roles);
1007
}
1008
// ------------------------------------------------------------------
1009
// Functions to help identify views that are running or ran
1010

    
1011
/**
1012
 * Set the current 'page view' that is being displayed so that it is easy
1013
 * for other modules or the theme to identify.
1014
 */
1015
function &views_set_page_view($view = NULL) {
1016
  static $cache = NULL;
1017
  if (isset($view)) {
1018
    $cache = $view;
1019
  }
1020

    
1021
  return $cache;
1022
}
1023

    
1024
/**
1025
 * Find out what, if any, page view is currently in use. Please note that
1026
 * this returns a reference, so be careful! You can unintentionally modify the
1027
 * $view object.
1028
 *
1029
 * @return view
1030
 *   A fully formed, empty $view object.
1031
 */
1032
function &views_get_page_view() {
1033
  return views_set_page_view();
1034
}
1035

    
1036
/**
1037
 * Set the current 'current view' that is being built/rendered so that it is
1038
 * easy for other modules or items in drupal_eval to identify
1039
 *
1040
 * @return view
1041
 */
1042
function &views_set_current_view($view = NULL) {
1043
  static $cache = NULL;
1044
  if (isset($view)) {
1045
    $cache = $view;
1046
  }
1047

    
1048
  return $cache;
1049
}
1050

    
1051
/**
1052
 * Find out what, if any, current view is currently in use. Please note that
1053
 * this returns a reference, so be careful! You can unintentionally modify the
1054
 * $view object.
1055
 *
1056
 * @return view
1057
 */
1058
function &views_get_current_view() {
1059
  return views_set_current_view();
1060
}
1061

    
1062
// ------------------------------------------------------------------
1063
// Include file helpers
1064

    
1065
/**
1066
 * Include views .inc files as necessary.
1067
 */
1068
function views_include($file) {
1069
  ctools_include($file, 'views');
1070
}
1071

    
1072
/**
1073
 * Load views files on behalf of modules.
1074
 */
1075
function views_module_include($api, $reset = FALSE) {
1076
  if ($reset) {
1077
    $cache = &drupal_static('ctools_plugin_api_info');
1078
    if (isset($cache['views']['views'])) {
1079
      unset($cache['views']['views']);
1080
    }
1081
  }
1082
  ctools_include('plugins');
1083
  return ctools_plugin_api_include('views', $api, views_api_minimum_version(), views_api_version());
1084
}
1085

    
1086
/**
1087
 * Get a list of modules that support the current views API.
1088
 */
1089
function views_get_module_apis($api = 'views', $reset = FALSE) {
1090
  if ($reset) {
1091
    $cache = &drupal_static('ctools_plugin_api_info');
1092
    if (isset($cache['views']['views'])) {
1093
      unset($cache['views']['views']);
1094
    }
1095
  }
1096
  ctools_include('plugins');
1097
  return ctools_plugin_api_info('views', $api, views_api_minimum_version(), views_api_version());
1098
}
1099

    
1100
/**
1101
 * Include views .css files.
1102
 */
1103
function views_add_css($file) {
1104
  // We set preprocess to FALSE because we are adding the files conditionally,
1105
  // and we don't want to generate duplicate cache files.
1106
  // TODO: at some point investigate adding some files unconditionally and
1107
  // allowing preprocess.
1108
  drupal_add_css(drupal_get_path('module', 'views') . "/css/$file.css", array('preprocess' => FALSE));
1109
}
1110

    
1111
/**
1112
 * Include views .js files.
1113
 */
1114
function views_add_js($file) {
1115
  // If javascript has been disabled by the user, never add js files.
1116
  if (variable_get('views_no_javascript', FALSE)) {
1117
    return;
1118
  }
1119
  static $base = TRUE, $ajax = TRUE;
1120
  if ($base) {
1121
    drupal_add_js(drupal_get_path('module', 'views') . "/js/base.js");
1122
    $base = FALSE;
1123
  }
1124
  if ($ajax && in_array($file, array('ajax', 'ajax_view'))) {
1125
    drupal_add_library('system', 'drupal.ajax');
1126
    drupal_add_library('system', 'jquery.form');
1127
    $ajax = FALSE;
1128
  }
1129
  ctools_add_js($file, 'views');
1130
}
1131

    
1132
/**
1133
 * Load views files on behalf of modules.
1134
 */
1135
function views_include_handlers($reset = FALSE) {
1136
  static $finished = FALSE;
1137
  // Ensure this only gets run once.
1138
  if ($finished && !$reset) {
1139
    return;
1140
  }
1141

    
1142
  views_include('base');
1143
  views_include('handlers');
1144
  views_include('cache');
1145
  views_include('plugins');
1146
  views_module_include('views', $reset);
1147
  $finished = TRUE;
1148
}
1149

    
1150
// -----------------------------------------------------------------------
1151
// Views handler functions
1152

    
1153
/**
1154
 * Fetch a handler from the data cache.
1155
 *
1156
 * @param $table
1157
 *   The name of the table this handler is from.
1158
 * @param $field
1159
 *   The name of the field this handler is from.
1160
 * @param $key
1161
 *   The type of handler. i.e, sort, field, argument, filter, relationship
1162
 * @param $override
1163
 *   Override the actual handler object with this class. Used for
1164
 *   aggregation when the handler is redirected to the aggregation
1165
 *   handler.
1166
 *
1167
 * @return views_handler
1168
 *   An instance of a handler object. May be views_handler_broken.
1169
 */
1170
function views_get_handler($table, $field, $key, $override = NULL) {
1171
  static $recursion_protection = array();
1172

    
1173
  $data = views_fetch_data($table, FALSE);
1174
  $handler = NULL;
1175
  views_include('handlers');
1176

    
1177
  // Support old views_data entries conversion.
1178

    
1179
  // Support conversion on table level.
1180
  if (isset($data['moved to'])) {
1181
    $moved = array($data['moved to'], $field);
1182
  }
1183
  // Support conversion on datafield level.
1184
  if (isset($data[$field]['moved to'])) {
1185
    $moved = $data[$field]['moved to'];
1186
  }
1187
  // Support conversion on handler level.
1188
  if (isset($data[$field][$key]['moved to'])) {
1189
    $moved = $data[$field][$key]['moved to'];
1190
  }
1191

    
1192
  if (isset($data[$field][$key]) || !empty($moved)) {
1193
    if (!empty($moved)) {
1194
      list($moved_table, $moved_field) = $moved;
1195
      if (!empty($recursion_protection[$moved_table][$moved_field])) {
1196
        // recursion detected!
1197
        return NULL;
1198
      }
1199

    
1200
      $recursion_protection[$moved_table][$moved_field] = TRUE;
1201
      $handler = views_get_handler($moved_table, $moved_field, $key, $override);
1202
      $recursion_protection = array();
1203
      if ($handler) {
1204
        // store these values so we know what we were originally called.
1205
        $handler->original_table = $table;
1206
        $handler->original_field = $field;
1207
        if (empty($handler->actual_table)) {
1208
          $handler->actual_table = $moved_table;
1209
          $handler->actual_field = $moved_field;
1210
        }
1211
      }
1212
      return $handler;
1213
    }
1214

    
1215
    // Set up a default handler:
1216
    if (empty($data[$field][$key]['handler'])) {
1217
      $data[$field][$key]['handler'] = 'views_handler_' . $key;
1218
    }
1219

    
1220
    if ($override) {
1221
      $data[$field][$key]['override handler'] = $override;
1222
    }
1223

    
1224
    $handler = _views_prepare_handler($data[$field][$key], $data, $field, $key);
1225
  }
1226

    
1227
  if ($handler) {
1228
    return $handler;
1229
  }
1230

    
1231
  // DEBUG -- identify missing handlers
1232
  vpr("Missing handler: @table @field @key", array('@table' => $table, '@field' => $field, '@key' => $key));
1233
  $broken = array(
1234
    'title' => t('Broken handler @table.@field', array('@table' => $table, '@field' => $field)),
1235
    'handler' => 'views_handler_' . $key . '_broken',
1236
    'table' => $table,
1237
    'field' => $field,
1238
  );
1239
  return _views_create_handler($broken, 'handler', $key);
1240
}
1241

    
1242
/**
1243
 * Fetch Views' data from the cache
1244
 */
1245
function views_fetch_data($table = NULL, $move = TRUE, $reset = FALSE) {
1246
  views_include('cache');
1247
  return _views_fetch_data($table, $move, $reset);
1248
}
1249

    
1250
// -----------------------------------------------------------------------
1251
// Views plugin functions
1252

    
1253
/**
1254
 * Fetch the plugin data from cache.
1255
 */
1256
function views_fetch_plugin_data($type = NULL, $plugin = NULL, $reset = FALSE) {
1257
  views_include('cache');
1258
  return _views_fetch_plugin_data($type, $plugin, $reset);
1259
}
1260

    
1261
/**
1262
 * Fetch a list of all base tables available
1263
 *
1264
 * @param $type
1265
 *   Either 'display', 'style' or 'row'
1266
 * @param $key
1267
 *   For style plugins, this is an optional type to restrict to. May be 'normal',
1268
 *   'summary', 'feed' or others based on the neds of the display.
1269
 * @param $base
1270
 *   An array of possible base tables.
1271
 *
1272
 * @return
1273
 *   A keyed array of in the form of 'base_table' => 'Description'.
1274
 */
1275
function views_fetch_plugin_names($type, $key = NULL, $base = array()) {
1276
  $data = views_fetch_plugin_data();
1277

    
1278
  $plugins[$type] = array();
1279

    
1280
  foreach ($data[$type] as $id => $plugin) {
1281
    // Skip plugins that don't conform to our key.
1282
    if ($key && (empty($plugin['type']) || $plugin['type'] != $key)) {
1283
      continue;
1284
    }
1285
    if (empty($plugin['no ui']) && (empty($base) || empty($plugin['base']) || array_intersect($base, $plugin['base']))) {
1286
      $plugins[$type][$id] = $plugin['title'];
1287
    }
1288
  }
1289

    
1290
  if (!empty($plugins[$type])) {
1291
    asort($plugins[$type]);
1292
    return $plugins[$type];
1293
  }
1294
  // fall-through
1295
  return array();
1296
}
1297

    
1298
/**
1299
 * Get a handler for a plugin
1300
 *
1301
 * @return views_plugin
1302
 *
1303
 * The created plugin object.
1304
 */
1305
function views_get_plugin($type, $plugin, $reset = FALSE) {
1306
  views_include('handlers');
1307
  $definition = views_fetch_plugin_data($type, $plugin, $reset);
1308
  if (!empty($definition)) {
1309
    return _views_create_handler($definition, $type);
1310
  }
1311
}
1312

    
1313
/**
1314
 * Load the current enabled localization plugin.
1315
 *
1316
 * @return The name of the localization plugin.
1317
 */
1318
function views_get_localization_plugin() {
1319
  $plugin = variable_get('views_localization_plugin', '');
1320
  // Provide sane default values for the localization plugin.
1321
  if (empty($plugin)) {
1322
    if (module_exists('locale')) {
1323
      $plugin = 'core';
1324
    }
1325
    else {
1326
      $plugin = 'none';
1327
    }
1328
  }
1329

    
1330
  return $plugin;
1331
}
1332

    
1333
// -----------------------------------------------------------------------
1334
// Views database functions
1335

    
1336
/**
1337
 * Get all view templates.
1338
 *
1339
 * Templates are special in-code views that are never active, but exist only
1340
 * to be cloned into real views as though they were templates.
1341
 */
1342
function views_get_all_templates() {
1343
  $templates = array();
1344
  $modules = views_module_include('views_template');
1345

    
1346
  foreach ($modules as $module => $info) {
1347
    $function = $module . '_views_templates';
1348
    if (function_exists($function)) {
1349
      $new = $function();
1350
      if ($new && is_array($new)) {
1351
        $templates = array_merge($new, $templates);
1352
      }
1353
    }
1354
  }
1355

    
1356
  return $templates;
1357
}
1358

    
1359
/**
1360
 * Create an empty view to work with.
1361
 *
1362
 * @return view
1363
 *   A fully formed, empty $view object. This object must be populated before
1364
 *   it can be successfully saved.
1365
 */
1366
function views_new_view() {
1367
  views_include('view');
1368
  $view = new view();
1369
  $view->vid = 'new';
1370
  $view->add_display('default');
1371

    
1372
  return $view;
1373
}
1374

    
1375
/**
1376
 * Return a list of all views and display IDs that have a particular
1377
 * setting in their display's plugin settings.
1378
 *
1379
 * @return
1380
 * @code
1381
 * array(
1382
 *   array($view, $display_id),
1383
 *   array($view, $display_id),
1384
 * );
1385
 * @endcode
1386
 */
1387
function views_get_applicable_views($type) {
1388
  // @todo: Use a smarter flagging system so that we don't have to
1389
  // load every view for this.
1390
  $result = array();
1391
  $views = views_get_all_views();
1392

    
1393
  foreach ($views as $view) {
1394
    // Skip disabled views.
1395
    if (!empty($view->disabled)) {
1396
      continue;
1397
    }
1398

    
1399
    if (empty($view->display)) {
1400
      // Skip this view as it is broken.
1401
      vsm(t("Skipping broken view @view", array('@view' => $view->name)));
1402
      continue;
1403
    }
1404

    
1405
    // Loop on array keys because something seems to muck with $view->display
1406
    // a bit in PHP4.
1407
    foreach (array_keys($view->display) as $id) {
1408
      $plugin = views_fetch_plugin_data('display', $view->display[$id]->display_plugin);
1409
      if (!empty($plugin[$type])) {
1410
        // This view uses hook menu. Clone it so that different handlers
1411
        // don't trip over each other, and add it to the list.
1412
        $v = $view->clone_view();
1413
        if ($v->set_display($id) && $v->display_handler->get_option('enabled')) {
1414
          $result[] = array($v, $id);
1415
        }
1416
        // In PHP 4.4.7 and presumably earlier, if we do not unset $v
1417
        // here, we will find that it actually overwrites references
1418
        // possibly due to shallow copying issues.
1419
        unset($v);
1420
      }
1421
    }
1422
  }
1423
  return $result;
1424
}
1425

    
1426
/**
1427
 * Return an array of all views as fully loaded $view objects.
1428
 *
1429
 * @param $reset
1430
 *   If TRUE, reset the static cache forcing views to be reloaded.
1431
 */
1432
function views_get_all_views($reset = FALSE) {
1433
  ctools_include('export');
1434
  return ctools_export_crud_load_all('views_view', $reset);
1435
}
1436

    
1437
/**
1438
 * Returns an array of all enabled views, as fully loaded $view objects.
1439
 */
1440
function views_get_enabled_views() {
1441
  $views = views_get_all_views();
1442
  return array_filter($views, 'views_view_is_enabled');
1443
}
1444

    
1445
/**
1446
 * Returns an array of all disabled views, as fully loaded $view objects.
1447
 */
1448
function views_get_disabled_views() {
1449
  $views = views_get_all_views();
1450
  return array_filter($views, 'views_view_is_disabled');
1451
}
1452

    
1453
/**
1454
 * Return an array of view as options array, that can be used by select,
1455
 * checkboxes and radios as #options.
1456
 *
1457
 * @param bool $views_only
1458
 *  If TRUE, only return views, not displays.
1459
 * @param string $filter
1460
 *  Filters the views on status. Can either be 'all' (default), 'enabled' or
1461
 *  'disabled'
1462
 * @param  mixed $exclude_view
1463
 *  view or current display to exclude
1464
 *  either a
1465
 *  - views object (containing $exclude_view->name and $exclude_view->current_display)
1466
 *  - views name as string:  e.g. my_view
1467
 *  - views name and display id (separated by ':'): e.g. my_view:default
1468
 * @param bool $optgroup
1469
 *  If TRUE, returns an array with optgroups for each view (will be ignored for
1470
 *  $views_only = TRUE). Can be used by select
1471
 * @param bool $sort
1472
 *  If TRUE, the list of views is sorted ascending.
1473
 *
1474
 * @return array
1475
 *  an associative array for use in select.
1476
 *  - key: view name and display id separated by ':', or the view name only
1477
 */
1478
function views_get_views_as_options($views_only = FALSE, $filter = 'all', $exclude_view = NULL, $optgroup = FALSE, $sort = FALSE) {
1479

    
1480
  // Filter the big views array.
1481
  switch ($filter) {
1482
    case 'all':
1483
    case 'disabled':
1484
    case 'enabled':
1485
      $func = "views_get_{$filter}_views";
1486
      $views = $func();
1487
      break;
1488
    default:
1489
      return array();
1490
  }
1491

    
1492
  // Prepare exclude view strings for comparison.
1493
  if (empty($exclude_view)) {
1494
    $exclude_view_name = '';
1495
    $exclude_view_display = '';
1496
  }
1497
  elseif (is_object($exclude_view)) {
1498
    $exclude_view_name = $exclude_view->name;
1499
    $exclude_view_display = $exclude_view->current_display;
1500
  }
1501
  else {
1502
    list($exclude_view_name, $exclude_view_display) = explode(':', $exclude_view);
1503
  }
1504

    
1505
  $options = array();
1506
  foreach ($views as $view) {
1507
    // Return only views.
1508
    if ($views_only && $view->name != $exclude_view_name) {
1509
      $options[$view->name] = $view->get_human_name();
1510
    }
1511
    // Return views with display ids.
1512
    else {
1513
      foreach ($view->display as $display_id => $display) {
1514
        if (!($view->name == $exclude_view_name && $display_id == $exclude_view_display)) {
1515
          if ($optgroup) {
1516
            $options[$view->name][$view->name . ':' . $display->id] = t('@view : @display', array('@view' => $view->name, '@display' => $display->id));
1517
          }
1518
          else {
1519
            $options[$view->name . ':' . $display->id] = t('View: @view - Display: @display', array('@view' => $view->name, '@display' => $display->id));
1520
          }
1521
        }
1522
      }
1523
    }
1524
  }
1525
  if ($sort) {
1526
    ksort($options);
1527
  }
1528
  return $options;
1529
}
1530

    
1531
/**
1532
 * Returns TRUE if a view is enabled, FALSE otherwise.
1533
 */
1534
function views_view_is_enabled($view) {
1535
  return empty($view->disabled);
1536
}
1537

    
1538
/**
1539
 * Returns TRUE if a view is disabled, FALSE otherwise.
1540
 */
1541
function views_view_is_disabled($view) {
1542
  return !empty($view->disabled);
1543
}
1544

    
1545
/**
1546
 * Get a view from the database or from default views.
1547
 *
1548
 * This function is just a static wrapper around views::load(). This function
1549
 * isn't called 'views_load()' primarily because it might get a view
1550
 * from the default views which aren't technically loaded from the database.
1551
 *
1552
 * @param $name
1553
 *   The name of the view.
1554
 * @param $reset
1555
 *   If TRUE, reset this entry in the load cache.
1556
 * @return view
1557
 *   A reference to the $view object. Use $reset if you're sure you want
1558
 *   a fresh one.
1559
 */
1560
function views_get_view($name, $reset = FALSE) {
1561
  if ($reset) {
1562
    $cache = &drupal_static('ctools_export_load_object');
1563
    if (isset($cache['views_view'][$name])) {
1564
      unset($cache['views_view'][$name]);
1565
    }
1566
  }
1567

    
1568
  ctools_include('export');
1569
  $view = ctools_export_crud_load('views_view', $name);
1570
  if ($view) {
1571
    $view->update();
1572
    return $view->clone_view();
1573
  }
1574
}
1575

    
1576
/**
1577
 * Find the real location of a table.
1578
 *
1579
 * If a table has moved, find the new name of the table so that we can
1580
 * change its name directly in options where necessary.
1581
 */
1582
function views_move_table($table) {
1583
  $data = views_fetch_data($table, FALSE);
1584
  if (isset($data['moved to'])) {
1585
    $table = $data['moved to'];
1586
  }
1587

    
1588
  return $table;
1589
}
1590

    
1591
/**
1592
 * Export callback to load the view subrecords, which are the displays.
1593
 */
1594
function views_load_display_records(&$views) {
1595
  // Get vids from the views.
1596
  $names = array();
1597
  foreach ($views as $view) {
1598
    if (empty($view->display)) {
1599
      $names[$view->vid] = $view->name;
1600
    }
1601
  }
1602

    
1603
  if (empty($names)) {
1604
    return;
1605
  }
1606

    
1607
  foreach (view::db_objects() as $key) {
1608
    $object_name = "views_$key";
1609
    $result = db_query("SELECT * FROM {{$object_name}} WHERE vid IN (:vids) ORDER BY vid, position",
1610
      array(':vids' => array_keys($names)));
1611

    
1612
    foreach ($result as $data) {
1613
      $object = new $object_name(FALSE);
1614
      $object->load_row($data);
1615

    
1616
      // Because it can get complicated with this much indirection,
1617
      // make a shortcut reference.
1618
      $location = &$views[$names[$object->vid]]->$key;
1619

    
1620
      // If we have a basic id field, load the item onto the view based on
1621
      // this ID, otherwise push it on.
1622
      if (!empty($object->id)) {
1623
        $location[$object->id] = $object;
1624
      }
1625
      else {
1626
        $location[] = $object;
1627
      }
1628
    }
1629
  }
1630
}
1631

    
1632
/**
1633
 * Export CRUD callback to save a view.
1634
 */
1635
function views_save_view(&$view) {
1636
  return $view->save();
1637
}
1638

    
1639
/**
1640
 * Export CRUD callback to delete a view.
1641
 */
1642
function views_delete_view(&$view) {
1643
  return $view->delete(TRUE);
1644
}
1645

    
1646
/**
1647
 * Export CRUD callback to export a view.
1648
 */
1649
function views_export_view(&$view, $indent = '') {
1650
  return $view->export($indent);
1651
}
1652

    
1653
/**
1654
 * Export callback to change view status.
1655
 */
1656
function views_export_status($view, $status) {
1657
  ctools_export_set_object_status($view, $status);
1658
  views_invalidate_cache();
1659
}
1660

    
1661
// ------------------------------------------------------------------
1662
// Views debug helper functions
1663

    
1664
/**
1665
 * Provide debug output for Views.
1666
 *
1667
 * This relies on devel.module
1668
 * or on the debug() function if you use a simpletest.
1669
 *
1670
 * @param $message
1671
 *   The message/variable which should be debugged.
1672
 *   This either could be
1673
 *     * an array/object which is converted to pretty output
1674
 *     * a translation source string which is used together with the parameter placeholders.
1675
 *
1676
 * @param $placeholder
1677
 *   The placeholders which are used for the translation source string.
1678
 */
1679
function views_debug($message, $placeholders = array()) {
1680
  if (!is_string($message)) {
1681
    $output = '<pre>' . var_export($message, TRUE) . '</pre>';
1682
  }
1683
  if (module_exists('devel') && variable_get('views_devel_output', FALSE) && user_access('access devel information')) {
1684
    $devel_region = variable_get('views_devel_region', 'footer');
1685
    if ($devel_region == 'watchdog') {
1686
      $output = $message;
1687
      watchdog('views_logging', $output, $placeholders);
1688
    }
1689
    else if ($devel_region == 'drupal_debug') {
1690
      $output = empty($output) ? t($message, $placeholders) : $output;
1691
      dd($output);
1692
    }
1693
    else {
1694
      $output = empty($output) ? t($message, $placeholders) : $output;
1695
      dpm($output);
1696
    }
1697
  }
1698
  elseif (isset($GLOBALS['drupal_test_info'])) {
1699
    $output = empty($output) ? t($message, $placeholders) : $output;
1700
    debug($output);
1701
  }
1702
}
1703

    
1704
/**
1705
 * Shortcut to views_debug()
1706
 */
1707
function vpr($message, $placeholders = array()) {
1708
  views_debug($message, $placeholders);
1709
}
1710

    
1711
/**
1712
 * Debug messages
1713
 */
1714
function vsm($message) {
1715
  if (module_exists('devel')) {
1716
    dpm($message);
1717
  }
1718
}
1719

    
1720
function views_trace() {
1721
  $message = '';
1722
  foreach (debug_backtrace() as $item) {
1723
    if (!empty($item['file']) && !in_array($item['function'], array('vsm_trace', 'vpr_trace', 'views_trace'))) {
1724
      $message .= basename($item['file']) . ": " . (empty($item['class']) ? '' : ($item['class'] . '->')) . "$item[function] line $item[line]" . "\n";
1725
    }
1726
  }
1727
  return $message;
1728
}
1729

    
1730
function vsm_trace() {
1731
  vsm(views_trace());
1732
}
1733

    
1734
function vpr_trace() {
1735
  dpr(views_trace());
1736
}
1737

    
1738
// ------------------------------------------------------------------
1739
// Views form (View with form elements)
1740

    
1741
/**
1742
 * Returns TRUE if the passed-in view contains handlers with views form
1743
 * implementations, FALSE otherwise.
1744
 */
1745
function views_view_has_form_elements($view) {
1746
  foreach ($view->field as $field) {
1747
    if (property_exists($field, 'views_form_callback') || method_exists($field, 'views_form')) {
1748
      return TRUE;
1749
    }
1750
  }
1751
  $area_handlers = array_merge(array_values($view->header), array_values($view->footer));
1752
  $empty = empty($view->result);
1753
  foreach ($area_handlers as $area) {
1754
    if (method_exists($area, 'views_form') && !$area->views_form_empty($empty)) {
1755
      return TRUE;
1756
    }
1757
  }
1758
  return FALSE;
1759
}
1760

    
1761
/**
1762
 * This is the entry function. Just gets the form for the current step.
1763
 * The form is always assumed to be multistep, even if it has only one
1764
 * step (the default 'views_form_views_form' step). That way it is actually
1765
 * possible for modules to have a multistep form if they need to.
1766
 */
1767
function views_form($form, &$form_state, $view, $output) {
1768
  $form_state['step'] = isset($form_state['step']) ? $form_state['step'] : 'views_form_views_form';
1769
  // Cache the built form to prevent it from being rebuilt prior to validation
1770
  // and submission, which could lead to data being processed incorrectly,
1771
  // because the views rows (and thus, the form elements as well) have changed
1772
  // in the meantime.
1773
  $form_state['cache'] = TRUE;
1774

    
1775
  $form = array();
1776
  $query = drupal_get_query_parameters($_GET, array('q'));
1777
  $form['#action'] = url($view->get_url(), array('query' => $query));
1778
  // Tell the preprocessor whether it should hide the header, footer, pager...
1779
  $form['show_view_elements'] = array(
1780
    '#type' => 'value',
1781
    '#value' => ($form_state['step'] == 'views_form_views_form') ? TRUE : FALSE,
1782
  );
1783

    
1784
  $form = $form_state['step']($form, $form_state, $view, $output);
1785
  return $form;
1786
}
1787

    
1788
/**
1789
 * Callback for the main step of a Views form.
1790
 * Invoked by views_form().
1791
 */
1792
function views_form_views_form($form, &$form_state, $view, $output) {
1793
  $form['#prefix'] = '<div class="views-form">';
1794
  $form['#suffix'] = '</div>';
1795
  $form['#theme'] = 'views_form_views_form';
1796
  $form['#validate'][] = 'views_form_views_form_validate';
1797
  $form['#submit'][] = 'views_form_views_form_submit';
1798

    
1799
  // Add the output markup to the form array so that it's included when the form
1800
  // array is passed to the theme function.
1801
  $form['output'] = array(
1802
    '#type' => 'markup',
1803
    '#markup' => $output,
1804
    // This way any additional form elements will go before the view
1805
    // (below the exposed widgets).
1806
    '#weight' => 50,
1807
  );
1808

    
1809
  $substitutions = array();
1810
  foreach ($view->field as $field_name => $field) {
1811
    $form_element_name = $field_name;
1812
    if (method_exists($field, 'form_element_name')) {
1813
      $form_element_name = $field->form_element_name();
1814
    }
1815
    $method_form_element_row_id_exists = FALSE;
1816
    if (method_exists($field, 'form_element_row_id')) {
1817
      $method_form_element_row_id_exists = TRUE;
1818
    }
1819

    
1820
    // If the field provides a views form, allow it to modify the $form array.
1821
    $has_form = FALSE;
1822
    if (property_exists($field, 'views_form_callback')) {
1823
      $callback = $field->views_form_callback;
1824
      $callback($view, $field, $form, $form_state);
1825
      $has_form = TRUE;
1826
    }
1827
    elseif (method_exists($field, 'views_form')) {
1828
      $field->views_form($form, $form_state);
1829
      $has_form = TRUE;
1830
    }
1831

    
1832
    // Build the substitutions array for use in the theme function.
1833
    if ($has_form) {
1834
      foreach ($view->result as $row_id => $row) {
1835
        if ($method_form_element_row_id_exists) {
1836
          $form_element_row_id = $field->form_element_row_id($row_id);
1837
        }
1838
        else {
1839
          $form_element_row_id = $row_id;
1840
        }
1841

    
1842
        $substitutions[] = array(
1843
          'placeholder' => '<!--form-item-' . $form_element_name . '--' . $form_element_row_id . '-->',
1844
          'field_name' => $form_element_name,
1845
          'row_id' => $form_element_row_id,
1846
        );
1847
      }
1848
    }
1849
  }
1850

    
1851
  // Give the area handlers a chance to extend the form.
1852
  $area_handlers = array_merge(array_values($view->header), array_values($view->footer));
1853
  $empty = empty($view->result);
1854
  foreach ($area_handlers as $area) {
1855
    if (method_exists($area, 'views_form') && !$area->views_form_empty($empty)) {
1856
      $area->views_form($form, $form_state);
1857
    }
1858
  }
1859

    
1860
  $form['#substitutions'] = array(
1861
    '#type' => 'value',
1862
    '#value' => $substitutions,
1863
  );
1864
  $form['actions'] = array(
1865
    '#type' => 'container',
1866
    '#attributes' => array('class' => array('form-actions')),
1867
    '#weight' => 100,
1868
  );
1869
  $form['actions']['submit'] = array(
1870
    '#type' => 'submit',
1871
    '#value' => t('Save'),
1872
  );
1873

    
1874
  return $form;
1875
}
1876

    
1877
/**
1878
 * Validate handler for the first step of the views form.
1879
 * Calls any existing views_form_validate functions located
1880
 * on the views fields.
1881
 */
1882
function views_form_views_form_validate($form, &$form_state) {
1883
  $view = $form_state['build_info']['args'][0];
1884

    
1885
  // Call the validation method on every field handler that has it.
1886
  foreach ($view->field as $field_name => $field) {
1887
    if (method_exists($field, 'views_form_validate')) {
1888
      $field->views_form_validate($form, $form_state);
1889
    }
1890
  }
1891

    
1892
  // Call the validate method on every area handler that has it.
1893
  foreach (array('header', 'footer') as $area) {
1894
    foreach ($view->{$area} as $area_name => $area_handler) {
1895
      if (method_exists($area_handler, 'views_form_validate')) {
1896
        $area_handler->views_form_validate($form, $form_state);
1897
      }
1898
    }
1899
  }
1900
}
1901

    
1902
/**
1903
 * Submit handler for the first step of the views form.
1904
 * Calls any existing views_form_submit functions located
1905
 * on the views fields.
1906
 */
1907
function views_form_views_form_submit($form, &$form_state) {
1908
  $view = $form_state['build_info']['args'][0];
1909

    
1910
  // Call the submit method on every field handler that has it.
1911
  foreach ($view->field as $field_name => $field) {
1912
    if (method_exists($field, 'views_form_submit')) {
1913
      $field->views_form_submit($form, $form_state);
1914
    }
1915
  }
1916

    
1917
  // Call the submit method on every area handler that has it.
1918
  foreach (array('header', 'footer') as $area) {
1919
    foreach ($view->{$area} as $area_name => $area_handler) {
1920
      if (method_exists($area_handler, 'views_form_submit')) {
1921
        $area_handler->views_form_submit($form, $form_state);
1922
      }
1923
    }
1924
  }
1925
}
1926

    
1927
// ------------------------------------------------------------------
1928
// Exposed widgets form
1929

    
1930
/**
1931
 * Form builder for the exposed widgets form.
1932
 *
1933
 * Be sure that $view and $display are references.
1934
 */
1935
function views_exposed_form($form, &$form_state) {
1936
  // Don't show the form when batch operations are in progress.
1937
  if ($batch = batch_get() && isset($batch['current_set'])) {
1938
    return array(
1939
      // Set the theme callback to be nothing to avoid errors in template_preprocess_views_exposed_form().
1940
      '#theme' => '',
1941
    );
1942
  }
1943

    
1944
  // Make sure that we validate because this form might be submitted
1945
  // multiple times per page.
1946
  $form_state['must_validate'] = TRUE;
1947
  $view = &$form_state['view'];
1948
  $display = &$form_state['display'];
1949

    
1950
  $form_state['input'] = $view->get_exposed_input();
1951

    
1952
  // Let form plugins know this is for exposed widgets.
1953
  $form_state['exposed'] = TRUE;
1954
  // Check if the form was already created
1955
  if ($cache = views_exposed_form_cache($view->name, $view->current_display)) {
1956
    return $cache;
1957
  }
1958

    
1959
  $form['#info'] = array();
1960

    
1961
  if (!variable_get('clean_url', FALSE)) {
1962
    $form['q'] = array(
1963
      '#type' => 'hidden',
1964
      '#value' => $view->get_url(),
1965
    );
1966
  }
1967

    
1968
  // Go through each handler and let it generate its exposed widget.
1969
  foreach ($view->display_handler->handlers as $type => $value) {
1970
    foreach ($view->$type as $id => $handler) {
1971
      if ($handler->can_expose() && $handler->is_exposed()) {
1972
        // Grouped exposed filters have their own forms.
1973
        // Instead of render the standard exposed form, a new Select or
1974
        // Radio form field is rendered with the available groups.
1975
        // When an user choose an option the selected value is split
1976
        // into the operator and value that the item represents.
1977
        if ($handler->is_a_group()) {
1978
          $handler->group_form($form, $form_state);
1979
          $id = $handler->options['group_info']['identifier'];
1980
        }
1981
        else {
1982
          $handler->exposed_form($form, $form_state);
1983
        }
1984
        if ($info = $handler->exposed_info()) {
1985
          $form['#info']["$type-$id"] = $info;
1986
        }
1987
      }
1988
    }
1989
  }
1990

    
1991
  $form['submit'] = array(
1992
    '#name' => '', // prevent from showing up in $_GET.
1993
    '#type' => 'submit',
1994
    '#value' => t('Apply'),
1995
    '#id' => drupal_html_id('edit-submit-' . $view->name),
1996
  );
1997

    
1998
  $form['#action'] = url($view->display_handler->get_url());
1999
  $form['#theme'] = views_theme_functions('views_exposed_form', $view, $display);
2000
  $form['#id'] = drupal_clean_css_identifier('views_exposed_form-' . check_plain($view->name) . '-' . check_plain($display->id));
2001
//  $form['#attributes']['class'] = array('views-exposed-form');
2002

    
2003
  // If using AJAX, we need the form plugin.
2004
  if ($view->use_ajax) {
2005
    drupal_add_library('system', 'jquery.form');
2006
  }
2007
  ctools_include('dependent');
2008

    
2009
  $exposed_form_plugin = $form_state['exposed_form_plugin'];
2010
  $exposed_form_plugin->exposed_form_alter($form, $form_state);
2011

    
2012
  // Save the form
2013
  views_exposed_form_cache($view->name, $view->current_display, $form);
2014

    
2015
  return $form;
2016
}
2017

    
2018
/**
2019
 * Implement hook_form_alter for the exposed form.
2020
 *
2021
 * Since the exposed form is a GET form, we don't want it to send a wide
2022
 * variety of information.
2023
 */
2024
function views_form_views_exposed_form_alter(&$form, &$form_state) {
2025
  $form['form_build_id']['#access'] = FALSE;
2026
  $form['form_token']['#access'] = FALSE;
2027
  $form['form_id']['#access'] = FALSE;
2028
}
2029

    
2030
/**
2031
 * Validate handler for exposed filters
2032
 */
2033
function views_exposed_form_validate(&$form, &$form_state) {
2034
  foreach (array('field', 'filter') as $type) {
2035
    $handlers = &$form_state['view']->$type;
2036
    foreach ($handlers as $key => $handler) {
2037
      $handlers[$key]->exposed_validate($form, $form_state);
2038
    }
2039
  }
2040
  $exposed_form_plugin = $form_state['exposed_form_plugin'];
2041
  $exposed_form_plugin->exposed_form_validate($form, $form_state);
2042
}
2043

    
2044
/**
2045
 * Submit handler for exposed filters
2046
 */
2047
function views_exposed_form_submit(&$form, &$form_state) {
2048
  foreach (array('field', 'filter') as $type) {
2049
    $handlers = &$form_state['view']->$type;
2050
    foreach ($handlers as $key => $info) {
2051
      $handlers[$key]->exposed_submit($form, $form_state);
2052
    }
2053
  }
2054
  $form_state['view']->exposed_data = $form_state['values'];
2055
  $form_state['view']->exposed_raw_input = array();
2056

    
2057

    
2058
  $exclude = array('q', 'submit', 'form_build_id', 'form_id', 'form_token', 'exposed_form_plugin', '', 'reset');
2059
  $exposed_form_plugin = $form_state['exposed_form_plugin'];
2060
  $exposed_form_plugin->exposed_form_submit($form, $form_state, $exclude);
2061

    
2062
  foreach ($form_state['values'] as $key => $value) {
2063
    if (!in_array($key, $exclude)) {
2064
      $form_state['view']->exposed_raw_input[$key] = $value;
2065
    }
2066
  }
2067
}
2068

    
2069
/**
2070
 * Save the Views exposed form for later use.
2071
 *
2072
 * @param $views_name
2073
 *   String. The views name.
2074
 * @param $display_name
2075
 *   String. The current view display name.
2076
 * @param $form_output
2077
 *   Array (optional). The form structure. Only needed when inserting the value.
2078
 * @return
2079
 *   Array. The form structure, if any. Otherwise, return FALSE.
2080
 */
2081
function views_exposed_form_cache($views_name, $display_name, $form_output = NULL) {
2082
  // When running tests for exposed filters, this cache should
2083
  // be cleared between each test.
2084
  $views_exposed = &drupal_static(__FUNCTION__);
2085

    
2086
  // Save the form output
2087
  if (!empty($form_output)) {
2088
    $views_exposed[$views_name][$display_name] = $form_output;
2089
    return;
2090
  }
2091

    
2092
  // Return the form output, if any
2093
  return empty($views_exposed[$views_name][$display_name]) ? FALSE : $views_exposed[$views_name][$display_name];
2094
}
2095

    
2096
// ------------------------------------------------------------------
2097
// Misc helpers
2098

    
2099
/**
2100
 * Build a list of theme function names for use most everywhere.
2101
 */
2102
function views_theme_functions($hook, $view, $display = NULL) {
2103
  require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'views') . "/theme/theme.inc";
2104
  return _views_theme_functions($hook, $view, $display);
2105
}
2106

    
2107
/**
2108
 * Substitute current time; this works with cached queries.
2109
 */
2110
function views_views_query_substitutions($view) {
2111
  global $language_content;
2112
  return array(
2113
    '***CURRENT_VERSION***' => VERSION,
2114
    '***CURRENT_TIME***' => REQUEST_TIME,
2115
    '***CURRENT_LANGUAGE***' => $language_content->language,
2116
    '***DEFAULT_LANGUAGE***' => language_default('language'),
2117
  );
2118
}
2119

    
2120
/**
2121
 * Implements hook_query_TAG_alter().
2122
 *
2123
 * This is the hook_query_alter() for queries tagged by Views and is used to
2124
 * add in substitutions from hook_views_query_substitutions().
2125
 */
2126
function views_query_views_alter(QueryAlterableInterface $query) {
2127
  $substitutions = $query->getMetaData('views_substitutions');
2128
  $tables =& $query->getTables();
2129
  $where =& $query->conditions();
2130

    
2131
  // Replaces substitions in tables.
2132
  foreach ($tables as $table_name => $table_metadata) {
2133
    foreach ($table_metadata['arguments'] as $replacement_key => $value) {
2134
      if (isset($substitutions[$value])) {
2135
        $tables[$table_name]['arguments'][$replacement_key] = $substitutions[$value];
2136
      }
2137
    }
2138
  }
2139

    
2140
  // Replaces substitions in filter criterias.
2141
  _views_query_tag_alter_condition($query, $where, $substitutions);
2142
}
2143

    
2144
/**
2145
 * Replaces the substitutions recursive foreach condition.
2146
 */
2147
function _views_query_tag_alter_condition(QueryAlterableInterface $query, &$conditions, $substitutions) {
2148
  foreach ($conditions as $condition_id => &$condition) {
2149
    if (is_numeric($condition_id)) {
2150
      if (is_string($condition['field'])) {
2151
        $condition['field'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['field']);
2152
      }
2153
      elseif (is_object($condition['field'])) {
2154
        $sub_conditions =& $condition['field']->conditions();
2155
        _views_query_tag_alter_condition($query, $sub_conditions, $substitutions);
2156
      }
2157
      // $condition['value'] is a subquery so alter the subquery recursive.
2158
      // Therefore take sure to get the metadata of the main query.
2159
      if (is_object($condition['value'])) {
2160
        $subquery = $condition['value'];
2161
        $subquery->addMetaData('views_substitutions', $query->getMetaData('views_substitutions'));
2162
        views_query_views_alter($condition['value']);
2163
      }
2164
      elseif (isset($condition['value'])) {
2165
        $condition['value'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['value']);
2166
      }
2167
    }
2168
  }
2169
}
2170

    
2171
/**
2172
 * Embed a view using a PHP snippet.
2173
 *
2174
 * This function is meant to be called from PHP snippets, should one wish to
2175
 * embed a view in a node or something. It's meant to provide the simplest
2176
 * solution and doesn't really offer a lot of options, but breaking the function
2177
 * apart is pretty easy, and this provides a worthwhile guide to doing so.
2178
 *
2179
 * Note that this function does NOT display the title of the view. If you want
2180
 * to do that, you will need to do what this function does manually, by
2181
 * loading the view, getting the preview and then getting $view->get_title().
2182
 *
2183
 * @param $name
2184
 *   The name of the view to embed.
2185
 * @param $display_id
2186
 *   The display id to embed. If unsure, use 'default', as it will always be
2187
 *   valid. But things like 'page' or 'block' should work here.
2188
 * @param ...
2189
 *   Any additional parameters will be passed as arguments.
2190
 */
2191
function views_embed_view($name, $display_id = 'default') {
2192
  $args = func_get_args();
2193
  array_shift($args); // remove $name
2194
  if (count($args)) {
2195
    array_shift($args); // remove $display_id
2196
  }
2197

    
2198
  $view = views_get_view($name);
2199
  if (!$view || !$view->access($display_id)) {
2200
    return;
2201
  }
2202

    
2203
  return $view->preview($display_id, $args);
2204
}
2205

    
2206
/**
2207
 * Get the result of a view.
2208
 *
2209
 * @param string $name
2210
 *   The name of the view to retrieve the data from.
2211
 * @param string $display_id
2212
 *   The display id. On the edit page for the view in question, you'll find
2213
 *   a list of displays at the left side of the control area. "Master"
2214
 *   will be at the top of that list. Hover your cursor over the name of the
2215
 *   display you want to use. An URL will appear in the status bar of your
2216
 *   browser. This is usually at the bottom of the window, in the chrome.
2217
 *   Everything after #views-tab- is the display ID, e.g. page_1.
2218
 * @param ...
2219
 *   Any additional parameters will be passed as arguments.
2220
 * @return array
2221
 *   An array containing an object for each view item.
2222
 */
2223
function views_get_view_result($name, $display_id = NULL) {
2224
  $args = func_get_args();
2225
  array_shift($args); // remove $name
2226
  if (count($args)) {
2227
    array_shift($args); // remove $display_id
2228
  }
2229

    
2230
  $view = views_get_view($name);
2231
  if (is_object($view)) {
2232
    if (is_array($args)) {
2233
      $view->set_arguments($args);
2234
    }
2235
    if (is_string($display_id)) {
2236
      $view->set_display($display_id);
2237
    }
2238
    else {
2239
      $view->init_display();
2240
    }
2241
    $view->pre_execute();
2242
    $view->execute();
2243
    return $view->result;
2244
  }
2245
  else {
2246
    return array();
2247
  }
2248
}
2249

    
2250
/**
2251
 * Export a field.
2252
 */
2253
function views_var_export($var, $prefix = '', $init = TRUE) {
2254
  if (is_array($var)) {
2255
    if (empty($var)) {
2256
      $output = 'array()';
2257
    }
2258
    else {
2259
      $output = "array(\n";
2260
      foreach ($var as $key => $value) {
2261
        $output .= "  " . views_var_export($key, '', FALSE) . " => " . views_var_export($value, '  ', FALSE) . ",\n";
2262
      }
2263
      $output .= ')';
2264
    }
2265
  }
2266
  elseif (is_bool($var)) {
2267
    $output = $var ? 'TRUE' : 'FALSE';
2268
  }
2269
  elseif (is_string($var) && strpos($var, "\n") !== FALSE) {
2270
    // Replace line breaks in strings with a token for replacement
2271
    // at the very end. This protects multi-line strings from
2272
    // unintentional indentation.
2273
    $var = str_replace("\n", "***BREAK***", $var);
2274
    $output = var_export($var, TRUE);
2275
  }
2276
  else {
2277
    $output = var_export($var, TRUE);
2278
  }
2279

    
2280
  if ($prefix) {
2281
    $output = str_replace("\n", "\n$prefix", $output);
2282
  }
2283

    
2284
  if ($init) {
2285
    $output = str_replace("***BREAK***", "\n", $output);
2286
  }
2287

    
2288
  return $output;
2289
}
2290

    
2291
/**
2292
 * Prepare a string for use as a valid CSS identifier (element, class or ID name).
2293
 * This function is similar to a core version but with more sane filter values.
2294
 *
2295
 * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
2296
 * CSS identifiers (including element names, classes, and IDs in selectors.)
2297
 *
2298
 * @param $identifier
2299
 *   The identifier to clean.
2300
 * @param $filter
2301
 *   An array of string replacements to use on the identifier.
2302
 * @return
2303
 *   The cleaned identifier.
2304
 *
2305
 * @see drupal_clean_css_identifier()
2306
 */
2307
function views_clean_css_identifier($identifier, $filter = array(' ' => '-', '/' => '-', '[' => '-', ']' => '')) {
2308
  // By default, we filter using Drupal's coding standards.
2309
  $identifier = strtr($identifier, $filter);
2310

    
2311
  // Valid characters in a CSS identifier are:
2312
  // - the hyphen (U+002D)
2313
  // - a-z (U+0030 - U+0039)
2314
  // - A-Z (U+0041 - U+005A)
2315
  // - the underscore (U+005F)
2316
  // - 0-9 (U+0061 - U+007A)
2317
  // - ISO 10646 characters U+00A1 and higher
2318
  // We strip out any character not in the above list.
2319
  $identifier = preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $identifier);
2320

    
2321
  return $identifier;
2322
}
2323

    
2324
/**
2325
 * Implement hook_views_exportables().
2326
 */
2327
function views_views_exportables($op = 'list', $views = NULL, $name = 'foo') {
2328
  $all_views = views_get_all_views();
2329
  if ($op == 'list') {
2330

    
2331
    foreach ($all_views as $name => $view) {
2332
      // in list, $views is a list of tags.
2333
      if (empty($views) || in_array($view->tag, $views)) {
2334
        $return[$name] = array(
2335
          'name' => check_plain($name),
2336
          'desc' => check_plain($view->description),
2337
          'tag' => check_plain($view->tag)
2338
        );
2339
      }
2340
    }
2341
    return $return;
2342
  }
2343

    
2344
  if ($op == 'export') {
2345
    $code = "/**\n";
2346
    $code .= " * Implement hook_views_default_views().\n";
2347
    $code .= " */\n";
2348
    $code .= "function " . $name . "_views_default_views() {\n";
2349
    foreach ($views as $view => $truth) {
2350
      $code .= "  /*\n";
2351
      $code .= "   * View " . var_export($all_views[$view]->name, TRUE) . "\n";
2352
      $code .= "   */\n";
2353
      $code .= $all_views[$view]->export('  ');
2354
      $code .= '  $views[$view->name] = $view;' . "\n\n";
2355
    }
2356
    $code .= "  return \$views;\n";
2357
    $code .= "}\n";
2358

    
2359
    return $code;
2360
  }
2361
}
2362

    
2363
/**
2364
 * #process callback to see if we need to check_plain() the options.
2365
 *
2366
 * Since FAPI is inconsistent, the #options are sanitized for you in all cases
2367
 * _except_ checkboxes. We have form elements that are sometimes 'select' and
2368
 * sometimes 'checkboxes', so we need decide late in the form rendering cycle
2369
 * if the options need to be sanitized before they're rendered. This callback
2370
 * inspects the type, and if it's still 'checkboxes', does the sanitation.
2371
 */
2372
function views_process_check_options($element, &$form_state) {
2373
  if ($element['#type'] == 'checkboxes' || $element['#type'] == 'checkbox') {
2374
    $element['#options'] = array_map('check_plain', $element['#options']);
2375
  }
2376
  return $element;
2377
}
2378

    
2379
/**
2380
 * Trim the field down to the specified length.
2381
 *
2382
 * @param $alter
2383
 *   - max_length: Maximum lenght of the string, the rest gets truncated.
2384
 *   - word_boundary: Trim only on a word boundary.
2385
 *   - ellipsis: Show an ellipsis (...) at the end of the trimmed string.
2386
 *   - html: Take sure that the html is correct.
2387
 *
2388
 * @param $value
2389
 *   The string which should be trimmed.
2390
 */
2391
function views_trim_text($alter, $value) {
2392
  if (drupal_strlen($value) > $alter['max_length']) {
2393
    $value = drupal_substr($value, 0, $alter['max_length']);
2394
    // TODO: replace this with cleanstring of ctools
2395
    if (!empty($alter['word_boundary'])) {
2396
      $regex = "(.*)\b.+";
2397
      if (function_exists('mb_ereg')) {
2398
        mb_regex_encoding('UTF-8');
2399
        $found = mb_ereg($regex, $value, $matches);
2400
      }
2401
      else {
2402
        $found = preg_match("/$regex/us", $value, $matches);
2403
      }
2404
      if ($found) {
2405
        $value = $matches[1];
2406
      }
2407
    }
2408
    // Remove scraps of HTML entities from the end of a strings
2409
    $value = rtrim(preg_replace('/(?:<(?!.+>)|&(?!.+;)).*$/us', '', $value));
2410

    
2411
    if (!empty($alter['ellipsis'])) {
2412
      $value .= t('...');
2413
    }
2414
  }
2415
  if (!empty($alter['html'])) {
2416
    $value = _filter_htmlcorrector($value);
2417
  }
2418

    
2419
  return $value;
2420
}
2421

    
2422
/**
2423
 * Adds one to each key of the array.
2424
 *
2425
 * For example array(0 => 'foo') would be array(1 => 'foo').
2426
 */
2427
function views_array_key_plus($array) {
2428
  $keys = array_keys($array);
2429
  rsort($keys);
2430
  foreach ($keys as $key) {
2431
    $array[$key+1] = $array[$key];
2432
    unset($array[$key]);
2433
  }
2434
  asort($array);
2435
  return $array;
2436
}
2437

    
2438
/**
2439
 * Report to CTools that we use hook_views_api instead of hook_ctools_plugin_api()
2440
 */
2441
function views_ctools_plugin_api_hook_name() {
2442
  return 'views_api';
2443
}
2444

    
2445
// Declare API compatibility on behalf of core modules:
2446

    
2447
/**
2448
 * Implements hook_views_api().
2449
 *
2450
 * This one is used as the base to reduce errors when updating.
2451
 */
2452
function views_views_api() {
2453
  return array(
2454
    // in your modules do *not* use views_api_version()!!!
2455
    'api' => views_api_version(),
2456
    'path' => drupal_get_path('module', 'views') . '/modules',
2457
  );
2458
}
2459

    
2460
if (!function_exists('aggregator_views_api')) {
2461
  function aggregator_views_api() { return views_views_api(); }
2462
}
2463

    
2464
if (!function_exists('book_views_api')) {
2465
  function book_views_api() { return views_views_api(); }
2466
}
2467

    
2468
if (!function_exists('comment_views_api')) {
2469
  function comment_views_api() { return views_views_api(); }
2470
}
2471

    
2472
if (!function_exists('field_views_api')) {
2473
  function field_views_api() { return views_views_api(); }
2474
}
2475

    
2476
if (!function_exists('file_views_api')) {
2477
  function file_views_api() { return views_views_api(); }
2478
}
2479

    
2480
if (!function_exists('filter_views_api')) {
2481
  function filter_views_api() { return views_views_api(); }
2482
}
2483

    
2484
if (!function_exists('image_views_api')) {
2485
  function image_views_api() { return views_views_api(); }
2486
}
2487

    
2488
if (!function_exists('locale_views_api')) {
2489
  function locale_views_api() { return views_views_api(); }
2490
}
2491

    
2492
if (!function_exists('node_views_api')) {
2493
  function node_views_api() { return views_views_api(); }
2494
}
2495

    
2496
if (!function_exists('poll_views_api')) {
2497
  function poll_views_api() { return views_views_api(); }
2498
}
2499

    
2500
if (!function_exists('profile_views_api')) {
2501
  function profile_views_api() { return views_views_api(); }
2502
}
2503

    
2504
if (!function_exists('search_views_api')) {
2505
  function search_views_api() { return views_views_api(); }
2506
}
2507

    
2508
if (!function_exists('statistics_views_api')) {
2509
  function statistics_views_api() { return views_views_api(); }
2510
}
2511

    
2512
if (!function_exists('system_views_api')) {
2513
  function system_views_api() { return views_views_api(); }
2514
}
2515

    
2516
if (!function_exists('tracker_views_api')) {
2517
  function tracker_views_api() { return views_views_api(); }
2518
}
2519

    
2520
if (!function_exists('taxonomy_views_api')) {
2521
  function taxonomy_views_api() { return views_views_api(); }
2522
}
2523

    
2524
if (!function_exists('translation_views_api')) {
2525
  function translation_views_api() { return views_views_api(); }
2526
}
2527

    
2528
if (!function_exists('user_views_api')) {
2529
  function user_views_api() { return views_views_api(); }
2530
}
2531

    
2532
if (!function_exists('contact_views_api')) {
2533
  function contact_views_api() { return views_views_api(); }
2534
}