Patch #484554 by Damien Tournoud: Stop relying on Apache for determining the current path.

From: damz <damz@damz-dev.local>


---
 .htaccess                           |    2 -
 bootstrap.inc                       |   34 +++++++++++-----
 common.inc                          |   45 ++++++++-------------
 comment/comment.module              |    4 +-
 search/search.test                  |    4 +-
 simpletest/tests/common.test        |   75 +++++++++++++++++++++++++++++++++--
 simpletest/tests/system_test.module |   18 +++++++-
 update/update.fetch.inc             |    4 +-
 8 files changed, 135 insertions(+), 51 deletions(-)

diff --git .htaccess .htaccess
index 0ebc207..1627658 100644
--- .htaccess
+++ .htaccess
@@ -88,7 +88,7 @@ DirectoryIndex index.php index.html index.htm
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_URI} !=/favicon.ico
-  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
+  RewriteRule ^(.*)$ index.php [L]
 </IfModule>
 
 # $Id: .htaccess,v 1.101 2009-05-16 13:19:12 webchick Exp $
diff --git includes/bootstrap.inc includes/bootstrap.inc
index 12ba6f5..f660922 100644
--- includes/bootstrap.inc
+++ includes/bootstrap.inc
@@ -394,6 +394,8 @@ function conf_path($require_settings = TRUE, $reset = FALSE) {
  * Initialize variables needed for the rest of the execution.
  */
 function drupal_initialize_variables() {
+  global $base_path;
+
   if (!isset($_SERVER['HTTP_REFERER'])) {
     $_SERVER['HTTP_REFERER'] = '';
   }
@@ -418,6 +420,25 @@ function drupal_initialize_variables() {
     $_SERVER['HTTP_HOST'] = '';
   }
 
+  // When the path is not present in $_GET['q'], derive it from the URL.
+  if (!isset($_GET['q'])) {
+    // $_SERVER['SCRIPT_NAME'] can't, in contrast to $_SERVER['PHP_SELF'],
+    // be modified by a visitor.
+    if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
+      $base_path = "/$dir/";
+    }
+    else {
+      $base_path = '/';
+    }
+
+    if (substr($_SERVER['REQUEST_URI'], 0, strlen($base_path)) == $base_path) {
+      $_GET['q'] = urldecode(strtok(substr($_SERVER['REQUEST_URI'], strlen($base_path)), "?#"));
+    }
+    else {
+      $_GET['q'] = '';
+    }
+  }
+
   // Enforce E_ALL, but allow users to set levels not part of E_ALL.
   error_reporting(E_ALL | error_reporting());
 
@@ -479,16 +500,9 @@ function conf_init() {
 
     $base_url = $base_root .= '://' . $_SERVER['HTTP_HOST'];
 
-    // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
-    // be modified by a visitor.
-    if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
-      $base_path = "/$dir";
-      $base_url .= $base_path;
-      $base_path .= '/';
-    }
-    else {
-      $base_path = '/';
-    }
+    // Note: $base_path has already be derived from SCRIPT_NAME
+    // by drupal_initialize_variables().
+    $base_url .= rtrim($base_path, '/');
   }
 
   if ($cookie_domain) {
diff --git includes/common.inc includes/common.inc
index 0bf5751..c7663a6 100644
--- includes/common.inc
+++ includes/common.inc
@@ -233,7 +233,7 @@ function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
   $params = array();
 
   foreach ($query as $key => $value) {
-    $key = drupal_urlencode($key);
+    $key = urlencode($key);
     if ($parent) {
       $key = $parent . '[' . $key . ']';
     }
@@ -246,7 +246,7 @@ function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
       $params[] = drupal_query_string_encode($value, $exclude, $key);
     }
     else {
-      $params[] = $key . '=' . drupal_urlencode($value);
+      $params[] = $key . '=' . urlencode($value);
     }
   }
 
@@ -2052,7 +2052,7 @@ function url($path = NULL, array $options = array()) {
 
   $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
   $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
-  $path = drupal_urlencode($prefix . $path);
+  $path = drupal_encode_path($prefix . $path);
 
   if (variable_get('clean_url', '0')) {
     // With Clean URLs.
@@ -3143,33 +3143,24 @@ function drupal_json($var = NULL) {
 }
 
 /**
- * Wrapper around urlencode() which avoids Apache quirks.
+ * Encode a full path of a URL.
  *
- * Should be used when placing arbitrary data in an URL. Note that Drupal paths
- * are urlencoded() when passed through url() and do not require urlencoding()
- * of individual components.
+ * Drupal is calling this function automatically in url(), you should generally
+ * not call it directly.
  *
- * Notes:
- * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
- *   in Apache where it 404s on any path containing '%2F'.
- * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
- *   URLs are used, which are interpreted as delimiters by PHP. These
- *   characters are double escaped so PHP will still see the encoded version.
- * - With clean URLs, Apache changes '//' to '/', so every second slash is
- *   double escaped.
- *
- * @param $text
- *   String to encode
+ * @param $path
+ *   The full URL path to encode.
+ * @return
+ *   The encoded version of the path. Only unsafe characters are encoded.
  */
-function drupal_urlencode($text) {
-  if (variable_get('clean_url', '0')) {
-    return str_replace(array('%2F', '%26', '%23', '//'),
-                        array('/', '%2526', '%2523', '/%252F'),
-                        rawurlencode($text));
-  }
-  else {
-    return str_replace('%2F', '/', rawurlencode($text));
-  }
+function drupal_encode_path($path) {
+  $encoded_path = rawurlencode($path);
+
+  // Revert other characters encoded by rawurlencode() but that don't need to
+  // be according to RFC1738 (all those characters are valid in a 'hpart' part).
+  return str_replace(array('%2F', '%3B', '%3A', '%40', '%26', '%3D', '%24', '%21', '%2A', '%27', '%28', '%29', '%2C'),
+                     array('/', ';', ':', '@', '&', '=', '$', '!', '*', "'", '(', ')', ','),
+                     $encoded_path);
 }
 
 /**
diff --git modules/comment/comment.module modules/comment/comment.module
index 06f7fa9..3d1df72 100644
--- modules/comment/comment.module
+++ modules/comment/comment.module
@@ -2005,10 +2005,10 @@ function theme_comment_post_forbidden($node) {
       // We cannot use drupal_get_destination() because these links
       // sometimes appear on /node and taxonomy listing pages.
       if (variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
-        $destination = 'destination=' . drupal_urlencode("comment/reply/$node->nid#comment-form");
+        $destination = 'destination=' . urlencode("comment/reply/$node->nid#comment-form");
       }
       else {
-        $destination = 'destination=' . drupal_urlencode("node/$node->nid#comment-form");
+        $destination = 'destination=' . urlencode("node/$node->nid#comment-form");
       }
 
       if (variable_get('user_register', 1)) {
diff --git modules/search/search.test modules/search/search.test
index e06198a..711cec9 100644
--- modules/search/search.test
+++ modules/search/search.test
@@ -266,11 +266,11 @@ class SearchAdvancedSearchForm extends DrupalWebTestCase {
     $this->assertNotEqual($dummy_title, $this->node->title, t("Dummy title doens't equal node title"));
 
     // Search for the dummy title with a GET query.
-    $this->drupalGet('search/node/' . drupal_urlencode($dummy_title));
+    $this->drupalGet('search/node/' . $dummy_title);
     $this->assertNoText($this->node->title, t('Page node is not found with dummy title.'));
 
     // Search for the title of the node with a GET query.
-    $this->drupalGet('search/node/' . drupal_urlencode($this->node->title));
+    $this->drupalGet('search/node/' . $this->node->title);
     $this->assertText($this->node->title, t('Page node is found with GET query.'));
 
     // Search for the title of the node with a POST query.
diff --git modules/simpletest/tests/common.test modules/simpletest/tests/common.test
index 8ff4823..c0c1a3e 100644
--- modules/simpletest/tests/common.test
+++ modules/simpletest/tests/common.test
@@ -2,28 +2,93 @@
 // $Id: common.test,v 1.45 2009-06-06 15:43:05 dries Exp $
 
 /**
- * Tests for the l() function.
+ * Tests for URL handling.
  */
-class CommonLUnitTest extends DrupalUnitTestCase {
+class CommonLinksUnitTest extends DrupalWebTestCase {
 
   public static function getInfo() {
     return array(
-      'name' => t('Tests for the l() function'),
-      'description' => t('Confirm that url() works correctly with various input.'),
+      'name' => t('URL Handling'),
+      'description' => t('Confirm that URLs are handled correctly with various input.'),
       'group' => t('System'),
     );
   }
 
+  function setUp() {
+    parent::setUp('system_test');
+  }
+
   /**
    * Confirm that invalid text given as $path is filtered.
    */
-  function testLXSS() {
+  function testLinkXSS() {
     $text = $this->randomName();
     $path = "<SCRIPT>alert('XSS')</SCRIPT>";
     $link = l($text, $path);
     $sanitized_path = check_url(url($path));
     $this->assertTrue(strpos($link, $sanitized_path) != FALSE, t('XSS attack @path was filtered', array('@path' => $path)));
   }
+
+  /**
+   * Confirm that URLs with complex path parts are handled correctly.
+   */
+  function testPathIdempotence() {
+    $test_case = array(
+      // Standard ASCII characters should be returned as-is.
+      'abcd' => 'abcd',
+      // "/" is the path separator, is should be returned as-is.
+      'a/b' => 'a/b',
+      // Spaces and '+' should be conserved.
+      'a+b c+d' => 'a+b c+d',
+      // Non-ASCII Unicode characters should be conserved.
+      'àéèïç€' => 'àéèïç€',
+      // 'safe' characters according to RFC1738 should be conserved.
+      '$-_.+' => '$-_.+',
+      // 'extra' characters according to RFC1738 should be conserved.
+      "!*'()," => "!*'(),",
+      // The reserved characters should be conserved too.
+      ';:@&=' => ';:@&=',
+    );
+
+    foreach ($test_case as $input => $expected) {
+      $this->drupalGet('system-test/print/' . $input);
+      $output = $this->drupalGetContent();
+      if (!empty($output)) {
+        $this->assertIdentical($output, $expected, t('Path %input is returned as %output (expected %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
+      }
+      else {
+        $this->fail(t('Failed to test path %input, invalid value returned.', array('%input' => $input)));
+      }
+    }
+  }
+
+  /**
+   * Confirm that URL paths are encoded correctly.
+   */
+  function testEncodePath() {
+    $test_case = array(
+      // Standard ASCII characters should be returned as-is.
+      'abcd' => 'abcd',
+      // "/" is the path separator, is should be returned as-is.
+      'a/b' => 'a/b',
+      'a//b' => 'a//b',
+      // Spaces and '+' should be encoded.
+      'a+b c+d' => 'a%2Bb%20c%2Bd',
+      // Non-ASCII Unicode characters should be encoded.
+      'àéèïç€' => '%C3%A0%C3%A9%C3%A8%C3%AF%C3%A7%E2%82%AC',
+      // 'safe' characters according to RFC1738 should be returned as-is.
+      '$-_.' => '$-_.',
+      // 'extra' characters according to RFC1738 should be returned as-is, too.
+      "!*'()," => "!*'(),",
+      // The reserved characters should be returned as-is, too.
+      ';:@&=' => ';:@&=',
+    );
+
+    foreach ($test_case as $input => $expected) {
+      $output = drupal_encode_path($input);
+      $this->assertIdentical($output, $expected, t('Path %input is encoded as %output (expected %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
+    }
+  }
 }
 
 class CommonSizeTestCase extends DrupalUnitTestCase {
diff --git modules/simpletest/tests/system_test.module modules/simpletest/tests/system_test.module
index 9c82e5b..409e56f 100644
--- modules/simpletest/tests/system_test.module
+++ modules/simpletest/tests/system_test.module
@@ -50,7 +50,6 @@ function system_test_menu() {
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
-
   $items['system-test/variable-get'] = array(
     'title' => 'Variable Get',
     'page callback' => 'variable_get',
@@ -58,7 +57,13 @@ function system_test_menu() {
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
-
+  $items['system-test/print'] = array(
+    'title' => 'Print',
+    'page callback' => 'system_test_print',
+    'page arguments' => array(),
+    'access callback' => TRUE,
+    'type' => MENU_CALLBACK,
+  );
   return $items;
 }
 
@@ -165,3 +170,12 @@ function system_test_exit() {
   watchdog('system_test', 'hook_exit');
 }
 
+/**
+ * Print the text that was passed.
+ */
+function system_test_print() {
+  $args = arg();
+  array_shift($args);
+  array_shift($args);
+  echo implode('/', $args);
+}
diff --git modules/update/update.fetch.inc modules/update/update.fetch.inc
index 9bca0f0..3a7c78f 100644
--- modules/update/update.fetch.inc
+++ modules/update/update.fetch.inc
@@ -114,10 +114,10 @@ function _update_build_fetch_url($project, $site_key = '') {
   if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
     $url .= (strpos($url, '?') === TRUE) ? '&' : '?';
     $url .= 'site_key=';
-    $url .= drupal_urlencode($site_key);
+    $url .= urlencode($site_key);
     if (!empty($project['info']['version'])) {
       $url .= '&version=';
-      $url .= drupal_urlencode($project['info']['version']);
+      $url .= urlencode($project['info']['version']);
     }
   }
   return $url;
