From c13c330c8b6689397ff572dffada1c01dc050b32 Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Tue, 28 Jan 2014 22:40:07 -0600
Subject: [PATCH] oops: Fix finding key of existing file

If a file is attached via email and sent into the system, and a file is on
record with the same signature (hash) and size, the system will not save the
file. Instead, the key of the existing file would be found and used instead.

This patch fixes a bug in AttachmentFile::save. The key was generated for
the new file; however, if it was determined to be a duplicate, the key of
the existing file was not returned. Therefore generated key, which wasn't
saved to the database, was returned. Therefore, the wrong key was placed in
the body of the message with cid:<key> for inline images, although that key
would not exist in the database.

This patch correctly returns the existing key from the ::save() method
for de-duplicated files.
---
 include/class.file.php | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/include/class.file.php b/include/class.file.php
index cc9063066..98b66e46b 100644
--- a/include/class.file.php
+++ b/include/class.file.php
@@ -322,14 +322,16 @@ class AttachmentFile {
         }
 
         // Check and see if the file is already on record
-        $sql = 'SELECT id FROM '.FILE_TABLE
+        $sql = 'SELECT id, key FROM '.FILE_TABLE
             .' WHERE signature='.db_input($file['signature'])
             .' AND size='.db_input($file['size']);
 
         // If the record exists in the database already, a file with the
         // same hash and size is already on file -- just return its ID
-        if ($id = db_result(db_query($sql)))
+        if (list($id, $key) = db_fetch_row(db_query($sql))) {
+            $file['key'] = $key;
             return $id;
+        }
 
         $sql='INSERT INTO '.FILE_TABLE.' SET created=NOW() '
             .',type='.db_input(strtolower($file['type']))
-- 
GitLab