From 2aa53691b0a3f4539cbd49d75aa7aa10678dc34a Mon Sep 17 00:00:00 2001
From: Owen Barton <drupal@owenbarton.com>
Date: Tue, 26 Apr 2011 16:50:40 -0700
Subject: [PATCH] Issue #935592: User picture is deleted after calls to user_save()

---
 modules/user/user.module |   35 +++++++++++++++++++++++------------
 1 files changed, 23 insertions(+), 12 deletions(-)

diff --git a/modules/user/user.module b/modules/user/user.module
index 92a55bc..1cb94e8 100644
--- a/modules/user/user.module
+++ b/modules/user/user.module
@@ -460,12 +460,23 @@ function user_save($account, $edit = array(), $category = 'account') {
     }
 
     if (is_object($account) && !$account->is_new) {
-      // Process picture uploads.
-      if (!$delete_previous_picture = empty($edit['picture']->fid)) {
+
+      // Process picture uploads only if the picture key is present in the edit
+      // array.
+      if (array_key_exists('picture', $edit)) {
         $picture = $edit['picture'];
-        // If the picture is a temporary file move it to its final location and
-        // make it permanent.
-        if (!$picture->status) {
+        $delete_previous_picture = FALSE;
+
+        // If the picture has been set to NULL, any existing picture should be
+        // marked for deletion.
+        if (is_null($picture)) {
+          $delete_previous_picture = TRUE;
+        }
+        // If the picture has been set to a file object that is different from
+        // the existing file, make that file permanent and mark the previous
+        // file for deletion. If the fid matches the old one no change has been
+        // made so nothing needs to be done.
+        elseif (isset($picture->fid) && (!isset($account->picture->fid) || $picture->fid != $account->picture->fid) && $picture->status != FILE_STATUS_PERMANENT) {
           $info = image_get_info($picture->uri);
           $picture_directory =  file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');
 
@@ -481,15 +492,15 @@ function user_save($account, $edit = array(), $category = 'account') {
             file_usage_add($picture, 'user', 'user', $account->uid);
           }
         }
-      }
 
-      // Delete the previous picture if it was deleted or replaced.
-      if ($delete_previous_picture && !empty($account->picture->fid)) {
-        file_usage_delete($account->picture, 'user', 'user', $account->uid);
-        file_delete($account->picture);
-      }
+        // Delete the previous picture if it was deleted or replaced.
+        if ($delete_previous_picture && !empty($account->picture->fid)) {
+          file_usage_delete($account->picture, 'user', 'user', $account->uid);
+          file_delete($account->picture);
+        }
 
-      $edit['picture'] = empty($edit['picture']->fid) ? 0 : $edit['picture']->fid;
+        $edit['picture'] = empty($edit['picture']->fid) ? 0 : $edit['picture']->fid;
+      }
 
       // Do not allow 'uid' to be changed.
       $edit['uid'] = $account->uid;
-- 
1.7.1

