Skip to content
view.inc 76 KiB
Newer Older
 * @file
 * @defgroup views_objects Objects that represent a View or part of a view
 * @{
 * These objects are the core of Views do the bulk of the direction and
 * storing of data. All database activity is in these objects.
 */

/**
 * An object to contain all of the data to generate a view.
 *
 * Also includes the member functions to build the view query, execute the
 * query and render the output.

  /**
   *
   */
  public $db_table = 'views_view';

  /**
   *
   */
  public $base_table = 'node';

  /**
   *
   */
  public $base_field = 'nid';
Daniel Wehner's avatar
Daniel Wehner committed
  /**
   * The id of the view, which is used only for views in the database.
   *
   * @var number
   */
Daniel Wehner's avatar
Daniel Wehner committed

  /**
   * The description of the view, which is used only in the interface.
   *
   * @var string
   */
Daniel Wehner's avatar
Daniel Wehner committed
  /**
   * The "tags" of a view.
   * The tags are stored as a single string, though it is used as multiple tags
   * for example in the views overview.
   *
   * @var string
   */
Daniel Wehner's avatar
Daniel Wehner committed

Daniel Wehner's avatar
Daniel Wehner committed
  /**
   * The human readable name of the view.
   *
   * @var string
   */
  /**
   * The core version the view was created for.

  /**
   * The views-api version this view was created by.
   *
   * Some examples of the variable are 3.0 or 3.0-alpha1
   *
   * @var string
   */
   * This value is used for exported view, to provide some default views which
   * aren't enabled.
  public $disabled;

  /**
   * State variable.
   */
  public $built = FALSE;
  /**
   * State variable.
   */
  public $executed = FALSE;

  /**
   * State variable.
   */
  public $editing = FALSE;
  /**
   * Where the results of a query will go.
   *
   * The array must use a numeric index starting at 0.
   *
   * @var array
   */
  // May be used to override the current pager info.
  public $current_page = NULL;
  public $items_per_page = NULL;
  public $offset = NULL;
  public $total_rows = NULL;

  // Places to put attached renderings.
  public $attachment_before = '';
  public $attachment_after = '';

  // Exposed widget input.
  public $exposed_data = array();
  public $exposed_input = array();
  // Exposed widget input directly from the $form_state['values'].

  // Used to store views that were previously running if we recurse.
  // To avoid recursion in views embedded into areas.
  // Is the current stored view runned as an attachment to another view.
  // Stores the next steps of form items to handle.
  // It's an array of stack items, which contain the form id, the type of form,
  // the view, the display and some additional arguments.
  // @see views_ui_add_form_to_stack()
  /**
   * Identifier of the current display.
   *
   * @var string
   */
   * The current used display plugin.
   *
   * @var views_plugin_display
   */
Daniel Wehner's avatar
Daniel Wehner committed
  /**
   * Stores all display handlers of this view.
   *
   * @var array[views_display]
   */
  /**
   * The current used style plugin.
   *
   * @var views_plugin_style
   */
  /**
   * Stored the changed options of the style plugin.
   *
   * @deprecated Better use $view->style_plugin->options
Daniel Wehner's avatar
Daniel Wehner committed
  /**
   * Stores the current active row while rendering.
   *
   * @var int
   */
   * Allow to override the url of the current view.
   *
   * @var string
   */
  /**
   * Allow to override the path used for generated urls.
   *
   * @var string
   */
  /**
   * Allow to override the used database which is used for this query.
   */
  /**
   * Here comes a list of the possible handler which are active on this view.
   */

  /**
   * Stores the field handlers which are initialized on this view.
   * @var array[views_handler_field]
   */

  /**
   * Stores the argument handlers which are initialized on this view.
   * @var array[views_handler_argument]
   */

  /**
   * Stores the sort handlers which are initialized on this view.
   * @var array[views_handler_sort]
   */

  /**
   * Stores the filter handlers which are initialized on this view.
   * @var array[views_handler_filter]
   */

  /**
   * Stores the relationship handlers which are initialized on this view.
   * @var array[views_handler_relationship]
   */

  /**
   * Stores the area handlers for the header which are initialized on this view.
   * @var array[views_handler_area]
   */

  /**
   * Stores the area handlers for the footer which are initialized on this view.
   * @var array[views_handler_area]
   */
   * The area handlers for the empty text which are initialized on this view.
   *
   * @var array[views_handler_area]
   */

    // Make sure all of the sub objects are arrays.
    foreach ($this->db_objects() as $object) {
      $this->$object = array();
    }
  }

  /**
   * Perform automatic updates when loading or importing a view.
   *
   * Over time, some things about Views or Drupal data has changed. this
   * attempts to do some automatic updates that must happen to ensure older
   * views will at least try to work.
    // When views are converted automatically the base_table should be renamed
    // to have a working query.
    $this->base_table = views_move_table($this->base_table);
  }

  /**
   * Returns a list of the sub-object types used by this view. These types are
   * stored on the display, and are used in the build process.
   */
    return array('argument', 'field', 'sort', 'filter', 'relationship', 'header', 'footer', 'empty');
  }

  /**
   * Returns the complete list of dependent objects in a view, for the purpose
   * of initialization and loading/saving to/from the database.
   */
  static function db_objects() {
    return array('display');
  }

  /**
   * Set the arguments that come to this view. Usually from the URL
   * but possibly from elsewhere.
   */
    $this->args = $args;
  }

  /**
   * Change/Set the current page for the pager.
   */
  public function set_current_page($page) {

    // If the pager is already initialized, pass it through to the pager.
    if (!empty($this->query->pager)) {
      return $this->query->pager->set_current_page($page);
    }
    // If the pager is already initialized, pass it through to the pager.
    if (!empty($this->query->pager)) {
      return $this->query->pager->get_current_page();
    }

    if (isset($this->current_page)) {
      return $this->current_page;
    }
    // If the pager is already initialized, pass it through to the pager.
    if (!empty($this->query->pager)) {
      return $this->query->pager->get_items_per_page();
    }

    if (isset($this->items_per_page)) {
      return $this->items_per_page;
    }
  public function set_items_per_page($items_per_page) {
    $this->items_per_page = $items_per_page;

    // If the pager is already initialized, pass it through to the pager.
    if (!empty($this->query->pager)) {
      $this->query->pager->set_items_per_page($items_per_page);
    // If the pager is already initialized, pass it through to the pager.
    if (!empty($this->query->pager)) {
      return $this->query->pager->get_offset();
    }
  /**
   * Set the offset on the pager.
   */
    $this->offset = $offset;

    // If the pager is already initialized, pass it through to the pager.
    if (!empty($this->query->pager)) {
      $this->query->pager->set_offset($offset);
    }
  }

  /**
   * Determine if the pager actually uses a pager.
   */
    if (!empty($this->query->pager)) {
      return $this->query->pager->use_pager();
    }
  }

  /**
   * Whether or not AJAX should be used. If AJAX is used, paging,
   * tablesorting and exposed filters will be fetched via an AJAX call
   * rather than a page refresh.
   */
  public function set_use_ajax($use_ajax) {
    $this->use_ajax = $use_ajax;
  }

  /**
   * Set the exposed filters input to an array. If unset they will be taken
   * from $_GET when the time comes.
   */
  public function set_exposed_input($filters) {
    $this->exposed_input = $filters;
  }

  /**
   * Figure out what the exposed input for this view is.
   */

      // If filters are not overridden, store the 'remember' settings on the
      // default display. If they are, store them on this display. This way,
      // multiple displays in the same view can share the same filters and
      // remember settings.
      $display_id = ($this->display_handler->is_defaulted('filters')) ? 'default' : $this->current_display;

      // Start with remembered input via session.
      if (!empty($_SESSION['views'][$this->name][$display_id])) {
        $this->exposed_input = $_SESSION['views'][$this->name][$display_id];
      }

      // Fetch exposed input values from $_GET. Overwrite if clashing.
      foreach ($_GET as $key => $value) {
        if (!in_array($key, array('page', 'q'))) {
          $this->exposed_input[$key] = $value;
        }
      }
    }

    return $this->exposed_input;
  }

  /**
   * Set the display for this view and initialize the display handler.
   */
  public function init_display($reset = FALSE) {
    // The default display is always the first one in the list.
    if (isset($this->current_display)) {
      return TRUE;
    }

    foreach (array_keys($this->display) as $id) {
      // Correct for shallow cloning
      // Often we'll have a cloned view so we don't mess up each other's
      // displays, but the clone is pretty shallow and doesn't necessarily
      // clone the displays. We can tell this by looking to see if a handler
      // has already been set; if it has, but $this->current_display is not
      // set, then something is dreadfully wrong.
      if (!empty($this->display[$id]->handler)) {
        $this->display[$id] = clone $this->display[$id];
        unset($this->display[$id]->handler);
      }
      $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
      if (!empty($this->display[$id]->handler)) {
        $this->display[$id]->handler->localization_keys = array($id);
        // Initialize the new display handler with data.
        $this->display[$id]->handler->init($this, $this->display[$id]);
        // If this is NOT the default display handler, let it know which is
        // since it may well utilize some data from the default.
        // This assumes that the 'default' handler is always first. It always
        // is. Make sure of it.
        if ($id != 'default') {
          $this->display[$id]->handler->default_display = &$this->display['default']->handler;
    $this->display_handler = &$this->display['default']->handler;

    return TRUE;
  }

  /**
   * Get the first display that is accessible to the user.
   *
   *   Either a single display id or an array of display ids.
   */
  public function choose_display($displays) {
    if (!is_array($displays)) {
      return $displays;
    }

    $this->init_display();

    foreach ($displays as $display_id) {
      if ($this->display[$display_id]->handler->access()) {
        return $display_id;
      }
    }

    return 'default';
  }

  /**
   * Set the display as current.
   *
   *   The id of the display to mark as current.
   */
  public function set_display($display_id = NULL) {
    // If we have not already initialized the display, do so. But be careful.
    if (empty($this->current_display)) {
      $this->init_display();

      // If handlers were not initialized, and no argument was sent, set up
      // to the default display.
      if (empty($display_id)) {
        $display_id = 'default';
      }
    }

    $display_id = $this->choose_display($display_id);

    // If no display id sent in and one wasn't chosen above, we're finished.
    if (empty($display_id)) {
    }

    // Ensure the requested display exists.
    if (empty($this->display[$display_id])) {
      $display_id = 'default';
      if (empty($this->display[$display_id])) {
        vpr('set_display() called with invalid display id @display.', array('@display' => $display_id));
        return FALSE;
      }
    }

    // Set the current display.
    $this->current_display = $display_id;

    // Ensure requested display has a working handler.
    if (empty($this->display[$display_id]->handler)) {
      return FALSE;
    }

    $this->display_handler = &$this->display[$display_id]->handler;

    return TRUE;
  }

  /**
   * Find and initialize the style plugin.
   *
   * Note that arguments may have changed which style plugin we use, so
   * check the view object first, then ask the display handler.
   */
    if (isset($this->style_plugin)) {
      return is_object($this->style_plugin);
    }

    if (!isset($this->plugin_name)) {
      $this->plugin_name = $this->display_handler->get_option('style_plugin');
      $this->style_options = $this->display_handler->get_option('style_options');
    }

    $this->style_plugin = views_get_plugin('style', $this->plugin_name);

    if (empty($this->style_plugin)) {
      return FALSE;
    }

    // Init the new style handler with data..
    $this->style_plugin->init($this, $this->display[$this->current_display], $this->style_options);
    return TRUE;
  }

  /**
   * Attempt to discover if the view has handlers missing relationships.
   *
   * This will try to add relationships automatically if it can, and will
   * remove the handlers if it cannot.
   */
  public function fix_missing_relationships() {
    if (isset($this->relationships_fixed)) {
      return;
    }

    $this->relationships_fixed = TRUE;

    // Go through all of our handler types and test them to see if they
    // are missing relationships. Missing relationships can cause fatally
    // broken Views.
    $base_tables = array(
      $this->base_table => TRUE,
      '#global' => TRUE,
    );

    // For each relationship we have, make sure we mark the base it provides as
    // available.
    foreach ($this->display_handler->get_option('relationships') as $id => $options) {
      $options['table'] = views_move_table($options['table']);
      $data = views_fetch_data($options['table'], FALSE);
      if (isset($data[$options['field']]['relationship']['base'])) {
        $base_tables[$data[$options['field']]['relationship']['base']] = TRUE;
      }
    }

    $base_tables = array_keys($base_tables);
    $missing_base_tables = array();

    $types = views_object_types();
    foreach ($types as $key => $info) {
      foreach ($this->display_handler->get_option($info['plural']) as $id => $options) {
        $options['table'] = views_move_table($options['table']);
        $data = views_fetch_data($options['table'], FALSE);

        $valid_bases = array($options['table']);
        if (isset($data['table']['join'])) {
          $valid_bases = array_merge($valid_bases, array_keys($data['table']['join']));
        }

        // If the base table is missing, record it so we can try to fix it.
        if (!array_intersect($valid_bases, $base_tables)) {
          $missing_base_tables[$options['table']][] = array('type' => $key, 'id' => $id);
        }
      }
    }

    if (!empty($missing_base_tables)) {
      // This will change handlers, so make sure any existing handlers get
      // tossed.
      $this->display_handler->handlers = array();
      $this->relationships_changed = TRUE;
      $this->changed = TRUE;

      // Try to fix it.
      foreach ($missing_base_tables as $table => $handlers) {
        $data = views_fetch_data($table);
        $relationship = NULL;

        // Does the missing base table have a default relationship we can
        // throw in?
        if (isset($data['table']['default_relationship'][$this->base_table])) {
          // Create the relationship.
          $info = $data['table']['default_relationship'][$this->base_table];

          $relationship_options = isset($info['options']) ? $info['options'] : array();
          $relationship = $this->add_item($this->current_display, 'relationship', $info['table'], $info['field'], $relationship_options);
        }
        foreach ($handlers as $handler) {
          $options = $this->display_handler->get_option($types[$handler['type']]['plural']);
          if ($relationship) {
            $options[$handler['id']]['relationship'] = $relationship;
          }
          else {
            unset($options[$handler['id']]);
          }
          $this->display_handler->set_option($types[$handler['type']]['plural'], $options);
        }
      }
    }
  }

      foreach (views_object_types() as $key => $info) {
        $this->_init_handler($key, $info);
      }
      $this->inited = TRUE;
    }
  }

   *
   * Like style initialization, pager initialization is held until late
   * to allow for overrides.
   */
    if (empty($this->query->pager)) {
      // If the query doesn't exist, initialize it.
      if (empty($this->query)) {
        $this->init_query();
      }
      $this->query->pager = $this->display_handler->get_plugin('pager');

      if ($this->query->pager->use_pager()) {
        $this->query->pager->set_current_page($this->current_page);
      }

      // These overrides may have been set earlier via $view->set_*
      // functions.
      if (isset($this->items_per_page)) {
        $this->query->pager->set_items_per_page($this->items_per_page);
      }

      if (isset($this->offset)) {
        $this->query->pager->set_offset($this->offset);
      }
    }
  }

  /**
   * Create a list of base tables eligible for this view. Used primarily
   * for the UI. Display must be already initialized.
   */
    $base_tables = array(
      $this->base_table => TRUE,
      '#global' => TRUE,
    );

    foreach ($this->display_handler->get_handlers('relationship') as $handler) {
      $base_tables[$handler->definition['base']] = TRUE;
    }
    return $base_tables;
  }

  /**
   * Run the pre_query() on all active handlers.
    foreach (views_object_types() as $key => $info) {
      $handlers = &$this->$key;
      $position = 0;
      foreach ($handlers as $id => $handler) {
        $handlers[$id]->position = $position;
        $handlers[$id]->pre_query();
        $position++;
      }
    }
  }

  /**
   * Run the post_execute() on all active handlers.
   */
    foreach (views_object_types() as $key => $info) {
      $handlers = &$this->$key;
      foreach ($handlers as $id => $handler) {
        $handlers[$id]->post_execute($this->result);
      }
    }
  }

  /**
   * Attach all of the handlers for each type.
   *
   * @param string $key
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'.
   * @param array $info
   *   The $info from views_object_types for this object.
   */
  public function _init_handler($key, $info) {
    // Load the requested items from the display onto the object.
    $this->$key = &$this->display_handler->get_handlers($key);

    // This reference deals with difficult PHP indirection.
    $handlers = &$this->$key;

    // Run through and test for accessibility.
    foreach ($handlers as $id => $handler) {
      if (!$handler->access()) {
        unset($handlers[$id]);
      }
    }
  }

  /**
   * Build all the arguments.
   */
    // Initially, we want to build sorts and fields. This can change, though,
    // if we get a summary view.
    if (empty($this->argument)) {
      return TRUE;
    }

    // build arguments.
    $position = -1;

    // Create a title for use in the breadcrumb trail.
    $title = $this->display_handler->get_option('title');

    $this->build_info['breadcrumb'] = array();
    $breadcrumb_args = array();
    $substitutions = array();

    $status = TRUE;

    // Iterate through each argument and process.
    foreach ($this->argument as $id => $arg) {
      $position++;

      if ($argument->broken()) {
        continue;
      }

      $argument->set_relationship();

      $arg = isset($this->args[$position]) ? $this->args[$position] : NULL;
      $argument->position = $position;

      if (isset($arg) || $argument->has_default_argument()) {
        if (!isset($arg)) {
          $arg = $argument->get_default_argument();
          // make sure default args get put back.
          if (isset($arg)) {
            $this->args[$position] = $arg;
          }
        }

        // Set the argument, which will also validate that the argument can be
        // set.
        if (!$argument->set_argument($arg)) {
          $status = $argument->validate_fail($arg);
          break;
        }

        if ($argument->is_exception()) {
          $arg_title = $argument->exception_title();
          $argument->query($this->display_handler->use_group_by());
        $substitutions['%' . ($position + 1)] = $arg_title;
        $substitutions['!' . ($position + 1)] = strip_tags(decode_entities($arg));

        // Since we're really generating the breadcrumb for the item above us,
        // check the default action of this argument.
        if ($this->display_handler->uses_breadcrumb() && $argument->uses_breadcrumb()) {
          $path = $this->get_url($breadcrumb_args);
          if (strpos($path, '%') === FALSE) {
            if (!empty($argument->options['breadcrumb_enable']) && !empty($argument->options['breadcrumb'])) {
              $breadcrumb = $argument->options['breadcrumb'];
            }
            else {
              $breadcrumb = $title;
            }
            $this->build_info['breadcrumb'][$path] = str_replace(array_keys($substitutions), $substitutions, $breadcrumb);
          }
        }

        // Allow the argument to muck with this breadcrumb.
        $argument->set_breadcrumb($this->build_info['breadcrumb']);

        // Test to see if we should use this argument's title.
        if (!empty($argument->options['title_enable']) && !empty($argument->options['title'])) {
          $title = $argument->options['title'];
        }

        $breadcrumb_args[] = $arg;
      }
      else {
        // determine default condition and handle.
        $status = $argument->default_action();
        break;
      }

      unset($argument);
    }

    // set the title in the build info.
    if (!empty($title)) {
      $this->build_info['title'] = $title;
    }

    // Store the arguments for later use.
    $this->build_info['substitutions'] = $substitutions;

    return $status;
  }

  /**
   * Do some common building initialization.
   */
    if (!empty($this->query)) {
      $class = get_class($this->query);
      if ($class && $class != 'stdClass') {
        // return if query is already initialized.
    // Create and initialize the query object.
    $views_data = views_fetch_data($this->base_table);
    $this->base_field = !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '';
    if (!empty($views_data['table']['base']['database'])) {
      $this->base_database = $views_data['table']['base']['database'];
    }
    // Load the options.
    $query_options = $this->display_handler->get_option('query');

    // Create and initialize the query object.
    $plugin = !empty($views_data['table']['base']['query class']) ? $views_data['table']['base']['query class'] : 'views_query';
    $this->query = views_get_plugin('query', $plugin);

    if (empty($this->query)) {
      return FALSE;
    }

    $this->query->init($this->base_table, $this->base_field, $query_options['options']);
    return TRUE;
  public function build($display_id = NULL) {
    if (!empty($this->built)) {
      return;
    }

    if (empty($this->current_display) || $display_id) {
      if (!$this->set_display($display_id)) {
        return FALSE;
      }
    }

    // Let modules modify the view just prior to building it.
    foreach (module_implements('views_pre_build') as $module) {
      $function = $module . '_views_pre_build';
      $function($this);
    }

    // Attempt to load from cache.
    // @todo Load a build_info from cache.
    // If that fails, let's build!
    $this->build_info = array(
      'query' => '',
      'count_query' => '',
      'query_args' => array(),
    );

    $this->init_query();

    // Call a module hook and see if it wants to present us with a
    // pre-built query or instruct us not to build the query for
    // some reason.
    // @todo Implement this. Use the same mechanism Panels uses.
    // Run through our handlers and ensure they have necessary information.
    $this->init_handlers();

    // Let the handlers interact with each other if they really want.
    $this->_pre_query();

    if ($this->display_handler->uses_exposed()) {
      $exposed_form = $this->display_handler->get_plugin('exposed_form');