/[drupal]/contributions/modules/views/views.module
ViewVC logotype

Contents of /contributions/modules/views/views.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.341 - (show annotations) (download) (as text)
Thu Sep 24 23:33:44 2009 UTC (2 months ago) by merlinofchaos
Branch: MAIN
CVS Tags: DRUPAL-6--2-7, HEAD
Branch point for: DRUPAL-6--2, DRUPAL-7--3
Changes since 1.340: +2 -3 lines
File MIME type: text/x-php
#408894 by dereine: Views AJAX incorrectly used "access content" permission.
1 <?php
2 // $Id: views.module,v 1.340 2009/09/15 22:43:42 merlinofchaos Exp $
3 /**
4 * @file
5 * Primarily Drupal hooks and global API functions to manipulate views.
6 *
7 * This is the main module file for Views. The main entry points into
8 * this module are views_page() and views_block(), where it handles
9 * incoming page and block requests.
10 */
11
12 /**
13 * Advertise the current views api version
14 */
15 function views_api_version() {
16 return 2.0;
17 }
18
19 /**
20 * Implementation of hook_theme(). Register views theming functions.
21 */
22 function views_theme() {
23 $path = drupal_get_path('module', 'views');
24 require_once "./$path/theme/theme.inc";
25
26 // Some quasi clever array merging here.
27 $base = array(
28 'file' => 'theme.inc',
29 'path' => "$path/theme",
30 );
31
32 // Our extra version of pager from pager.inc
33 $hooks['views_mini_pager'] = $base + array(
34 'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
35 'pattern' => 'views_mini_pager__',
36 );
37
38 $arguments = array(
39 'display' => array('view' => NULL),
40 'style' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
41 'row' => array('view' => NULL, 'options' => NULL, 'row' => NULL, 'field_alias' => NULL),
42 );
43
44 // Default view themes
45 $hooks['views_view_field'] = $base + array(
46 'pattern' => 'views_view_field__',
47 'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
48 );
49
50 $plugins = views_fetch_plugin_data();
51
52 // Register theme functions for all style plugins
53 foreach ($plugins as $type => $info) {
54 foreach ($info as $plugin => $def) {
55 if (isset($def['theme'])) {
56 $hooks[$def['theme']] = array(
57 'pattern' => $def['theme'] . '__',
58 'file' => $def['theme file'],
59 'path' => $def['theme path'],
60 'arguments' => $arguments[$type],
61 );
62
63 $include = './' . $def['theme path'] . '/' . $def['theme file'];
64 if (file_exists($include)) {
65 require_once $include;
66 }
67
68 if (!function_exists('theme_' . $def['theme'])) {
69 $hooks[$def['theme']]['template'] = views_css_safe($def['theme']);
70 }
71 }
72 if (isset($def['additional themes'])) {
73 foreach ($def['additional themes'] as $theme => $theme_type) {
74 if (empty($theme_type)) {
75 $theme = $theme_type;
76 $theme_type = $type;
77 }
78
79 $hooks[$theme] = array(
80 'pattern' => $theme . '__',
81 'file' => $def['theme file'],
82 'path' => $def['theme path'],
83 'arguments' => $arguments[$theme_type],
84 );
85
86 if (!function_exists('theme_' . $theme)) {
87 $hooks[$theme]['template'] = views_css_safe($theme);
88 }
89 }
90 }
91 }
92 }
93
94 $hooks['views_exposed_form'] = $base + array(
95 'template' => 'views-exposed-form',
96 'pattern' => 'views_exposed_form__',
97 'arguments' => array('form' => NULL),
98 );
99
100 $hooks['views_more'] = $base + array(
101 'template' => 'views-more',
102 'pattern' => 'views_more__',
103 'arguments' => array('more_url' => NULL, 'link_text' => 'more'),
104 );
105 return $hooks;
106 }
107
108 /**
109 * A theme preprocess function to automatically allow view-based node
110 * templates if called from a view.
111 *
112 * The 'modules/node.views.inc' file is a better place for this, but
113 * we haven't got a chance to load that file before Drupal builds the
114 * node portion of the theme registry.
115 */
116 function views_preprocess_node(&$vars) {
117 // The 'view' attribute of the node is added in template_preprocess_views_view_row_node()
118 if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
119 $vars['view'] = &$vars['node']->view;
120 $vars['template_files'][] = 'node-view-' . $vars['node']->view->name;
121 if(!empty($vars['node']->view->current_display)) {
122 $vars['template_files'][] = 'node-view-' . $vars['node']->view->name . '-' . $vars['node']->view->current_display;
123 }
124 }
125 }
126
127 /**
128 * A theme preprocess function to automatically allow view-based node
129 * templates if called from a view.
130 */
131 function views_preprocess_comment(&$vars) {
132 // The 'view' attribute of the node is added in template_preprocess_views_view_row_comment()
133 if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
134 $vars['view'] = &$vars['node']->view;
135 $vars['template_files'][] = 'comment-view-' . $vars['node']->view->name;
136 if(!empty($vars['node']->view->current_display)) {
137 $vars['template_files'][] = 'comment-view-' . $vars['node']->view->name . '-' . $vars['node']->view->current_display;
138 }
139 }
140 }
141
142 /*
143 * Implementation of hook_perm()
144 */
145 function views_perm() {
146 return array('access all views', 'administer views');
147 }
148
149 /**
150 * Implementation of hook_menu().
151 */
152 function views_menu() {
153 // Any event which causes a menu_rebuild could potentially mean that the
154 // Views data is updated -- module changes, profile changes, etc.
155 views_invalidate_cache();
156 $items = array();
157 $items['views/ajax'] = array(
158 'title' => 'Views',
159 'page callback' => 'views_ajax',
160 'access callback' => TRUE,
161 'description' => 'Ajax callback for view loading.',
162 'file' => 'includes/ajax.inc',
163 'type' => MENU_CALLBACK,
164 );
165 // Path is not admin/build/views due to menu complications with the wildcards from
166 // the generic ajax callback.
167 $items['admin/views/ajax/autocomplete/user'] = array(
168 'page callback' => 'views_ajax_autocomplete_user',
169 'access callback' => 'user_access',
170 'access arguments' => array('access content'),
171 'file' => 'includes/ajax.inc',
172 'type' => MENU_CALLBACK,
173 );
174 return $items;
175 }
176
177 /**
178 * Implementation of hook_menu_alter().
179 */
180 function views_menu_alter(&$callbacks) {
181 $our_paths = array();
182 $views = views_get_applicable_views('uses hook menu');
183 foreach ($views as $data) {
184 list($view, $display_id) = $data;
185 $result = $view->execute_hook_menu($display_id);
186 if (is_array($result)) {
187 // The menu system doesn't support having two otherwise
188 // identical paths with different placeholders. So we
189 // want to remove the existing items from the menu whose
190 // paths would conflict with ours.
191
192 // First, we must find any existing menu items that may
193 // conflict. We use a regular expression because we don't
194 // know what placeholders they might use. Note that we
195 // first construct the regex itself by replacing %views_arg
196 // in the display path, then we use this constructed regex
197 // (which will be something like '#^(foo/%[^/]*/bar)$#') to
198 // search through the existing paths.
199 $regex = '#^(' . preg_replace('#%views_arg#', '%[^/]*', implode('|', array_keys($result))) . ')$#';
200 $matches = preg_grep($regex, array_keys($callbacks));
201
202 // Remove any conflicting items that were found.
203 foreach ($matches as $path) {
204 // Don't remove the paths we just added!
205 if (!isset($our_paths[$path])) {
206 unset($callbacks[$path]);
207 }
208 }
209 foreach ($result as $path => $item) {
210 if (!isset($callbacks[$path])) {
211 // Add a new item, possibly replacing (and thus effectively
212 // overriding) one that we removed above.
213 $callbacks[$path] = $item;
214 }
215 else {
216 // This item already exists, so it must be one that we added.
217 // We change the various callback arguments to pass an array
218 // of possible display IDs instead of a single ID.
219 $callbacks[$path]['page arguments'][1] = (array)$callbacks[$path]['page arguments'][1];
220 $callbacks[$path]['page arguments'][1][] = $display_id;
221 $callbacks[$path]['access arguments'][] = $item['access arguments'][0];
222 $callbacks[$path]['load arguments'][1] = (array)$callbacks[$path]['load arguments'][1];
223 $callbacks[$path]['load arguments'][1][] = $display_id;
224 }
225 $our_paths[$path] = TRUE;
226 }
227 }
228 }
229
230 // Save memory: Destroy those views.
231 foreach ($views as $data) {
232 list($view, $display_id) = $data;
233 $view->destroy();
234 }
235 }
236
237 /**
238 * Helper function for menu loading. This will automatically be
239 * called in order to 'load' a views argument; primarily it
240 * will be used to perform validation.
241 *
242 * @param $value
243 * The actual value passed.
244 * @param $name
245 * The name of the view. This needs to be specified in the 'load function'
246 * of the menu entry.
247 * @param $index
248 * The menu argument index. This counts from 1.
249 */
250 function views_arg_load($value, $name, $display_id, $index) {
251 if ($view = views_get_view($name)) {
252 $view->set_display($display_id);
253 $view->init_handlers();
254
255 $ids = array_keys($view->argument);
256
257 $indexes = array();
258 $path = explode('/', $view->get_path());
259
260 foreach ($path as $id => $piece) {
261 if ($piece == '%' && !empty($ids)) {
262 $indexes[$id] = array_shift($ids);
263 }
264 }
265
266 if (isset($indexes[$index])) {
267 if (isset($view->argument[$indexes[$index]])) {
268 $arg = $view->argument[$indexes[$index]]->validate_argument($value) ? $value : FALSE;
269 $view->destroy();
270 return $arg;
271 }
272 }
273 $view->destroy();
274 }
275 }
276
277 /**
278 * Page callback entry point; requires a view and a display id, then
279 * passes control to the display handler.
280 */
281 function views_page() {
282 $args = func_get_args();
283 $name = array_shift($args);
284 $display_id = array_shift($args);
285
286 // Load the view
287 if ($view = views_get_view($name)) {
288 return $view->execute_display($display_id, $args);
289 }
290
291 // Fallback; if we get here no view was found or handler was not valid.
292 return drupal_not_found();
293 }
294
295 /**
296 * Implementation of hook_block
297 */
298 function views_block($op = 'list', $delta = 0, $edit = array()) {
299 switch ($op) {
300 case 'list':
301 $items = array();
302 $views = views_get_all_views();
303 foreach ($views as $view) {
304 // disabled views get nothing.
305 if (!empty($view->disabled)) {
306 continue;
307 }
308
309 $view->init_display();
310 foreach ($view->display as $display_id => $display) {
311
312 if (isset($display->handler) && !empty($display->handler->definition['uses hook block'])) {
313 $result = $display->handler->execute_hook_block();
314 if (is_array($result)) {
315 $items = array_merge($items, $result);
316 }
317 }
318
319 if (isset($display->handler) && $display->handler->get_option('exposed_block')) {
320 $result = $display->handler->get_special_blocks();
321 if (is_array($result)) {
322 $items = array_merge($items, $result);
323 }
324 }
325 }
326 }
327
328 // block.module has a delta length limit of 32, but our deltas can
329 // unfortunately be longer because view names can be 32 and display IDs
330 // can also be 32. So for very long deltas, change to md5 hashes.
331 $hashes = array();
332
333 // get the keys because we're modifying the array and we don't want to
334 // confuse PHP too much.
335 $keys = array_keys($items);
336 foreach ($keys as $delta) {
337 if (strlen($delta) >= 32) {
338 $hash = md5($delta);
339 $hashes[$hash] = $delta;
340 $items[$hash] = $items[$delta];
341 unset($items[$delta]);
342 }
343 }
344
345 variable_set('views_block_hashes', $hashes);
346 // Save memory: Destroy those views.
347 foreach ($views as $view) {
348 $view->destroy();
349 }
350
351 return $items;
352 case 'view':
353 $start = views_microtime();
354 // if this is 32, this should be an md5 hash.
355 if (strlen($delta) == 32) {
356 $hashes = variable_get('views_block_hashes', array());
357 if (!empty($hashes[$delta])) {
358 $delta = $hashes[$delta];
359 }
360 }
361
362 // This indicates it's a special one.
363 if (substr($delta, 0, 1) == '-') {
364 list($nothing, $type, $name, $display_id) = explode('-', $delta);
365 // Put the - back on.
366 $type = '-' . $type;
367 if ($view = views_get_view($name)) {
368 if ($view->access($display_id)) {
369 $view->set_display($display_id);
370 if (isset($view->display_handler)) {
371 $output = $view->display_handler->view_special_blocks($type);
372 $view->destroy();
373 return $output;
374 }
375 }
376 $view->destroy();
377 }
378 }
379
380 list($name, $display_id) = explode('-', $delta);
381 // Load the view
382 if ($view = views_get_view($name)) {
383 if ($view->access($display_id)) {
384 $output = $view->execute_display($display_id);
385 vpr("Block $view->name execute time: " . (views_microtime() - $start) * 1000 . "ms");
386 $view->destroy();
387 return $output;
388 }
389 $view->destroy();
390 }
391 break;
392 }
393 }
394
395 /**
396 * Implementation of hook_flush_caches().
397 */
398 function views_flush_caches() {
399 return array('cache_views', 'cache_views_data');
400 }
401
402 /**
403 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
404 */
405 function views_invalidate_cache() {
406 cache_clear_all('*', 'cache_views', true);
407 }
408
409 /**
410 * Determine if the logged in user has access to a view.
411 *
412 * This function should only be called from a menu hook or some other
413 * embedded source. Each argument is the result of a call to
414 * views_plugin_access::get_access_callback() which is then used
415 * to determine if that display is accessible. If *any* argument
416 * is accessible, then the view is accessible.
417 */
418 function views_access() {
419 if (user_access('access all views')) {
420 return TRUE;
421 }
422
423 $args = func_get_args();
424 foreach ($args as $arg) {
425 if ($arg === TRUE) {
426 return TRUE;
427 }
428
429 if (!is_array($arg)) {
430 continue;
431 }
432
433 list($callback, $arguments) = $arg;
434 if (function_exists($callback) && call_user_func_array($callback, $arguments)) {
435 return TRUE;
436 }
437 }
438
439 return FALSE;
440 }
441
442 /**
443 * Access callback to determine if the logged in user has any of the
444 * requested roles.
445 *
446 * This must be in views.module as it is called by menu access callback
447 * and can be called often.
448 */
449 function views_check_roles($rids) {
450 global $user;
451 $roles = array_keys($user->roles);
452 $roles[] = $user->uid ? DRUPAL_AUTHENTICATED_RID : DRUPAL_ANONYMOUS_RID;
453 return array_intersect(array_filter($rids), $roles);
454 }
455 // ------------------------------------------------------------------
456 // Functions to help identify views that are running or ran
457
458 /**
459 * Set the current 'page view' that is being displayed so that it is easy
460 * for other modules or the theme to identify.
461 */
462 function &views_set_page_view($view = NULL) {
463 static $cache = NULL;
464 if (isset($view)) {
465 $cache = $view;
466 }
467
468 return $cache;
469 }
470
471 /**
472 * Find out what, if any, page view is currently in use. Please note that
473 * this returns a reference, so be careful! You can unintentionally modify the
474 * $view object.
475 */
476 function &views_get_page_view() {
477 return views_set_page_view();
478 }
479
480 /**
481 * Set the current 'current view' that is being built/rendered so that it is
482 * easy for other modules or items in drupal_eval to identify
483 */
484 function &views_set_current_view($view = NULL) {
485 static $cache = NULL;
486 if (isset($view)) {
487 $cache = $view;
488 }
489
490 return $cache;
491 }
492
493 /**
494 * Find out what, if any, current view is currently in use. Please note that
495 * this returns a reference, so be careful! You can unintentionally modify the
496 * $view object.
497 */
498 function &views_get_current_view() {
499 return views_set_current_view();
500 }
501
502 // ------------------------------------------------------------------
503 // Include file helpers
504
505 /**
506 * Include views .inc files as necessary.
507 */
508 function views_include($file) {
509 static $used = array();
510 if (!isset($used[$file])) {
511 require_once './' . drupal_get_path('module', 'views') . "/includes/$file.inc";
512 }
513
514 $used[$file] = TRUE;
515 }
516
517 /**
518 * Load views files on behalf of modules.
519 */
520 function views_module_include($file) {
521 foreach (views_get_module_apis() as $module => $info) {
522 if (file_exists("./$info[path]/$module.$file")) {
523 require_once "./$info[path]/$module.$file";
524 }
525 }
526 }
527
528 /**
529 * Get a list of modules that support the current views API.
530 */
531 function views_get_module_apis() {
532 static $cache = NULL;
533 if (!isset($cache)) {
534 $cache = array();
535 foreach (module_implements('views_api') as $module) {
536 $function = $module . '_views_api';
537 $info = $function();
538 if (isset($info['api']) && $info['api'] == 2.000) {
539 if (!isset($info['path'])) {
540 $info['path'] = drupal_get_path('module', $module);
541 }
542 $cache[$module] = $info;
543 }
544 }
545 }
546
547 return $cache;
548 }
549
550 /**
551 * Include views .css files.
552 */
553 function views_add_css($file) {
554 // We set preprocess to FALSE because we are adding the files conditionally,
555 // and we don't want to generate duplicate cache files.
556 // TODO: at some point investigate adding some files unconditionally and
557 // allowing preprocess.
558 drupal_add_css(drupal_get_path('module', 'views') . "/css/$file.css", 'module', 'all', FALSE);
559 }
560
561 /**
562 * Include views .js files.
563 */
564 function views_add_js($file) {
565 // If javascript has been disabled by the user, never add js files.
566 if (variable_get('views_no_javascript', FALSE)) {
567 return;
568 }
569
570 static $base = TRUE;
571 if ($base) {
572 drupal_add_js(drupal_get_path('module', 'views') . "/js/base.js");
573 $base = FALSE;
574 }
575 drupal_add_js(drupal_get_path('module', 'views') . "/js/$file.js");
576 }
577
578 /**
579 * Load views files on behalf of modules.
580 */
581 function views_include_handlers() {
582 static $finished = FALSE;
583 // Ensure this only gets run once.
584 if ($finished) {
585 return;
586 }
587
588 views_include('base');
589 views_include('handlers');
590 views_include('cache');
591 views_include('plugins');
592 _views_include_handlers();
593 $finished = TRUE;
594 }
595
596 /**
597 * Load default views files on behalf of modules.
598 */
599 function views_include_default_views() {
600 static $finished = FALSE;
601 // Ensure this only gets run once.
602 if ($finished) {
603 return;
604 }
605
606 // Default views hooks may be in the normal handler file,
607 // or in a separate views_default file at the discretion of
608 // the module author.
609 views_include_handlers();
610
611 _views_include_default_views();
612 $finished = TRUE;
613 }
614
615 // -----------------------------------------------------------------------
616 // Views handler functions
617
618 /**
619 * Fetch a handler from the data cache.
620 *
621 * @param $table
622 * The name of the table this handler is from.
623 * @param $field
624 * The name of the field this handler is from.
625 * @param $key
626 * The type of handler. i.e, sort, field, argument, filter, relationship
627 *
628 * @return
629 * An instance of a handler object. May be views_handler_broken.
630 */
631 function views_get_handler($table, $field, $key) {
632 $data = views_fetch_data($table);
633 if (isset($data[$field][$key])) {
634 // Set up a default handler:
635 if (empty($data[$field][$key]['handler'])) {
636 $data[$field][$key]['handler'] = 'views_handler_' . $key;
637 }
638 return _views_prepare_handler($data[$field][$key], $data, $field);
639 }
640 // DEBUG -- identify missing handlers
641 vpr("Missing handler: $table $field $key");
642 $broken = array(
643 'title' => t('Broken handler @table.@field', array('@table' => $table, '@field' => $field)),
644 'handler' => 'views_handler_' . $key . '_broken',
645 'table' => $table,
646 'field' => $field,
647 );
648 return _views_create_handler($broken);
649 }
650
651 /**
652 * Fetch Views' data from the cache
653 */
654 function views_fetch_data($table = NULL) {
655 views_include('cache');
656 return _views_fetch_data($table);
657 }
658
659 // -----------------------------------------------------------------------
660 // Views plugin functions
661
662 /**
663 * Fetch the plugin data from cache.
664 */
665 function views_fetch_plugin_data($type = NULL, $plugin = NULL) {
666 views_include('cache');
667 return _views_fetch_plugin_data($type, $plugin);
668 }
669
670 /**
671 * Get a handler for a plugin
672 */
673 function views_get_plugin($type, $plugin) {
674 $definition = views_fetch_plugin_data($type, $plugin);
675 if (!empty($definition)) {
676 return _views_create_handler($definition, $type);
677 }
678 }
679
680 // -----------------------------------------------------------------------
681 // Views database functions
682
683 /**
684 * Get a view from the default views defined by modules.
685 *
686 * Default views are cached per-language. This function will rescan the
687 * default_views hook if necessary.
688 *
689 * @param $view_name
690 * The name of the view to load.
691 * @return
692 * A view object or NULL if it is not available.
693 */
694 function &views_get_default_view($view_name) {
695 $null = NULL;
696 $cache = views_discover_default_views();
697
698 if (isset($cache[$view_name])) {
699 return $cache[$view_name];
700 }
701 return $null;
702 }
703
704 /**
705 * Create an empty view to work with.
706 *
707 * @return
708 * A fully formed, empty $view object. This object must be populated before
709 * it can be successfully saved.
710 */
711 function views_new_view() {
712 views_include('view');
713 $view = new view();
714 $view->vid = 'new';
715 $view->add_display('default');
716
717 return $view;
718 }
719
720 /**
721 * Scan all modules for default views and rebuild the default views cache.
722 *
723 * @return An associative array of all known default views.
724 */
725 function views_discover_default_views() {
726 static $cache = array();
727
728 if (empty($cache)) {
729 views_include('cache');
730 $cache = _views_discover_default_views();
731 }
732 return $cache;
733 }
734
735 /**
736 * Return a list of all views and display IDs that have a particular
737 * setting in their display's plugin settings.
738 *
739 * @return
740 * @code
741 * array(
742 * array($view, $display_id),
743 * array($view, $display_id),
744 * );
745 * @endcode
746 */
747 function views_get_applicable_views($type) {
748 // @todo: Use a smarter flagging system so that we don't have to
749 // load every view for this.
750 $result = array();
751 $views = views_get_all_views();
752
753 foreach ($views as $view) {
754 // Skip disabled views.
755 if (!empty($view->disabled)) {
756 continue;
757 }
758
759 if (empty($view->display)) {
760 // Skip this view as it is broken.
761 vsm(t("Skipping broken view @view", array('@view' => $view->name)));
762 continue;
763 }
764
765 // Loop on array keys because something seems to muck with $view->display
766 // a bit in PHP4.
767 foreach (array_keys($view->display) as $id) {
768 $plugin = views_fetch_plugin_data('display', $view->display[$id]->display_plugin);
769 if (!empty($plugin[$type])) {
770 // This view uses hook menu. Clone it so that different handlers
771 // don't trip over each other, and add it to the list.
772 $v = $view->clone_view();
773 if ($v->set_display($id)) {
774 $result[] = array($v, $id);
775 }
776 // In PHP 4.4.7 and presumably earlier, if we do not unset $v
777 // here, we will find that it actually overwrites references
778 // possibly due to shallow copying issues.
779 unset($v);
780 }
781 }
782 }
783 return $result;
784 }
785
786 /**
787 * Return an array of all views as fully loaded $view objects.
788 *
789 * @param $reset
790 * If TRUE, reset the static cache forcing views to be reloaded.
791 */
792 function views_get_all_views($reset = FALSE) {
793 static $views = array();
794
795 if (empty($views) || $reset) {
796 $views = array();
797
798 // First, get all applicable views.
799 views_include('view');
800 $views = view::load_views();
801
802 // Get all default views.
803 $status = variable_get('views_defaults', array());
804
805 foreach (views_discover_default_views() as $view) {
806 // Determine if default view is enabled or disabled.
807 if (isset($status[$view->name])) {
808 $view->disabled = $status[$view->name];
809 }
810
811 // If overridden, also say so.
812 if (!empty($views[$view->name])) {
813 $views[$view->name]->type = t('Overridden');
814 }
815 else {
816 $view->type = t('Default');
817 $views[$view->name] = $view;
818 }
819 }
820
821 }
822 return $views;
823 }
824
825 /**
826 * Get a view from the database or from default views.
827 *
828 * This function is just a static wrapper around views::load(). This function
829 * isn't called 'views_load()' primarily because it might get a view
830 * from the default views which aren't technically loaded from the database.
831 *
832 * @param $name
833 * The name of the view.
834 * @param $reset
835 * If TRUE, reset this entry in the load cache.
836 * @return $view
837 * A reference to the $view object. Use $reset if you're sure you want
838 * a fresh one.
839 */
840 function views_get_view($name, $reset = FALSE) {
841 views_include('view');
842 $view = view::load($name, $reset);
843 $default_view = views_get_default_view($name);
844
845 if (empty($view) && empty($default_view)) {
846 return;
847 }
848 elseif (empty($view) && !empty($default_view)) {
849 $default_view->type = t('Default');
850 return $default_view->clone_view();
851 }
852 elseif (!empty($view) && !empty($default_view)) {
853 $view->type = t('Overridden');
854 }
855
856 return $view->clone_view();
857 }
858
859
860 // ------------------------------------------------------------------
861 // Views debug helper functions
862
863 /**
864 * Provide debug output for Views. This relies on devel.module
865 */
866 function views_debug($message) {
867 if (module_exists('devel') && variable_get('views_devel_output', FALSE) && user_access('access devel information')) {
868 if (is_string($message)) {
869 $output = $message;
870 }
871 else {
872 $output = var_export($message, TRUE);
873 }
874 if (variable_get('views_devel_region', 'footer') != 'watchdog') {
875 drupal_set_content(variable_get('views_devel_region', 'footer'), '<pre>' . $output . '</pre>');
876 }
877 else {
878 watchdog('views_logging', '<pre>' . $output . '</pre>');
879 }
880 }
881 }
882
883 /**
884 * Shortcut to views_debug()
885 */
886 function vpr($message) {
887 views_debug($message);
888 }
889
890 /**
891 * Debug messages
892 */
893 function vsm($message) {
894 if (module_exists('devel')) {
895 dsm($message);
896 }
897 }
898
899 function views_trace() {
900 $message = '';
901 foreach (debug_backtrace() as $item) {
902 if (!empty($item['file']) && !in_array($item['function'], array('vsm_trace', 'vpr_trace', 'views_trace'))) {
903 $message .= basename($item['file']) . ": " . (empty($item['class']) ? '' : ($item['class'] . '->')) . "$item[function] line $item[line]" . "\n";
904 }
905 }
906 return $message;
907 }
908
909 function vsm_trace() {
910 vsm(views_trace());
911 }
912
913 function vpr_trace() {
914 dpr(views_trace());
915 }
916
917 // ------------------------------------------------------------------
918 // Exposed widgets form
919
920 /**
921 * Form builder for the exposed widgets form.
922 *
923 * Be sure that $view and $display are references.
924 */
925 function views_exposed_form(&$form_state) {
926 // Don't show the form when batch operations are in progress.
927 $batch =& batch_get();
928 if (!empty($batch)) {
929 return array(
930 // Set the theme callback to be nothing to avoid errors in template_preprocess_views_exposed_form().
931 '#theme' => '',
932 );
933 }
934
935 // Make sure that we validate because this form might be submitted
936 // multiple times per page.
937 $form_state['must_validate'] = TRUE;
938 $view = &$form_state['view'];
939 $display = &$form_state['display'];
940
941 $form_state['input'] = $view->get_exposed_input();
942
943 // Let form plugins know this is for exposed widgets.
944 $form_state['exposed'] = TRUE;
945 // Check if the form was already created
946 if ($cache = views_exposed_form_cache($view->name, $view->current_display)) {
947 return $cache;
948 }
949
950 $form['#info'] = array();
951
952 if (!variable_get('clean_url', FALSE)) {
953 $form['q'] = array(
954 '#type' => 'hidden',
955 '#value' => $view->get_url(),
956 );
957 }
958
959 // Go through each filter and let it generate its info.
960 foreach ($view->filter as $id => $filter) {
961 $view->filter[$id]->exposed_form($form, $form_state);
962 if ($info = $view->filter[$id]->exposed_info()) {
963 $form['#info']['filter-' . $id] = $info;
964 }
965 }
966
967 // @todo deal with exposed sorts
968
969 $form['submit'] = array(
970 '#name' => '', // prevent from showing up in $_GET.
971 '#type' => 'submit',
972 '#value' => t('Apply'),
973 '#id' => form_clean_id('edit-submit-' . $view->name),
974 );
975
976 $form['#action'] = url($view->get_url());
977 $form['#theme'] = views_theme_functions('views_exposed_form', $view, $display);
978 $form['#id'] = views_css_safe('views_exposed_form-' . check_plain($view->name) . '-' . check_plain($display->id));
979 // $form['#attributes']['class'] = array('views-exposed-form');
980
981 // If using AJAX, we need the form plugin.
982 if ($view->use_ajax) {
983 drupal_add_js('misc/jquery.form.js');
984 }
985 views_add_js('dependent');
986
987 // Save the form
988 views_exposed_form_cache($view->name, $view->current_display, $form);
989
990 return $form;
991 }
992
993 /**
994 * Validate handler for exposed filters
995 */
996 function views_exposed_form_validate(&$form, &$form_state) {
997 foreach (array('field', 'filter') as $type) {
998 $handlers = &$form_state['view']->$type;
999 foreach ($handlers as $key => $handler) {
1000 $handlers[$key]->exposed_validate($form, $form_state);
1001 }
1002 }
1003 }
1004
1005 /**
1006 * Submit handler for exposed filters
1007 */
1008 function views_exposed_form_submit(&$form, &$form_state) {
1009 foreach (array('field', 'filter') as $type) {
1010 $handlers = &$form_state['view']->$type;
1011 foreach ($handlers as $key => $info) {
1012 $handlers[$key]->exposed_submit($form, $form_state);
1013 }
1014 }
1015 $form_state['view']->exposed_data = $form_state['values'];
1016 $form_state['view']->exposed_raw_input = array();
1017
1018 foreach ($form_state['values'] as $key => $value) {
1019 if (!in_array($key, array('q', 'submit', 'form_build_id', 'form_id', 'form_token', ''))) {
1020 $form_state['view']->exposed_raw_input[$key] = $value;
1021 }
1022 }
1023 }
1024
1025 /**
1026 * Save the Views exposed form for later use.
1027 *
1028 * @param $views_name
1029 * String. The views name.
1030 * @param $display_name
1031 * String. The current view display name.
1032 * @param $form_output
1033 * Array (optional). The form structure. Only needed when inserting the value.
1034 * @return
1035 * Array. The form structure, if any. Otherwise, return FALSE.
1036 */
1037 function views_exposed_form_cache($views_name, $display_name, $form_output = NULL) {
1038 static $views_exposed;
1039
1040 // Save the form output
1041 if (!empty($form_output)) {
1042 $views_exposed[$views_name][$display_name] = $form_output;
1043 return;
1044 }
1045
1046 // Return the form output, if any
1047 return empty($views_exposed[$views_name][$display_name]) ? FALSE : $views_exposed[$views_name][$display_name];
1048 }
1049
1050 // ------------------------------------------------------------------
1051 // Misc helpers
1052
1053 /**
1054 * Build a list of theme function names for use most everywhere.
1055 */
1056 function views_theme_functions($hook, $view, $display = NULL) {
1057 require_once './' . drupal_get_path('module', 'views') . "/theme/theme.inc";
1058 return _views_theme_functions($hook, $view, $display);
1059 }
1060
1061 /**
1062 * Views' replacement for drupal_get_form so that we can do more with
1063 * less.
1064 *
1065 * Items that can be set on the form_state include:
1066 * - input: The source of input. If unset this will be $_POST.
1067 * - no_redirect: Absolutely do not redirect the form even if instructed
1068 * to do so.
1069 * - rerender: If no_redirect is set and the form was successfully submitted,
1070 * rerender the form. Otherwise it will just return.
1071 *
1072 */
1073 function drupal_build_form($form_id, &$form_state) {
1074 views_include('form');
1075 return _drupal_build_form($form_id, $form_state);
1076 }
1077
1078 /**
1079 * Substitute current time; this works with cached queries.
1080 */
1081 function views_views_query_substitutions($view) {
1082 global $language;
1083 return array(
1084 '***CURRENT_VERSION***' => VERSION,
1085 '***CURRENT_TIME***' => time(),
1086 '***CURRENT_LANGUAGE***' => $language->language,
1087 '***DEFAULT_LANGUAGE***' => language_default('language'),
1088 '***NO_LANGUAGE***' => '',
1089 );
1090 }
1091
1092 /**
1093 * Embed a view using a PHP snippet.
1094 *
1095 * This function is meant to be called from PHP snippets, should one wish to
1096 * embed a view in a node or something. It's meant to provide the simplest
1097 * solution and doesn't really offer a lot of options, but breaking the function
1098 * apart is pretty easy, and this provides a worthwhile guide to doing so.
1099 *
1100 * Note that this function does NOT display the title of the view. If you want
1101 * to do that, you will need to do what this function does manually, by
1102 * loading the view, getting the preview and then getting $view->get_title().
1103 *
1104 * @param $name
1105 * The name of the view to embed.
1106 * @param $display_id
1107 * The display id to embed. If unsure, use 'default', as it will always be
1108 * valid. But things like 'page' or 'block' should work here.
1109 * @param ...
1110 * Any additional parameters will be passed as arguments.
1111 */
1112 function views_embed_view($name, $display_id = 'default') {
1113 $args = func_get_args();
1114 array_shift($args); // remove $name
1115 if (count($args)) {
1116 array_shift($args); // remove $display_id
1117 }
1118
1119 $view = views_get_view($name);
1120 if (!$view || !$view->access($display_id)) {
1121 return;
1122 }
1123
1124 return $view->preview($display_id, $args);
1125 }
1126
1127 /**
1128 * Export a field.
1129 */
1130 function views_var_export($var, $prefix = '', $init = TRUE) {
1131 if (is_array($var)) {
1132 if (empty($var)) {
1133 $output = 'array()';
1134 }
1135 else {
1136 $output = "array(\n";
1137 foreach ($var as $key => $value) {
1138 $output .= " '$key' => " . views_var_export($value, ' ', FALSE) . ",\n";
1139 }
1140 $output .= ')';
1141 }
1142 }
1143 else if (is_bool($var)) {
1144 $output = $var ? 'TRUE' : 'FALSE';
1145 }
1146 else if (is_string($var) && strpos($var, "\n") !== FALSE) {
1147 // Replace line breaks in strings with a token for replacement
1148 // at the very end. This protects multi-line strings from
1149 // unintentional indentation.
1150 $var = str_replace("\n", "***BREAK***", $var);
1151 $output = var_export($var, TRUE);
1152 }
1153 else {
1154 $output = var_export($var, TRUE);
1155 }
1156
1157 if ($prefix) {
1158 $output = str_replace("\n", "\n$prefix", $output);
1159 }
1160
1161 if ($init) {
1162 $output = str_replace("***BREAK***", "\n", $output);
1163 }
1164
1165 return $output;
1166 }
1167
1168 /**
1169 * Prepare the specified string for use as a CSS identifier.
1170 */
1171 function views_css_safe($string) {
1172 return str_replace('_', '-', $string);
1173 }
1174
1175 /**
1176 * Implementation of hook_views_exportables().
1177 */
1178 function views_views_exportables($op = 'list', $views = NULL, $name = 'foo') {
1179 $all_views = views_get_all_views();
1180 if ($op == 'list') {
1181
1182 foreach ($all_views as $name => $view) {
1183 // in list, $views is a list of tags.
1184 if (empty($views) || in_array($view->tag, $views)) {
1185 $return[$name] = array(
1186 'name' => check_plain($name),
1187 'desc' => check_plain($view->description),
1188 'tag' => check_plain($view->tag)
1189 );
1190 }
1191 }
1192 return $return;
1193 }
1194
1195 if ($op == 'export') {
1196 $code = "/**\n";
1197 $code .= " * Implementation of hook_views_default_views().\n";
1198 $code .= " */\n";
1199 $code .= "function " . $name . "_views_default_views() {\n";
1200 foreach ($views as $view => $truth) {
1201 $code .= " /*\n";
1202 $code .= " * View ". var_export($all_views[$view]->name, TRUE) ."\n";
1203 $code .= " */\n";
1204 $code .= $all_views[$view]->export(' ');
1205 $code .= ' $views[$view->name] = $view;' . "\n\n";
1206 }
1207 $code .= " return \$views;\n";
1208 $code .= "}\n";
1209
1210 return $code;
1211 }
1212 }
1213
1214 /**
1215 * Microtime helper function to return a float time value (php4 & php5 safe).
1216 */
1217 function views_microtime() {
1218 list($usec, $sec) = explode(' ', microtime());
1219 return (float)$sec + (float)$usec;
1220 }

  ViewVC Help
Powered by ViewVC 1.1.2