Fix for Fix for This code will extract files form a zip file uploaded via a specific FileField

  1. <?php
  2. function my_unzip_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  3.   if ($node->type == 'test') {
  4.     dsm($node);
  5.     switch ($op) {
  6.       case 'update':
  7.         if (!is_null($node->field_zipfile[0])) {
  8.           my_unzip_unzip($node);
  9.         }
  10.         break;
  11.     } // /switch ($op)
  12.   }
  13. }
  14.  
  15. /**
  16.  * This function unzip a zip file uploaded via a specific FileField field.
  17.  */
  18. function my_unzip_unzip($node) {
  19.   // Define the FileField field here.
  20.   $zipfilepath = $node->field_zipfile[0]['filepath'];
  21.   // Define the directory for unzipped files here.
  22.   $unzipdir = file_directory_path() . '/nid_' . $node->nid . '/unzipfiles';
  23.   $macdir_in_unzipdir = $unzipdir . '/__MACOSX';
  24.  
  25.   // if the directory for unzipped files doesn't exist yet, create the directory.
  26.   if (!file_exists($unzipdir)){
  27.     mkdir($unzipdir);
  28.   }
  29.  
  30.   // Actual unzipping.
  31.   $zip = new ZipArchive;
  32.   $res = $zip->open($zipfilepath);
  33.   if ($res === TRUE) {
  34.     $zip->extractTo($unzipdir);
  35.     $zip->close();
  36.   } else {
  37.     drupal_set_message($message = 'The decompression was failed.', $type = 'error');
  38.   }
  39.  
  40.   // If the zip file was created on the Mac platform, special directory and files will be included in the zip file.  The code below will delete these directory and files.
  41.   if (file_exists($macdir_in_unzipdir)){
  42.     deleteDirectory($macdir_in_unzipdir);
  43.   }
  44. }
  45.  
  46.  
  47. /**
  48.  * Delete a specific directory.
  49.  * Delete files inside the directory, if such exist.
  50.  */
  51. function deleteDirectory($dir) {
  52.   if (!file_exists($dir)) return true;
  53.   if (!is_dir($dir)) return unlink($dir);
  54.   foreach (scandir($dir) as $item) {
  55.     if ($item == '.' || $item == '..') continue;
  56.     if (!deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
  57.   }
  58.   return rmdir($dir);
  59. }

Submit Fix

Any tags you'd like to associate with your code, delimitered by commas (example: Views, CCK, Module, etc).
Select the syntax highlighting mode to use.