Skip to content
views.module 58.8 KiB
Newer Older
Earl Miles's avatar
Earl Miles committed
// $Name$

// ---------------------------------------------------------------------------
// Drupal Hooks

 * Implementation of hook_help()
 */
function views_help($section) {
  switch ($section) {
    case 'admin/help#views':
      return t('The views module creates customized views of node lists. You may need to activate the Views UI module to get to the user administration pages.');
 * Implementation of hook_menu()
 */
function views_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    // Invalidate the views cache to ensure that views data gets rebuilt.
    // This is the best way to tell that module configuration has changed.
    if (arg(0) == 'admin' && arg(2) == 'modules') {
    
    views_menu_standard_items($items);
  }
  else {
    views_menu_inline_items($items);
  }
  return $items;
}

/**
 * Add the menu items for all non-inline views to the menu
 */
function views_menu_standard_items(&$items) {
  $result = db_query("SELECT * FROM {view_view} WHERE page = 1");
  while ($view = db_fetch_object($result)) {
    // This happens before the next check; even if it's put off for later
    // it is still used.
    $used[$view->name] = true;
    // Skip views with inline arguments.
    if ($view->url{0} == '$' || strpos($view->url, '/$') !== FALSE) {
      continue;
    }

    // unpack the array
    $view->access = ($view->access ? explode(', ', $view->access) : array());

    _views_create_menu_item($items, $view, $view->url);
  }
  $default_views = _views_get_default_views();
  $views_status = variable_get('views_defaults', array());
Earl Miles's avatar
Earl Miles committed

  // Process default views
  foreach ($default_views as $name => $view) {
    if ($view->page && !$used[$name] &&
     ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
      // skip views with inline args
      if ($view->url{0} == '$' || strpos($view->url, '/$') !== FALSE) {
        continue;
      }
Earl Miles's avatar
Earl Miles committed

      _views_create_menu_item($items, $view, $view->url);
function views_menu_inline_items(&$items) {
  // I don't think we gain anything by caching these, there should never
  // be all that many, and caching == a database hit.
  $tokens = module_invoke_all('views_url_tokens');
  $args = explode('/', $_GET['q']);
  $urls = views_get_all_urls();
  foreach ($urls as $view_name => $url) {
    if ($url{0} != '$' && strpos($url, '/$') === FALSE) {
      if (module_exists('views_ui') && user_access('administer views')) {
        $view_args = $args;
        foreach (explode('/', $url) as $num => $element) {
          if ($element != $args[$num]) {
            continue 2;
          }
          unset($view_args[$num]);
        }
        views_menu_admin_items($items, $view_name, $view_args, $args);
    else {
      // Do substitution on args.
      $use_view = $use_menu = FALSE;
      $menu_args = $view_args = $menu_path = array();

      foreach (explode('/', $url) as $num => $element) {
        if ($element{0} == '$') {
          // If we pass the token check, this view is definitely being used.
          list($token, $argument) = explode('-', $element);
          if ($tokens[$token] && function_exists($tokens[$token])) {
            if (!($use_view = $use_menu = $tokens[$token]($element, $argument, arg($num)))) {
              break;
            }
          $menu_path[] = $view_args[] = arg($num);
        }
        else {
          unset($menu_args[$num]);
          $menu_path[] = $element;
          if ($element != arg($num)) {
            $use_menu = FALSE;
        // we are only using views that match our URL, up to the
        // point where we hit an inline arg.
        if (!$use_view && $element != arg($num)) {
          break;
        }
      }
      if ($use_view) {
        $view = views_get_view($view_name);
        $view->args = $view_args;
        _views_create_menu_item($items, $view, $path, MENU_CALLBACK, $view_args);

      if (module_exists('views_ui') && user_access('administer views') && $use_menu) {
        views_menu_admin_items($items, $view_name, $menu_args, $args);
      }
Earl Miles's avatar
Earl Miles committed
/**
 * Add the adminstrative items to a view.
Earl Miles's avatar
Earl Miles committed
 */
function views_menu_admin_items(&$items, $view_name, $view_args, $args) {
  // See what the last arg is.
  $last_arg = array_pop($args);
  if (in_array($last_arg, array('edit', 'view', 'clone', 'export'))) {
    array_pop($view_args);
  }
  else {
    $args[] = $last_arg;
  }
Earl Miles's avatar
Earl Miles committed

  $path = implode('/', $args);
  $view = views_get_view($view_name);
  views_ui_add_menu_items($items, $view, $path, $path != $_GET['q'] && !empty($view_args), $view_args);
}
Earl Miles's avatar
Earl Miles committed

/**
 * Load all of the URLs we use; this is cached in a special manner
 * in an attempt to make the menu system both flexible and yet not
 * overly intensive.
 */
function views_get_all_urls() {
  $cache = cache_get("views_urls", 'cache_views');
  if ($cache == 0) {
    $views = array();
    $used = array();
    $result = db_query("SELECT name, url FROM {view_view} WHERE page = 1");
Earl Miles's avatar
Earl Miles committed

    while ($view = db_fetch_object($result)) {
      $used[$view->name] = TRUE;
      $views[$view->name] = $view->url;
Earl Miles's avatar
Earl Miles committed
    }

    views_load_cache();
    $default_views = _views_get_default_views();
    $views_status = variable_get('views_defaults', array());
Earl Miles's avatar
Earl Miles committed

    foreach ($default_views as $name => $view) {
      if ($view->page && !$used[$name] && ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
        if ($view->url{0} == '$' || strpos($view->url, '/$') !== FALSE) {
          $views[$view->name] = $view->url;
        }
Earl Miles's avatar
Earl Miles committed
      }
    }
    cache_set("views_urls", 'cache_views', serialize($views));
  }
  else {
    $views = unserialize($cache->data);
Earl Miles's avatar
Earl Miles committed
  }
Earl Miles's avatar
Earl Miles committed
}

/**
 * Helper function to add a menu item for a view.
 */
function _views_create_menu_item(&$items, $view, $path, $local_task_type = MENU_NORMAL_ITEM, $args = array()) {
    global $user;
    $roles = array_keys($user->roles);
    if ($user->uid) {
      $roles[] = DRUPAL_AUTHENTICATED_RID;
    }
    else {
      $roles[] = DRUPAL_ANONYMOUS_RID;
    }
  }
  $title = views_get_title($view, 'menu');
  $type = _views_menu_type($view);
  if ($type == MENU_LOCAL_TASK || $type == MENU_DEFAULT_LOCAL_TASK) {
    $weight = $view->menu_tab_weight;
  }
  $access = user_access('access all views') || !$view->access || array_intersect($view->access, $roles);
  $items[] = _views_menu_item($path, $title, $view, $args, $access, $type, $weight);
  if ($type == MENU_DEFAULT_LOCAL_TASK) {
    $items[] = _views_menu_item(dirname($path), $title, $view, $args, $access, $local_task_type, $weight);
/**
 * Helper function to create a menu item for a view.
 */
function _views_menu_item($path, $title, $view, $args, $access, $type, $weight = NULL) {
  array_unshift($args, $view->name);
  $retval = array('path' => $path,
    'title' => $title,
    'callback' => 'views_view_page',
    'callback arguments' => $args,
    'access' => user_access('access content') && $access,
  if ($weight !== NULL) {
    $retval['weight'] = $weight;
  }
  return $retval;
/**
 * Determine what menu type a view needs to use.
 */
function _views_menu_type($view) {
  if ($view->menu) {
    if ($view->menu_tab_default) {
      $type = MENU_DEFAULT_LOCAL_TASK;
    }
    else if ($view->menu_tab) {
      $type = MENU_LOCAL_TASK;
    }
    else {
      $type = MENU_NORMAL_ITEM;
    }
  }
  else {
    $type = MENU_CALLBACK;
  }
  return $type;
}
/**
 * Implementation of hook_perm
 */
function views_perm() {
  return array('access all views');
}

 * Implementation of hook_block()
 */
function views_block($op = 'list', $delta = 0) {
  $block = array();
  if ($op == 'list') {
    // Grab views from the database and provide them as blocks.
    $result = db_query("SELECT vid, block_title, page_title, name FROM {view_view} WHERE block = 1");
    while ($view = db_fetch_object($result)) {
Earl Miles's avatar
Earl Miles committed
      $block[$view->name]['info'] = filter_xss_admin(views_get_title($view, 'block-info'));
    $default_views = _views_get_default_views();
    $views_status = variable_get('views_defaults', array());

    foreach ($default_views as $name => $view) {
      if (!isset($block[$name]) && $view->block &&
        ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
        $title = filter_xss_admin(views_get_title($view, 'block'));
        $block[$name]['info'] = empty($title) ? $name : $title;
    }
    return $block;
  }
  else if ($op == 'view') {
    return views_view_block($delta);
  }
}

// ---------------------------------------------------------------------------
// View Construction

 * Ensure that all the arrays in a view exist so we don't run into array
 * operations on a non-array error.
 */
Earl Miles's avatar
Earl Miles committed
function _views_check_arrays(&$view) {
Earl Miles's avatar
Earl Miles committed
  $fields = array('field', 'sort', 'argument', 'filter', 'exposed_filter', 'access');

  foreach($fields as $field) {
    if (!is_array($view->$field)) {
      $view->$field = array();
    }
 * This function loads a view by name or vid; if not found in db, it looks
 * for a default view by that name.
 */
Earl Miles's avatar
Earl Miles committed
    return $view;
Earl Miles's avatar
Earl Miles committed

  if (is_int($view_name)) {
    return; // don't bother looking if view_name is an int!
Earl Miles's avatar
Earl Miles committed

  $default_views = _views_get_default_views();
Earl Miles's avatar
Earl Miles committed

    $view = $default_views[$view_name];
    $view->is_cacheable = _views_is_cacheable($view);
    return $view;
Earl Miles's avatar
Earl Miles committed
}

 * This views a view by page, and should only be used as a callback.
 *
 * @param $view_name
 *   The name or id of the view to load
 * @param $args
 *   The arguments from the end of the url. Usually passed from the menu system.
 *
 * @return
 *   The view page.
function views_view_page() {
  $args = func_get_args();
  $view_name = array_shift($args);
  $view = views_get_view($view_name);
  if (!$view) {
    drupal_not_found();
    exit;
  }
  $output = views_build_view('page', $view, $args, $view->use_pager, $view->nodes_per_page);
  if ($output === FALSE) {
  return $output;
 * This views a view by block. Can be used as a callback or programmatically.
 */
function views_view_block($vid) {
  if (!$user->roles) {
    return NULL;
  }

  $roles = array_keys($user->roles);
  if ($view->access && !array_intersect($roles, $view->access)) {
    return NULL;
  }

  $content = views_build_view('block', $view, array(), false, $view->nodes_per_block);
  if ($content) {
    $block['content'] = $content;
Earl Miles's avatar
Earl Miles committed
    $block['subject'] = filter_xss_admin(views_get_title($view, 'block'));
function &views_set_current_view(&$view) {
  static $current_view = NULL;
  if ($view !== NULL) {
    unset($current_view);
    $current_view = &$view;
    unset($GLOBALS['current_view']);
    $GLOBALS['current_view'] = &$view;
  }
  return $current_view;
}

function &views_get_current_view() {
  $dummy = NULL;
  return views_set_current_view($dummy);
 * This builds the basic view.
 * @param $type
 *    'page' -- Produce output as a page, sent through theme.
 *      The only real difference between this and block is that
 *      a page uses drupal_set_title to change the page title.
 *    'block' -- Produce output as a block, sent through theme.
 *    'embed' -- Use this if you want to embed a view onto another page,
 *      and don't want any block or page specific things to happen to it.
 *    'result' -- return an $info array. The array contains:
 *      query: The actual query ran.
 *      countquery: The count query that would be run if limiting was required.
 *      summary: True if an argument was missing and a summary was generated.
 *      level: What level the missing argument was at.
 *      result: Database object you can use db_fetch_object on.
 *    'items' -- return info array as above, except instead of result,
 *      items: An array of objects containing the results of the query.
Earl Miles's avatar
Earl Miles committed
 *    'queries' -- returns an array, summarizing the queries, but does not
 *      run them.
 * @param $view
 *   The actual view object. Use views_get_view() if you only have the name or
 *   vid.
 * @param $args
 *   args taken from the URL. Not relevant for many views. Can be null.
 * @param $use_pager
 *   If set, use a pager. Set this to the pager id you want it
 *   to use if you plan on using multiple pagers on a page. To go with the
 *   default setting, set to $view->use_pager. Note that the pager element
 *   id will be decremented in order to have the IDs start at 0.
 * @param $limit
 *   Required if $use_pager is set; if $limit is set and $use_pager is
 *   not, this will be the maximum number of records returned. This is ignored
 *   if using a view set to return a random result. To go with the default
 *   setting set to $view->nodes_per_page or $view->nodes_per_block. If
 *   $use_pager is set and this field is not, you'll get a SQL error. Don't
 *   do that!
 * @param $page
 *   $use_pager is false, and $limit is !0, $page tells it what page to start
 *   on, in case for some reason a particular section of view is needed,
Earl Miles's avatar
Earl Miles committed
 * @param $offset
 *   If $use_pager == false, skip the first $offset results. Does not work
 *   with pager.
 *   without paging on.
Earl Miles's avatar
Earl Miles committed
function views_build_view($type, &$view, $args = array(), $use_pager = false, $limit = 0, $page = 0, $offset = 0) {
  // Fix a number of annoying whines when NULL is passed in..
  if ($args == NULL) {
    $args = array();
  }

Earl Miles's avatar
Earl Miles committed

  $view->build_type = $type;
  $view->type = ($type == 'block' ? $view->block_type : $view->page_type);
    $result = eval($view->view_args_php);
    if (is_array($result)) {
      $args = $result;
    }
Earl Miles's avatar
Earl Miles committed
  // Call a hook that'll let modules modify the view query before it is created
  foreach (module_implements('views_pre_query') as $module) {
    $function = $module .'_views_pre_query';
    $output .= $function($view);
  }

Earl Miles's avatar
Earl Miles committed
  if ($type == 'queries') {
    return $info;
  }
Earl Miles's avatar
Earl Miles committed
  $items = array();
  if ($query) {
    if ($use_pager) {
      $cquery = db_rewrite_sql($info['countquery'], 'node', 'nid', $info['rewrite_args']);
      $result = pager_query($query, $limit, $use_pager - 1, $cquery, $info['args']);
      $view->total_rows = $GLOBALS['pager_total_items'][$use_pager - 1];
    }
    else {
      $result = ($limit ? db_query_range($query, $info['args'], $page * $limit + $offset, $limit) : db_query($query, $info['args']));
    }
    $view->num_rows = db_num_rows($result);
    if ($type == 'result') {
      $info['result'] = $result;
      return $info;
    }

    while ($item = db_fetch_object($result)) {
      $items[] = $item;
    }

  if ($type == 'items') {
    $info['items'] = $items;
    return $info;
  }
  // Call a hook that'll let modules modify the view just before it is displayed.
  foreach (module_implements('views_pre_view') as $module) {
    $function = $module .'_views_pre_view';
  $view->real_url = views_get_url($view, $args);

  $view->pager_limit = $limit;
  $output .= views_theme('views_view', $view, $type, $items, $info['level'], $args);
  // Call a hook that'll let modules modify the view just after it is displayed.
  foreach (module_implements('views_post_view') as $module) {
    $function = $module .'_views_post_view';
    $output .= $function($view, $items, $output);
Earl Miles's avatar
Earl Miles committed
  return $output;
// ---------------------------------------------------------------------------
// Utility

/**
 * Load the cache sub-module
 */
function views_load_cache() {
  $path = drupal_get_path('module', 'views');
  require_once("./$path/views_cache.inc");
}

/**
 * Load the query sub-module
 */
function views_load_query() {
  $path = drupal_get_path('module', 'views');
  require_once("./$path/views_query.inc");
}

Earl Miles's avatar
Earl Miles committed
/**
Earl Miles's avatar
Earl Miles committed
 * @param $function
 *   The name of the function to call.
 * @param $view
 *   The view being themed.
 */
function views_theme() {
  $args = func_get_args();
  $function = array_shift($args);
  $view = $args[0];

  if (!($func = theme_get_function($function . "_" . $view->name))) {
    $func = theme_get_function($function);
  }

  if ($func) {
    return call_user_func_array($func, $args);
  }
}

/**
 * Easily theme any item to a field name.
 * field name will be in the format of TABLENAME_FIELDNAME
 * You have to understand a bit about the views data to utilize this.
 *
 * @param $function
 *   The name of the function to call.
 * @param $field_name
 *   The field being themed.
 */
function views_theme_field() {
  $args = func_get_args();
  $function = array_shift($args);
  $field_name = array_shift($args);
  $view = array_pop($args);
  if (!($func = theme_get_function($function . '_' . $view->name . '_' . $field_name))) {
    if (!($func = theme_get_function($function . '_' . $field_name))) {
      $func = theme_get_function($function);
    }
  }

  if ($func) {
    return call_user_func_array($func, $args);
  }
}

 * Figure out what timezone we're in; needed for some date manipulations.
function _views_get_timezone() {
  global $user;
  if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
    $timezone = $user->timezone;
  }
  else {
    $timezone = variable_get('date_default_timezone', 0);
  // set up the database timezone
  if (in_array($GLOBALS['db_type'], array('mysql', 'mysqli'))) {
    static $already_set = false;
    if (!$already_set) {
      if ($GLOBALS['db_type'] == 'mysqli' || version_compare(mysql_get_server_info(), '4.1.3', '>=')) {
        db_query("SET @@session.time_zone = '+00:00'");
      } 
      $already_set = true;
    }
  }


/**
 * Figure out what the URL of the view we're currently looking at is.
 */
function views_get_url($view, $args) {
  $url = $view->url;

  if (!empty($url)) {
    $where = 1;
    foreach ($args as $arg) {
      // This odd construct prevents us from strposing once there is no
      // longer an $arg to replace.
        $url = substr_replace($url, $arg, $where, 4);
      }
      else {
        $url .= "/$arg";
      }
 * Figure out what the title of a view should be.
 */
function views_get_title($view, $context = 'menu', $args = NULL) {
  if (($context == 'menu' || $context == 'admin') && $view->menu_title)
  if ($context == 'block-info') {
    return $view->description ? $view->description : $view->name;
  }

  // Grab the title from the highest argument we got. If there is no such
  // title, track back until we find a title.

  if (is_array($args)) {
    $rargs = array_reverse(array_keys($args));
    foreach ($rargs as $arg_id) {
      if ($title = $view->argument[$arg_id]['title']) {
        break;
      }
    }
  if (!$title && ($context == 'menu' || $context == 'page' || $context == 'admin')) {
    $title = $view->page_title;
  if (!$title && ($context == 'block' || $context == 'admin')) {
    $title = $view->block_title;
Earl Miles's avatar
Earl Miles committed
  views_load_cache();
  $arginfo = _views_get_arguments();
  foreach ($view->argument as $i => $arg) {
    if ($arg['wildcard'] == $args[$i] && $arg['wildcard_substitution'] != '') {
      $title = str_replace("%" . ($i + 1), $arg['wildcard_substitution'], $title);
    }
    else if (function_exists($arginfo[$argtype]['handler'])) {
      $rep = $arginfo[$argtype]['handler']('title', $args[$i], $argtype);
      $title = str_replace("%" . ($i + 1), $rep, $title);
    }
  }
  return $title;
}

 * Determine whether or not a view is cacheable. A view is not cacheable if
 * there is some kind of user input or data required. For example, views
 * that need to restrict to the 'current' user, or any views that require
 * arguments or allow click-sorting are not cacheable.
 */
Earl Miles's avatar
Earl Miles committed
function _views_is_cacheable(&$view) {
  // views with arguments are immediately not cacheable.
  if (!empty($view->argument) || !empty($view->exposed_filter) || !empty($view->no_cache)) {
Earl Miles's avatar
Earl Miles committed
    return false;
Earl Miles's avatar
Earl Miles committed

Earl Miles's avatar
Earl Miles committed
  $filters = _views_get_filters();

  foreach ($view->filter as $i => $filter) {
    if ($filters[$filter['field']]['cacheable'] == 'no')  {
Earl Miles's avatar
Earl Miles committed
      return false;
Earl Miles's avatar
Earl Miles committed
  }
  foreach ($view->field as $i => $field) {
Earl Miles's avatar
Earl Miles committed
  return true;
}

/**
 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
 */
function views_invalidate_cache() {
  cache_clear_all('*', 'cache_views', true);
// ---------------------------------------------------------------------------
// Database functions

 * Provide all the fields in a view.
 */
function _views_view_fields() {
  return array('vid', 'name', 'description', 'access', 'page', 'page_title', 'page_header', 'page_header_format', 'page_footer', 'page_footer_format', 'page_empty', 'page_empty_format', 'page_type', 'use_pager', 'nodes_per_page', 'url', 'menu', 'menu_tab', 'menu_tab_default', 'menu_tab_weight', 'menu_title', 'block', 'block_title', 'block_use_page_header', 'block_header', 'block_header_format', 'block_use_page_footer', 'block_footer', 'block_footer_format', 'block_use_page_empty', 'block_empty', 'block_empty_format', 'block_type', 'nodes_per_block', 'block_more', 'url', 'breadcrumb_no_home', 'changed', 'view_args_php', 'is_cacheable');
 * Delete a view from the database.
 */
function _views_delete_view($view) {
  $view->vid = intval($view->vid);
  db_query("DELETE FROM {view_view} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_sort} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_argument} where vid=%d", $view->vid);
  db_query("DELETE FROM {view_tablefield} where vid=%d", $view->vid);
  cache_clear_all('views_query:' . $view->name, 'cache_views');
/**
 * Load a view from the database -- public version of the function.
 */
function views_load_view($arg) {
  return _views_load_view($arg);
}

 * Load a view from the database.
 * (deprecated; use views_load_view in favor of this function).
function _views_load_view($arg) {
  static $cache = array();
  $which = is_numeric($arg) ? 'vid' : 'name';
  if (isset($cache[$which][$arg])) {
    return $cache[$which][$arg];
  }
  $where = (is_numeric($arg) ? "v.vid =  %d" : "v.name = '%s'");
  $view = db_fetch_object(db_query("SELECT v.* FROM {view_view} v WHERE $where", $arg));
  $view->access = ($view->access ? explode(', ', $view->access) : array());

  // load the sorting criteria too.
  $result = db_query("SELECT * FROM {view_sort} vs WHERE vid = $view->vid ORDER BY position ASC");

Earl Miles's avatar
Earl Miles committed
  $view->sort = array();
  while ($sort = db_fetch_array($result)) {
    if (substr($sort['field'], 0, 2) == 'n.') {
      $sort['field'] = 'node' . substr($sort['field'], 1);
    }
Earl Miles's avatar
Earl Miles committed
    $view->sort[] = $sort;
  $result = db_query("SELECT * FROM {view_argument} WHERE vid = $view->vid ORDER BY position ASC");

  $view->argument = array();
  while ($arg = db_fetch_array($result)) {
  $result = db_query("SELECT * FROM {view_tablefield} WHERE vid = $view->vid ORDER BY position ASC");
  while ($arg = db_fetch_array($result)) {
    if ($arg['tablename'] == 'n') {
      $arg['tablename'] = 'node';
    }
    $arg['id'] = $arg['fullname'] = "$arg[tablename].$arg[field]";
    $arg['queryname'] = "$arg[tablename]_$arg[field]";
    $view->field[] = $arg;
  $result = db_query("SELECT * FROM {view_filter} WHERE vid = $view->vid ORDER BY position ASC");
  $filters = _views_get_filters();
  while ($filter = db_fetch_array($result)) {
    if (substr($filter['field'], 0, 2) == 'n.') {
      $filter['field'] = 'node' . substr($filter['field'], 1);
Earl Miles's avatar
Earl Miles committed
    if ($filter['operator'] == 'AND' ||
        $filter['operator'] == 'OR' ||
        $filter['operator'] == 'NOR' ||
        $filters[$filter['field']]['value-type'] == 'array' ) {
      if ($filter['value'] !== NULL && $filter['value'] !== '') {
        $filter['value'] = explode(',', $filter['value']);
      }
      else {
        $filter['value'] = array();
      }
  $result = db_query("SELECT * FROM {view_exposed_filter} WHERE vid = $view->vid ORDER BY position ASC");

  $view->exposed_filter = array();
  while ($arg = db_fetch_array($result)) {
    $arg['id'] = $arg['field'];
    $view->exposed_filter[] = $arg;
  }

  $cache['vid'][$view->vid] = $view;
Earl Miles's avatar
Earl Miles committed
  $cache['name'][$view->name] = $view;
 * Save a view to the database.
 */
function _views_save_view($view) {
Earl Miles's avatar
Earl Miles committed
  _views_check_arrays($view);
Earl Miles's avatar
Earl Miles committed

  $view->is_cacheable = _views_is_cacheable($view);
  $view->access = implode(', ', $view->access);

Earl Miles's avatar
Earl Miles committed
  $view->changed = time();
  $fields = _views_view_fields();
  if ($view->vid) {
    // update
    // Prepare the query:
    foreach ($view as $key => $value) {
      if (in_array($key, $fields)) {
        $q[] = db_escape_string($key) ." = '%s'";
        $v[] = $value;
      }
    }

    // Update the view in the database:
    db_query("UPDATE {view_view} SET " . implode(', ', $q) . " WHERE vid = '$view->vid'", $v);
    db_query("DELETE from {view_sort} WHERE vid='$view->vid'");
    db_query("DELETE from {view_argument} WHERE vid='$view->vid'");
    db_query("DELETE from {view_tablefield} WHERE vid='$view->vid'");
    db_query("DELETE from {view_filter} WHERE vid='$view->vid'");
    db_query("DELETE from {view_exposed_filter} WHERE vid='$view->vid'");
    cache_clear_all('views_query:' . $view->name, 'cache_views');
  }
  else {
    // insert

    // This method really saves on typos, and makes it a lot easier to add fields
    // later on.
    $view->vid = db_next_id('{view_view}_vid');

    // Prepare the query:
    foreach ($view as $key => $value) {
      if (in_array((string) $key, $fields)) {
        $k[] = db_escape_string($key);
        $v[] = $value;
        $s[] = is_numeric($value) ? '%d' : "'%s'";
    db_query("INSERT INTO {view_view} (" . implode(", ", $k) . ") VALUES (" . implode(", ", $s) . ")", $v);
Earl Miles's avatar
Earl Miles committed
  foreach ($view->sort as $i => $sort) {
    db_query("INSERT INTO {view_sort} (vid, position, field, sortorder, options) VALUES (%d, %d, '%s', '%s', '%s')", $view->vid, $i, $sort['field'], $sort['sortorder'], $sort['options']);
Earl Miles's avatar
Earl Miles committed
  foreach ($view->argument as $i => $arg) {
    db_query("INSERT INTO {view_argument} (vid, type, argdefault, title, options, position, wildcard, wildcard_substitution) VALUES (%d, '%s', %d, '%s', '%s', %d, '%s', '%s')", $view->vid, $arg['type'], $arg['argdefault'], $arg['title'], $arg['options'], $i, $arg['wildcard'], $arg['wildcard_substitution']);
Earl Miles's avatar
Earl Miles committed
  foreach ($view->field as $i => $arg) {
    db_query("INSERT INTO {view_tablefield} (vid, tablename, field, label, handler, sortable, defaultsort, options, position) VALUES (%d, '%s', '%s', '%s', '%s', %d, '%s', '%s', %d)", $view->vid, $arg['tablename'], $arg['field'], $arg['label'], $arg['handler'], $arg['sortable'], $arg['defaultsort'], $arg['options'], $i);
Earl Miles's avatar
Earl Miles committed
  foreach ($view->filter as $i => $arg) {
    if (is_array($arg['value'])) {
Earl Miles's avatar
Earl Miles committed
      $arg['value'] = implode(',', $arg['value']);
    db_query("INSERT INTO {view_filter} (vid, tablename, field, value, operator, options, position) VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d)", $view->vid, $arg['tablename'], $arg['field'], $arg['value'], $arg['operator'], $arg['options'], $i);
  foreach ($view->exposed_filter as $i => $arg) {
    db_query("INSERT INTO {view_exposed_filter} (vid, field, label, optional, is_default, single, operator, position) VALUES (%d, '%s', '%s', %d, %d, %d, %d, %d)", $view->vid, $arg['field'], $arg['label'], $arg['optional'], $arg['is_default'], $arg['single'], $arg['operator'], $i);
  }
}

// ---------------------------------------------------------------------------
// Helper functions to build views and view data
/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to a $table array and returns it.
 */
function views_new_table($table_name, $provider, $left_table, $left_field, $right_field, $extra = NULL) {
  $table['name'] = $table_name;
  $table['provider'] = $provider;
  $table['join']['left']['table'] = $left_table;
  $table['join']['left']['field'] = $left_field;
Earl Miles's avatar
Earl Miles committed
  $table['join']['right']['field'] = $right_field;
  if ($extra) {
    $table['join']['extra'] = $extra;
  }
  return $table;
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */
function views_table_add_field(&$table, $name, $label, $help, $others = array()) {
  views_table_add_data($table, 'fields', $name, $label, $help, $others);
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */
function views_table_add_filter(&$table, $name, $label, $help, $others = array()) {
  views_table_add_data($table, 'filters', $name, $label, $help, $others);
}

/**
 * Helper function to make table creation a little easier. It adds the necessary
 * data to the $table array.
 */