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