You are here

views404.module in Views 404 6

Same filename and directory in other branches
  1. 7 views404.module

Return 404 if internal path doesn't match the view path

File

views404.module
View source
<?php

/**
 * @file
 * Return 404 if internal path doesn't match the view path
 */

/**
 * Implementation of hook_views_pre_view().
 */
function views404_views_pre_view(&$view) {
  $path = $view->display_handler->options['path'];
  if (!empty($path)) {

    // init variables
    ini_set('display_errors', 1);
    $path_array = explode('/', $path);
    $path_array_no_wild = explode('/', array_shift(explode('/%', $path)));
    $args = array_filter(arg());
    $matched = array_intersect($path_array, $args);
    $conflicting_in_view = array_diff($path_array, $matched);
    $conflicting_in_args = array_diff($args, $matched);

    // Get view arguments if path doesn't contain a %
    $view_arguments = $view->display_handler->options['arguments'];
    if (count($view_arguments) == 0 && count($path_array) == count($path_array_no_wild)) {
      foreach ($view->display_handler->view->display as $value) {
        if ($value->display_options['path'] == $path) {
          $view_arguments = $value->handler->default_display->options['arguments'];
          break;
        }
      }
    }

    // Return if view is embedded
    foreach ($path_array_no_wild as $key => $value) {
      if ($value != $args[$key]) {
        return;
      }
    }

    // Add in % for each argument, as needed
    if (count($view_arguments) > 0) {
      foreach ($view_arguments as $type => $data) {
        if (count($conflicting_in_view) < count($conflicting_in_args)) {
          $path_array[] = '%';

          // Re init varables to take into account the % in the path
          $path = implode('/', $path_array);
          $matched = array_intersect($path_array, $args);
          $conflicting_in_view = array_diff($path_array, $matched);
          $conflicting_in_args = array_diff($args, $matched);
        }
        else {
          break;
        }
      }
    }

    // Return if parameter count matches
    if (count($conflicting_in_view) == count($conflicting_in_args)) {
      return;
    }

    // If we got this far, odds are this is a 404
    watchdog('views404', t('View path: !path <br />Path given: !args <br />Matched: !match<br />Was Looking for: !looking<br />Got this instead: !got<br />Number of view arguments: !viewarg', array(
      '!path' => $path,
      '!args' => implode('/', $args),
      '!match' => implode('/', $matched),
      '!looking' => implode('/', $conflicting_in_view),
      '!got' => implode('<strong>/</strong>', $conflicting_in_args),
      '!viewarg' => count($view_arguments),
    )));
    drupal_not_found();
    exit;
  }
}

Functions

Namesort descending Description
views404_views_pre_view Implementation of hook_views_pre_view().