From 3ca00167c79a7882c9ec8e58723b46c5bc2ad3d6 Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Wed, 8 Apr 2015 16:27:55 -0500
Subject: [PATCH] forms: Cleanup file attachments when custom data is deleted

---
 include/class.dynamic_forms.php |  9 +++++++++
 include/class.forms.php         | 17 +++++++++++++++++
 include/class.organization.php  |  9 +++++++++
 3 files changed, 35 insertions(+)

diff --git a/include/class.dynamic_forms.php b/include/class.dynamic_forms.php
index 3bb5fcf7e..582c40a78 100644
--- a/include/class.dynamic_forms.php
+++ b/include/class.dynamic_forms.php
@@ -1130,6 +1130,15 @@ class DynamicFormEntryAnswer extends VerySimpleModel {
         $v = $this->toString();
         return is_string($v) ? $v : (string) $this->getValue();
     }
+
+    function delete() {
+        if (!parent::delete())
+            return false;
+
+        // Allow the field to cleanup anything else in the database
+        $this->getField()->db_cleanup();
+        return true;
+    }
 }
 
 class SelectionField extends FormField {
diff --git a/include/class.forms.php b/include/class.forms.php
index 01bd11ade..0249de4d8 100644
--- a/include/class.forms.php
+++ b/include/class.forms.php
@@ -397,6 +397,15 @@ class FormField {
         return $this->toString($this->value);
     }
 
+    /**
+     * When data for this field is deleted permanently from some storage
+     * backend (like a database), other associated data may need to be
+     * cleaned as well. This hook allows fields to participate when the data
+     * for a field is cleaned up.
+     */
+    function db_cleanup() {
+    }
+
     /**
      * Returns an HTML friendly value for the data in the field.
      */
@@ -1678,6 +1687,14 @@ class FileUploadField extends FormField {
         }
         return implode(', ', $files);
     }
+
+    function db_cleanup() {
+        // Delete associated attachments from the database, if any
+        $this->getFiles();
+        if (isset($this->attachments)) {
+            $this->attachments->deleteAll();
+        }
+    }
 }
 
 class Widget {
diff --git a/include/class.organization.php b/include/class.organization.php
index 458a1f7ee..587d0d5a7 100644
--- a/include/class.organization.php
+++ b/include/class.organization.php
@@ -336,6 +336,15 @@ class Organization extends OrganizationModel {
         return $this->save();
     }
 
+    function delete() {
+        if (!parent::delete())
+            return false;
+
+        foreach ($this->getDynamicData(false) as $entry) {
+            $entry->delete();
+        }
+    }
+
     static function fromVars($vars) {
 
         if (!($org = Organization::lookup(array('name' => $vars['name'])))) {
-- 
GitLab