From e49df1e78ed853299cb79088254c97279270d990 Mon Sep 17 00:00:00 2001
From: uberhacker <edreel@gmail.com>
Date: Fri, 22 Apr 2011 16:33:55 -0400
Subject: [PATCH] [#1036684] by uberhacker.  Initial D7 commit.

---
 README.txt                      |   13 +-
 zipcart-block-downloads.tpl.php |   21 ++-
 zipcart.admin.inc               |  125 ++++++++++++--
 zipcart.info                    |   12 +-
 zipcart.js                      |   60 +++++--
 zipcart.module                  |  363 +++++++++++++++++++++++----------------
 6 files changed, 398 insertions(+), 196 deletions(-)

diff --git a/README.txt b/README.txt
index 08080ac..4c994ed 100644
--- a/README.txt
+++ b/README.txt
@@ -9,16 +9,11 @@ want to give users the capacity to select several files for download, then downl
 in a single archive.
 
 
-DEMO
-
-Take a look at http://zipcart.demo.giantrobot.co.nz/ to get an idea of how this works.
-
-
 USAGE
 
 There are two steps to using this module.
 
-* Visit admin/settings/zipcart and select the appropriate Zip handler.
+* Visit admin/config/media/zipcart and select the appropriate Zip Method handler.
 
 * Update your theme with download links to ZipCart, using theme('zipcart_download').
   This function simply wraps l(), so the parameters are similar: $html, $path, $options.
@@ -26,10 +21,10 @@ There are two steps to using this module.
   
     <?php print theme('zipcart_download', 'Download file', 'sites/default/files/file1.txt'); ?>
 
-* You need to expose the "ZipCart Downloads" block via admin/build/block/list
+* You need to expose the "ZipCart Downloads" block via admin/structure/block
   This block provides the link for users to build the zip with their files and download it.
 
-* Configure permissions for roles to access ZipCart downloads at admin/user/permissions
+* Configure permissions for roles to access ZipCart downloads at admin/people/permissions
 
 JAVASCRIPT ENHANCEMENTS
 
@@ -41,4 +36,4 @@ and you may want to ensure the ZipCart Downloads block is always visible on scre
 is fixed on screen if there are files to download.
 
 If JS is not present or enabled, the module should continue to work as per normal, with
-a message displayed to the user as each file is added to the cart.
\ No newline at end of file
+a message displayed to the user as each file is added to the cart.
diff --git a/zipcart-block-downloads.tpl.php b/zipcart-block-downloads.tpl.php
index 7b753be..76d120b 100644
--- a/zipcart-block-downloads.tpl.php
+++ b/zipcart-block-downloads.tpl.php
@@ -2,10 +2,23 @@
 /**
  * Template to display My Downloads link.
  *
+ * $title - the block title
+ * $width - the block width
  * $count - number of files in cart currently
- * $files - the files
+ * $files - the library files
+ * $path - the library path
  */
  ?>
-<div class="zipcart-block-downloads">
-  <?php print l(t('My Downloads (<span class="zipcart-download-count">!count</span> files)', array('!count' => $count)), 'zipcart/get', array('html' => TRUE, 'query' => _zipcart_get_destination_alias())) ; ?>
-</div>
\ No newline at end of file
+<div class="zipcart-block-downloads" style="width:<?php print $width; ?>px;">
+<?php
+  if ($count) {
+    print l(t($title . ' (<span class="zipcart-download-count">%count</span>)', array('%count' => $count)), 'zipcart/get', array('html' => TRUE, 'query' => _zipcart_get_destination_alias())) . '<br />';
+    if (!empty($files)) {
+      foreach($files as $file) {
+        print '<div class="zipcart-file">' . basename($file) . '</div>';
+      }
+    }
+    print l(t('Empty your cart'), 'zipcart/empty', array('query' => array('destination' => $path)));
+  }
+?>
+</div>
diff --git a/zipcart.admin.inc b/zipcart.admin.inc
index 3b1d6e8..aa5775f 100644
--- a/zipcart.admin.inc
+++ b/zipcart.admin.inc
@@ -1,12 +1,14 @@
 <?php
+// $Id$
 
 /**
- * Settings form
+ * @file
+ * ZipCart Admin Settings Form
  */
 function zipcart_settings_form() {
-  $methods = _zipcart_get_available_methods() ;
+  $methods = _zipcart_get_available_methods();
   foreach ( $methods as $k => $v ) {
-    $options[$k] = $v['title'] ;
+    $options[$k] = $v['title'];
   }
   $form['zipcart_zip_method'] = array(
     '#title' => t('Zip Method'),
@@ -14,30 +16,127 @@ function zipcart_settings_form() {
     '#default_value' => variable_get('zipcart_zip_method', ''),
     '#options' => $options,
     '#description' => t('Method used to generate bundle files.'),
-  ) ;
+  );
 
-  $form['zipcart_zip_dir'] = array(
-    '#title' => t('Zip Cache Directory'),
+  $form['zipcart_zip_prefix'] = array(
+    '#title' => t('Zip File Prefix'),
     '#type' => 'textfield',
-    '#default_value' => variable_get('zipcart_cache', 'zipcart'),
-    '#description' => t('Directory to build files in, relative to !dir.', array('!dir' => file_directory_path())),
-  ) ;
+    '#size' => 20,
+    '#default_value' => variable_get('zipcart_zip_prefix', 'Files'),
+    '#description' => t('Enter the prefix for the zip file. The current date and time will be appended at the time of download.'),
+  );
+
+  $form['zipcart_zip_limit'] = array(
+    '#title' => t('Zip File Limit'),
+    '#type' => 'textfield',
+    '#size' => 20,
+    '#default_value' => variable_get('zipcart_zip_limit', 16),
+    '#description' => t('Enter the maximum number of files allowed in a zip file.'),
+  );
+
+  $form['zipcart_zip_size'] = array(
+    '#title' => t('Max Zip File Size'),
+    '#type' => 'textfield',
+    '#size' => 20,
+    '#default_value' => variable_get('zipcart_zip_size', 32768),
+    '#description' => t('Enter the maximum file size in kilobytes allowed for a zip file.'),
+  );
+
+  $form['zipcart_file_dirs'] = array(
+    '#title' => t('Valid File Directories'),
+    '#type' => 'textarea',
+    '#cols' => 30,
+    '#rows' => 3,
+    '#default_value' => variable_get('zipcart_file_dirs', 'zipcart'),
+    '#description' => t('Valid directories to place library files, relative to %dir. Enter each directory on a separate line. Do not include leading or trailing slash.', array('%dir' => variable_get('file_public_path', 'sites/default/files'))),
+  );
+
+  $form['zipcart_file_library'] = array(
+    '#title' => t('File Library URL'),
+    '#type' => 'textfield',
+    '#size' => 20,
+    '#default_value' => variable_get('zipcart_file_library', 'file-library'),
+    '#description' => t('Enter the URL to where files can be selected to create the zip file.'),
+  );
+
+  $form['zipcart_block_title'] = array(
+    '#title' => t('Cart Block Title'),
+    '#type' => 'textfield',
+    '#size' => 20,
+    '#default_value' => variable_get('zipcart_block_title', 'My Downloads'),
+    '#description' => t('Enter the block title for the cart.'),
+  );
+
+  $form['zipcart_option_fieldset'] = array(
+    '#title' => t('Message Options'),
+    '#type' => 'fieldset',
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_added'] = array(
+    '#title' => t('Display file added to cart message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_added', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_queued'] = array(
+    '#title' => t('Display no files queued message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_queued', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_emptied'] = array(
+    '#title' => t('Display cart emptied message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_emptied', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_create'] = array(
+    '#title' => t('Display unable to create file message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_create', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_downloaded'] = array(
+    '#title' => t('Display file downloaded message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_downloaded', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_limit'] = array(
+    '#title' => t('Display file limit exceeded message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_limit', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_size'] = array(
+    '#title' => t('Display file size limit exceeded message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_size', 1),
+  );
+
+  $form['zipcart_option_fieldset']['zipcart_display_path'] = array(
+    '#title' => t('Display path is not valid message'),
+    '#type' => 'checkbox',
+    '#default_value' => variable_get('zipcart_display_path', 1),
+  );
 
   $items['zip_builtin'] = array( 
     '#type' => 'fieldset',
     '#title' => 'PHP Zip settings',
-  ) ;
+  );
 
   $items['zip_pecl'] = array(
     '#type' => 'fieldset',
     '#title' => 'PECL Zip settings',
-  ) ;
+  );
 
   $items['zip_external'] = array(
     '#type' => 'fieldset',
     '#title' => 'External Zip binary settings',
-  ) ;
+  );
 
-  return system_settings_form($form) ;
+  return system_settings_form($form);
 }
 
diff --git a/zipcart.info b/zipcart.info
index 9d96ea2..483807d 100644
--- a/zipcart.info
+++ b/zipcart.info
@@ -1,6 +1,10 @@
-core = "6.x"
-description = "Allow users to add files to a cart, then download them as a zip."
 name = "ZipCart"
-package = "Other"
+description = "Allow users to add files to a cart, then download them as a zip."
+core = "7.x"
+package = "Media"
 project = "zipcart"
-; dependencies[] = "jquery_update"
+dependencies[] = "jquery_update"
+dependencies[] = "shadowbox"
+files[] = zipcart.admin.inc
+files[] = zipcart.module
+files[] = zipcart.js
diff --git a/zipcart.js b/zipcart.js
index 7018f6f..976908e 100644
--- a/zipcart.js
+++ b/zipcart.js
@@ -1,7 +1,31 @@
+// $Id$
+
+// Global killswitch: only run if we are in a supported browser.
+if (Drupal.jsEnabled) {
+  (function($) {
+    $(document).ready(function(){
+/*
+      $("a.fancybox").mouseover(function(){
+        alert('stuff');
+      });
+*/
+      // Display preview links in fancybox
+
+      $("a.fancybox").fancybox({
+        'titleShow'     : false,
+        'transitionIn'  : 'none',
+        'transitionOut' : 'none',
+        'frameWidth'    : '960',
+        'frameHeight'   : '960',
+      });
+    });
+  })(jQuery);
+}
+
 Drupal.zipcart = {
 
   init: function() {
-    $('a.zipcart').click( Drupal.zipcart.addToCart ) ;
+    $('a.zipcart').click( Drupal.zipcart.addToCart );
   },
 
   addToCart: function(e) {
@@ -9,7 +33,7 @@ Drupal.zipcart = {
     // this next wants cleanup (and possibly using 'is' instead of the below)
     // basically: get me the clicked 'a', or the parent 'a'.
     if ( e.target.tagName.toLowerCase() == 'a' ) {
-      a = e.target ;
+      a = e.target;
     }
     else {
       if ( a = $(e.target).parents('a[href]') ) {
@@ -22,16 +46,16 @@ Drupal.zipcart = {
     
     e.preventDefault();
     // add AJAX parameter
-    filePath = $(a).attr('href').replace(Drupal.settings.zipcart.path_add, Drupal.settings.zipcart.path_add_ajax) ;
+    filePath = $(a).attr('href').replace(Drupal.settings.zipcart.path_add, Drupal.settings.zipcart.path_add_ajax);
     // add Drupal basePath
-    filePath = Drupal.settings.basePath + filePath ;
+    filePath = Drupal.settings.basePath + filePath;
     // remove multiple slashes at start
     filePath = filePath.replace(/^\/+/, '/');
     $.ajax({
       'url': filePath,
       'dataType': 'json',
       success: function(data, textStatus, req) {
-        Drupal.settings.zipcart.cart = data.cart ;
+        Drupal.settings.zipcart.cart = data.cart;
         cart = $('.zipcart-block-downloads');
         // copy the element for animation - with thanks to jQuery 'fake' plugin by Carl Fürstenberg
         orig_offset = $(a).offset();
@@ -60,33 +84,33 @@ Drupal.zipcart = {
           height: orig_height/2 
         };
         animCallback = function(data) {
-          clone.fadeOut().remove() ;
-          $('.zipcart-download-count').html( Drupal.settings.zipcart.cart.length ) ;
+          clone.fadeOut().remove();
+          $('.zipcart-download-count').html( Drupal.settings.zipcart.cart.length );
         }
         clone.animate(animProps, 'slow', 'swing', animCallback);
       },
       error: function(req, textStatus, errorThrown) {
-        alert('Unable to add the file to your ZipCart.');
+        alert(Drupal.t('Unable to add the file to your ZipCart.'));
 /*
         console.log(req);
         console.log(textStatus);
         console.log(errorThrown);
 */
         switch ( textStatus ) {
-          case 'timeout' :
-          case 'null' :
-          case 'error' :
-          case 'parsererror' :
-          case 'notmodified' :
-            break ;
-          default :
-            break ;
+          case 'timeout':
+          case 'null':
+          case 'error':
+          case 'parsererror':
+          case 'notmodified':
+            break;
+          default:
+            break;
         }
         // probably not permitted - handle file access restriction here
       }
     });  
   }
   
-} ;
+};
 
-Drupal.behaviors.zipcart = Drupal.zipcart.init ;
\ No newline at end of file
+Drupal.behaviors.zipcart = Drupal.zipcart.init;
diff --git a/zipcart.module b/zipcart.module
index 45708b9..4bb50b5 100644
--- a/zipcart.module
+++ b/zipcart.module
@@ -1,6 +1,10 @@
 <?php
+// $Id$
 
 /**
+ * @file
+ * ZipCart Module File
+ &
  * TODO:
  * 
  * prevent access outside files dir
@@ -11,126 +15,168 @@
 
 define('ZIPCART_PATH_ADD', 'zipcart/add');
 define('ZIPCART_PATH_GET', 'zipcart/get');
+define('ZIPCART_PATH_EMPTY', 'zipcart/empty');
 
 /**
- * Implementation of hook_menu()
+ * Implements hook_menu()
  */
 function zipcart_menu() {
-  $items['admin/settings/zipcart'] = array(
+  $items['admin/config/media/zipcart'] = array(
     'page callback' => 'drupal_get_form',
     'page arguments' => array( 'zipcart_settings_form' ),
     'title' => 'ZipCart',
-    'description' => 'Configure Zip settings for ZipCart',
-    'access arguments' => array( 'administer site configuration' ),
+    'description' => 'Configure settings for ZipCart',
+    'access arguments' => array( 'administer zipcart' ),
     'type' => MENU_NORMAL_ITEM,
     'file' => 'zipcart.admin.inc',
-  ) ;
+  );
   $items[ZIPCART_PATH_ADD] = array(
     'page callback' => 'zipcart_add_file_to_cart',
     'page arguments' => array( FALSE ),
     'title' => 'Add file to Download Cart',
     'type' => MENU_CALLBACK,
     'access arguments' => array('access content'),
-  ) ;
-  $items[ZIPCART_PATH_ADD .'/AJAX'] = array(
+  );
+  $items[ZIPCART_PATH_ADD . '/AJAX'] = array(
     'page callback' => 'zipcart_add_file_to_cart',
     'page arguments' => array( TRUE ),
     'title' => 'Add file to Download Cart',
     'type' => MENU_CALLBACK,
     'access arguments' => array('access content'),
-  ) ;
-  $items['zipcart/get'] = array(
+  );
+  $items[ZIPCART_PATH_GET] = array(
     'page callback' => 'zipcart_get_zip',
     'title' => 'Download Cart Files',
     'type' => MENU_CALLBACK,
     'access arguments' => array('access content'),
-  ) ;
-  return $items ;
+  );
+  $items[ZIPCART_PATH_EMPTY] = array(
+    'page callback' => 'zipcart_empty_cart',
+    'title' => 'Empty Cart Files',
+    'type' => MENU_CALLBACK,
+    'access arguments' => array('access content'),
+  );
+  return $items;
 }
 
 /**
- * Implementation of hook_init().
+ * Implements hook_init().
  */
 function zipcart_init() {
   drupal_add_js(drupal_get_path('module', 'zipcart') . '/zipcart.js');
-  drupal_add_js(array('zipcart' => array('path_add' => ZIPCART_PATH_ADD, 'path_add_ajax' => ZIPCART_PATH_ADD .'/AJAX')), 'setting');
+  drupal_add_js(array('zipcart' => array('path_add' => ZIPCART_PATH_ADD, 'path_add_ajax' => ZIPCART_PATH_ADD . '/AJAX')), 'setting');
 }
 
 /**
- * Implementation of hook_theme().
+ * Implements hook_theme().
  */
 function zipcart_theme($existing, $type, $theme, $path) {
   return array(
     'zipcart_block_downloads' => array(
       'template' => 'zipcart-block-downloads',
-      'arguments' => array(
+      'variables' => array(
+        'title' => variable_get('zipcart_block_title', 'My Downloads'),
+        'width' => variable_get('zipcart_block_width', 200),
         'count' => ( !empty($_SESSION['zipcart']['files']) ) ? sizeof($_SESSION['zipcart']['files']) : 0,
         'files' => ( !empty($_SESSION['zipcart']['files']) ) ? $_SESSION['zipcart']['files'] : NULL,
+        'path' => variable_get('zipcart_file_library', 'file-library'),
       ),
     ),
     'zipcart_download' => array(
-      'arguments' => array(
+      'variables' => array(
         'text' => 'Download',
         'path' => NULL,
         'options' => array(),
       ),
     ),
-  ) ;
+  );
 }
 
 /**
- * Implementation of hook_perm().
+ * Implements hook_permission().
  */
-function zipcart_perm() {
+function zipcart_permission() {
   return array(
-    'access zipcart downloads',
-  ) ;
+    'administer zipcart' => array(
+      'title' => t('Administer ZipCart'),
+      'description' => t('Allow users to administer ZipCart'),
+    ),
+    'access zipcart downloads' => array(
+      'title' => t('Access ZipCart Downloads'),
+      'description' => t('Allow users to access ZipCart downloads'),
+    ),
+  );
 }
 
 /**
- * Implementation of hook_block().
+ * Implements hook_block_info().
  */
-function zipcart_block($op='list', $delta=0, $edit=array()) {
-  switch ($op) {
-    case 'list' :
-      $blocks[0] = array(
-        'info'  => t('ZipCart Downloads'),
-        'cache' => BLOCK_NO_CACHE,
-      ) ;
-      return $blocks ;
-    case 'view':
-      if ( user_access('access zipcart downloads') ) {
-        switch ($delta) {
-          case '0':
-            $block = array(
-              'subject' => t('My Downloads'),
-              'content' => theme('zipcart_block_downloads'),
-            );
-            return $block ;
-        }
-      }
-    case 'configure':
-    case 'save':
-      return ;
-    
+function zipcart_block_info() {
+  $blocks[0] = array(
+    'info' => t('ZipCart Downloads'),
+    'cache' => DRUPAL_NO_CACHE,
+  );
+  return $blocks;
+}
+
+/**
+ * Implements hook_block_configure().
+ */
+function zipcart_block_configure($delta = '') {
+  $form = array();
+  if ($delta == 0) {
+    $form['zipcart_block_width'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Block width'),
+      '#size' => 5,
+      '#description' => t('Enter the ZipCart block width in pixels.'),
+      '#default_value' => variable_get('zipcart_block_width', 200),
+    );
+  }
+  return $form;
+}
+
+/**
+ * Implements hook_block_save().
+ */
+function zipcart_block_save($delta = '', $edit = array()) {
+  if ($delta == 0) {
+    variable_set('zipcart_block_width', $edit['zipcart_block_width']);
   }
+  return;
 }
 
 /**
- * Implementation of hook_file_download.
+ * Implements hook_block_view().
+ */
+function zipcart_block_view($delta = '') {
+  if ( user_access('access zipcart downloads') ) {
+    switch ($delta) {
+      case '0':
+        $subject = variable_get('zipcart_block_title', 'My Downloads');
+        $block = array(
+          'subject' => $subject,
+          'content' => theme('zipcart_block_downloads'),
+        );
+        return $block;
+    }
+  }
+}
+
+/**
+ * Implements hook_file_download.
  */
 function zipcart_file_download($filepath) {
-  // dpm($filepath);
 }
 
 /**
- * Implementation of hook_zipmethods.
+ * Implements hook_zipmethods.
  */
 function zipcart_zipmethods() {
   $methods['zip_builtin'] = array(
     'title'    => 'PHP Zip extension',
     'callback' => '_zipcart_phpzip',
-  ) ;
+  );
 /*
   $methods['zip_pecl'] = array(
     'title'    => 'PECL Zip',
@@ -149,20 +195,22 @@ function zipcart_zipmethods() {
  */
 function _zipcart_get_available_methods() {
   foreach ( module_implements('zipmethods') as $module ) {
-    $function = $module .'_zipmethods' ;
+    $function = $module . '_zipmethods';
     if ( $methods = $function() ) {
       if ( is_array($methods) ) {
-        foreach( $methods as $key => $method ) {
-          $avail_methods[$key] = $method ;
+        foreach ( $methods as $key => $method ) {
+          $avail_methods[$key] = $method;
         }
       }
     }
   }
-  return $avail_methods ;
+  return $avail_methods;
 }
 
+/**
+ * Implements hook_form_alter
+ */
 function zipcart_form_alter(&$form, &$form_state, $form_id) {
-
 }
 
 /**
@@ -176,10 +224,10 @@ function zipcart_add_file_to_cart($ajax = FALSE) {
   $path       = implode('/', $path_parts);
   $path       = str_replace(ZIPCART_PATH_ADD, '', $path);
   $path       = trim($path, '/');
-  $filename   = basename($path);
-
-  $success = FALSE ;
+  $target     = file_uri_target($path);
+  $filename   = basename($target);
 
+  $success = FALSE;
   $headers = module_invoke_all('file_download', $path);
   if ( !in_array(-1, $headers) ) {
     // ok, hook_file_download didn't object
@@ -187,14 +235,20 @@ function zipcart_add_file_to_cart($ajax = FALSE) {
     $files = module_invoke_all('filterzip', $files);
   
     if ( !empty( $files ) ) {
-      $_SESSION['zipcart']['files'][] = $path ;
-      $success = TRUE ;  
+      $subject = variable_get('zipcart_block_title', 'My Downloads');
+      $limit = variable_get('zipcart_zip_limit', 16);
+      $count = isset($_SESSION['zipcart']['files']) ? count($_SESSION['zipcart']['files']) : 0;
+      if ($count >= $limit) {
+        $display = variable_get('zipcart_display_limit', 1);
+        if ($display) drupal_set_message(t($subject . ' is limited to ' . $limit . ' files.'));
+      }
+      else {
+        $_SESSION['zipcart']['files'][] = $path;
+        $success = TRUE;
+      }
     }
   }
 
-//  dpm($files);
-//  dpm(array($success), 'success');
-
   $_SESSION['zipcart']['files'] = array_unique($_SESSION['zipcart']['files']);
   $result = array(
     'cart' => $_SESSION['zipcart']['files'],
@@ -204,42 +258,56 @@ function zipcart_add_file_to_cart($ajax = FALSE) {
     die(drupal_json($result));
   }
   else {
+    $display = variable_get('zipcart_display_added', 1);
     if ( $success ) {
-      drupal_set_message(t('The file %filename has been added to your cart. !download', array('%filename' => $filename, '!download' => l('Click here to download', 'zipcart/get'))));
+      $subject = variable_get('zipcart_block_title', 'My Downloads');
+      if ($display) drupal_set_message(t('The file %filename has been added to your cart. %download', array('%filename' => $filename, '%download' => 'Click ' . $subject . ' to checkout.')));
     }
     else {
-      drupal_set_message(t('The file !filename could not be added to your cart.', array('!filename' => $filename)));    
+      if ($display) drupal_set_message(t('The file %filename could not be added to your cart.', array('%filename' => $filename)));    
     }
-    drupal_goto();
+    $file_lib = variable_get('zipcart_file_library', 'file-library');
+    drupal_goto($file_lib);
   }
 }
 
 /**
+ * Empty the cart files
+ */
+function zipcart_empty_cart() {
+  unset($_SESSION['zipcart']['files']);
+  $display = variable_get('zipcart_display_emptied', 1);
+  if ($display) drupal_set_message(t('Your cart has been emptied.'));
+  $file_lib = variable_get('zipcart_file_library', 'file-library');
+  drupal_goto($file_lib);
+}
+
+/**
  * Get the files as a zip
  */
 function zipcart_get_zip() {
   if ( empty( $_SESSION['zipcart']['files'] ) ) {
-    drupal_set_message('Sorry, there are no files queued for you to download.');
-    drupal_goto();
+    $display = variable_get('zipcart_display_queued', 1);
+    if ($display) drupal_set_message(t('Sorry, there are no files queued for you to download.'));
+    $file_lib = variable_get('zipcart_file_library', 'file-library');
+    drupal_goto($file_lib);
   }
   else {
-    $files = $_SESSION['zipcart']['files'] ;
+    $files = $_SESSION['zipcart']['files'];
     $files = module_invoke_all('filterzip', $files);
     
     if ( !empty($files) ) {      
-      $zipcart_dir = file_directory_path() .'/'. variable_get('zipcart_cache','zipcart') ;
-      if (file_check_directory($zipcart_dir, 1)) {
-        $methods = _zipcart_get_available_methods() ;
-        $zipmethod = variable_get('zipcart_zip_method', 'zip_builtin');
-        if ( isset( $methods[$zipmethod] ) ) {
-          $zipfunction = $methods[$zipmethod]['callback'] ;
-          if ( !$zipfunction($files) ) {
-            return 'Download failed.' ;
-          }
-          else {
-            drupal_set_message('Zip downloaded');
-            return TRUE ;
-          }
+      $methods = _zipcart_get_available_methods();
+      $zipmethod = variable_get('zipcart_zip_method', 'zip_builtin');
+      if ( isset( $methods[$zipmethod] ) ) {
+        $zipfunction = $methods[$zipmethod]['callback'];
+        if ( !$zipfunction($files) ) {
+          return t('Download failed.');
+        }
+        else {
+          $display = variable_get('zipcart_display_downloaded', 1);
+          if ($display) drupal_set_message(t('Zip downloaded.'));
+          return TRUE;
         }
       }
     }
@@ -252,21 +320,25 @@ function zipcart_get_zip() {
  * You can add files.
  * You can filter files.
  */
-function zipcart_filterzip(&$files) {
-  // don't ever share these files
-  // $excluded = array( 'sites/.*settings.*php' ) ;
-  // only ever include these files 
-  // $included = array( 'sites/files/.*' ) ;
-  // always include a certain file
-  // $add = array( 'sites/default/files/README.txt' ) ;
+function zipcart_filterzip($files) {
+  // Check for valid paths
+  $valid_dirs = array();
+  $pub_path = variable_get('file_public_path', 'sites/default/files');
+  $file_dirs = explode("\n", variable_get('zipcart_file_dirs', 'zipcart'));
+  foreach ( $file_dirs as $file_dir ) {
+    $valid_dirs[] = drupal_realpath($pub_path . '/' . $file_dir);
+  }
   foreach ( $files as $i => &$file ) {
-    if ( !file_check_location($file, file_directory_path()) ) { 
-      watchdog('zipcart', t('Forbidding download of !file', 
-                            array('!file' => $file)));      
+    $file_path = dirname(drupal_realpath($file));
+    if (!in_array($file_path, $valid_dirs)) {
+      $message = t('Path %path is not valid. Forbidding download of %file.', array('%path' => $file_path, '%file' => $file));
+      $display = variable_get('zipcart_display_path', 1);
+      if ($display) drupal_set_message($message);
+      watchdog('zipcart', $message);
       unset($files[$i]);
     }
   }
-  return $files ;
+  return $files;
 }
 
 /**
@@ -274,101 +346,96 @@ function zipcart_filterzip(&$files) {
  */
 function _zipcart_phpzip($files) {
   $zip = new ZipArchive;
-  $filename = tempnam(file_directory_temp(), 'zip');
-  // $filename = file_directory_path() .'/'. variable_get('zipcart_cache','zipcart') .'/'. time() .'.zip' ;
-  $zip_open = $zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) ;
-  $zip->setArchiveComment('Generated by ZipCart for Drupal.');
+  $tmp_dir = file_directory_temp();
+  $pub_dir = variable_get('file_public_path', 'sites/default/files');
+  $filename = drupal_tempnam($tmp_dir, 'zip');
+  $tmp_uri = 'temporary://' . substr($filename, strlen($tmp_dir) + 1);
+  $zip_open = $zip->open($filename, ZIPARCHIVE::OVERWRITE) ;
   if ($zip_open === TRUE) {
-    // would be nice to handle duplicate filenames sensibly here
+    // would be nice to handle duplicate filenames here
     foreach ( $files as $file ) {
-      if (file_exists($file)) {
-        if ( $zip->addFile(realpath($file), basename($file)) ) {
-          // drupal_set_message(t('!file added to Zip.', array('!file' => $file)));
-        }
-        else {
-          // drupal_set_message(t('!file could not be added to Zip.', array('!file' => $file)), 'error');
-          watchdog('zipcart', 'Failed to add !file to Zip.', array('!file' => $file), WATCHDOG_ERROR);
-        }
-      }
-      else {
-        watchdog('zipcart', 'Failed to locate !file.', array('!file' => $file), WATCHDOG_ERROR);
-        // drupal_set_message('!file not found.', array('!file' => $file), 'error');
-      }
+      $target = file_uri_target($file);
+      $pub_file = $pub_dir . '/' . $target;
+      $zip->addFile($pub_file, basename($pub_file));
     }
     $zip->close();
-    $headers = module_invoke_all('file_download', $filename);
-    if (in_array(-1, $headers)) {
-      return drupal_access_denied();
+    // Check to make sure the filesize is not greater than zipcart_zip_size
+    $filesize = filesize($filename);
+    $kbsize = $filesize / 1024;
+    $maxsize = variable_get('zipcart_zip_size', 32768);
+    $valid = 1;
+    if ($kbsize > $maxsize) {
+      $display = variable_get('zipcart_display_size', 1);
+      if ($display) drupal_set_message(t('Download filesize exceeds ' . $maxsize . ' kilobytes.'));
+      $valid = 0;
     }
-    // remove any content-disposition headers here
-    if (count($headers)) {
-      foreach ( $headers as $k => $header ) {
-        if ( stristr($header, 'Content-Disposition:') === 0 ) {
-          unset($headers[$k]) ;
-        }
-      }
+    if ($valid) {
+      $headers = array(
+        'Content-Type' => 'application/octet-stream',
+        'Content-Size' => $filesize,
+        'Content-Disposition' => 'attachment; filename="' . _zipcart_zip_filename() . '"',
+      );
+      // FIXME: it would be nice to wait until the file transfer completes before we clear the 
+      // files out of the session. However, if we do that, the user can't add new files to their
+      // cart until the zip is downloaded. So we'll do this first.
+      unset($_SESSION['zipcart']['files']);
+      drupal_register_shutdown_function('_zipcart_remove_zip', $filename);
+      file_transfer($tmp_uri, $headers);
     }
-    $headers[] = 'Content-Disposition: attachment; filename="'. _zipcart_zip_filename() .'"' ;
-    // FIXME: it would be nice to wait until the file transfer completes before we clear the 
-    // files out of the session. However, if we do that, the user can't add new files to their
-    // cart until the zip is downloaded. So we'll do this first.
-    $_SESSION['zipcart']['files'] = array();
-    register_shutdown_function('_zipcart_remove_zip', $filename);
-    file_transfer($filename, $headers);
   }
   else {
-    drupal_set_message(t('Unable to create file !filename.', array('!filename' => $filename)), 'error');
+    $display = variable_get('zipcart_display_create', 1);
+    if ($display) drupal_set_message(t('Unable to create file %filename.', array('%filename' => $filename)), 'error');
     drupal_access_denied();
-    return FALSE ;
-  }  
+    return FALSE;
+  }
 }
 
 /**
- * 
+ * Get the zip filename
  */
 function _zipcart_zip_filename() {
-  $filename = 'Files - '. date('Y-m-d_Hi') .'.zip' ;
-  return $filename ;
+  $prefix = variable_get('zipcart_zip_prefix', 'Files');
+  $filename = $prefix . '_' . date('Y-m-d_Hi') . '.zip';
+  return $filename;
 }
 
 /**
- *
+ * Get the destination alias
  */
 function _zipcart_get_destination_alias() {
   if (isset($_REQUEST['destination'])) {
-    return 'destination='. urlencode(drupal_get_path_alias($_REQUEST['destination']));
+    $path = check_plain(drupal_get_path_alias($_REQUEST['destination']));
   }
   else {
     // Use $_GET here to retrieve the original path in source form.
-    $path = isset($_GET['q']) ? $_GET['q'] : '';
-    $query = drupal_query_string_encode($_GET, array('q'));
-    if ($query != '') {
-      $path .= '?'. $query;
-    }
-    return 'destination='. urlencode(drupal_get_path_alias($path));
+    $path = isset($_GET['q']) ? check_plain(drupal_get_path_alias($_GET['q'])) : '';
   }
+  return array(
+    'destination' => $path,
+  );
 }
 
 /**
  * Theme function to generate a download link.
  */
-function theme_zipcart_download($text, $path, $options=array()) {
+function theme_zipcart_download($args = array()) {
+  $text = !empty($args['text']) ? $args['text'] : '';
+  $path = !empty($args['path']) ? $args['path'] : '';
+  $options = !empty($args['options']) ? $args['options'] : array();
   $default_options = array(
     'attributes' => array( 
       'class' => 'zipcart',
     ),
     'query' => _zipcart_get_destination_alias(),
-  ) ;
+  );
   $options = array_merge($default_options, $options);
-//  dpm($options);
-//  dpm(array($text, $path, $options));
-  return l($text, ZIPCART_PATH_ADD .'/'. $path, $options);
+  return l($text, ZIPCART_PATH_ADD . '/' . $path, $options);
 }
 
 /**
  * Clean up built zips as required.
  */
 function _zipcart_remove_zip($filename) {
-  unlink($filename);
+  drupal_unlink($filename);
 }
-        
-- 
1.7.4.2

