*** image/contrib/image_attach/image_attach.module	2011-03-03 01:20:26.000000000 +0800
--- image/contrib/image_attach/image_attach.module	2011-03-15 20:18:53.499809161 +0800
***************
*** 176,181 ****
--- 176,188 ----
        $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('Auto Delete'),
+       '#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 attached images when node is deleted or enables node to automatically delete images being detached.')
+     );
    }
  }
  
***************
*** 414,419 ****
--- 421,450 ----
    switch ($op) {
      case 'insert':
      case 'update':
+       // Check if auto delete is enabled
+       if (variable_get('image_attach_auto_delete_' . $node->type, 0) == 1) {        
+         if (!empty($node->iids)) {
+           $db_params = array($node->nid);
+           $where_in = array();
+           foreach ($node->iids as $iid) {
+             $db_params[] = $iid;
+             $where_in[] = '%d';
+           }
+           $where_in = implode(',',$where_in);
+           // select detached iids
+           $nids = db_query("SELECT iid FROM {image_attach} WHERE nid = %d AND iid NOT IN({$where_in})", $db_params);
+           while ($nid = db_result($nids)) {
+             node_delete($nid);
+           }
+         }
+         // if none was selected from multi select box
+         else {
+           $nids = db_query("SELECT iid FROM {image_attach} WHERE nid = %d", $node->nid);
+           while ($nid = db_result($nids)) {
+             node_delete($nid);
+           }
+         }
+       }
        db_query("DELETE FROM {image_attach} WHERE nid = %d", $node->nid);
        if (!empty($node->iids)) {
          // Populate weight column with placeholder values.
***************
*** 425,430 ****
--- 456,468 ----
        break;
  
      case 'delete':
+       if (variable_get('image_attach_auto_delete_' . $node->type, 0) == 1) {
+         // delete attached images
+         $nids = db_query("SELECT iid FROM {image_attach} WHERE nid = %d", $node->nid);
+         while ($nid = db_result($nids)) {
+           node_delete($nid);
+         }
+       }
        db_query("DELETE FROM {image_attach} WHERE nid = %d", $node->nid);
        break;
  
***************
*** 734,738 ****
      );
      return $extra;
    }
! }
! 
--- 772,775 ----
      );
      return $extra;
    }
! }
\ No newline at end of file
