document the way to update the views data
[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 */
ce174eb6
EM
700function views_module_include($api, $reset = FALSE) {
701 if ($reset) {
702 $cache = &drupal_static('ctools_plugin_api_info');
703 if (isset($cache['views']['views'])) {
704 unset($cache['views']['views']);
5ed42115
KS
705 }
706 }
ce174eb6
EM
707 ctools_include('plugins');
708 return ctools_plugin_api_include('views', $api, views_api_minimum_version(), views_api_version());
5ed42115
KS
709}
710
711/**
712 * Get a list of modules that support the current views API.
713 */
ce174eb6
EM
714function views_get_module_apis($api = 'views', $reset = FALSE) {
715 if ($reset) {
716 $cache = &drupal_static('ctools_plugin_api_info');
717 if (isset($cache['views']['views'])) {
718 unset($cache['views']['views']);
5ed42115
KS
719 }
720 }
ce174eb6
EM
721 ctools_include('plugins');
722 return ctools_plugin_api_info('views', $api, views_api_minimum_version(), views_api_version());
5ed42115
KS
723}
724
725/**
726 * Include views .css files.
727 */
728function views_add_css($file) {
729 // We set preprocess to FALSE because we are adding the files conditionally,
730 // and we don't want to generate duplicate cache files.
731 // TODO: at some point investigate adding some files unconditionally and
732 // allowing preprocess.
733 drupal_add_css(drupal_get_path('module', 'views') . "/css/$file.css", array('preprocess' => FALSE));
734}
735
736/**
737 * Include views .js files.
738 */
739function views_add_js($file) {
740 // If javascript has been disabled by the user, never add js files.
741 if (variable_get('views_no_javascript', FALSE)) {
742 return;
743 }
5ed42115
KS
744 static $base = TRUE, $ajax = TRUE;
745 if ($base) {
746 drupal_add_js(drupal_get_path('module', 'views') . "/js/base.js");
747 $base = FALSE;
748 }
dd50052c
KS
749 if ($ajax && in_array($file, array('ajax', 'ajax_view'))) {
750 drupal_add_library('system', 'drupal.ajax');
751 drupal_add_library('system', 'jquery.form');
752 $ajax = FALSE;
5ed42115 753 }
dd50052c 754 ctools_add_js($file, 'views');
5ed42115
KS
755}
756
757/**
758 * Load views files on behalf of modules.
759 */
760function views_include_handlers($reset = FALSE) {
761 static $finished = FALSE;
762 // Ensure this only gets run once.
763 if ($finished && !$reset) {
764 return;
765 }
766
767 views_include('base');
768 views_include('handlers');
769 views_include('cache');
770 views_include('plugins');
ce174eb6 771 views_module_include('views', $reset);
5ed42115
KS
772 $finished = TRUE;
773}
774
5ed42115
KS
775// -----------------------------------------------------------------------
776// Views handler functions
777
778/**
779 * Fetch a handler from the data cache.
780 *
781 * @param $table
782 * The name of the table this handler is from.
783 * @param $field
784 * The name of the field this handler is from.
785 * @param $key
786 * The type of handler. i.e, sort, field, argument, filter, relationship
787 * @param $override
788 * Override the actual handler object with this class. Used for
789 * aggregation when the handler is redirected to the aggregation
790 * handler.
791 *
792 * @return
793 * An instance of a handler object. May be views_handler_broken.
794 */
795function views_get_handler($table, $field, $key, $override = NULL) {
213ad79a
DW
796 static $recursion_protection = array();
797
5ed42115
KS
798 $data = views_fetch_data($table);
799 $handler = NULL;
800
801 if (isset($data[$field][$key])) {
213ad79a
DW
802 // Support old views_data entries conversion.
803 if (isset($data[$field][$key]['moved to'])) {
804 list($moved_table, $moved_field) = $data[$field][$key]['moved to'];
805 if (!empty($recursion_protection[$moved_table][$moved_field])) {
806 // recursion detected!
807 return NULL;
808 }
809 $recursion_protection[$moved_table][$moved_field] = TRUE;
810 $handler = views_get_handler($moved_table, $moved_field, $key, $override);
811 $recursion_protection = array();
812 if ($handler) {
813 // store these values so we know what we were originally called.
814 $handler->original_table = $table;
815 $handler->original_field = $field;
816 if (empty($handler->actual_table)) {
817 $handler->actual_table = $moved_table;
818 $handler->actual_field = $moved_field;
819 }
820 }
821 return $handler;
822 }
823
5ed42115
KS
824 // Set up a default handler:
825 if (empty($data[$field][$key]['handler'])) {
826 $data[$field][$key]['handler'] = 'views_handler_' . $key;
827 }
828
829 if ($override) {
830 $data[$field][$key]['override handler'] = $override;
831 }
832
6199495d 833 $handler = _views_prepare_handler($data[$field][$key], $data, $field, $key);
5ed42115
KS
834 }
835
836 if ($handler) {
837 return $handler;
838 }
839
840 // DEBUG -- identify missing handlers
213ad79a 841 vpr("Missing handler: $table $field $key");
5ed42115
KS
842 $broken = array(
843 'title' => t('Broken handler @table.@field', array('@table' => $table, '@field' => $field)),
844 'handler' => 'views_handler_' . $key . '_broken',
845 'table' => $table,
846 'field' => $field,
847 );
cca2fbe7 848 return _views_create_handler($broken, 'handler', $key);
5ed42115
KS
849}
850
851/**
852 * Fetch Views' data from the cache
853 */
854function views_fetch_data($table = NULL, $reset = FALSE) {
855 views_include('cache');
856 return _views_fetch_data($table, $reset);
857}
858
859// -----------------------------------------------------------------------
860// Views plugin functions
861
862/**
863 * Fetch the plugin data from cache.
864 */
865function views_fetch_plugin_data($type = NULL, $plugin = NULL, $reset = FALSE) {
866 views_include('cache');
867 return _views_fetch_plugin_data($type, $plugin, $reset);
868}
869
870/**
871 * Get a handler for a plugin
872 */
873function views_get_plugin($type, $plugin, $reset = FALSE) {
874 views_include('handlers');
875 $definition = views_fetch_plugin_data($type, $plugin, $reset);
876 if (!empty($definition)) {
877 return _views_create_handler($definition, $type);
878 }
879}
880
881// -----------------------------------------------------------------------
882// Views database functions
883
884/**
ce174eb6
EM
885 * Get all view templates.
886 *
887 * Templates are special in-code views that are never active, but exist only
888 * to be cloned into real views as though they were templates.
889 */
890function views_get_all_templates() {
891 $templates = array();
892 $modules = views_module_include('views_template');
893
894 foreach ($modules as $module => $info) {
895 $function = $module . '_views_templates';
896 if (function_exists($function)) {
897 $new = $function();
898 if ($new && is_array($new)) {
899 $templates = array_merge($new, $templates);
900 }
901 }
902 }
903
904 return $templates;
905}
906
907/**
5ed42115
KS
908 * Create an empty view to work with.
909 *
910 * @return
911 * A fully formed, empty $view object. This object must be populated before
912 * it can be successfully saved.
913 */
914function views_new_view() {
915 views_include('view');
916 $view = new view();
917 $view->vid = 'new';
918 $view->add_display('default');
919
920 return $view;
921}
922
923/**
5ed42115
KS
924 * Return a list of all views and display IDs that have a particular
925 * setting in their display's plugin settings.
926 *
927 * @return
928 * @code
929 * array(
930 * array($view, $display_id),
931 * array($view, $display_id),
932 * );
933 * @endcode
934 */
935function views_get_applicable_views($type) {
936 // @todo: Use a smarter flagging system so that we don't have to
937 // load every view for this.
938 $result = array();
939 $views = views_get_all_views();
940
941 foreach ($views as $view) {
942 // Skip disabled views.
943 if (!empty($view->disabled)) {
944 continue;
945 }
946
947 if (empty($view->display)) {
948 // Skip this view as it is broken.
949 vsm(t("Skipping broken view @view", array('@view' => $view->name)));
950 continue;
951 }
952
953 // Loop on array keys because something seems to muck with $view->display
954 // a bit in PHP4.
955 foreach (array_keys($view->display) as $id) {
956 $plugin = views_fetch_plugin_data('display', $view->display[$id]->display_plugin);
957 if (!empty($plugin[$type])) {
958 // This view uses hook menu. Clone it so that different handlers
959 // don't trip over each other, and add it to the list.
960 $v = $view->clone_view();
961 if ($v->set_display($id)) {
962 $result[] = array($v, $id);
963 }
964 // In PHP 4.4.7 and presumably earlier, if we do not unset $v
965 // here, we will find that it actually overwrites references
966 // possibly due to shallow copying issues.
967 unset($v);
968 }
969 }
970 }
971 return $result;
972}
973
974/**
975 * Return an array of all views as fully loaded $view objects.
976 *
977 * @param $reset
978 * If TRUE, reset the static cache forcing views to be reloaded.
979 */
980function views_get_all_views($reset = FALSE) {
29576778
EM
981 ctools_include('export');
982 return ctools_export_crud_load_all('views_view', 'views', $reset);
5ed42115
KS
983}
984
985/**
1b649ff6
DR
986 * Returns an array of all enabled views, as fully loaded $view objects.
987 */
988function views_get_enabled_views() {
989 $views = views_get_all_views();
990 return array_filter($views, 'views_view_is_enabled');
991}
992
993/**
994 * Returns an array of all disabled views, as fully loaded $view objects.
995 */
996function views_get_disabled_views() {
997 $views = views_get_all_views();
998 return array_filter($views, 'views_view_is_disabled');
999}
1000
1001/**
1002 * Returns TRUE if a view is enabled, FALSE otherwise.
1003 */
1004function views_view_is_enabled($view) {
1005 return empty($view->disabled);
1006}
1007
1008/**
1009 * Returns TRUE if a view is disabled, FALSE otherwise.
1010 */
1011function views_view_is_disabled($view) {
1012 return !empty($view->disabled);
1013}
1014
1015/**
5ed42115
KS
1016 * Get a view from the database or from default views.
1017 *
1018 * This function is just a static wrapper around views::load(). This function
1019 * isn't called 'views_load()' primarily because it might get a view
1020 * from the default views which aren't technically loaded from the database.
1021 *
1022 * @param $name
1023 * The name of the view.
1024 * @param $reset
1025 * If TRUE, reset this entry in the load cache.
1026 * @return $view
1027 * A reference to the $view object. Use $reset if you're sure you want
1028 * a fresh one.
1029 */
1030function views_get_view($name, $reset = FALSE) {
29576778
EM
1031 if ($reset) {
1032 $cache = &drupal_static('ctools_export_load_object');
1033 if (isset($cache['views_view'][$name])) {
1034 unset($cache['views_view'][$name]);
5ed42115 1035 }
5ed42115
KS
1036 }
1037
29576778
EM
1038 ctools_include('export');
1039 $view = ctools_export_crud_load('views_view', $name);
1040 if ($view) {
1041 return $view->clone_view();
1042 }
5ed42115
KS
1043}
1044
ced80ad3
EM
1045/**
1046 * Export callback to load the view subrecords, which are the displays.
1047 */
1048function views_load_display_records(&$views) {
1049 // Get vids from the views.
1050 $names = array();
1051 foreach ($views as $view) {
1052 if (empty($view->display)) {
1053 $names[$view->vid] = $view->name;
1054 }
1055 }
1056
1057 if (empty($names)) {
1058 return;
1059 }
1060
1061 foreach (view::db_objects() as $key) {
1062 $object_name = "views_$key";
1063 $result = db_query("SELECT * FROM {{$object_name}} WHERE vid IN (:vids) ORDER BY vid, position",
1064 array(':vids' => array_keys($names)));
1065
1066 foreach ($result as $data) {
1067 $object = new $object_name(FALSE);
1068 $object->load_row($data);
1069
1070 // Because it can get complicated with this much indirection,
1071 // make a shortcut reference.
1072 $location = &$views[$names[$object->vid]]->$key;
1073
1074 // If we have a basic id field, load the item onto the view based on
1075 // this ID, otherwise push it on.
1076 if (!empty($object->id)) {
1077 $location[$object->id] = $object;
1078 }
1079 else {
1080 $location[] = $object;
1081 }
1082 }
1083 }
1084}
1085
1086/**
1087 * Export CRUD callback to save a view.
1088 */
1089function views_save_view(&$view) {
1090 return $view->save();
1091}
1092
1093/**
1094 * Export CRUD callback to export a view.
1095 */
1096function views_delete_view(&$view) {
1097 return $view->delete(TRUE);
1098}
1099
1100/**
1101 * Export CRUD callback to export a view.
1102 */
1103function views_export_view(&$view, $indent = '') {
1104 return $view->export($indent);
1105}
1106
5ed42115
KS
1107// ------------------------------------------------------------------
1108// Views debug helper functions
1109
1110/**
dd50052c
KS
1111 * Provide debug output for Views. This relies on devel.module
1112 */
1113function views_debug($message) {
1114 if (module_exists('devel') && variable_get('views_devel_output', FALSE) && user_access('access devel information')) {
1115 if (is_string($message)) {
1116 $output = $message;
1117 }
1118 else {
1119 $output = var_export($message, TRUE);
1120 }
1121 if (variable_get('views_devel_region', 'footer') != 'watchdog') {
dc196b7d 1122 drupal_add_region_content(variable_get('views_devel_region', 'footer'), '<pre>' . $output . '</pre>');
dd50052c
KS
1123 }
1124 else {
1125 watchdog('views_logging', '<pre>' . $output . '</pre>');
1126 }
1127 }
1128}
1129
1130/**
1131 * Shortcut to views_debug()
1132 */
1133function vpr($message) {
1134 views_debug($message);
1135}
1136
1137/**
5ed42115
KS
1138 * Debug messages
1139 */
1140function vsm($message) {
1141 if (module_exists('devel')) {
1142 dsm($message);
1143 }
1144}
1145
1146function views_trace() {
1147 $message = '';
1148 foreach (debug_backtrace() as $item) {
1149 if (!empty($item['file']) && !in_array($item['function'], array('vsm_trace', 'vpr_trace', 'views_trace'))) {
1150 $message .= basename($item['file']) . ": " . (empty($item['class']) ? '' : ($item['class'] . '->')) . "$item[function] line $item[line]" . "\n";
1151 }
1152 }
1153 return $message;
1154}
1155
1156function vsm_trace() {
1157 vsm(views_trace());
1158}
1159
1160function vpr_trace() {
1161 dpr(views_trace());
1162}
1163
1164// ------------------------------------------------------------------
1165// Exposed widgets form
1166
1167/**
1168 * Form builder for the exposed widgets form.
1169 *
1170 * Be sure that $view and $display are references.
1171 */
1172function views_exposed_form($form, &$form_state) {
1173 // Don't show the form when batch operations are in progress.
1174 if ($batch = batch_get() && isset($batch['current_set'])) {
1175 return array(
1176 // Set the theme callback to be nothing to avoid errors in template_preprocess_views_exposed_form().
1177 '#theme' => '',
1178 );
1179 }
1180
1181 // Make sure that we validate because this form might be submitted
1182 // multiple times per page.
1183 $form_state['must_validate'] = TRUE;
1184 $view = &$form_state['view'];
1185 $display = &$form_state['display'];
1186
1187 $form_state['input'] = $view->get_exposed_input();
1188
1189 // Let form plugins know this is for exposed widgets.
1190 $form_state['exposed'] = TRUE;
1191 // Check if the form was already created
1192 if ($cache = views_exposed_form_cache($view->name, $view->current_display)) {
1193 return $cache;
1194 }
1195
1196 $form['#info'] = array();
1197
1198 if (!variable_get('clean_url', FALSE)) {
1199 $form['q'] = array(
1200 '#type' => 'hidden',
1201 '#value' => $view->get_url(),
1202 );
1203 }
1204
1205 // Go through each handler and let it generate its exposed widget.
1206 foreach ($view->display_handler->handlers as $type => $value) {
1207 foreach ($view->$type as $id => $handler) {
1208 if ($handler->can_expose() && $handler->is_exposed()) {
1209 $handler->exposed_form($form, $form_state);
1210 if ($info = $handler->exposed_info()) {
1211 $form['#info']["$type-$id"] = $info;
1212 }
1213 }
1214 }
1215 }
1216
1217 $form['submit'] = array(
1218 '#name' => '', // prevent from showing up in $_GET.
1219 '#type' => 'submit',
1220 '#value' => t('Apply'),
1221 '#id' => drupal_html_id('edit-submit-' . $view->name),
1222 );
1223
1224 $form['#action'] = url($view->get_url());
1225 $form['#theme'] = views_theme_functions('views_exposed_form', $view, $display);
1226 $form['#id'] = drupal_clean_css_identifier('views_exposed_form-' . check_plain($view->name) . '-' . check_plain($display->id));
1227// $form['#attributes']['class'] = array('views-exposed-form');
1228
1229 // If using AJAX, we need the form plugin.
1230 if ($view->use_ajax) {
dd50052c 1231 drupal_add_library('system', 'jquery.form');
5ed42115
KS
1232 }
1233 ctools_include('dependent');
1234
1235 $exposed_form_plugin = $form_state['exposed_form_plugin'];
1236 $exposed_form_plugin->exposed_form_alter($form, $form_state);
1237
1238 // Save the form
1239 views_exposed_form_cache($view->name, $view->current_display, $form);
1240
1241 return $form;
1242}
1243
1244/**
1245 * Validate handler for exposed filters
1246 */
1247function views_exposed_form_validate(&$form, &$form_state) {
1248 foreach (array('field', 'filter') as $type) {
1249 $handlers = &$form_state['view']->$type;
1250 foreach ($handlers as $key => $handler) {
1251 $handlers[$key]->exposed_validate($form, $form_state);
1252 }
1253 }
1254 $exposed_form_plugin = $form_state['exposed_form_plugin'];
1255 $exposed_form_plugin->exposed_form_validate($form, $form_state);
1256}
1257
1258/**
1259 * Submit handler for exposed filters
1260 */
1261function views_exposed_form_submit(&$form, &$form_state) {
1262 foreach (array('field', 'filter') as $type) {
1263 $handlers = &$form_state['view']->$type;
1264 foreach ($handlers as $key => $info) {
1265 $handlers[$key]->exposed_submit($form, $form_state);
1266 }
1267 }
1268 $form_state['view']->exposed_data = $form_state['values'];
1269 $form_state['view']->exposed_raw_input = array();
1270
1271
1272 $exclude = array('q', 'submit', 'form_build_id', 'form_id', 'form_token', 'exposed_form_plugin', '');
1273 $exposed_form_plugin = $form_state['exposed_form_plugin'];
1274 $exposed_form_plugin->exposed_form_submit($form, $form_state, $exclude);
ced80ad3 1275
5ed42115
KS
1276 foreach ($form_state['values'] as $key => $value) {
1277 if (!in_array($key, $exclude)) {
1278 $form_state['view']->exposed_raw_input[$key] = $value;
1279 }
1280 }
1281}
1282
1283/**
1284 * Save the Views exposed form for later use.
1285 *
1286 * @param $views_name
1287 * String. The views name.
1288 * @param $display_name
1289 * String. The current view display name.
1290 * @param $form_output
1291 * Array (optional). The form structure. Only needed when inserting the value.
1292 * @return
1293 * Array. The form structure, if any. Otherwise, return FALSE.
1294 */
1295function views_exposed_form_cache($views_name, $display_name, $form_output = NULL) {
1296 static $views_exposed;
1297
1298 // Save the form output
1299 if (!empty($form_output)) {
1300 $views_exposed[$views_name][$display_name] = $form_output;
1301 return;
1302 }
1303
1304 // Return the form output, if any
1305 return empty($views_exposed[$views_name][$display_name]) ? FALSE : $views_exposed[$views_name][$display_name];
1306}
1307
1308// ------------------------------------------------------------------
1309// Misc helpers
1310
1311/**
1312 * Build a list of theme function names for use most everywhere.
1313 */
1314function views_theme_functions($hook, $view, $display = NULL) {
1315 require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'views') . "/theme/theme.inc";
1316 return _views_theme_functions($hook, $view, $display);
1317}
1318
1319/**
1320 * Substitute current time; this works with cached queries.
1321 */
1322function views_views_query_substitutions($view) {
dd50052c 1323 global $language_content;
5ed42115
KS
1324 return array(
1325 '***CURRENT_VERSION***' => VERSION,
1326 '***CURRENT_TIME***' => REQUEST_TIME,
dd50052c 1327 '***CURRENT_LANGUAGE***' => $language_content->language,
5ed42115 1328 '***DEFAULT_LANGUAGE***' => language_default('language'),
5ed42115
KS
1329 );
1330}
1331
1332/**
1333 * Implements hook_query_TAG_alter().
1334 *
1335 * This is the hook_query_alter() for queries tagged by Views and is used to
1336 * add in substitutions from hook_views_query_substitutions().
1337 */
1338function views_query_views_alter(QueryAlterableInterface $query) {
1339 $substitutions = $query->getMetaData('views_substitutions');
1340 $tables =& $query->getTables();
1341 $where =& $query->conditions();
1342
1343 // Replaces substitions in tables.
1344 foreach ($tables as $table_name => $table_metadata) {
1345 foreach ($table_metadata['arguments'] as $replacement_key => $value) {
1346 if (isset($substitutions[$value])) {
1347 $tables[$table_name]['arguments'][$replacement_key] = $substitutions[$value];
1348 }
1349 }
1350 }
1351
1352 // Replaces substitions in filter criterias.
1353 _views_query_tag_alter_condition($query, $where, $substitutions);
1354}
1355
1356/**
1357 * Replaces the substitutions recursive foreach condition.
1358 */
1359function _views_query_tag_alter_condition(QueryAlterableInterface $query, &$conditions, $substitutions) {
1360 foreach ($conditions as $condition_id => &$condition) {
1361 if (is_numeric($condition_id)) {
1362 if (is_string($condition['field'])) {
1363 $condition['field'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['field']);
1364 }
1365 elseif (is_object($condition['field'])) {
1366 $sub_conditions =& $condition['field']->conditions();
1367 _views_query_tag_alter_condition($query, $sub_conditions, $substitutions);
1368 }
1369 // $condition['value'] is a subquery so alter the subquery recursive.
1370 // Therefore take sure to get the metadata of the main query.
1371 if (is_object($condition['value'])) {
1372 $subquery = $condition['value'];
1373 $subquery->addMetaData('views_substitutions', $query->getMetaData('views_substitutions'));
1374 views_query_views_alter($condition['value']);
1375 }
1376 elseif (isset($condition['value'])) {
1377 $condition['value'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['value']);
1378 }
1379 }
1380 }
1381}
1382
1383/**
1384 * Embed a view using a PHP snippet.
1385 *
1386 * This function is meant to be called from PHP snippets, should one wish to
1387 * embed a view in a node or something. It's meant to provide the simplest
1388 * solution and doesn't really offer a lot of options, but breaking the function
1389 * apart is pretty easy, and this provides a worthwhile guide to doing so.
1390 *
1391 * Note that this function does NOT display the title of the view. If you want
1392 * to do that, you will need to do what this function does manually, by
1393 * loading the view, getting the preview and then getting $view->get_title().
1394 *
1395 * @param $name
1396 * The name of the view to embed.
1397 * @param $display_id
1398 * The display id to embed. If unsure, use 'default', as it will always be
1399 * valid. But things like 'page' or 'block' should work here.
1400 * @param ...
1401 * Any additional parameters will be passed as arguments.
1402 */
1403function views_embed_view($name, $display_id = 'default') {
1404 $args = func_get_args();
1405 array_shift($args); // remove $name
1406 if (count($args)) {
1407 array_shift($args); // remove $display_id
1408 }
1409
1410 $view = views_get_view($name);
1411 if (!$view || !$view->access($display_id)) {
1412 return;
1413 }
1414
1415 return $view->preview($display_id, $args);
1416}
1417
1418/**
1419* Get the result of a view.
1420*
1421* @param string $name
1422* The name of the view to retrieve the data from.
1423* @param string $display_id
1424* The display id. On the edit page for the view in question, you'll find
86e0d16d 1425* a list of displays at the left side of the control area. "Master"
5ed42115
KS
1426* will be at the top of that list. Hover your cursor over the name of the
1427* display you want to use. An URL will appear in the status bar of your
1428* browser. This is usually at the bottom of the window, in the chrome.
1429* Everything after #views-tab- is the display ID, e.g. page_1.
1430 * @param ...
1431 * Any additional parameters will be passed as arguments.
1432* @return
1433* array
1434* An array containing an object for each view item.
1435*/
1436function views_get_view_result($name, $display_id = NULL) {
1437 $args = func_get_args();
1438 array_shift($args); // remove $name
1439 if (count($args)) {
1440 array_shift($args); // remove $display_id
1441 }
1442
1443 $view = views_get_view($name);
1444 if (is_object($view)) {
1445 if (is_array($args)) {
1446 $view->set_arguments($args);
1447 }
1448 if (is_string($display_id)) {
1449 $view->set_display($display_id);
1450 }
1451 else {
1452 $view->init_display();
1453 }
1454 $view->pre_execute();
1455 $view->execute();
1456 return $view->result;
1457 }
1458 else {
1459 return array();
1460 }
1461}
1462
1463/**
1464 * Export a field.
1465 */
1466function views_var_export($var, $prefix = '', $init = TRUE) {
1467 if (is_array($var)) {
1468 if (empty($var)) {
1469 $output = 'array()';
1470 }
1471 else {
1472 $output = "array(\n";
1473 foreach ($var as $key => $value) {
46bb9b7a 1474 $output .= " " . views_var_export($key, '', FALSE) . " => " . views_var_export($value, ' ', FALSE) . ",\n";
5ed42115
KS
1475 }
1476 $output .= ')';
1477 }
1478 }
1479 elseif (is_bool($var)) {
1480 $output = $var ? 'TRUE' : 'FALSE';
1481 }
1482 elseif (is_string($var) && strpos($var, "\n") !== FALSE) {
1483 // Replace line breaks in strings with a token for replacement
1484 // at the very end. This protects multi-line strings from
1485 // unintentional indentation.
1486 $var = str_replace("\n", "***BREAK***", $var);
1487 $output = var_export($var, TRUE);
1488 }
1489 else {
1490 $output = var_export($var, TRUE);
1491 }
1492
1493 if ($prefix) {
1494 $output = str_replace("\n", "\n$prefix", $output);
1495 }
1496
1497 if ($init) {
1498 $output = str_replace("***BREAK***", "\n", $output);
1499 }
1500
1501 return $output;
1502}
1503
1504/**
1505 * Implement hook_views_exportables().
1506 */
1507function views_views_exportables($op = 'list', $views = NULL, $name = 'foo') {
1508 $all_views = views_get_all_views();
1509 if ($op == 'list') {
1510
1511 foreach ($all_views as $name => $view) {
1512 // in list, $views is a list of tags.
1513 if (empty($views) || in_array($view->tag, $views)) {
1514 $return[$name] = array(
1515 'name' => check_plain($name),
1516 'desc' => check_plain($view->description),
1517 'tag' => check_plain($view->tag)
1518 );
1519 }
1520 }
1521 return $return;
1522 }
1523
1524 if ($op == 'export') {
1525 $code = "/**\n";
1526 $code .= " * Implement hook_views_default_views().\n";
1527 $code .= " */\n";
1528 $code .= "function " . $name . "_views_default_views() {\n";
1529 foreach ($views as $view => $truth) {
1530 $code .= " /*\n";
1531 $code .= " * View " . var_export($all_views[$view]->name, TRUE) . "\n";
1532 $code .= " */\n";
1533 $code .= $all_views[$view]->export(' ');
1534 $code .= ' $views[$view->name] = $view;' . "\n\n";
1535 }
1536 $code .= " return \$views;\n";
1537 $code .= "}\n";
1538
1539 return $code;
1540 }
1541}
1542
1543/**
1544 * #process callback to see if we need to check_plain() the options.
1545 *
1546 * Since FAPI is inconsistent, the #options are sanitized for you in all cases
1547 * _except_ checkboxes. We have form elements that are sometimes 'select' and
1548 * sometimes 'checkboxes', so we need decide late in the form rendering cycle
1549 * if the options need to be sanitized before they're rendered. This callback
1550 * inspects the type, and if it's still 'checkboxes', does the sanitation.
1551 */
1552function views_process_check_options($element, &$form_state) {
1553 if ($element['#type'] == 'checkboxes' || $element['#type'] == 'checkbox') {
1554 $element['#options'] = array_map('check_plain', $element['#options']);
1555 }
1556 return $element;
1557}
1558
1559/**
1560 * Trim the field down to the specified length.
1561 *
1562 * @param $alter
1563 * - max_length: Maximum lenght of the string, the rest gets truncated.
1564 * - word_boundary: Trim only on a word boundary.
1565 * - ellipsis: Trim only on a word boundary.
1566 * - html: Take sure that the html is correct.
1567 *
1568 * @param $value
1569 * The string which should be trimmed.
1570 */
1571function views_trim_text($alter, $value) {
1572 if (drupal_strlen($value) > $alter['max_length']) {
1573 $value = drupal_substr($value, 0, $alter['max_length']);
1574 // TODO: replace this with cleanstring of ctools
1575 if (!empty($alter['word_boundary'])) {
1576 $regex = "(.*)\b.+";
1577 if (function_exists('mb_ereg')) {
1578 mb_regex_encoding('UTF-8');
1579 $found = mb_ereg($regex, $value, $matches);
1580 }
1581 else {
1582 $found = preg_match("/$regex/us", $value, $matches);
1583 }
1584 if ($found) {
1585 $value = $matches[1];
1586 }
1587 }
1588 // Remove scraps of HTML entities from the end of a strings
1589 $value = rtrim(preg_replace('/(?:<(?!.+>)|&(?!.+;)).*$/us', '', $value));
1590
1591 if (!empty($alter['ellipsis'])) {
1592 $value .= '...';
1593 }
1594 }
1595 if (!empty($alter['html'])) {
1596 $value = _filter_htmlcorrector($value);
1597 }
1598
1599 return $value;
1600}
ced80ad3 1601
ce174eb6
EM
1602/**
1603 * Report to CTools that we use hook_views_api instead of hook_ctools_plugin_api()
1604 */
1605function views_ctools_plugin_api_hook_name() {
1606 return 'views_api';
1607}
1608
ced80ad3
EM
1609// Declare API compatibility on behalf of core modules:
1610
1611/**
1612 * Implements hook_views_api().
1613 *
1614 * This one is used as the base to reduce errors when updating.
1615 */
1616function views_views_api() {
1617 return array(
1618 // in your modules do *not* use views_api_version()!!!
1619 'api' => views_api_version(),
1620 'path' => drupal_get_path('module', 'views') . '/modules',
1621 );
1622}
1623
1624function aggregator_views_api() { return views_views_api(); }
1625
1626function book_views_api() { return views_views_api(); }
1627
1628function comment_views_api() { return views_views_api(); }
1629
1630function locale_views_api() { return views_views_api(); }
1631
1632function field_views_api() { return views_views_api(); }
1633
1634function filter_views_api() { return views_views_api(); }
1635
1636function node_views_api() { return views_views_api(); }
1637
1638function poll_views_api() { return views_views_api(); }
1639
1640function profile_views_api() { return views_views_api(); }
1641
1642function search_views_api() { return views_views_api(); }
1643
1644function statistics_views_api() { return views_views_api(); }
1645
1646function system_views_api() { return views_views_api(); }
1647
1648function taxonomy_views_api() { return views_views_api(); }
1649
1650function translation_views_api() { return views_views_api(); }
1651
1652function upload_views_api() { return views_views_api(); }
1653
1654function user_views_api() { return views_views_api(); }
1655
1656function contact_views_api() { return views_views_api(); }