views.module

Tracking 6.x-3.x branch
  1. drupal
    1. 5 contributions/views/views.module
    2. 6 contributions/views/views.module
    3. 7 contributions/views/views.module
    4. 8 drupal/core/modules/views/views.module

Primarily Drupal hooks and global API functions to manipulate views.

This is the main module file for Views. The main entry points into this module are views_page() and views_block(), where it handles incoming page and block requests.

Functions & methods

NameDescription
drupal_build_formViews' replacement for drupal_get_form so that we can do more with less.
views_accessDetermine if the logged in user has access to a view.
views_add_cssInclude views .css files.
views_add_jsInclude views .js files.
views_api_minimum_versionViews will not load plugins advertising a version older than this.
views_api_versionAdvertise the current views api version
views_arg_loadHelper function for menu loading. This will automatically be called in order to 'load' a views argument; primarily it will be used to perform validation.
views_array_key_plusAdds one to each key of the array.
views_blockImplementation of hook_block
views_check_permAccess callback for the views_plugin_access_perm access plugin.
views_check_rolesAccess callback for the views_plugin_access_role access plugin.
views_css_safePrepare the specified string for use as a CSS identifier.
views_debugProvide debug output for Views. This relies on devel.module
views_discover_default_viewsScan all modules for default views and rebuild the default views cache.
views_embed_viewEmbed a view using a PHP snippet.
views_exposed_formForm builder for the exposed widgets form.
views_exposed_form_cacheSave the Views exposed form for later use.
views_exposed_form_submitSubmit handler for exposed filters
views_exposed_form_validateValidate handler for exposed filters
views_fetch_dataFetch Views' data from the cache
views_fetch_plugin_dataFetch the plugin data from cache.
views_flush_cachesImplementation of hook_flush_caches().
views_formThis is the entry function. Just gets the form for the current step. The form is always assumed to be multistep, even if it has only one step (the default 'views_form_views_form' step). That way it is actually possible for modules to have a…
views_formsImplements hook_forms().
views_form_idReturns a form ID for a Views form using the name and display of the View.
views_form_submitThe basic form submit handler. Fires the hook_views_form_submit() function.
views_form_validateThe basic form validate handler. Fires the hook_views_form_validate() function.
views_form_views_formCallback for the main step of a Views form. Invoked by views_form().
views_form_views_form_submitSubmit handler for the first step of the views form. Calls any existing views_form_submit functions located on the views fields.
views_form_views_form_validateValidate handler for the first step of the views form. Calls any existing views_form_validate functions located on the views fields.
views_get_all_viewsReturn an array of all views as fully loaded $view objects.
views_get_applicable_viewsReturn a list of all views and display IDs that have a particular setting in their display's plugin settings.
views_get_current_viewFind out what, if any, current view is currently in use. Please note that this returns a reference, so be careful! You can unintentionally modify the $view object.
views_get_default_viewGet a view from the default views defined by modules.
views_get_handlerFetch a handler from the data cache.
views_get_localization_pluginLoad the current enabled localization plugin.
views_get_module_apisGet a list of modules that support the current views API.
views_get_page_viewFind out what, if any, page view is currently in use. Please note that this returns a reference, so be careful! You can unintentionally modify the $view object.
views_get_pluginGet a handler for a plugin
views_get_viewGet a view from the database or from default views.
views_get_view_resultGet the result of a view. *
views_import_accessAccess callback to determine if the user can import Views.
views_includeInclude views .inc files as necessary.
views_include_default_viewsLoad default views files on behalf of modules.
views_include_handlersLoad views files on behalf of modules.
views_initImplementation of hook_init().
views_invalidate_cacheInvalidate the views cache, forcing a rebuild on the next grab of table data.
views_language_list+ * Returns an array of language names. + * + * This is a one to one copy of locale_language_list because we can't rely on enabled locale module. + * + *
views_menuImplementation of hook_menu().
views_menu_alterImplementation of hook_menu_alter().
views_microtimeMicrotime helper function to return a float time value (php4 & php5 safe).
views_module_includeLoad views files on behalf of modules.
views_new_viewCreate an empty view to work with.
views_pagePage callback entry point; requires a view and a display id, then passes control to the display handler.
views_perm
views_preprocess_blockA theme preprocess function to automatically allow blocks with view-based block templates if called from a view.
views_preprocess_commentA theme preprocess function to automatically allow view-based node templates if called from a view.
views_preprocess_nodeA theme preprocess function to automatically allow view-based node templates if called from a view.
views_set_current_viewSet the current 'current view' that is being built/rendered so that it is easy for other modules or items in drupal_eval to identify
views_set_page_viewSet the current 'page view' that is being displayed so that it is easy for other modules or the theme to identify.
views_themeImplementation of hook_theme(). Register views theming functions.
views_theme_functionsBuild a list of theme function names for use most everywhere.
views_trace
views_trim_textTrim the field down to the specified length.
views_var_exportExport a field.
views_views_exportablesImplementation of hook_views_exportables().
views_views_query_substitutionsSubstitute current time; this works with cached queries.
views_view_has_form_elementsReturns TRUE if the passed-in view contains handlers with views form implementations, FALSE otherwise.
vprShortcut to views_debug()
vpr_trace
vsmDebug messages
vsm_trace
_views_find_module_templatesScans a directory of a module for template files.

File

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