Index: /tmp/dr/drupal/includes/file.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/file.inc,v
retrieving revision 1.241
diff -u -r1.241 file.inc
--- file.inc	20 Nov 2010 09:43:43 -0000	1.241
+++ file.inc	30 Nov 2010 18:08:31 -0000
@@ -2280,7 +2280,8 @@
  * @see http://drupal.org/node/515192
  *
  * @param $directory
- *   The directory where the temporary filename will be created.
+ *   The directory where the temporary filename will be created. This should
+ *   already exist and be writeable by PHP.
  * @param $prefix
  *   The prefix of the generated temporary filename.
  *   Note: Windows uses only the first three characters of prefix.
@@ -2295,10 +2296,20 @@
   $scheme = file_uri_scheme($directory);
 
   if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
-    $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
+    $local_directory = drupal_realpath($directory);
 
-    if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
-      return $scheme . '://' . basename($filename);
+    if ($filename = tempnam(drupal_realpath($directory), $prefix)) {
+      // If the specified directory doesn't exist then PHP's tempname may return
+      // a file in the system temporary directory, but then we can't assume that
+      // we can just use the same name in our returned URI, so we return failure
+      // in this case.
+      if (dirname($filename) != $local_directory) {
+        return FALSE;
+      }
+      else {
+        $uri = $scheme .'://' . file_uri_target($directory) . '/' . basename($filename);
+        return file_stream_wrapper_uri_normalize($uri);
+      }
     }
     else {
       return FALSE;
