From ef6c36f78438025edc0d3903a0692179a2311062 Mon Sep 17 00:00:00 2001
From: Joey O. Chua <joey@chua.homeip.net>
Date: Sun, 20 Mar 2011 20:11:43 +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..d41c3e8 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} ia_outer WHERE ia_outer.nid = %d AND (SELECT COUNT(ia_inner.nid) attached_count FROM {image_attach} ia_inner WHERE ia_inner.iid = ia_outer.iid) = 1", $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.5

