Skip to content
views.module 53.7 KiB
Newer Older
  // hook init is called even on cached pages, but we don't want to
  // actually do anything in that case.
  if (!function_exists('drupal_get_path')) {
    return;
  }
  // Load all our module 'on behalfs'.
  $path = drupal_get_path('module', 'views') . '/modules';
  $files = system_listing('views_.*\.inc$', $path, 'name', 0);

  foreach($files as $file) {
    // The filename format is very specific. It must be views_MODULENAME.inc
    $module = substr_replace($file->name, '', 0, 6);
    if (module_exist($module)) {
      require_once($file->filename);
    }
  }
}

// ---------------------------------------------------------------------------
 * Return the arguments array; construct one if we haven't already. The
 * array is cached in a global, safely named variable so that arguments
 * are only constructed once per run.
 */
function _views_get_arguments($titles = false) {
  global $locale;
Earl Miles's avatar
Earl Miles committed

    $data = cache_get("views_arguments:$locale");
    $cache = unserialize($data->data);
    if (is_array($cache)) {
      $arguments = module_invoke_all('views_arguments');
      foreach ($arguments as $name => $arg) {
        if ($arg['option'] && !is_array($arg['option'])) {
          if ($arg['option'] == 'string' || $arg['option'] == 'integer') {
            $arg['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
          }
          else {
            $arg['option'] = array('#type' => 'select', '#options' => $arg['option']);
          }
        }
        $views_arguments['base'][$name] = $arg['name'];
        $views_arguments['title'][$name] = $arg;
      cache_set("views_arguments:$locale", serialize($cache));
Earl Miles's avatar
Earl Miles committed
    }
  }
  return ($titles ? $views_arguments['base'] : $views_arguments['title']);
Earl Miles's avatar
Earl Miles committed
}
 * Constructs the full table information array. Caches it into a global array
 * so that it will only be called once per run.
 */
function _views_get_tables($full = false) {
  global $locale;
Earl Miles's avatar
Earl Miles committed

    $data = cache_get("views_tables:$locale");
    $cache = unserialize($data->data);
Earl Miles's avatar
Earl Miles committed

Earl Miles's avatar
Earl Miles committed
    }
      $table_data = module_invoke_all('views_tables');
      $views_tables['tables'] = $table_data;

      foreach ($table_data as $name => $table) {
        if (is_array($table['filters'])) {
          foreach ($table['filters'] as $filter => $data) {
            // translate for deprecated APIs...
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            if ($data['list']) {
              $data['value'] = array('#type' => 'select', '#options' => $data['list']);
              if ($data['list-type'] != 'select') {
                $data['value']['#multiple'] = TRUE;
              }
            }
            else if (!$data['value']) {
              $data['value'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
            }
            $views_tables['filters']['titles']["$name.$filter"] = $data['name'];
            $views_tables['filters']['base']["$name.$filter"] = $data;
          foreach ($table['fields'] as $field => $data) {
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            $views_tables['fields']['titles']["$name.$field"] = $data['name'];
            $views_tables['fields']['base']["$name.$field"] = $data;
          foreach ($table['sorts'] as $field => $data) {
            if ($data['option'] && !is_array($data['option'])) {
              if ($data['option'] == 'string' || $data['option'] == 'integer') {
                $data['option'] = array('#type' => 'textfield', '#size' => 10, '#maxlength' => 255);
              }
              else {
                $data['option'] = array('#type' => 'select', '#options' => $data['option']);
              }
            }
            $views_tables['sorts']['titles']["$name.$field"] = $data['name'];
            $views_tables['sorts']['base']["$name.$field"] = $data;
      cache_set("views_tables:$locale", serialize($views_tables));
  return ($full ? $views_tables : $views_tables['tables']);
 * Gets the filter information; if it doesn't exist, call the function
 * that constructs all that.
 */
Earl Miles's avatar
Earl Miles committed
function _views_get_filters($titles = false) {
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['filters']['titles'] : $table_data['filters']['base']);
Earl Miles's avatar
Earl Miles committed
}

 * Gets the field information; if it doesn't exist, call the function
 * that constructs all that.
 */
Earl Miles's avatar
Earl Miles committed
function _views_get_fields($titles = false) {
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['fields']['titles'] : $table_data['fields']['base']);
Earl Miles's avatar
Earl Miles committed
}

 * Gets the sort information; if it doesn't exist, call the function
 * that constructs all that.
 */
Earl Miles's avatar
Earl Miles committed
function _views_get_sorts($titles = false) {
  $table_data = _views_get_tables(true);
  return ($titles ? $table_data['sorts']['titles'] : $table_data['sorts']['base']);
}
Earl Miles's avatar
Earl Miles committed

 * Invalidate the views cache, forcing a rebuild on the next grab of table data.
 */
function views_invalidate_cache() {
  cache_clear_all('views_', true);
Earl Miles's avatar
Earl Miles committed
}

 * Ensures that views have legitimate information; a bit more is stored on
 * the $view object than is in the database, and this isn't necessarily
 * set when a view is constructed externally.
 */
function _views_sanitize_view(&$view) {
  _views_check_arrays($view); // so reference works.
  foreach ($view->field as $i => $field) {
    $view->field[$i]['id'] = $view->field[$i]['fullname'] = "$field[tablename].$field[field]";
    $view->field[$i]['queryname'] = "$field[tablename]_$field[field]";

  foreach ($view->filter as $i => $filter) {
    $view->filter[$i]['id'] = $view->filter[$i]['field'] = "$filter[tablename].$filter[field]";

  foreach ($view->exposed_filter as $i => $exposed_filter) {
    $view->exposed_filter[$i]['id'] = $view->exposed_filter[$i]['field'] = "$exposed_filter[tablename].$exposed_filter[field]";

  foreach ($view->sort as $i => $sort) {
    $view->sort[$i]['id'] = $view->sort[$i]['field'] = "$sort[tablename].$sort[field]";
  }

  foreach ($view->argument as $i => $argument) {
    $view->argument[$i]['id'] = $view->argument[$i]['type'];
  }
 * Build default view information from all modules and cache it.
 */
Earl Miles's avatar
Earl Miles committed
function _views_get_default_views() {
  global $locale;
Earl Miles's avatar
Earl Miles committed

    $data = cache_get("views_default_views:$locale");
    $cache = unserialize($data->data);

    if (is_array($cache)) {
      // We have to make sure table data is built in order to be sure about providers.
      $tables = array_keys(_views_get_tables());
      $views = module_invoke_all('views_default_views');
      $views_default_views = array();
      foreach ($views as $i => $view) {
        if (!is_array($view->requires) || !array_diff($view->requires, $tables)) {
Earl Miles's avatar
Earl Miles committed
          _views_sanitize_view($view);
      cache_set("views_default_views:$locale", serialize($views_default_views));
/**
 * Return the style plugins; construct one if we haven't already. The
 * array is cached in a static variable so that arguments
 * are only constructed once per run.
 */
function _views_get_style_plugins($titles = false) {
  static $views_style_plugins;
  global $locale;

  if (!$views_style_plugins) {
    $data = cache_get("views_style_plugins:$locale");
    $cache = unserialize($data->data);
    if (is_array($cache)) {
      $views_style_plugins = $cache;
    }
    else {
      $arguments = module_invoke_all('views_style_plugins');
      foreach ($arguments as $name => $arg) {
        $views_style_plugins['title'][$name] = $arg['name'];
        $views_style_plugins['base'][$name] = $arg;
      }
      $cache = $views_style_plugins;
      cache_set("views_style_plugins:$locale", serialize($cache));
    }
  }
  return ($titles ? $views_style_plugins['title'] : $views_style_plugins['base']);
}

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

 * Implementation of hook_help()
 */
function views_help($section) {
  switch ($section) {
    case 'admin/help#views':
    case 'admin/modules#description':
      return t('The views module creates customized views of node lists.');
 * Implementation of hook_menu()
 */
function views_menu($may_cache) {
  $items = array();
  global $locale;
    // 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(1) == 'modules') {
    $result = db_query("SELECT * FROM {view_view} WHERE page = 1");
    while ($view = db_fetch_object($result)) {
      // unpack the array
      $view->access = ($view->access ? explode(', ', $view->access) : array());

      // This happens before the next check; even if it's put off for later
      // it is still used.
      $used[$view->name] = true;
      if (strrpos($view->url, '$arg')) {
        $arg_result = db_query("SELECT * FROM {view_argument} WHERE vid = %d", $view->vid);
        while ($view->argument[] = db_fetch_array($arg_result));
        array_pop($view->argument); // get rid of the NULL at the end.
        $views_with_inline_args[$view->name] = $view;
      _views_create_menu_item($items, $view, $view->url, array($view->name));
    $default_views = _views_get_default_views();
    $views_status = variable_get('views_defaults', array());

    foreach ($default_views as $name => $view) {
Earl Miles's avatar
Earl Miles committed
      if ($view->page && !$used[$name] &&
       ($views_status[$name] == 'enabled' || (!$view->disabled && $views_status[$name] != 'disabled'))) {
        if (strrpos($view->url, '$arg')) {
          $views_with_inline_args[$view->name] = $view;

        _views_create_menu_item($items, $view, $view->url, array($view->name));
    cache_set("views_with_inline_args:$locale", serialize($views_with_inline_args), CACHE_TEMPORARY);
    $data = cache_get("views_with_inline_args:$locale");
    if (is_array($views)) {
      foreach ($views as $view) {
        // Do substitution on args.
        $view_args = array($view->name);
        $menu_path = array();
        foreach (explode('/', $view->url) as $num => $element) {
          if ($element == '$arg') {
            $menu_path[] = arg($num);
            $view_args[] = arg($num);
            $view->args[] = arg($num);
        _views_create_menu_item($items, $view, $path, $view_args, MENU_CALLBACK);
/**
 * Helper function to add a menu item for a view.
 */
function _views_create_menu_item(&$items, $view, $path, $args, $local_task_type = MENU_NORMAL_ITEM) {
  static $roles = NULL;
  if ($roles == NULL) {
    global $user;
    $roles = array_keys($user->roles);
  }
  $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 = !$view->access || array_intersect($view->access, $roles);
  $items[] = _views_menu_item($path, $title, $args, $access, $type, $weight);
  if ($type == MENU_DEFAULT_LOCAL_TASK) {
    $items[] = _views_menu_item(dirname($path), $title, $args, $access, $local_task_type, $weight);
/**
 * Helper function to create a menu item for a view.
 */
function _views_menu_item($path, $title, $args, $access, $type, $weight = NULL) {
  $retval = array('path' => $path,
    'title' => $title,
    'callback' => 'views_view_page',
    'callback arguments' => $args,
    'access' => $access,
    'type' => $type,
  );
  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_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)) {
      $block[$view->name]['info'] = 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'))) {
        $block[$name]['info'] = views_get_title($view, 'block');
    }
    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.
 */
function views_get_view($view_name) {
  $view = _views_load_view($view_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

  if (isset($default_views[$view_name])) {
    return $default_views[$view_name];
Earl Miles's avatar
Earl Miles committed
}

 * This views a view by page, and should only be used as a callback.
 */
function views_view_page() {
  $args = func_get_args();
  // FIXME: Most of this code is unnecessary now that we add our
  // $view info as a callback argument via the menu hook.
  while ($next = array_shift($args)) {
  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) {
  global $user;
  $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;
    $block['subject'] = views_get_title($view, 'block');
    return $block;
  }
  else {
    return NULL;
  }
 * 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.
 * @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.
 * @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,
 *   without paging on.
function views_build_view($type, $view, $args = array(), $use_pager = false, $limit = 0, $page = 0) {
  $GLOBALS['current_view'] = &$view;
Earl Miles's avatar
Earl Miles committed

  $viewtype = ($type == 'block' ? $view->block_type : $view->page_type);

  if ($view->view_args_php) {
    ob_start();
    $args = eval($view->view_args_php);
    ob_end_clean();
  }

  if ($view->query) {
    $info['query'] = $view->query;
    $info['countquery'] = $view->countquery;
Earl Miles's avatar
Earl Miles committed
      $view->table_header = _views_construct_header($view, $fields);
Earl Miles's avatar
Earl Miles committed
  }
  else {
    $path = drupal_get_path('module', 'views');
    require_once("$path/views_query.inc");

Earl Miles's avatar
Earl Miles committed
    $info = _views_build_query($view, $args);
    if ($info['fail']) {
Earl Miles's avatar
Earl Miles committed
  }

  // Run-time replacement so we can do cacheing
  $replacements = module_invoke_all('views_query_substitutions', $view);
  foreach ($replacements as $src => $dest) {
    $info['query'] = str_replace($src, $dest, $info['query']);
    $info['countquery'] = str_replace($src, $dest, $info['countquery']);
    if (is_array($info['args'])) {
      foreach ($info['args'] as $id => $arg) {
        $info['args'][$id] = str_replace($src, $dest, $arg);
      }
  $query = db_rewrite_sql($info['query'], 'node');

    $cquery = db_rewrite_sql($info['countquery'], 'node', 'nid', $info['rewrite_args']);
    $result = pager_query($query, $limit, $use_pager, $cquery, $info['args']);
    $result = ($limit ? db_query_range($query, $info['args'], $page * $limit, $limit) : db_query($query, $info['args']));
  }

  if ($type == 'result') {
    $info['result'] = $result;
Earl Miles's avatar
Earl Miles committed
    return $info;
Earl Miles's avatar
Earl Miles committed
  $items = array();
  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);

  $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

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);

  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);

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

  $where = 1;
  foreach ($args as $arg) {
    // This odd construct prevents us from strposing once there is no
    // longer an $arg to replace.
    if ($where && $where = strpos('$arg', $url)) {
      $url = substr_replace($url, $arg, $where, 4);
    }
    else {
      $url .= "/$arg";
    }
  }

  return $url;
}

 * Figure out what the title of a view should be.
 */
function views_get_title($view, $context = 'menu', $args = NULL) {
  if ($context == 'menu' && $view->menu_title)
    return $view->menu_title;

  if ($context == 'block' && $view->block_title) {
  if ($context == 'block-info') {
    return $view->description ? $view->description : $view->name;
  }

  if ($args === NULL)
    $args = $view->args;

  $count = count($args);
  if ($count >= count($view->argument)) {
  }
  else {
    $title = $view->argument[$count]['title'];
  }
  if (!$title && $context == 'menu') {
    $title = $view->block_title;
  }

  if (!$view->argument) {
    return $title;
  }

  $arginfo = _views_get_arguments();
  foreach ($view->argument as $i => $arg) {
    $argtype = $arg['type'];
    if (function_exists($arginfo[$argtype]['handler'])) {
      $rep = $arginfo[$argtype]['handler']('title', $args[$i], $argtype);
      $title = str_replace("%" . ($i + 1), $rep, $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)) {
Earl Miles's avatar
Earl Miles committed
    return false;
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;
}

// ---------------------------------------------------------------------------
// 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', 'query', 'countquery', 'view_args_php');
 * 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);
 * Load a view from the database.
 */
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

  // cache the query
  if (_views_is_cacheable($view)) {
    $path = drupal_get_path('module', 'views');
    require_once("$path/views_query.inc");

Earl Miles's avatar
Earl Miles committed
    $info = _views_build_query($view);
    $view->query = _views_replace_args($info['query'], $info['args']);
    $view->countquery = _views_replace_args($info['countquery'], $info['args']);
Earl Miles's avatar
Earl Miles committed
  }
    $view->query = NULL;
    $view->countquery = NULL;
  $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'");
  }
  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'";