Merge branch 'master' of https://github.com/ksenzee/views3ui
[project/views.git] / views.module
CommitLineData
5ed42115 1<?php
6199495d 2// $Id: views.module,v 1.341.4.54 2011/02/06 14:29:01 dereine Exp $
5ed42115
KS
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 */
15function views_api_version() {
16 return '3.0-alpha1';
17}
18
19/**
20 * Views will not load plugins advertising a version older than this.
21 */
22function views_api_minimum_version() {
23 return '2';
24}
25
26/**
27 * Implement hook_init().
28 */
29function views_init() {
30 drupal_add_css(drupal_get_path('module', 'views') .'/css/views.css');
31}
32
33/**
34 * Implement hook_theme(). Register views theming functions.
35 */
dd50052c 36function views_theme($existing, $type, $theme, $path) {
5ed42115
KS
37 $path = drupal_get_path('module', 'views');
38 include_once $path . '/theme/theme.inc';
39
40 // Some quasi clever array merging here.
41 $base = array(
42 'file' => 'theme.inc',
43 'path' => $path . '/theme',
44 );
45
46 // Our extra version of pager from pager.inc
47 $hooks['views_mini_pager'] = $base + array(
48 'variables' => array('tags' => array(), 'quantity' => 10, 'element' => 0, 'parameters' => array()),
49 'pattern' => 'views_mini_pager__',
50 );
51
52 $arguments = array(
53 'display' => array('view' => NULL),
54 'style' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
55 'row' => array('view' => NULL, 'options' => NULL, 'row' => NULL, 'field_alias' => NULL),
56 );
57
58 // Default view themes
59 $hooks['views_view_field'] = $base + array(
60 'pattern' => 'views_view_field__',
61 'variables' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
62 );
63
64 $plugins = views_fetch_plugin_data();
65
66 // Register theme functions for all style plugins
67 foreach ($plugins as $type => $info) {
68 foreach ($info as $plugin => $def) {
69 if (isset($def['theme'])) {
70 $hooks[$def['theme']] = array(
71 'pattern' => $def['theme'] . '__',
72 'file' => $def['theme file'],
73 'path' => $def['theme path'],
74 'variables' => $arguments[$type],
75 );
76
77 $include = DRUPAL_ROOT . '/' . $def['theme path'] . '/' . $def['theme file'];
78 if (file_exists($include)) {
79 require_once $include;
80 }
81
82 if (!function_exists('theme_' . $def['theme'])) {
83 $hooks[$def['theme']]['template'] = drupal_clean_css_identifier($def['theme']);
84 }
85 }
86 if (isset($def['additional themes'])) {
87 foreach ($def['additional themes'] as $theme => $theme_type) {
88 if (empty($theme_type)) {
89 $theme = $theme_type;
90 $theme_type = $type;
91 }
92
93 $hooks[$theme] = array(
94 'pattern' => $theme . '__',
95 'file' => $def['theme file'],
96 'path' => $def['theme path'],
97 'variables' => $arguments[$theme_type],
98 );
99
100 if (!function_exists('theme_' . $theme)) {
101 $hooks[$theme]['template'] = drupal_clean_css_identifier($theme);
102 }
103 }
104 }
105 }
106 }
107
108 $hooks['views_exposed_form'] = $base + array(
109 'template' => 'views-exposed-form',
110 'pattern' => 'views_exposed_form__',
111 'render element' => 'form',
112 );
113
114 $hooks['views_more'] = $base + array(
115 'template' => 'views-more',
116 'pattern' => 'views_more__',
117 'variables' => array('more_url' => NULL, 'link_text' => 'more'),
118 );
dd50052c
KS
119
120 // Add theme suggestions which are part of modules.
121 foreach (views_get_module_apis() as $info) {
122 if (isset($info['template path'])) {
123 $hooks += _views_find_module_templates($hooks, $info['template path']);
124 }
125 }
5ed42115
KS
126 return $hooks;
127}
128
129/**
dd50052c
KS
130 * Scans a directory of a module for template files.
131 *
132 * @param $cache
133 * The existing cache of theme hooks to test against.
134 * @param $path
135 * The path to search.
ced80ad3 136 *
dd50052c
KS
137 * @see drupal_find_theme_templates
138 */
139function _views_find_module_templates($cache, $path) {
140 $regex = '/' . '\.tpl\.php' . '$' . '/';
141
142 // Because drupal_system_listing works the way it does, we check for real
143 // templates separately from checking for patterns.
144 $files = drupal_system_listing($regex, $path, 'name', 0);
145 foreach ($files as $template => $file) {
146 // Chop off the remaining extensions if there are any. $template already
147 // has the rightmost extension removed, but there might still be more,
148 // such as with .tpl.php, which still has .tpl in $template at this point.
149 if (($pos = strpos($template, '.')) !== FALSE) {
150 $template = substr($template, 0, $pos);
151 }
152 // Transform - in filenames to _ to match function naming scheme
153 // for the purposes of searching.
154 $hook = strtr($template, '-', '_');
155 if (isset($cache[$hook])) {
156 $templates[$hook] = array(
157 'template' => $template,
158 'path' => dirname($file->filename),
159 'includes' => isset($cache[$hook]['includes']) ? $cache[$hook]['includes'] : NULL,
160 );
161 }
162 // Ensure that the pattern is maintained from base themes to its sub-themes.
163 // Each sub-theme will have their templates scanned so the pattern must be
164 // held for subsequent runs.
165 if (isset($cache[$hook]['pattern'])) {
166 $templates[$hook]['pattern'] = $cache[$hook]['pattern'];
167 }
168 }
169
170 $patterns = array_keys($files);
171
172 foreach ($cache as $hook => $info) {
173 if (!empty($info['pattern'])) {
174 // Transform _ in pattern to - to match file naming scheme
175 // for the purposes of searching.
176 $pattern = strtr($info['pattern'], '_', '-');
177
178 $matches = preg_grep('/^'. $pattern .'/', $patterns);
179 if ($matches) {
180 foreach ($matches as $match) {
181 $file = substr($match, 0, strpos($match, '.'));
182 // Put the underscores back in for the hook name and register this pattern.
183 $templates[strtr($file, '-', '_')] = array(
184 'template' => $file,
185 'path' => dirname($files[$match]->filename),
186 'variables' => $info['variables'],
187 'base hook' => $hook,
188 'includes' => isset($info['includes']) ? $info['includes'] : NULL,
189 );
190 }
191 }
192 }
193 }
194
195 return $templates;
196}
197
198/**
5ed42115
KS
199 * A theme preprocess function to automatically allow view-based node
200 * templates if called from a view.
201 *
202 * The 'modules/node.views.inc' file is a better place for this, but
203 * we haven't got a chance to load that file before Drupal builds the
204 * node portion of the theme registry.
205 */
206function views_preprocess_node(&$vars) {
207 // The 'view' attribute of the node is added in template_preprocess_views_view_row_node()
208 if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
209 $vars['view'] = &$vars['node']->view;
210 $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
211 if (!empty($vars['node']->view->current_display)) {
212 $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;
213 }
214 }
215}
216
217/**
218 * A theme preprocess function to automatically allow view-based node
219 * templates if called from a view.
220 */
221function views_preprocess_comment(&$vars) {
222 // The 'view' attribute of the node is added in template_preprocess_views_view_row_comment()
223 if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
224 $vars['view'] = &$vars['node']->view;
225 $vars['theme_hook_suggestions'][] = 'comment__view__' . $vars['node']->view->name;
226 if (!empty($vars['node']->view->current_display)) {
227 $vars['theme_hook_suggestions'][] = 'comment__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;
228 }
229 }
230}
231
232/*
233 * Implement hook_permission().
234 */
235function views_permission() {
236 return array(
237 'administer views' => array(
238 'title' => t('Administer views'),
239 'description' => t('Access the views administration pages.'),
240 ),
241 'access all views' => array(
242 'title' => t('Access all views'),
243 'description' => t('Bypass access control when accessing views.'),
244 ),
245 );
246}
247
248/**
249 * Implement hook_menu().
250 */
251function views_menu() {
252 // Any event which causes a menu_rebuild could potentially mean that the
253 // Views data is updated -- module changes, profile changes, etc.
254 views_invalidate_cache();
255 $items = array();
256 $items['views/ajax'] = array(
257 'title' => 'Views',
258 'page callback' => 'views_ajax',
dd50052c 259 'delivery callback' => 'ajax_deliver',
5ed42115
KS
260 'access callback' => TRUE,
261 'description' => 'Ajax callback for view loading.',
262 'type' => MENU_CALLBACK,
dd50052c 263 'file' => 'includes/ajax.inc',
5ed42115
KS
264 );
265 // Path is not admin/structure/views due to menu complications with the wildcards from
266 // the generic ajax callback.
267 $items['admin/views/ajax/autocomplete/user'] = array(
268 'page callback' => 'views_ajax_autocomplete_user',
269 'access callback' => 'user_access',
270 'access arguments' => array('access content'),
271 'type' => MENU_CALLBACK,
272 'file' => 'includes/ajax.inc',
273 );
274 // Define another taxonomy autocomplete because the default one of drupal
275 // does not support a vid a argument anymore
276 $items['admin/views/ajax/autocomplete/taxonomy'] = array(
277 'page callback' => 'views_ajax_autocomplete_taxonomy',
278 'access callback' => 'user_access',
279 'access arguments' => array('access content'),
280 'type' => MENU_CALLBACK,
281 'file' => 'includes/ajax.inc',
282 );
283 return $items;
284}
285
286/**
287 * Implement hook_menu_alter().
288 */
289function views_menu_alter(&$callbacks) {
290 $our_paths = array();
291 $views = views_get_applicable_views('uses hook menu');
292 foreach ($views as $data) {
293 list($view, $display_id) = $data;
294 $result = $view->execute_hook_menu($display_id, $callbacks);
295 if (is_array($result)) {
296 // The menu system doesn't support having two otherwise
297 // identical paths with different placeholders. So we
298 // want to remove the existing items from the menu whose
299 // paths would conflict with ours.
300
301 // First, we must find any existing menu items that may
302 // conflict. We use a regular expression because we don't
303 // know what placeholders they might use. Note that we
304 // first construct the regex itself by replacing %views_arg
305 // in the display path, then we use this constructed regex
306 // (which will be something like '#^(foo/%[^/]*/bar)$#') to
307 // search through the existing paths.
308 $regex = '#^(' . preg_replace('#%views_arg#', '%[^/]*', implode('|', array_keys($result))) . ')$#';
309 $matches = preg_grep($regex, array_keys($callbacks));
310
311 // Remove any conflicting items that were found.
312 foreach ($matches as $path) {
313 // Don't remove the paths we just added!
314 if (!isset($our_paths[$path])) {
315 unset($callbacks[$path]);
316 }
317 }
318 foreach ($result as $path => $item) {
319 if (!isset($callbacks[$path])) {
320 // Add a new item, possibly replacing (and thus effectively
321 // overriding) one that we removed above.
322 $callbacks[$path] = $item;
323 }
324 else {
325 // This item already exists, so it must be one that we added.
326 // We change the various callback arguments to pass an array
327 // of possible display IDs instead of a single ID.
328 $callbacks[$path]['page arguments'][1] = (array)$callbacks[$path]['page arguments'][1];
329 $callbacks[$path]['page arguments'][1][] = $display_id;
330 $callbacks[$path]['access arguments'][] = $item['access arguments'][0];
331 $callbacks[$path]['load arguments'][1] = (array)$callbacks[$path]['load arguments'][1];
332 $callbacks[$path]['load arguments'][1][] = $display_id;
333 }
334 $our_paths[$path] = TRUE;
335 }
336 }
337 }
338
339 // Save memory: Destroy those views.
340 foreach ($views as $data) {
341 list($view, $display_id) = $data;
342 $view->destroy();
343 }
344}
345
346/**
347 * Helper function for menu loading. This will automatically be
348 * called in order to 'load' a views argument; primarily it
349 * will be used to perform validation.
350 *
351 * @param $value
352 * The actual value passed.
353 * @param $name
354 * The name of the view. This needs to be specified in the 'load function'
355 * of the menu entry.
46bb9b7a 356 * @param $display_id
357 * The display id that will be loaded for this menu item.
5ed42115
KS
358 * @param $index
359 * The menu argument index. This counts from 1.
360 */
361function views_arg_load($value, $name, $display_id, $index) {
46bb9b7a 362 static $views = array();
363
364 // Make sure we haven't already loaded this views argument for a similar menu
365 // item elsewhere.
366 $key = $name . ':' . $display_id . ':' . $value . ':' . $index;
367 if (isset($views[$key])) {
368 return $views[$key];
369 }
370
5ed42115
KS
371 if ($view = views_get_view($name)) {
372 $view->set_display($display_id);
373 $view->init_handlers();
374
375 $ids = array_keys($view->argument);
376
377 $indexes = array();
378 $path = explode('/', $view->get_path());
379
380 foreach ($path as $id => $piece) {
381 if ($piece == '%' && !empty($ids)) {
382 $indexes[$id] = array_shift($ids);
383 }
384 }
385
386 if (isset($indexes[$index])) {
387 if (isset($view->argument[$indexes[$index]])) {
388 $arg = $view->argument[$indexes[$index]]->validate_argument($value) ? $value : FALSE;
389 $view->destroy();
46bb9b7a 390
391 // Store the output in case we load this same menu item again.
392 $views[$key] = $arg;
5ed42115
KS
393 return $arg;
394 }
395 }
396 $view->destroy();
397 }
398}
399
400/**
401 * Page callback entry point; requires a view and a display id, then
402 * passes control to the display handler.
403 */
404function views_page() {
405 $args = func_get_args();
406 $name = array_shift($args);
407 $display_id = array_shift($args);
408
409 // Load the view
410 if ($view = views_get_view($name)) {
411 return $view->execute_display($display_id, $args);
412 }
413
414 // Fallback; if we get here no view was found or handler was not valid.
415 return drupal_not_found();
416}
417
418/**
419 * Implement hook_block_info().
420 */
421function views_block_info() {
422 // Try to avoid instantiating all the views just to get the blocks info.
423 views_include('cache');
424 $cache = views_cache_get('views_block_items', TRUE);
425 if ($cache && is_array($cache->data)) {
426 return $cache->data;
427 }
428
429 $items = array();
430 $views = views_get_all_views();
431 foreach ($views as $view) {
432 // disabled views get nothing.
433 if (!empty($view->disabled)) {
434 continue;
435 }
436
437 $view->init_display();
438 foreach ($view->display as $display_id => $display) {
439
440 if (isset($display->handler) && !empty($display->handler->definition['uses hook block'])) {
441 $result = $display->handler->execute_hook_block_list();
442 if (is_array($result)) {
443 $items = array_merge($items, $result);
444 }
445 }
446
447 if (isset($display->handler) && $display->handler->get_option('exposed_block')) {
448 $result = $display->handler->get_special_blocks();
449 if (is_array($result)) {
450 $items = array_merge($items, $result);
451 }
452 }
453 }
454 }
455
456 // block.module has a delta length limit of 32, but our deltas can
457 // unfortunately be longer because view names can be 32 and display IDs
458 // can also be 32. So for very long deltas, change to md5 hashes.
459 $hashes = array();
460
461 // get the keys because we're modifying the array and we don't want to
462 // confuse PHP too much.
463 $keys = array_keys($items);
464 foreach ($keys as $delta) {
465 if (strlen($delta) >= 32) {
466 $hash = md5($delta);
467 $hashes[$hash] = $delta;
468 $items[$hash] = $items[$delta];
469 unset($items[$delta]);
470 }
471 }
472
473 // Only save hashes if they have changed.
474 $old_hashes = variable_get('views_block_hashes', array());
475 if ($hashes != $old_hashes) {
476 variable_set('views_block_hashes', $hashes);
477 }
478 // Save memory: Destroy those views.
479 foreach ($views as $view) {
480 $view->destroy();
481 }
482
483 views_cache_set('views_block_items', $items, TRUE);
484
485 return $items;
486}
487
488/**
489 * Implement hook_block_view().
490 */
491function views_block_view($delta) {
492 $start = microtime(TRUE);
493 // if this is 32, this should be an md5 hash.
494 if (strlen($delta) == 32) {
495 $hashes = variable_get('views_block_hashes', array());
496 if (!empty($hashes[$delta])) {
497 $delta = $hashes[$delta];
498 }
499 }
500
501 // This indicates it's a special one.
502 if (substr($delta, 0, 1) == '-') {
503 list($nothing, $type, $name, $display_id) = explode('-', $delta);
504 // Put the - back on.
505 $type = '-' . $type;
506 if ($view = views_get_view($name)) {
507 if ($view->access($display_id)) {
508 $view->set_display($display_id);
509 if (isset($view->display_handler)) {
510 $output = $view->display_handler->view_special_blocks($type);
511 $view->destroy();
512 return $output;
513 }
514 }
515 $view->destroy();
516 }
517 }
518
519 list($name, $display_id) = explode('-', $delta);
520 // Load the view
521 if ($view = views_get_view($name)) {
522 if ($view->access($display_id)) {
523 $output = $view->execute_display($display_id);
524 $view->destroy();
525 return $output;
526 }
527 $view->destroy();
528 }
529}
530
531/**
532 * Implements hook_flush_caches().
533 */
534function views_flush_caches() {
535 return array('cache_views', 'cache_views_data');
536}
537
538/**
539 * Implements hook_field_create_instance.
540 */
541function views_field_create_instance($instance) {
542 cache_clear_all('*', 'cache_views', TRUE);
543 cache_clear_all('*', 'cache_views_data', TRUE);
544}
545
546/**
547 * Implements hook_field_update_instance.
548 */
549function views_field_update_instance($instance, $prior_instance) {
550 cache_clear_all('*', 'cache_views', TRUE);
551 cache_clear_all('*', 'cache_views_data', TRUE);
552}
553
554/**
555 * Implements hook_field_delete_instance.
556 */
557function views_field_delete_instance($instance) {
558 cache_clear_all('*', 'cache_views', TRUE);
559 cache_clear_all('*', 'cache_views_data', TRUE);
560}
561
562/**
563 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
564 */
565function views_invalidate_cache() {
566 cache_clear_all('*', 'cache_views', TRUE);
567}
568
569/**
570 * Access callback to determine if the user can import Views.
571 *
572 * View imports require an additional access check because they are PHP
573 * code and PHP is more locked down than administer views.
574 */
575function views_import_access() {
576 return user_access('administer views') && user_access('use PHP for settings');
577}
578
579/**
580 * Determine if the logged in user has access to a view.
581 *
582 * This function should only be called from a menu hook or some other
583 * embedded source. Each argument is the result of a call to
584 * views_plugin_access::get_access_callback() which is then used
585 * to determine if that display is accessible. If *any* argument
586 * is accessible, then the view is accessible.
587 */
588function views_access() {
589 $args = func_get_args();
590 foreach ($args as $arg) {
591 if ($arg === TRUE) {
592 return TRUE;
593 }
594
595 if (!is_array($arg)) {
596 continue;
597 }
598
599 list($callback, $arguments) = $arg;
dd50052c
KS
600 $arguments = $arguments ? $arguments : array();
601 // Bring dynamic arguments to the access callback.
602 foreach ($arguments as $key => $value) {
603 if (is_int($value) && isset($args[$value])) {
604 $arguments[$key] = $args[$value];
605 }
606 }
5ed42115
KS
607 if (function_exists($callback) && call_user_func_array($callback, $arguments)) {
608 return TRUE;
609 }
610 }
611
612 return FALSE;
613}
614
615/**
616 * Access callback for the views_plugin_access_perm access plugin.
617 *
618 * Determine if the specified user has access to a view on the basis of
619 * permissions. If the $account argument is omitted, the current user
620 * is used.
621 */
622function views_check_perm($perm, $account = NULL) {
623 return user_access($perm, $account) || user_access('access all views', $account);
624}
625
626/**
627 * Access callback for the views_plugin_access_role access plugin.
628
629 * Determine if the specified user has access to a view on the basis of any of
630 * the requested roles. If the $account argument is omitted, the current user
631 * is used.
632 */
633function views_check_roles($rids, $account = NULL) {
634 global $user;
635 $account = isset($account) ? $account : $user;
636 $roles = array_keys($account->roles);
637 $roles[] = $account->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
638 return user_access('access all views', $account) || array_intersect(array_filter($rids), $roles);
639}
640// ------------------------------------------------------------------
641// Functions to help identify views that are running or ran
642
643/**
644 * Set the current 'page view' that is being displayed so that it is easy
645 * for other modules or the theme to identify.
646 */
647function &views_set_page_view($view = NULL) {
648 static $cache = NULL;
649 if (isset($view)) {
650 $cache = $view;
651 }
652
653 return $cache;
654}
655
656/**
657 * Find out what, if any, page view is currently in use. Please note that
658 * this returns a reference, so be careful! You can unintentionally modify the
659 * $view object.
660 */
661function &views_get_page_view() {
662 return views_set_page_view();
663}
664
665/**
666 * Set the current 'current view' that is being built/rendered so that it is
667 * easy for other modules or items in drupal_eval to identify
668 */
669function &views_set_current_view($view = NULL) {
670 static $cache = NULL;
671 if (isset($view)) {
672 $cache = $view;
673 }
674
675 return $cache;
676}
677
678/**
679 * Find out what, if any, current view is currently in use. Please note that
680 * this returns a reference, so be careful! You can unintentionally modify the
681 * $view object.
682 */
683function &views_get_current_view() {
684 return views_set_current_view();
685}
686
687// ------------------------------------------------------------------
688// Include file helpers
689
690/**
691 * Include views .inc files as necessary.
692 */
693function views_include($file) {
694 module_load_include('inc', 'views', "includes/$file");
695}
696
697/**
698 * Load views files on behalf of modules.
699 */
700function views_module_include($file, $reset = FALSE) {
701 foreach (views_get_module_apis($reset) as $module => $info) {
702 if (file_exists(DRUPAL_ROOT . "/$info[path]/$module.$file")) {
703 require_once DRUPAL_ROOT . "/$info[path]/$module.$file";
704 }
705 }
706}
707
708/**
709 * Get a list of modules that support the current views API.
710 */
711function views_get_module_apis($reset = FALSE) {
712 static $cache = NULL;
713 if (!isset($cache) || $reset) {
714 $cache = array();
715 foreach (module_implements('views_api') as $module) {
716 $info = module_invoke($module, 'views_api');
717 if (version_compare($info['api'], views_api_minimum_version(), '>=') &&
718 version_compare($info['api'], views_api_version(), '<=')) {
719 if (!isset($info['path'])) {
720 $info['path'] = drupal_get_path('module', $module);
721 }
722 $cache[$module] = $info;
723 }
724 }
725 }
726
727 return $cache;
728}
729
730/**
731 * Include views .css files.
732 */
733function views_add_css($file) {
734 // We set preprocess to FALSE because we are adding the files conditionally,
735 // and we don't want to generate duplicate cache files.
736 // TODO: at some point investigate adding some files unconditionally and
737 // allowing preprocess.
738 drupal_add_css(drupal_get_path('module', 'views') . "/css/$file.css", array('preprocess' => FALSE));
739}
740
741/**
742 * Include views .js files.
743 */
744function views_add_js($file) {
745 // If javascript has been disabled by the user, never add js files.
746 if (variable_get('views_no_javascript', FALSE)) {
747 return;
748 }
5ed42115
KS
749 static $base = TRUE, $ajax = TRUE;
750 if ($base) {
751 drupal_add_js(drupal_get_path('module', 'views') . "/js/base.js");
752 $base = FALSE;
753 }
dd50052c
KS
754 if ($ajax && in_array($file, array('ajax', 'ajax_view'))) {
755 drupal_add_library('system', 'drupal.ajax');
756 drupal_add_library('system', 'jquery.form');
757 $ajax = FALSE;
5ed42115 758 }
dd50052c 759 ctools_add_js($file, 'views');
5ed42115
KS
760}
761
762/**
763 * Load views files on behalf of modules.
764 */
765function views_include_handlers($reset = FALSE) {
766 static $finished = FALSE;
767 // Ensure this only gets run once.
768 if ($finished && !$reset) {
769 return;
770 }
771
772 views_include('base');
773 views_include('handlers');
774 views_include('cache');
775 views_include('plugins');
776 _views_include_handlers();
777 $finished = TRUE;
778}
779
780/**
781 * Load default views files on behalf of modules.
782 */
783function views_include_default_views($reset = FALSE) {
784 static $finished = FALSE;
785 // Ensure this only gets run once.
786 if ($finished && !$reset) {
787 return;
788 }
789
790 // Default views hooks may be in the normal handler file,
791 // or in a separate views_default file at the discretion of
792 // the module author.
793 views_include_handlers($reset);
794
795 _views_include_default_views($reset);
796 $finished = TRUE;
797}
798
799// -----------------------------------------------------------------------
800// Views handler functions
801
802/**
803 * Fetch a handler from the data cache.
804 *
805 * @param $table
806 * The name of the table this handler is from.
807 * @param $field
808 * The name of the field this handler is from.
809 * @param $key
810 * The type of handler. i.e, sort, field, argument, filter, relationship
811 * @param $override
812 * Override the actual handler object with this class. Used for
813 * aggregation when the handler is redirected to the aggregation
814 * handler.
815 *
816 * @return
817 * An instance of a handler object. May be views_handler_broken.
818 */
819function views_get_handler($table, $field, $key, $override = NULL) {
213ad79a
DW
820 static $recursion_protection = array();
821
5ed42115
KS
822 $data = views_fetch_data($table);
823 $handler = NULL;
824
825 if (isset($data[$field][$key])) {
213ad79a
DW
826 // Support old views_data entries conversion.
827 if (isset($data[$field][$key]['moved to'])) {
828 list($moved_table, $moved_field) = $data[$field][$key]['moved to'];
829 if (!empty($recursion_protection[$moved_table][$moved_field])) {
830 // recursion detected!
831 return NULL;
832 }
833 $recursion_protection[$moved_table][$moved_field] = TRUE;
834 $handler = views_get_handler($moved_table, $moved_field, $key, $override);
835 $recursion_protection = array();
836 if ($handler) {
837 // store these values so we know what we were originally called.
838 $handler->original_table = $table;
839 $handler->original_field = $field;
840 if (empty($handler->actual_table)) {
841 $handler->actual_table = $moved_table;
842 $handler->actual_field = $moved_field;
843 }
844 }
845 return $handler;
846 }
847
5ed42115
KS
848 // Set up a default handler:
849 if (empty($data[$field][$key]['handler'])) {
850 $data[$field][$key]['handler'] = 'views_handler_' . $key;
851 }
852
853 if ($override) {
854 $data[$field][$key]['override handler'] = $override;
855 }
856
6199495d 857 $handler = _views_prepare_handler($data[$field][$key], $data, $field, $key);
5ed42115
KS
858 }
859
860 if ($handler) {
861 return $handler;
862 }
863
864 // DEBUG -- identify missing handlers
213ad79a 865 vpr("Missing handler: $table $field $key");
5ed42115
KS
866 $broken = array(
867 'title' => t('Broken handler @table.@field', array('@table' => $table, '@field' => $field)),
868 'handler' => 'views_handler_' . $key . '_broken',
869 'table' => $table,
870 'field' => $field,
871 );
cca2fbe7 872 return _views_create_handler($broken, 'handler', $key);
5ed42115
KS
873}
874
875/**
876 * Fetch Views' data from the cache
877 */
878function views_fetch_data($table = NULL, $reset = FALSE) {
879 views_include('cache');
880 return _views_fetch_data($table, $reset);
881}
882
883// -----------------------------------------------------------------------
884// Views plugin functions
885
886/**
887 * Fetch the plugin data from cache.
888 */
889function views_fetch_plugin_data($type = NULL, $plugin = NULL, $reset = FALSE) {
890 views_include('cache');
891 return _views_fetch_plugin_data($type, $plugin, $reset);
892}
893
894/**
895 * Get a handler for a plugin
896 */
897function views_get_plugin($type, $plugin, $reset = FALSE) {
898 views_include('handlers');
899 $definition = views_fetch_plugin_data($type, $plugin, $reset);
900 if (!empty($definition)) {
901 return _views_create_handler($definition, $type);
902 }
903}
904
905// -----------------------------------------------------------------------
906// Views database functions
907
908/**
909 * Get a view from the default views defined by modules.
910 *
911 * Default views are cached per-language. This function will rescan the
912 * default_views hook if necessary.
913 *
914 * @param $view_name
915 * The name of the view to load.
916 * @return
917 * A view object or NULL if it is not available.
918 */
919function &views_get_default_view($view_name, $reset = FALSE) {
920 $null = NULL;
921
922 // Attempt to load individually cached view from cache.
923 views_include('cache');
924 if (!$reset) {
925 $data = views_cache_get("views_default:{$view_name}", TRUE);
926 if (isset($data->data) && is_object($data->data)) {
927 return $data->data;
928 }
929 }
930
931 // Otherwise, allow entire cache to be rebuilt.
932 $cache = views_discover_default_views($reset);
933 if (isset($cache[$view_name])) {
934 return $cache[$view_name];
935 }
936 return $null;
937}
938
939/**
940 * Create an empty view to work with.
941 *
942 * @return
943 * A fully formed, empty $view object. This object must be populated before
944 * it can be successfully saved.
945 */
946function views_new_view() {
947 views_include('view');
948 $view = new view();
949 $view->vid = 'new';
950 $view->add_display('default');
951
952 return $view;
953}
954
955/**
956 * Scan all modules for default views and rebuild the default views cache.
957 *
958 * @return An associative array of all known default views.
959 */
960function views_discover_default_views($reset = FALSE) {
961 static $cache = array();
962
963 if (empty($cache) || $reset) {
964 views_include('cache');
965 $cache = _views_discover_default_views($reset);
966 }
967 return $cache;
968}
969
970/**
971 * Return a list of all views and display IDs that have a particular
972 * setting in their display's plugin settings.
973 *
974 * @return
975 * @code
976 * array(
977 * array($view, $display_id),
978 * array($view, $display_id),
979 * );
980 * @endcode
981 */
982function views_get_applicable_views($type) {
983 // @todo: Use a smarter flagging system so that we don't have to
984 // load every view for this.
985 $result = array();
986 $views = views_get_all_views();
987
988 foreach ($views as $view) {
989 // Skip disabled views.
990 if (!empty($view->disabled)) {
991 continue;
992 }
993
994 if (empty($view->display)) {
995 // Skip this view as it is broken.
996 vsm(t("Skipping broken view @view", array('@view' => $view->name)));
997 continue;
998 }
999
1000 // Loop on array keys because something seems to muck with $view->display
1001 // a bit in PHP4.
1002 foreach (array_keys($view->display) as $id) {
1003 $plugin = views_fetch_plugin_data('display', $view->display[$id]->display_plugin);
1004 if (!empty($plugin[$type])) {
1005 // This view uses hook menu. Clone it so that different handlers
1006 // don't trip over each other, and add it to the list.
1007 $v = $view->clone_view();
1008 if ($v->set_display($id)) {
1009 $result[] = array($v, $id);
1010 }
1011 // In PHP 4.4.7 and presumably earlier, if we do not unset $v
1012 // here, we will find that it actually overwrites references
1013 // possibly due to shallow copying issues.
1014 unset($v);
1015 }
1016 }
1017 }
1018 return $result;
1019}
1020
1021/**
1022 * Return an array of all views as fully loaded $view objects.
1023 *
1024 * @param $reset
1025 * If TRUE, reset the static cache forcing views to be reloaded.
1026 */
1027function views_get_all_views($reset = FALSE) {
1028 static $views = array();
1029
1030 if (empty($views) || $reset) {
1031 $views = array();
1032
1033 // First, get all applicable views.
1034 views_include('view');
1035 $views = view::load_views();
1036
1037 // Get all default views.
1038 $status = variable_get('views_defaults', array());
1039
1040 foreach (views_discover_default_views($reset) as $view) {
1041 // Determine if default view is enabled or disabled.
1042 if (isset($status[$view->name])) {
1043 $view->disabled = $status[$view->name];
1044 }
1045
1046 // If overridden, also say so.
1047 if (!empty($views[$view->name])) {
1048 $views[$view->name]->type = t('Overridden');
1049 }
1050 else {
1051 $view->type = t('Default');
1052 $views[$view->name] = $view;
1053 }
1054 }
1055
1056 }
1057 return $views;
1058}
1059
1060/**
1b649ff6
DR
1061 * Returns an array of all enabled views, as fully loaded $view objects.
1062 */
1063function views_get_enabled_views() {
1064 $views = views_get_all_views();
1065 return array_filter($views, 'views_view_is_enabled');
1066}
1067
1068/**
1069 * Returns an array of all disabled views, as fully loaded $view objects.
1070 */
1071function views_get_disabled_views() {
1072 $views = views_get_all_views();
1073 return array_filter($views, 'views_view_is_disabled');
1074}
1075
1076/**
1077 * Returns TRUE if a view is enabled, FALSE otherwise.
1078 */
1079function views_view_is_enabled($view) {
1080 return empty($view->disabled);
1081}
1082
1083/**
1084 * Returns TRUE if a view is disabled, FALSE otherwise.
1085 */
1086function views_view_is_disabled($view) {
1087 return !empty($view->disabled);
1088}
1089
1090/**
5ed42115
KS
1091 * Get a view from the database or from default views.
1092 *
1093 * This function is just a static wrapper around views::load(). This function
1094 * isn't called 'views_load()' primarily because it might get a view
1095 * from the default views which aren't technically loaded from the database.
1096 *
1097 * @param $name
1098 * The name of the view.
1099 * @param $reset
1100 * If TRUE, reset this entry in the load cache.
1101 * @return $view
1102 * A reference to the $view object. Use $reset if you're sure you want
1103 * a fresh one.
1104 */
1105function views_get_view($name, $reset = FALSE) {
1106 views_include('view');
1107 $view = view::load($name, $reset);
1108 $default_view = views_get_default_view($name, $reset);
1109
1110 // The view does not exist.
1111 if (empty($view) && empty($default_view)) {
1112 return;
1113 }
1114 // The view is defined in code.
1115 elseif (empty($view) && !empty($default_view)) {
1116 $status = variable_get('views_defaults', array());
1117 if (isset($status[$default_view->name])) {
1118 $default_view->disabled = $status[$default_view->name];
1119 }
1120 $default_view->type = t('Default');
1121 return $default_view->clone_view();
1122 }
1123 // The view is overriden/defined in the database.
1124 elseif (!empty($view) && !empty($default_view)) {
1125 $view->type = t('Overridden');
1126 }
1127
1128 return $view->clone_view();
1129}
1130
ced80ad3
EM
1131/**
1132 * Export callback to load the view subrecords, which are the displays.
1133 */
1134function views_load_display_records(&$views) {
1135 // Get vids from the views.
1136 $names = array();
1137 foreach ($views as $view) {
1138 if (empty($view->display)) {
1139 $names[$view->vid] = $view->name;
1140 }
1141 }
1142
1143 if (empty($names)) {
1144 return;
1145 }
1146
1147 foreach (view::db_objects() as $key) {
1148 $object_name = "views_$key";
1149 $result = db_query("SELECT * FROM {{$object_name}} WHERE vid IN (:vids) ORDER BY vid, position",
1150 array(':vids' => array_keys($names)));
1151
1152 foreach ($result as $data) {
1153 $object = new $object_name(FALSE);
1154 $object->load_row($data);
1155
1156 // Because it can get complicated with this much indirection,
1157 // make a shortcut reference.
1158 $location = &$views[$names[$object->vid]]->$key;
1159
1160 // If we have a basic id field, load the item onto the view based on
1161 // this ID, otherwise push it on.
1162 if (!empty($object->id)) {
1163 $location[$object->id] = $object;
1164 }
1165 else {
1166 $location[] = $object;
1167 }
1168 }
1169 }
1170}
1171
1172/**
1173 * Export CRUD callback to save a view.
1174 */
1175function views_save_view(&$view) {
1176 return $view->save();
1177}
1178
1179/**
1180 * Export CRUD callback to export a view.
1181 */
1182function views_delete_view(&$view) {
1183 return $view->delete(TRUE);
1184}
1185
1186/**
1187 * Export CRUD callback to export a view.
1188 */
1189function views_export_view(&$view, $indent = '') {
1190 return $view->export($indent);
1191}
1192
5ed42115
KS
1193// ------------------------------------------------------------------
1194// Views debug helper functions
1195
1196/**
dd50052c
KS
1197 * Provide debug output for Views. This relies on devel.module
1198 */
1199function views_debug($message) {
1200 if (module_exists('devel') && variable_get('views_devel_output', FALSE) && user_access('access devel information')) {
1201 if (is_string($message)) {
1202 $output = $message;
1203 }
1204 else {
1205 $output = var_export($message, TRUE);
1206 }
1207 if (variable_get('views_devel_region', 'footer') != 'watchdog') {
dc196b7d 1208 drupal_add_region_content(variable_get('views_devel_region', 'footer'), '<pre>' . $output . '</pre>');
dd50052c
KS
1209 }
1210 else {
1211 watchdog('views_logging', '<pre>' . $output . '</pre>');
1212 }
1213 }
1214}
1215
1216/**
1217 * Shortcut to views_debug()
1218 */
1219function vpr($message) {
1220 views_debug($message);
1221}
1222
1223/**
5ed42115
KS
1224 * Debug messages
1225 */
1226function vsm($message) {
1227 if (module_exists('devel')) {
1228 dsm($message);
1229 }
1230}
1231
1232function views_trace() {
1233 $message = '';
1234 foreach (debug_backtrace() as $item) {
1235 if (!empty($item['file']) && !in_array($item['function'], array('vsm_trace', 'vpr_trace', 'views_trace'))) {
1236 $message .= basename($item['file']) . ": " . (empty($item['class']) ? '' : ($item['class'] . '->')) . "$item[function] line $item[line]" . "\n";
1237 }
1238 }
1239 return $message;
1240}
1241
1242function vsm_trace() {
1243 vsm(views_trace());
1244}
1245
1246function vpr_trace() {
1247 dpr(views_trace());
1248}
1249
1250// ------------------------------------------------------------------
1251// Exposed widgets form
1252
1253/**
1254 * Form builder for the exposed widgets form.
1255 *
1256 * Be sure that $view and $display are references.
1257 */
1258function views_exposed_form($form, &$form_state) {
1259 // Don't show the form when batch operations are in progress.
1260 if ($batch = batch_get() && isset($batch['current_set'])) {
1261 return array(
1262 // Set the theme callback to be nothing to avoid errors in template_preprocess_views_exposed_form().
1263 '#theme' => '',
1264 );
1265 }
1266
1267 // Make sure that we validate because this form might be submitted
1268 // multiple times per page.
1269 $form_state['must_validate'] = TRUE;
1270 $view = &$form_state['view'];
1271 $display = &$form_state['display'];
1272
1273 $form_state['input'] = $view->get_exposed_input();
1274
1275 // Let form plugins know this is for exposed widgets.
1276 $form_state['exposed'] = TRUE;
1277 // Check if the form was already created
1278 if ($cache = views_exposed_form_cache($view->name, $view->current_display)) {
1279 return $cache;
1280 }
1281
1282 $form['#info'] = array();
1283
1284 if (!variable_get('clean_url', FALSE)) {
1285 $form['q'] = array(
1286 '#type' => 'hidden',
1287 '#value' => $view->get_url(),
1288 );
1289 }
1290
1291 // Go through each handler and let it generate its exposed widget.
1292 foreach ($view->display_handler->handlers as $type => $value) {
1293 foreach ($view->$type as $id => $handler) {
1294 if ($handler->can_expose() && $handler->is_exposed()) {
1295 $handler->exposed_form($form, $form_state);
1296 if ($info = $handler->exposed_info()) {
1297 $form['#info']["$type-$id"] = $info;
1298 }
1299 }
1300 }
1301 }
1302
1303 $form['submit'] = array(
1304 '#name' => '', // prevent from showing up in $_GET.
1305 '#type' => 'submit',
1306 '#value' => t('Apply'),
1307 '#id' => drupal_html_id('edit-submit-' . $view->name),
1308 );
1309
1310 $form['#action'] = url($view->get_url());
1311 $form['#theme'] = views_theme_functions('views_exposed_form', $view, $display);
1312 $form['#id'] = drupal_clean_css_identifier('views_exposed_form-' . check_plain($view->name) . '-' . check_plain($display->id));
1313// $form['#attributes']['class'] = array('views-exposed-form');
1314
1315 // If using AJAX, we need the form plugin.
1316 if ($view->use_ajax) {
dd50052c 1317 drupal_add_library('system', 'jquery.form');
5ed42115
KS
1318 }
1319 ctools_include('dependent');
1320
1321 $exposed_form_plugin = $form_state['exposed_form_plugin'];
1322 $exposed_form_plugin->exposed_form_alter($form, $form_state);
1323
1324 // Save the form
1325 views_exposed_form_cache($view->name, $view->current_display, $form);
1326
1327 return $form;
1328}
1329
1330/**
1331 * Validate handler for exposed filters
1332 */
1333function views_exposed_form_validate(&$form, &$form_state) {
1334 foreach (array('field', 'filter') as $type) {
1335 $handlers = &$form_state['view']->$type;
1336 foreach ($handlers as $key => $handler) {
1337 $handlers[$key]->exposed_validate($form, $form_state);
1338 }
1339 }
1340 $exposed_form_plugin = $form_state['exposed_form_plugin'];
1341 $exposed_form_plugin->exposed_form_validate($form, $form_state);
1342}
1343
1344/**
1345 * Submit handler for exposed filters
1346 */
1347function views_exposed_form_submit(&$form, &$form_state) {
1348 foreach (array('field', 'filter') as $type) {
1349 $handlers = &$form_state['view']->$type;
1350 foreach ($handlers as $key => $info) {
1351 $handlers[$key]->exposed_submit($form, $form_state);
1352 }
1353 }
1354 $form_state['view']->exposed_data = $form_state['values'];
1355 $form_state['view']->exposed_raw_input = array();
1356
1357
1358 $exclude = array('q', 'submit', 'form_build_id', 'form_id', 'form_token', 'exposed_form_plugin', '');
1359 $exposed_form_plugin = $form_state['exposed_form_plugin'];
1360 $exposed_form_plugin->exposed_form_submit($form, $form_state, $exclude);
ced80ad3 1361
5ed42115
KS
1362 foreach ($form_state['values'] as $key => $value) {
1363 if (!in_array($key, $exclude)) {
1364 $form_state['view']->exposed_raw_input[$key] = $value;
1365 }
1366 }
1367}
1368
1369/**
1370 * Save the Views exposed form for later use.
1371 *
1372 * @param $views_name
1373 * String. The views name.
1374 * @param $display_name
1375 * String. The current view display name.
1376 * @param $form_output
1377 * Array (optional). The form structure. Only needed when inserting the value.
1378 * @return
1379 * Array. The form structure, if any. Otherwise, return FALSE.
1380 */
1381function views_exposed_form_cache($views_name, $display_name, $form_output = NULL) {
1382 static $views_exposed;
1383
1384 // Save the form output
1385 if (!empty($form_output)) {
1386 $views_exposed[$views_name][$display_name] = $form_output;
1387 return;
1388 }
1389
1390 // Return the form output, if any
1391 return empty($views_exposed[$views_name][$display_name]) ? FALSE : $views_exposed[$views_name][$display_name];
1392}
1393
1394// ------------------------------------------------------------------
1395// Misc helpers
1396
1397/**
1398 * Build a list of theme function names for use most everywhere.
1399 */
1400function views_theme_functions($hook, $view, $display = NULL) {
1401 require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'views') . "/theme/theme.inc";
1402 return _views_theme_functions($hook, $view, $display);
1403}
1404
1405/**
1406 * Substitute current time; this works with cached queries.
1407 */
1408function views_views_query_substitutions($view) {
dd50052c 1409 global $language_content;
5ed42115
KS
1410 return array(
1411 '***CURRENT_VERSION***' => VERSION,
1412 '***CURRENT_TIME***' => REQUEST_TIME,
dd50052c 1413 '***CURRENT_LANGUAGE***' => $language_content->language,
5ed42115 1414 '***DEFAULT_LANGUAGE***' => language_default('language'),
5ed42115
KS
1415 );
1416}
1417
1418/**
1419 * Implements hook_query_TAG_alter().
1420 *
1421 * This is the hook_query_alter() for queries tagged by Views and is used to
1422 * add in substitutions from hook_views_query_substitutions().
1423 */
1424function views_query_views_alter(QueryAlterableInterface $query) {
1425 $substitutions = $query->getMetaData('views_substitutions');
1426 $tables =& $query->getTables();
1427 $where =& $query->conditions();
1428
1429 // Replaces substitions in tables.
1430 foreach ($tables as $table_name => $table_metadata) {
1431 foreach ($table_metadata['arguments'] as $replacement_key => $value) {
1432 if (isset($substitutions[$value])) {
1433 $tables[$table_name]['arguments'][$replacement_key] = $substitutions[$value];
1434 }
1435 }
1436 }
1437
1438 // Replaces substitions in filter criterias.
1439 _views_query_tag_alter_condition($query, $where, $substitutions);
1440}
1441
1442/**
1443 * Replaces the substitutions recursive foreach condition.
1444 */
1445function _views_query_tag_alter_condition(QueryAlterableInterface $query, &$conditions, $substitutions) {
1446 foreach ($conditions as $condition_id => &$condition) {
1447 if (is_numeric($condition_id)) {
1448 if (is_string($condition['field'])) {
1449 $condition['field'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['field']);
1450 }
1451 elseif (is_object($condition['field'])) {
1452 $sub_conditions =& $condition['field']->conditions();
1453 _views_query_tag_alter_condition($query, $sub_conditions, $substitutions);
1454 }
1455 // $condition['value'] is a subquery so alter the subquery recursive.
1456 // Therefore take sure to get the metadata of the main query.
1457 if (is_object($condition['value'])) {
1458 $subquery = $condition['value'];
1459 $subquery->addMetaData('views_substitutions', $query->getMetaData('views_substitutions'));
1460 views_query_views_alter($condition['value']);
1461 }
1462 elseif (isset($condition['value'])) {
1463 $condition['value'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['value']);
1464 }
1465 }
1466 }
1467}
1468
1469/**
1470 * Embed a view using a PHP snippet.
1471 *
1472 * This function is meant to be called from PHP snippets, should one wish to
1473 * embed a view in a node or something. It's meant to provide the simplest
1474 * solution and doesn't really offer a lot of options, but breaking the function
1475 * apart is pretty easy, and this provides a worthwhile guide to doing so.
1476 *
1477 * Note that this function does NOT display the title of the view. If you want
1478 * to do that, you will need to do what this function does manually, by
1479 * loading the view, getting the preview and then getting $view->get_title().
1480 *
1481 * @param $name
1482 * The name of the view to embed.
1483 * @param $display_id
1484 * The display id to embed. If unsure, use 'default', as it will always be
1485 * valid. But things like 'page' or 'block' should work here.
1486 * @param ...
1487 * Any additional parameters will be passed as arguments.
1488 */
1489function views_embed_view($name, $display_id = 'default') {
1490 $args = func_get_args();
1491 array_shift($args); // remove $name
1492 if (count($args)) {
1493 array_shift($args); // remove $display_id
1494 }
1495
1496 $view = views_get_view($name);
1497 if (!$view || !$view->access($display_id)) {
1498 return;
1499 }
1500
1501 return $view->preview($display_id, $args);
1502}
1503
1504/**
1505* Get the result of a view.
1506*
1507* @param string $name
1508* The name of the view to retrieve the data from.
1509* @param string $display_id
1510* The display id. On the edit page for the view in question, you'll find
1511* a list of displays at the left side of the control area. "Defaults"
1512* will be at the top of that list. Hover your cursor over the name of the
1513* display you want to use. An URL will appear in the status bar of your
1514* browser. This is usually at the bottom of the window, in the chrome.
1515* Everything after #views-tab- is the display ID, e.g. page_1.
1516 * @param ...
1517 * Any additional parameters will be passed as arguments.
1518* @return
1519* array
1520* An array containing an object for each view item.
1521*/
1522function views_get_view_result($name, $display_id = NULL) {
1523 $args = func_get_args();
1524 array_shift($args); // remove $name
1525 if (count($args)) {
1526 array_shift($args); // remove $display_id
1527 }
1528
1529 $view = views_get_view($name);
1530 if (is_object($view)) {
1531 if (is_array($args)) {
1532 $view->set_arguments($args);
1533 }
1534 if (is_string($display_id)) {
1535 $view->set_display($display_id);
1536 }
1537 else {
1538 $view->init_display();
1539 }
1540 $view->pre_execute();
1541 $view->execute();
1542 return $view->result;
1543 }
1544 else {
1545 return array();
1546 }
1547}
1548
1549/**
1550 * Export a field.
1551 */
1552function views_var_export($var, $prefix = '', $init = TRUE) {
1553 if (is_array($var)) {
1554 if (empty($var)) {
1555 $output = 'array()';
1556 }
1557 else {
1558 $output = "array(\n";
1559 foreach ($var as $key => $value) {
46bb9b7a 1560 $output .= " " . views_var_export($key, '', FALSE) . " => " . views_var_export($value, ' ', FALSE) . ",\n";
5ed42115
KS
1561 }
1562 $output .= ')';
1563 }
1564 }
1565 elseif (is_bool($var)) {
1566 $output = $var ? 'TRUE' : 'FALSE';
1567 }
1568 elseif (is_string($var) && strpos($var, "\n") !== FALSE) {
1569 // Replace line breaks in strings with a token for replacement
1570 // at the very end. This protects multi-line strings from
1571 // unintentional indentation.
1572 $var = str_replace("\n", "***BREAK***", $var);
1573 $output = var_export($var, TRUE);
1574 }
1575 else {
1576 $output = var_export($var, TRUE);
1577 }
1578
1579 if ($prefix) {
1580 $output = str_replace("\n", "\n$prefix", $output);
1581 }
1582
1583 if ($init) {
1584 $output = str_replace("***BREAK***", "\n", $output);
1585 }
1586
1587 return $output;
1588}
1589
1590/**
1591 * Implement hook_views_exportables().
1592 */
1593function views_views_exportables($op = 'list', $views = NULL, $name = 'foo') {
1594 $all_views = views_get_all_views();
1595 if ($op == 'list') {
1596
1597 foreach ($all_views as $name => $view) {
1598 // in list, $views is a list of tags.
1599 if (empty($views) || in_array($view->tag, $views)) {
1600 $return[$name] = array(
1601 'name' => check_plain($name),
1602 'desc' => check_plain($view->description),
1603 'tag' => check_plain($view->tag)
1604 );
1605 }
1606 }
1607 return $return;
1608 }
1609
1610 if ($op == 'export') {
1611 $code = "/**\n";
1612 $code .= " * Implement hook_views_default_views().\n";
1613 $code .= " */\n";
1614 $code .= "function " . $name . "_views_default_views() {\n";
1615 foreach ($views as $view => $truth) {
1616 $code .= " /*\n";
1617 $code .= " * View " . var_export($all_views[$view]->name, TRUE) . "\n";
1618 $code .= " */\n";
1619 $code .= $all_views[$view]->export(' ');
1620 $code .= ' $views[$view->name] = $view;' . "\n\n";
1621 }
1622 $code .= " return \$views;\n";
1623 $code .= "}\n";
1624
1625 return $code;
1626 }
1627}
1628
1629/**
1630 * #process callback to see if we need to check_plain() the options.
1631 *
1632 * Since FAPI is inconsistent, the #options are sanitized for you in all cases
1633 * _except_ checkboxes. We have form elements that are sometimes 'select' and
1634 * sometimes 'checkboxes', so we need decide late in the form rendering cycle
1635 * if the options need to be sanitized before they're rendered. This callback
1636 * inspects the type, and if it's still 'checkboxes', does the sanitation.
1637 */
1638function views_process_check_options($element, &$form_state) {
1639 if ($element['#type'] == 'checkboxes' || $element['#type'] == 'checkbox') {
1640 $element['#options'] = array_map('check_plain', $element['#options']);
1641 }
1642 return $element;
1643}
1644
1645/**
1646 * Trim the field down to the specified length.
1647 *
1648 * @param $alter
1649 * - max_length: Maximum lenght of the string, the rest gets truncated.
1650 * - word_boundary: Trim only on a word boundary.
1651 * - ellipsis: Trim only on a word boundary.
1652 * - html: Take sure that the html is correct.
1653 *
1654 * @param $value
1655 * The string which should be trimmed.
1656 */
1657function views_trim_text($alter, $value) {
1658 if (drupal_strlen($value) > $alter['max_length']) {
1659 $value = drupal_substr($value, 0, $alter['max_length']);
1660 // TODO: replace this with cleanstring of ctools
1661 if (!empty($alter['word_boundary'])) {
1662 $regex = "(.*)\b.+";
1663 if (function_exists('mb_ereg')) {
1664 mb_regex_encoding('UTF-8');
1665 $found = mb_ereg($regex, $value, $matches);
1666 }
1667 else {
1668 $found = preg_match("/$regex/us", $value, $matches);
1669 }
1670 if ($found) {
1671 $value = $matches[1];
1672 }
1673 }
1674 // Remove scraps of HTML entities from the end of a strings
1675 $value = rtrim(preg_replace('/(?:<(?!.+>)|&(?!.+;)).*$/us', '', $value));
1676
1677 if (!empty($alter['ellipsis'])) {
1678 $value .= '...';
1679 }
1680 }
1681 if (!empty($alter['html'])) {
1682 $value = _filter_htmlcorrector($value);
1683 }
1684
1685 return $value;
1686}
ced80ad3
EM
1687
1688function views_views_default_hook_name() {
1689 return 'views_api';
1690}
1691
1692// Declare API compatibility on behalf of core modules:
1693
1694/**
1695 * Implements hook_views_api().
1696 *
1697 * This one is used as the base to reduce errors when updating.
1698 */
1699function views_views_api() {
1700 return array(
1701 // in your modules do *not* use views_api_version()!!!
1702 'api' => views_api_version(),
1703 'path' => drupal_get_path('module', 'views') . '/modules',
1704 );
1705}
1706
1707function aggregator_views_api() { return views_views_api(); }
1708
1709function book_views_api() { return views_views_api(); }
1710
1711function comment_views_api() { return views_views_api(); }
1712
1713function locale_views_api() { return views_views_api(); }
1714
1715function field_views_api() { return views_views_api(); }
1716
1717function filter_views_api() { return views_views_api(); }
1718
1719function node_views_api() { return views_views_api(); }
1720
1721function poll_views_api() { return views_views_api(); }
1722
1723function profile_views_api() { return views_views_api(); }
1724
1725function search_views_api() { return views_views_api(); }
1726
1727function statistics_views_api() { return views_views_api(); }
1728
1729function system_views_api() { return views_views_api(); }
1730
1731function taxonomy_views_api() { return views_views_api(); }
1732
1733function translation_views_api() { return views_views_api(); }
1734
1735function upload_views_api() { return views_views_api(); }
1736
1737function user_views_api() { return views_views_api(); }
1738
1739function contact_views_api() { return views_views_api(); }