From 8bbc5b40d3129cde39e7828613bbf3d3163f5fc3 Mon Sep 17 00:00:00 2001
From: Sofian Benaissa <sofian@koumbit.org>
Date: Wed, 3 Aug 2011 12:17:29 -0400
Subject: [PATCH] Patch #1002048 Work-around managed file uploads for open_basedir restrictions

---
 includes/file.inc |   43 ++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 42 insertions(+), 1 deletions(-)

diff --git a/includes/file.inc b/includes/file.inc
index e0da216..ccb00a9 100644
--- a/includes/file.inc
+++ b/includes/file.inc
@@ -1538,7 +1538,7 @@ function file_save_upload($source, $validators = array(), $destination = FALSE,
   // directory. This overcomes open_basedir restrictions for future file
   // operations.
   $file->uri = $file->destination;
-  if (!move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
+  if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
     form_set_error($source, t('File upload error. Could not move uploaded file.'));
     watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
     return FALSE;
@@ -1565,6 +1565,47 @@ function file_save_upload($source, $validators = array(), $destination = FALSE,
   return FALSE;
 }
 
+/**
+ * Moves an uploaded file to a new location.
+ *
+ * PHP's move_uploaded_file() does not properly support streams if safe_mode
+ * or open_basedir are enabled, so this function fills that gap.
+ *
+ * @see http://php.net/move_uploaded_file
+ *
+ * Compatibility: normal paths and stream wrappers.
+ * @see http://drupal.org/node/515192
+ *
+ * @param $filename
+ *   The filename of the uploaded file.
+ * @param $uri
+ *   A string containing the destination URI of the file.
+ *
+ * @return
+ *   TRUE on success, or FALSE on failure.
+ *
+ * @see move_uploaded_file()
+ * @ingroup php_wrappers
+ */
+function drupal_move_uploaded_file($filename, $uri) {
+  // Attempt to move the file using the provided URI. Errors are supressed here
+  // so that if streams aren't properly supported, we don't see a warning
+  // message for every upload.
+  $result = @move_uploaded_file($filename, $uri);
+  // If the move failed and a real path can be found, attempt to move the file
+  // using the real path.
+  if (!$result && drupal_realpath($uri)) {
+    $result = move_uploaded_file($filename, drupal_realpath($uri));
+  }
+  // Otherwsie, attempt the failed move again so that a useful error message
+  // is produced.
+  else {
+    $result = move_uploaded_file($filename, $uri);
+  }
+
+  return $result;
+}
+
 
 /**
  * Check that a file meets the criteria specified by the validators.
-- 
1.7.2.5

