From 5d5455a3a4c4910be22a1efb53de624f327177e6 Mon Sep 17 00:00:00 2001
From: Joey O. Chua <jochua@ceu.edu.ph>
Date: Thu, 17 Mar 2011 18:27:11 +0800
Subject: [PATCH] Issue #364796 by joeycbulk: Added feature automatic delete attached images when node deleted option.

---
 contrib/image_attach/image_attach.module |   15 +++++++++++++++
 1 files changed, 15 insertions(+), 0 deletions(-)

diff --git a/contrib/image_attach/image_attach.module b/contrib/image_attach/image_attach.module
index 87dda1f..bc9c8d7 100644
--- a/contrib/image_attach/image_attach.module
+++ b/contrib/image_attach/image_attach.module
@@ -176,6 +176,13 @@ function image_attach_form_node_type_form_alter(&$form, $form_state) {
       $link = l(t('Manage fields'), $_GET['q'] . '/fields');
       $form['image_attach']['#description'] = t('Since you installed CCK module, you can change the image weight in the !link page.', array('!link' => $link));
     }
+    $form['image_attach']['image_attach_auto_delete'] = array(
+      '#type' => 'radios',
+      '#title' => t('Automatically delete attached images when a node is deleted'),
+      '#default_value' => variable_get('image_attach_auto_delete_' . $form['#node_type']->type, 0),
+      '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
+      '#description' => t('This option enables automatic deletion of associated image nodes when parent node is deleted. Image nodes attached to a different node will not be deleted by this option.')
+    );
   }
 }
 
@@ -425,6 +432,14 @@ function image_attach_nodeapi(&$node, $op, $teaser, $page) {
       break;
 
     case 'delete':
+      if (variable_get('image_attach_auto_delete_' . $node->type, 0) == 1) {
+        // Delete attached image nodes associated with parent node. Make sure
+        // that the image node being deleted is not being used by other nodes.
+        $nids = db_query("SELECT iid FROM {image_attach} ia1 WHERE nid = %d AND NOT EXISTS(SELECT * FROM {image_attach} ia2 WHERE ia2.nid != ia1.nid AND ia2.nid != 0 AND ia2.iid = ia1.iid)", $node->nid);
+        while ($nid = db_result($nids)) {
+          node_delete($nid);
+        }
+      }
       db_query("DELETE FROM {image_attach} WHERE nid = %d", $node->nid);
       break;
 
-- 
1.7.2.3

