Projet

Général

Profil

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

root / drupal7 / sites / all / modules / views / views.module @ 87dbc3bf

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
  $items = array();
359
  $items['views/ajax'] = array(
360
    'title' => 'Views',
361
    'page callback' => 'views_ajax',
362
    'theme callback' => 'ajax_base_page_theme',
363
    'delivery callback' => 'ajax_deliver',
364
    'access callback' => TRUE,
365
    'description' => 'Ajax callback for view loading.',
366
    'type' => MENU_CALLBACK,
367
    'file' => 'includes/ajax.inc',
368
  );
369
  // Path is not admin/structure/views due to menu complications with the wildcards from
370
  // the generic ajax callback.
371
  $items['admin/views/ajax/autocomplete/user'] = array(
372
    'page callback' => 'views_ajax_autocomplete_user',
373
    'theme callback' => 'ajax_base_page_theme',
374
    'access callback' => 'user_access',
375
    'access arguments' => array('access user profiles'),
376
    'type' => MENU_CALLBACK,
377
    'file' => 'includes/ajax.inc',
378
  );
379
  // Define another taxonomy autocomplete because the default one of drupal
380
  // does not support a vid a argument anymore
381
  $items['admin/views/ajax/autocomplete/taxonomy'] = array(
382
    'page callback' => 'views_ajax_autocomplete_taxonomy',
383
    'theme callback' => 'ajax_base_page_theme',
384
    'access callback' => 'user_access',
385
    'access arguments' => array('access content'),
386
    'type' => MENU_CALLBACK,
387
    'file' => 'includes/ajax.inc',
388
  );
389
  return $items;
390
}
391

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

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

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

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

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

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

    
477
  if ($view = views_get_view($name)) {
478
    $view->set_display($display_id);
479
    $view->init_handlers();
480

    
481
    $ids = array_keys($view->argument);
482

    
483
    $indexes = array();
484
    $path = explode('/', $view->get_path());
485

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

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

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

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

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

    
528
  // Fallback; if we get here no view was found or handler was not valid.
529
  return MENU_NOT_FOUND;
530
}
531

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

    
546
    views_add_contextual_links($page, 'page', $view, $view->current_display);
547
  }
548
}
549

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

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

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

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

    
608
    $view->init_display();
609
    foreach ($view->display as $display_id => $display) {
610

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

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

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

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

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

    
654
  views_cache_set('views_block_items', $items, TRUE);
655

    
656
  return $items;
657
}
658

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

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

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

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

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

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

    
886
/**
887
 * Implements hook_flush_caches().
888
 */
889
function views_flush_caches() {
890
  return array('cache_views', 'cache_views_data');
891
}
892

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

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

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

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

    
924
  // Clear the page and block cache.
925
  cache_clear_all();
926

    
927
  // Set the menu as needed to be rebuilt.
928
  variable_set('menu_rebuild_needed', TRUE);
929

    
930
  // Allow modules to respond to the Views cache being cleared.
931
  module_invoke_all('views_invalidate_cache');
932
}
933

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

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

    
960
    if (!is_array($arg)) {
961
      continue;
962
    }
963

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

    
977
  return FALSE;
978
}
979

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

    
991
/**
992
 * Access callback for the views_plugin_access_role access plugin.
993

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

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

    
1018
  return $cache;
1019
}
1020

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

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

    
1045
  return $cache;
1046
}
1047

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

    
1059
// ------------------------------------------------------------------
1060
// Include file helpers
1061

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

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

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

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

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

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

    
1139
  views_include('base');
1140
  views_include('handlers');
1141
  views_include('cache');
1142
  views_include('plugins');
1143
  views_module_include('views', $reset);
1144
  $finished = TRUE;
1145
}
1146

    
1147
// -----------------------------------------------------------------------
1148
// Views handler functions
1149

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

    
1170
  $data = views_fetch_data($table, FALSE);
1171
  $handler = NULL;
1172
  views_include('handlers');
1173

    
1174
  // Support old views_data entries conversion.
1175

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

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

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

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

    
1217
    if ($override) {
1218
      $data[$field][$key]['override handler'] = $override;
1219
    }
1220

    
1221
    $handler = _views_prepare_handler($data[$field][$key], $data, $field, $key);
1222
  }
1223

    
1224
  if ($handler) {
1225
    return $handler;
1226
  }
1227

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

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

    
1247
// -----------------------------------------------------------------------
1248
// Views plugin functions
1249

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

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

    
1275
  $plugins[$type] = array();
1276

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

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

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

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

    
1327
  return $plugin;
1328
}
1329

    
1330
// -----------------------------------------------------------------------
1331
// Views database functions
1332

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

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

    
1353
  return $templates;
1354
}
1355

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

    
1369
  return $view;
1370
}
1371

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

    
1390
  foreach ($views as $view) {
1391
    // Skip disabled views.
1392
    if (!empty($view->disabled)) {
1393
      continue;
1394
    }
1395

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1585
  return $table;
1586
}
1587

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

    
1600
  if (empty($names)) {
1601
    return;
1602
  }
1603

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

    
1609
    foreach ($result as $data) {
1610
      $object = new $object_name(FALSE);
1611
      $object->load_row($data);
1612

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

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

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

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

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

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

    
1658
// ------------------------------------------------------------------
1659
// Views debug helper functions
1660

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

    
1701
/**
1702
 * Shortcut to views_debug()
1703
 */
1704
function vpr($message, $placeholders = array()) {
1705
  views_debug($message, $placeholders);
1706
}
1707

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

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

    
1727
function vsm_trace() {
1728
  vsm(views_trace());
1729
}
1730

    
1731
function vpr_trace() {
1732
  dpr(views_trace());
1733
}
1734

    
1735
// ------------------------------------------------------------------
1736
// Views form (View with form elements)
1737

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

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

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

    
1781
  $form = $form_state['step']($form, $form_state, $view, $output);
1782
  return $form;
1783
}
1784

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

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

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

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

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

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

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

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

    
1871
  return $form;
1872
}
1873

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

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

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

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

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

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

    
1924
// ------------------------------------------------------------------
1925
// Exposed widgets form
1926

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

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

    
1947
  $form_state['input'] = $view->get_exposed_input();
1948

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

    
1956
  $form['#info'] = array();
1957

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

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

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

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

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

    
2006
  $exposed_form_plugin = $form_state['exposed_form_plugin'];
2007
  $exposed_form_plugin->exposed_form_alter($form, $form_state);
2008

    
2009
  // Save the form
2010
  views_exposed_form_cache($view->name, $view->current_display, $form);
2011

    
2012
  return $form;
2013
}
2014

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

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

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

    
2054

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

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

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

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

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

    
2093
// ------------------------------------------------------------------
2094
// Misc helpers
2095

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

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

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

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

    
2137
  // Replaces substitions in filter criterias.
2138
  _views_query_tag_alter_condition($query, $where, $substitutions);
2139
}
2140

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

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

    
2195
  $view = views_get_view($name);
2196
  if (!$view || !$view->access($display_id)) {
2197
    return;
2198
  }
2199

    
2200
  return $view->preview($display_id, $args);
2201
}
2202

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

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

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

    
2277
  if ($prefix) {
2278
    $output = str_replace("\n", "\n$prefix", $output);
2279
  }
2280

    
2281
  if ($init) {
2282
    $output = str_replace("***BREAK***", "\n", $output);
2283
  }
2284

    
2285
  return $output;
2286
}
2287

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

    
2308
  // Valid characters in a CSS identifier are:
2309
  // - the hyphen (U+002D)
2310
  // - a-z (U+0030 - U+0039)
2311
  // - A-Z (U+0041 - U+005A)
2312
  // - the underscore (U+005F)
2313
  // - 0-9 (U+0061 - U+007A)
2314
  // - ISO 10646 characters U+00A1 and higher
2315
  // We strip out any character not in the above list.
2316
  $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);
2317

    
2318
  return $identifier;
2319
}
2320

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

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

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

    
2356
    return $code;
2357
  }
2358
}
2359

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

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

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

    
2416
  return $value;
2417
}
2418

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

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

    
2442
// Declare API compatibility on behalf of core modules:
2443

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

    
2457
if (!function_exists('aggregator_views_api')) {
2458
  function aggregator_views_api() { return views_views_api(); }
2459
}
2460

    
2461
if (!function_exists('book_views_api')) {
2462
  function book_views_api() { return views_views_api(); }
2463
}
2464

    
2465
if (!function_exists('comment_views_api')) {
2466
  function comment_views_api() { return views_views_api(); }
2467
}
2468

    
2469
if (!function_exists('field_views_api')) {
2470
  function field_views_api() { return views_views_api(); }
2471
}
2472

    
2473
if (!function_exists('file_views_api')) {
2474
  function file_views_api() { return views_views_api(); }
2475
}
2476

    
2477
if (!function_exists('filter_views_api')) {
2478
  function filter_views_api() { return views_views_api(); }
2479
}
2480

    
2481
if (!function_exists('image_views_api')) {
2482
  function image_views_api() { return views_views_api(); }
2483
}
2484

    
2485
if (!function_exists('locale_views_api')) {
2486
  function locale_views_api() { return views_views_api(); }
2487
}
2488

    
2489
if (!function_exists('node_views_api')) {
2490
  function node_views_api() { return views_views_api(); }
2491
}
2492

    
2493
if (!function_exists('poll_views_api')) {
2494
  function poll_views_api() { return views_views_api(); }
2495
}
2496

    
2497
if (!function_exists('profile_views_api')) {
2498
  function profile_views_api() { return views_views_api(); }
2499
}
2500

    
2501
if (!function_exists('search_views_api')) {
2502
  function search_views_api() { return views_views_api(); }
2503
}
2504

    
2505
if (!function_exists('statistics_views_api')) {
2506
  function statistics_views_api() { return views_views_api(); }
2507
}
2508

    
2509
if (!function_exists('system_views_api')) {
2510
  function system_views_api() { return views_views_api(); }
2511
}
2512

    
2513
if (!function_exists('tracker_views_api')) {
2514
  function tracker_views_api() { return views_views_api(); }
2515
}
2516

    
2517
if (!function_exists('taxonomy_views_api')) {
2518
  function taxonomy_views_api() { return views_views_api(); }
2519
}
2520

    
2521
if (!function_exists('translation_views_api')) {
2522
  function translation_views_api() { return views_views_api(); }
2523
}
2524

    
2525
if (!function_exists('user_views_api')) {
2526
  function user_views_api() { return views_views_api(); }
2527
}
2528

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