Index: CHANGELOG.txt
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_edi/CHANGELOG.txt,v
retrieving revision 1.5
diff -u -p -r1.5 CHANGELOG.txt
--- CHANGELOG.txt	5 Nov 2010 22:13:50 -0000	1.5
+++ CHANGELOG.txt	8 Nov 2010 18:08:21 -0000
@@ -11,3 +11,5 @@ bug #942844 by AntoineSolutions: Fixed v
 bug #943780 by AntoineSolutions: Fixed order statuses being updated when the
   export fails.
 task #950156 by AntoineSolutions: Cleaned up code.
+task #965738 by AntoineSolutions: Moved administration code into a new
+  uc_edi.admin.inc file.
Index: uc_edi.admin.inc
===================================================================
RCS file: uc_edi.admin.inc
diff -N uc_edi.admin.inc
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ uc_edi.admin.inc	8 Nov 2010 18:08:21 -0000
@@ -0,0 +1,712 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * Ubercart EDI administration and module settings UI.
+ */
+
+/**
+ * Form builder for the general EDI settings form.
+ *
+ * @see uc_edi_settings_form_validate()
+ * @ingroup forms.
+ */
+function uc_edi_settings_form() {
+  if ((trim(variable_get('uc_edi_order_import_dir', '')) == '' ||
+       trim(variable_get('uc_edi_order_import_archive_dir', '')) == '' ||
+       trim(variable_get('uc_edi_order_export_dir', '')) == '') &&
+       empty($_POST['form_id'])) {
+    drupal_set_message(t('One or more required directory fields need to be filled out. It is recommended that you use a directory outside of your document root for improved security. You may specify an absolute path on the server or a relative path from the Drupal directory.'), 'error');
+  }
+
+  $form['import'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Import settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+  $form['import']['orders'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Order import settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => TRUE,
+  );
+  $form['import']['orders']['uc_edi_order_import_dir'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Import directory'),
+    '#description' => t('The directory path to search for data files ready for import. Omit the trailing slash.'),
+    '#default_value' => variable_get('uc_edi_order_import_dir', ''),
+  );
+  $form['import']['orders']['uc_edi_order_import_archive_dir'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Import archive directory'),
+    '#description' => t('The directory path to move processed data files to for storage. Omit the trailing slash.'),
+    '#default_value' => variable_get('uc_edi_order_import_archive_dir', ''),
+  );
+  $form['import']['orders']['uc_edi_order_import_extension'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Import file extension'),
+    '#description' => t('Enter the file extension expected for order import files.'),
+    '#default_value' => variable_get('uc_edi_order_import_extension', 'edi'),
+    '#maxlength' => 6,
+  );
+  $form['import']['orders']['uc_edi_order_import_delimiter'] = array(
+    '#type' => 'select',
+    '#title' => t('Import pattern delimiter'),
+    '#options' => array(
+      ',' => t('comma (,)'),
+      '|' => t('pipe (|)'),
+      '\t' => t('tab (\t)'),
+    ),
+    '#default_value' => variable_get('uc_edi_order_import_delimiter', '\t'),
+  );
+  $form['import']['orders']['uc_edi_order_import_freq'] = array(
+    '#type' => 'select',
+    '#title' => t('Import frequency'),
+    '#description' => t('The frequency at which automatic imports should occur.'),
+    '#options' => array(
+      '1 second' => t('Every cron run'),
+      '1 hour' => t('Once an hour'),
+      '6 hours' => t('Every six hours'),
+      '12 hours' => t('Every twelve hours'),
+      '1 day' => t('Once a day'),
+      'never' => t('Never'),
+    ),
+    '#default_value' => variable_get('uc_edi_order_import_freq', '1 second'),
+  );
+  foreach (uc_order_status_list('general') as $status) {
+    $options[$status['id']] = $status['title'];
+  }
+  $form['import']['orders']['uc_edi_order_imported_status'] = array(
+    '#type' => 'select',
+    '#title' => t('Imported order status'),
+    '#description' => t('Select a status for orders to be moved to when a response is received for that order.'),
+    '#options' => $options,
+    '#default_value' => variable_get('uc_edi_order_imported_status', 'completed'),
+  );
+  $form['import']['orders']['uc_edi_order_import_rules'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Order import rules'),
+    '#description' => t('Order import rules have set patterns and keywords. <a href="!url">Click here</a> for help.', array('!url' => url('admin/help/uc_edi'))),
+    '#default_value' => variable_get('uc_edi_order_import_rules', 'ORD|id:2|us|oc:Your order has shipped via #3 with tracking number #4.'),
+  );
+
+  $form['export'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Export settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+  $form['export']['orders'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Order export settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => TRUE,
+  );
+  $form['export']['orders']['uc_edi_order_export_dir'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Export directory'),
+    '#description' => t('The directory path for exported data files. Omit the trailing slash.'),
+    '#default_value' => variable_get('uc_edi_order_export_dir', ''),
+  );
+  $form['export']['orders']['uc_edi_order_export_archive_dir'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Export archive directory'),
+    '#description' => t('The directory path for archiving exported data files. Omit the trailing slash.'),
+    '#default_value' => variable_get('uc_edi_order_export_archive_dir', ''),
+  );
+  $form['export']['orders']['uc_edi_order_export_prefix'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Export file prefix'),
+    '#description' => t('Enter a prefix to use for your exported order files. Leave blank for none.'),
+    '#default_value' => variable_get('uc_edi_order_export_prefix', 'export-'),
+    '#maxlength' => 10,
+  );
+  $form['export']['orders']['uc_edi_order_export_extension'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Export file extension'),
+    '#description' => t('Enter the file extension to use for your exported order files.'),
+    '#default_value' => variable_get('uc_edi_order_export_extension', 'edi'),
+    '#maxlength' => 6,
+  );
+  $form['export']['orders']['mail'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Export by email settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+  $form['export']['orders']['mail']['uc_edi_order_export_mail_to'] = array(
+    '#type' => 'textfield',
+    '#title' => t('E-mail a copy of the report file to this address (Requires the Mimemail module)'),
+    '#description' => t('If left blank, no e-mail will be sent.'),
+    '#disabled' => !(module_exists('mimemail')),
+    '#default_value' => variable_get('uc_edi_order_export_mail_to', ''),
+  );
+  $form['export']['orders']['mail']['uc_edi_order_export_mail_from'] = array(
+    '#type' => 'textfield',
+    '#title' => t('From address'),
+    '#description' => t('If left blank, the default site email address @mail will be used', array('@mail' => variable_get('site_mail', 'test@example.com'))),
+    '#disabled' => !(module_exists('mimemail')),
+    '#default_value' => variable_get('uc_edi_order_export_mail_from', ''),
+  );
+  $form['export']['orders']['mail']['uc_edi_order_export_mail_subject'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Message Subject'),
+    '#disabled' => !(module_exists('mimemail')),
+    '#default_value' => variable_get('uc_edi_order_export_mail_subject', ''),
+  );
+   $form['export']['orders']['mail']['uc_edi_order_export_mail_body'] = array(
+    '#type' => 'textarea',
+    '#title' => t('E-mail Message'),
+    '#disabled' => !(module_exists('mimemail')),
+    '#default_value' => variable_get('uc_edi_order_export_mail_body', ''),
+  );
+  $form['export']['orders']['uc_edi_order_export_method'] = array(
+    '#type' => 'radios',
+    '#title' => t('Export method'),
+    '#description' => t('The method used to export the order.'),
+    '#options' => array(
+      'checkout' => t('On checkout completion'),
+      'cron' => t('At a specified interval'),
+      'manual' => t('Manualy'),
+    ),
+    '#default_value' => variable_get('uc_edi_order_export_method', 'cron'),
+    '#ahah' => array(
+      'method' => 'replace',
+      'path' => 'admin/store/settings/edi/order-export-method-js',
+      'wrapper' => 'method-sub-wrapper',
+    ),
+  );
+  $form['export']['orders']['uc_edi_order_export_method_sub'] = uc_edi_order_export_method();
+  $form['export']['orders']['uc_edi_order_export_pattern'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Order export pattern'),
+    '#description' => t('This is the pattern used for each order in the export file.<br />Separate values by commas and use any order field keyword, i.e. !delivery_first_name.<br />Use: !_ to add a line break, !products to add the products, !delivery_name, !billing_name.<br />Add (#) to any key where # is the length you want the value to be.'),
+    '#default_value' => variable_get('uc_edi_order_export_pattern', '01, !billing_name(29), !order_id(6), !uid(10), !_, 02, !delivery_name(30), !delivery_street1(20), !delivery_street2(20), !_, 03, !delivery_city(15), !delivery_zone_code(2), !delivery_country_name(10), !delivery_postal_code(13), !_, 04, !delivery_phone(15), !spacer(15), !primary_email(41), !_, !products, 10, !billing_name(30), !billing_street1(30), !_, 11, !billing_street2(30), !billing_city(15), !billing_zone_code(2), !billing_country_name(20), !billing_postal_code(13), !_, 12, !billing_phone(15), !billing_first_name(15), !primary_email(41)'),
+  );
+  $form['export']['orders']['uc_edi_order_export_product_pattern'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Order product export pattern'),
+    '#description' => t('This is the pattern used for each order product in the export file.<br />Separate values by commas and use any product field keyword, i.e. !qty.<br />Use: !_ to add a line break, !# for the incremented order line number.'),
+    '#default_value' => variable_get('uc_edi_order_export_product_pattern', '05, !#(3), !spacer(3), !qty(11), EA, !price(16), !spacer(4), !model(15)'),
+  );
+  $form['export']['orders']['uc_edi_order_export_delimiter'] = array(
+    '#type' => 'select',
+    '#title' => t('Export pattern delimiter'),
+    '#options' => array(
+      '' => t('none'),
+      ',' => t('comma (,)'),
+      '|' => t('pipe (|)'),
+      '\t' => t('tab (\t)'),
+    ),
+    '#default_value' => variable_get('uc_edi_order_export_delimiter', '\t'),
+  );
+  $form['export']['orders']['uc_edi_order_export_next_batch_id'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Next order batch ID'),
+    '#description' => t('<b>DISABLED:</b> Adjusting this value may result in duplicate batch IDs. Adjustments must be made in the database.<br />The batch ID is incremented for every export and useful for tracking.'),
+    '#default_value' => variable_get('uc_edi_order_export_next_batch_id', 1000),
+    '#disabled' => TRUE,
+  );
+
+  $form = system_settings_form($form);
+
+  // We will call system_settings_form_submit() manually, so remove it for now.
+  unset($form['#submit']);
+  return $form;
+}
+
+/**
+ * Returns the unrendered method sub form.
+ */
+function uc_edi_order_export_method() {
+  // Retrieve variable values from $_POST or use the default.
+  $method = $_POST['uc_edi_order_export_method'] ? $_POST['uc_edi_order_export_method'] : variable_get('uc_edi_order_export_method', 'cron');
+  $frequency = $_POST['uc_edi_order_export_freq'] ? $_POST['uc_edi_order_export_freq'] : variable_get('uc_edi_order_export_freq', '1 day');
+  $status = $_POST['uc_edi_order_export_status'] ? $_POST['uc_edi_order_export_status'] : variable_get('uc_edi_order_export_status', 'edi_export');
+
+  // If the method has changed, alert the user to conditional action changnes.
+  if ($method != variable_get('uc_edi_order_export_method', 'cron')) {
+    if ($method == 'checkout') {
+      drupal_set_message(t('The <a href="!url1">Export the order</a> predicate will be enabled. Please verify your <a href="!url2">Conditional Actions configuration</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))), 'warning');
+    }
+    elseif (variable_get('uc_edi_order_export_method', 'cron') == 'checkout') {
+      drupal_set_message(t('The <a href="!url1">Export the order</a> predicate will be disabled. Please verify your <a href="!url2">Conditional Actions configuration</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))), 'warning');
+    }
+  }
+
+  // Create an array of order status options.
+  foreach (uc_order_status_list('general') as $uc_status) {
+    $options[$uc_status['id']] = $uc_status['title'];
+  }
+
+  // Build the default form.
+  $form['uc_edi_order_export_freq'] = array(
+    '#type' => 'select',
+    '#title' => t('Export frequency'),
+    '#description' => t('The frequency at which automatic exports should occur.'),
+    '#options' => array(
+      '1 second' => t('Every cron run'),
+      '1 hour' => t('Once an hour'),
+      '6 hours' => t('Every six hours'),
+      '12 hours' => t('Every twelve hours'),
+      '1 day' => t('Once a day'),
+    ),
+    '#default_value' => $frequency,
+  );
+  $form['uc_edi_order_export_status'] = array(
+    '#type' => 'select',
+    '#title' => t('Ready for export order status'),
+    '#description' => t('Select a status used to mark orders as ready for export.'),
+    '#options' => $options,
+    '#default_value' => $status,
+    '#ahah' => array(
+      'event' => 'change',
+      'method' => 'replace',
+      'path' => 'admin/store/settings/edi/order-export-method-js',
+      'wrapper' => 'method-sub-wrapper',
+    ),
+  );
+
+  // Generate the correct form based on the method.
+  switch ($method) {
+    // Export on checkout completion.
+    case 'checkout':
+      // Display help message to user.
+      $form['message'] = array(
+        '#value' => t('Exporting orders on checkout completion uses the <a href="!url1">Export the order</a> predicate for exporting orders. Please verify your <a href="!url2">Conditional Actions settings</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))),
+      );
+      // Hide unused form items.
+      $form['uc_edi_order_export_freq']['#type'] = 'hidden';
+      $form['uc_edi_order_export_status']['#type'] = 'hidden';
+      break;
+
+    // Export at a specified interval.
+    case 'cron':
+      // Nothing to do.
+      break;
+
+    // Export manually.
+    case 'manual':
+      // Display help message to user.
+      $form['message'] = array(
+        '#value' => t('Exporting orders manually can be accomplished using the <a href="!url">Manual EDI import/export form</a>.', array('!url' => url('admin/store/orders/edi'))),
+      );
+      // Hide unused form items.
+      $form['uc_edi_order_export_freq']['#type'] = 'hidden';
+      break;
+  }
+
+  // Validate Conditional Actions is configured correctly for the specified
+  // order export status.
+  if (!uc_edi_order_export_status_validate($method, $status)) {
+    form_set_error('uc_edi_order_export_status', t('A predicate must exist that sets the order status to that which is defined by the <strong>Ready for export order status</strong> field. See the <a href="!url">Export Configuration documentation</a>.', array('!url' => url('admin/help/uc_edi', array('fragment' => 'export-configuration')))));
+  }
+
+  // Add prefix and suffix elements.
+  $form += array(
+    '#prefix' => '<div id="method-sub-wrapper">',
+    '#suffix' => '</div>',
+  );
+
+  return $form;
+}
+
+/**
+ * Returns the rendered method sub form.
+ */
+function uc_edi_order_export_method_js() {
+  // Retrieve the unrendered frequency form.
+  $form = uc_edi_order_export_method();
+
+  // Remove #prefix and #suffix to avoid a duplicate wrapper.
+  unset($form['#prefix'], $form['#suffix']);
+
+  // Build and render the form, then return it in JSON format.
+  $form_state = array();
+  $form = form_builder($form['#name'], $form, $form_state);
+  $output = theme('status_messages', 'error');
+  $output .= theme('status_messages', 'warning');
+  $output .= drupal_render($form);
+  drupal_json(array('status' => TRUE, 'data' => $output));
+}
+
+/**
+ * Handels validation of the general EDI settings form.
+ *
+ * @see uc_edi_settings_form()
+ */
+function uc_edi_settings_form_validate($form, &$form_state) {
+  if (trim($form_state['values']['uc_edi_order_import_dir']) != '' &&
+      !is_dir($form_state['values']['uc_edi_order_import_dir'])) {
+    form_set_error('uc_edi_order_import_dir', t('You have specified a non-existent order import directory.'));
+  }
+  if (trim($form_state['values']['uc_edi_order_import_archive_dir']) != '' &&
+      !is_dir($form_state['values']['uc_edi_order_import_archive_dir'])) {
+    form_set_error('uc_edi_order_import_archive_dir', t('You have specified a non-existent order import archive directory.'));
+  }
+  if (trim($form_state['values']['uc_edi_order_export_dir']) != '' &&
+      !is_dir($form_state['values']['uc_edi_order_export_dir'])) {
+    form_set_error('uc_edi_order_export_dir', t('You have specified a non-existent order export directory.'));
+  }
+  if (trim($form_state['values']['uc_edi_order_export_archive_dir']) != '' &&
+      !is_dir($form_state['values']['uc_edi_order_export_archive_dir'])) {
+    form_set_error('uc_edi_order_export_archive_dir', t('You have specified a non-existent order export archive directory.'));
+  }
+  if (!valid_email_address($form_state['values']['uc_edi_order_export_mail_to']) &&
+      !empty($form_state['values']['uc_edi_order_export_mail_to']) &&
+      module_exists('mimemail')) {
+    form_set_error('uc_edi_order_export_mail_to', t('You have specified an invalid "to" e-mail address.'));
+  }
+  if (!valid_email_address($form_state['values']['uc_edi_order_export_mail_from']) &&
+      !empty($form_state['values']['uc_edi_order_export_mail_from']) &&
+      module_exists('mimemail')) {
+    form_set_error('uc_edi_order_export_mail_from', t('You have specified an invalid "from" e-mail address.'));
+  }
+}
+
+/**
+ * Verify Conditional Actions is configured to work with Ubercart EDI.
+ *
+ * @param $method
+ *   An export method.
+ * @param $status
+ *   An order status.
+ *
+ * @return boolean
+ *   Returns FALSE if the $method requires that a Conditional Actions predicate
+ *   set an orders status to $status and one does not exist, otherwise TRUE.
+ */
+function uc_edi_order_export_status_validate($method, $status) {
+  // If orders are not exported at checkout.
+  if ($method != 'checkout') {
+    // Load all the module defined predicates into a temporary array.
+    $temp = module_invoke_all('ca_predicate');
+
+    // Assign a default weight if need be.
+    foreach ($temp as $key => $value) {
+      $temp[$key]['#pid'] = $key;
+      if (!isset($value['#weight'])) {
+        $temp[$key]['#weight'] = 0;
+      }
+    }
+
+    // Load and loop through all the database stored predicates.
+    $result = db_query("SELECT * FROM {ca_predicates}");
+    while ($predicate = db_fetch_array($result)) {
+      // Prepare the database data into a predicate.
+      $predicate = ca_prepare_db_predicate($predicate);
+
+      // Overrides the module defined predicate if it's been modified by a user.
+      $temp[$predicate['#pid']] = $predicate;
+    }
+
+    usort($temp, 'ca_weight_sort');
+
+    // Copy the temporary array of predicates into a keyed array.
+    $predicates = array();
+    foreach ($temp as $predicate) {
+      $predicates[$predicate['#pid']] = $predicate;
+    }
+
+    // Load and loop through all the database stored predicates.
+    foreach ($predicates as $predicate) {
+      // Loop through all predicate actions.
+      foreach ($predicate['#actions'] as $action) {
+        // Return true is a predicate is found that sets an orders status to
+        // the status passed in.
+        if ($action['#settings']['order_status'] == $status) {
+          return TRUE;
+        }
+      }
+    }
+
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+/**
+ * Handler for submitting the settings form.
+ */
+function uc_edi_settings_form_submit($form, &$form_state) {
+  // Call the default submit handler first.
+  system_settings_form_submit($form, $form_state);
+
+  // If the export method has changed from or to 'checkout'.
+  if ($form['export']['orders']['uc_edi_order_export_method']['#default_value'] != $form['export']['orders']['uc_edi_order_export_method']['#value'] &&
+     ($form['export']['orders']['uc_edi_order_export_method']['#default_value'] == 'checkout' || $form['export']['orders']['uc_edi_order_export_method']['#value'] == 'checkout')) {
+    // Load the order export predicate.
+    $predicate = ca_load_predicate('uc_edi_order_export');
+    $update = FALSE;
+
+    // Update the 'Export the order' predicate based on export method.
+    if ($form_state['values']['uc_edi_order_export_method'] == 'checkout') {
+      if ($predicate['#status'] == 0) {
+        $predicate['#status'] = 1;
+        $update = TRUE;
+      }
+    }
+    else {
+      if ($predicate['#status'] == 1) {
+        $predicate['#status'] = 0;
+        $update = TRUE;
+      }
+    }
+
+    // If manual predicate update was required.
+    if ($update) {
+      ca_save_predicate($predicate);
+    }
+
+    // Inform the user that the predicate was updated.
+    drupal_set_message(t('The <a href="!url1">Export the order</a> predicate has been updated. Please verify your <a href="!url2">Conditional Actions settings</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))), 'warning');
+  }
+}
+
+/**
+ * Form builder for the manual import/export form.
+ *
+ * @see uc_edi_manual_form_order_import_submit()
+ * @see uc_edi_manual_form_order_import_reset()
+ * @see uc_edi_manual_form_order_export_submit()
+ * @see uc_edi_manual_form_order_export_reset()
+ * @ingroup forms
+ */
+function uc_edi_manual_form() {
+  $form['import'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Order import details'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  // Grab all valid files in the import directory.
+  $files = uc_edi_get_import_files(variable_get('uc_edi_order_import_dir', ''), variable_get('uc_edi_order_import_extension', 'edi'));
+
+  // Figure out how many seconds remain till the next import will run.
+  if (variable_get('uc_edi_order_import_freq', '1 second') != 'never') {
+    $elapsed = time() - variable_get('uc_edi_order_import_last', 0);
+    $needed = time() - strtotime(variable_get('uc_edi_order_import_freq', '1 second') . ' ago');
+    $seconds = $needed - $elapsed;
+  }
+  else {
+    $seconds = t('(auto import disabled) 0');
+  }
+
+  $form['import']['import_info'] = array(
+    '#value' => '<div><b>' . t('There are !count files ready to import in !seconds seconds:', array('!count' => count($files), '!seconds' => $seconds < 0 ? 0 : $seconds)) . '</b><br />' . implode(', ', $files) . '<p></p></div>',
+  );
+  $form['import']['import_now'] = array(
+    '#type' => 'submit',
+    '#submit' => array('uc_edi_manual_form_order_import_submit'),
+    '#value' => t('Import orders now'),
+  );
+  $form['import']['reset_import'] = array(
+    '#type' => 'submit',
+    '#submit' => array('uc_edi_manual_form_order_import_reset'),
+    '#value' => t('Reset import timer'),
+  );
+
+  // Retrieve orders ready for export from database.
+  $result = db_query("SELECT order_id FROM {uc_orders} WHERE order_status = '%s' ORDER BY order_id", variable_get('uc_edi_order_export_status', 'edi_export'));
+  $orders = array();
+  // Build export preview and keep count of orders.
+  while ($order = db_fetch_object($result)) {
+    $orders[] = $order->order_id;
+    $order = uc_order_load($order->order_id);
+    $preview .= uc_edi_generate_order_export($order);
+  }
+
+  $form['export'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Order export details'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+
+  // Number of orders ready for export.
+  $count = count($orders);
+  switch (variable_get('uc_edi_order_export_method', 'cron')) {
+    case 'checkout':
+      $message = t('Orders are configured to export on checkout completion. !count order(s) require manual export.', array('!count' => $count));
+      break;
+
+    case 'cron':
+      // Figure out how many seconds remain till the next export will run.
+      $elapsed = time() - variable_get('uc_edi_order_export_last', 0);
+      $needed = time() - strtotime(variable_get('uc_edi_order_export_freq', '1 day') . ' ago');
+      $seconds = $needed - $elapsed;
+      $message = t('Auto export configured to export !count orders in !seconds seconds:', array('!count' => $count, '!seconds' => $seconds < 0 ? 0 : $seconds));
+      break;
+
+    case 'manual':
+      $message = t('!count order(s) ready for manual export.', array('!count' => $count));
+      break;
+  }
+
+  $form['export']['export_info'] = array(
+    '#value' => '<div><b>' . $message . '</b><br />' . implode(', ', $orders) . '<p></p></div>',
+  );
+
+  // Display a fieldset with a preview of the export file.
+  $form['export']['export_preview'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Order export preview'),
+    '#collapsible' => TRUE,
+    '#collapsed' => TRUE,
+  );
+
+  if (count($orders) == 0) {
+    $preview = t('No orders awaiting export.');
+  }
+  elseif (empty($preview)) {
+    $preview = t('No output was generated. Check your order and product export patterns on the <a href="!url">Ubercart EDI settings</a> page.', array('!url' => url('admin/store/settings/edi')));
+  }
+  $form['export']['export_preview']['contents'] = array(
+    '#value' => '<div><pre>' . $preview . '</pre></div>',
+  );
+
+  $form['export']['export_now'] = array(
+    '#type' => 'submit',
+    '#submit' => array('uc_edi_manual_form_order_export_submit'),
+    '#value' => t('Export orders now'),
+  );
+  $form['export']['reset_export'] = array(
+    '#type' => 'submit',
+    '#submit' => array('uc_edi_manual_form_order_export_reset'),
+    '#value' => t('Reset export timer'),
+  );
+
+  return $form;
+}
+
+/**
+ * Handles manual order import submissions.
+ *
+ * @see uc_edi_manual_form()
+ */
+function uc_edi_manual_form_order_import_submit($form, &$form_state) {
+  uc_edi_import_orders();
+  drupal_set_message(t('Order import files have been processed.'));
+}
+
+/**
+ * Handles resetting the order import timer.
+ *
+ * @see uc_edi_manual_form()
+ */
+function uc_edi_manual_form_order_import_reset($form, &$form_state) {
+  variable_set('uc_edi_order_import_last', time());
+  drupal_set_message(t('Order import timer reset.'));
+}
+
+/**
+ * Handles manual order export submissions.
+ *
+ * @see uc_edi_manual_form()
+ */
+function uc_edi_manual_form_order_export_submit($form, &$form_state) {
+  // Export orders.
+   $filename = uc_edi_export_orders();
+
+  // If the export was successfull.
+  if ($filename) {
+    // Inform the user of a successfull export.
+    drupal_set_message(t('Order export file !file created.', array('!file' => $filename)));
+  }
+  else {
+    // Inform the user of an unsuccessfull export.
+    drupal_set_message(t('Problem creating the order export file. Check your EDI settings and directory permissions.'), 'error');
+  }
+}
+
+/**
+ * Handles resetting the order export timer.
+ *
+ * @see uc_edi_manual_form()
+ */
+function uc_edi_manual_form_order_export_reset($form, &$form_state) {
+  variable_set('uc_edi_order_export_last', time());
+  drupal_set_message(t('Order export timer reset.'));
+}
+
+/**
+ * Creates a table with links for downloading and archiving export files.
+ *
+ * @return string
+ *   An HTML table of order export files to be downloaded or archived if order
+ *   export files were found, otherwise a default message explaining that no
+ *   order export files were found.
+ */
+function uc_edi_export_download() {
+  $output = '';
+
+  $files = file_scan_directory(variable_get('uc_edi_order_export_dir', ''), '.*\\.' . variable_get('uc_edi_order_export_extension', 'edi'), array('.', '..', 'CVS'), 0, FALSE);
+  $rows = array();
+  foreach ($files as $file) {
+    $rows[] = array($file->basename, t('<a href="!url">Download</a>', array('!url' => url('admin/store/edi/download/file/' . $file->basename))), t('<a href="!url">Archive</a>', array('!url' => url('admin/store/edi/download/archive/' . $file->basename))));
+  }
+  $header = array(t('Order export file'), array('data' => t('Actions'), 'colspan' => 2));
+  if (count($rows)) {
+    $output .= theme('table', $header, $rows);
+  }
+  else {
+    $output .= t('No order EDI export files were found in the export directory.');
+  }
+
+  return $output;
+}
+
+/**
+ * Allows an order export file to be downloaded.
+ *
+ * @param $filename
+ *   The name of the order export file to be downloaded.
+ */
+function uc_edi_order_export_download_file($filename = '') {
+  $file = variable_get('uc_edi_order_export_dir', '') . '/' . $filename;
+
+  if (file_exists($file)) {
+    $data = fopen($file, 'rb');
+    ob_end_clean();
+
+    $headers = array(
+      'Content-Length:' . filesize($file),
+      'Content-Disposition: attachment; filename="' . basename($file) . '"',
+      'Content-Type: application/octet-stream'
+    );
+    foreach ($headers as $header) {
+      $header = preg_replace('/\r?\n(?!\t| )/', '', $header);
+      drupal_set_header($header);
+    }
+
+    while (!feof($data)) {
+      print fread($data, 1024);
+    }
+    fclose($data);
+    exit();
+  }
+  else {
+    drupal_not_found();
+  }
+}
+
+/**
+ * Archives an order export file.
+ *
+ * @param $filename
+ *   The name of the order export file to be archived.
+ */
+function uc_edi_order_export_archive_file($filename = '') {
+  if (@rename(variable_get('uc_edi_order_export_dir', '') . '/' . $filename, variable_get('uc_edi_order_export_archive_dir', '') . '/' . $filename)) {
+    drupal_set_message(t('The selected order export file %file was archived successfully.', array('%file' => $filename)));
+  }
+  else {
+    drupal_set_message(t('Problem archiving the order export file. Check your EDI settings and directory permissions.'), 'error');
+  }
+
+  drupal_goto('admin/store/edi/download');
+}
Index: uc_edi.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/uc_edi/uc_edi.module,v
retrieving revision 1.6
diff -u -p -r1.6 uc_edi.module
--- uc_edi.module	5 Nov 2010 22:13:50 -0000	1.6
+++ uc_edi.module	8 Nov 2010 18:08:21 -0000
@@ -92,11 +92,13 @@ function uc_edi_menu() {
     'page arguments' => array('uc_edi_settings_form'),
     'access arguments' => array('administer edi orders'),
     'type' => MENU_NORMAL_ITEM,
+    'file' => 'uc_edi.admin.inc',
   );
   $items['admin/store/settings/edi/order-export-method-js'] = array(
     'page callback' => 'uc_edi_order_export_method_js',
     'access arguments' => array('administer edi orders'),
     'type' => MENU_CALLBACK,
+    'file' => 'uc_edi.admin.inc',
   );
   $items['admin/store/edi'] = array(
     'title' => 'EDI import/export',
@@ -104,12 +106,14 @@ function uc_edi_menu() {
     'page arguments' => array('uc_edi_manual_form'),
     'access arguments' => array('administer edi orders'),
     'type' => MENU_NORMAL_ITEM,
+    'file' => 'uc_edi.admin.inc',
   );
   $items['admin/store/edi/manual'] =  array(
     'title' => 'Manual import/export',
     'description' => 'Manually import and export EDI files.',
     'type' => MENU_DEFAULT_LOCAL_TASK,
     'weight' => -1,
+    'file' => 'uc_edi.admin.inc',
   );
   $items['admin/store/edi/download'] = array(
     'title' => 'Download/Archive export files',
@@ -117,18 +121,21 @@ function uc_edi_menu() {
     'page callback' => 'uc_edi_export_download',
     'access arguments' => array('download edi orders'),
     'type' => MENU_LOCAL_TASK,
+    'file' => 'uc_edi.admin.inc',
   );
   $items['admin/store/edi/download/file/%'] = array(
     'page callback' => 'uc_edi_order_export_download_file',
     'page arguments' => array(5),
     'access arguments' => array('download edi orders'),
     'type' => MENU_CALLBACK,
+    'file' => 'uc_edi.admin.inc',
   );
   $items['admin/store/edi/download/archive/%'] = array(
     'page callback' => 'uc_edi_order_export_archive_file',
     'page arguments' => array(5),
     'access arguments' => array('download edi orders'),
     'type' => MENU_CALLBACK,
+    'file' => 'uc_edi.admin.inc',
   );
 
   return $items;
@@ -190,720 +197,11 @@ function uc_edi_order_state() {
   return $states;
 }
 
-/******************************************************************************
- * Callback Functions and Forms
- ******************************************************************************/
-
-/**
- * Form builder for the general EDI settings form.
- *
- * @see uc_edi_settings_form_validate()
- * @ingroup forms.
- */
-function uc_edi_settings_form() {
-  if ((trim(variable_get('uc_edi_order_import_dir', '')) == '' ||
-       trim(variable_get('uc_edi_order_import_archive_dir', '')) == '' ||
-       trim(variable_get('uc_edi_order_export_dir', '')) == '') &&
-       empty($_POST['form_id'])) {
-    drupal_set_message(t('One or more required directory fields need to be filled out. It is recommended that you use a directory outside of your document root for improved security. You may specify an absolute path on the server or a relative path from the Drupal directory.'), 'error');
-  }
-
-  $form['import'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Import settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-  $form['import']['orders'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Order import settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => TRUE,
-  );
-  $form['import']['orders']['uc_edi_order_import_dir'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Import directory'),
-    '#description' => t('The directory path to search for data files ready for import. Omit the trailing slash.'),
-    '#default_value' => variable_get('uc_edi_order_import_dir', ''),
-  );
-  $form['import']['orders']['uc_edi_order_import_archive_dir'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Import archive directory'),
-    '#description' => t('The directory path to move processed data files to for storage. Omit the trailing slash.'),
-    '#default_value' => variable_get('uc_edi_order_import_archive_dir', ''),
-  );
-  $form['import']['orders']['uc_edi_order_import_extension'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Import file extension'),
-    '#description' => t('Enter the file extension expected for order import files.'),
-    '#default_value' => variable_get('uc_edi_order_import_extension', 'edi'),
-    '#maxlength' => 6,
-  );
-  $form['import']['orders']['uc_edi_order_import_delimiter'] = array(
-    '#type' => 'select',
-    '#title' => t('Import pattern delimiter'),
-    '#options' => array(
-      ',' => t('comma (,)'),
-      '|' => t('pipe (|)'),
-      '\t' => t('tab (\t)'),
-    ),
-    '#default_value' => variable_get('uc_edi_order_import_delimiter', '\t'),
-  );
-  $form['import']['orders']['uc_edi_order_import_freq'] = array(
-    '#type' => 'select',
-    '#title' => t('Import frequency'),
-    '#description' => t('The frequency at which automatic imports should occur.'),
-    '#options' => array(
-      '1 second' => t('Every cron run'),
-      '1 hour' => t('Once an hour'),
-      '6 hours' => t('Every six hours'),
-      '12 hours' => t('Every twelve hours'),
-      '1 day' => t('Once a day'),
-      'never' => t('Never'),
-    ),
-    '#default_value' => variable_get('uc_edi_order_import_freq', '1 second'),
-  );
-  foreach (uc_order_status_list('general') as $status) {
-    $options[$status['id']] = $status['title'];
-  }
-  $form['import']['orders']['uc_edi_order_imported_status'] = array(
-    '#type' => 'select',
-    '#title' => t('Imported order status'),
-    '#description' => t('Select a status for orders to be moved to when a response is received for that order.'),
-    '#options' => $options,
-    '#default_value' => variable_get('uc_edi_order_imported_status', 'completed'),
-  );
-  $form['import']['orders']['uc_edi_order_import_rules'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Order import rules'),
-    '#description' => t('Order import rules have set patterns and keywords. <a href="!url">Click here</a> for help.', array('!url' => url('admin/help/uc_edi'))),
-    '#default_value' => variable_get('uc_edi_order_import_rules', 'ORD|id:2|us|oc:Your order has shipped via #3 with tracking number #4.'),
-  );
-
-  $form['export'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Export settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-  $form['export']['orders'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Order export settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => TRUE,
-  );
-  $form['export']['orders']['uc_edi_order_export_dir'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Export directory'),
-    '#description' => t('The directory path for exported data files. Omit the trailing slash.'),
-    '#default_value' => variable_get('uc_edi_order_export_dir', ''),
-  );
-  $form['export']['orders']['uc_edi_order_export_archive_dir'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Export archive directory'),
-    '#description' => t('The directory path for archiving exported data files. Omit the trailing slash.'),
-    '#default_value' => variable_get('uc_edi_order_export_archive_dir', ''),
-  );
-  $form['export']['orders']['uc_edi_order_export_prefix'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Export file prefix'),
-    '#description' => t('Enter a prefix to use for your exported order files. Leave blank for none.'),
-    '#default_value' => variable_get('uc_edi_order_export_prefix', 'export-'),
-    '#maxlength' => 10,
-  );
-  $form['export']['orders']['uc_edi_order_export_extension'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Export file extension'),
-    '#description' => t('Enter the file extension to use for your exported order files.'),
-    '#default_value' => variable_get('uc_edi_order_export_extension', 'edi'),
-    '#maxlength' => 6,
-  );
-  $form['export']['orders']['mail'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Export by email settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-  $form['export']['orders']['mail']['uc_edi_order_export_mail_to'] = array(
-    '#type' => 'textfield',
-    '#title' => t('E-mail a copy of the report file to this address (Requires the Mimemail module)'),
-    '#description' => t('If left blank, no e-mail will be sent.'),
-    '#disabled' => !(module_exists('mimemail')),
-    '#default_value' => variable_get('uc_edi_order_export_mail_to', ''),
-  );
-  $form['export']['orders']['mail']['uc_edi_order_export_mail_from'] = array(
-    '#type' => 'textfield',
-    '#title' => t('From address'),
-    '#description' => t('If left blank, the default site email address @mail will be used', array('@mail' => variable_get('site_mail', 'test@example.com'))),
-    '#disabled' => !(module_exists('mimemail')),
-    '#default_value' => variable_get('uc_edi_order_export_mail_from', ''),
-  );
-  $form['export']['orders']['mail']['uc_edi_order_export_mail_subject'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Message Subject'),
-    '#disabled' => !(module_exists('mimemail')),
-    '#default_value' => variable_get('uc_edi_order_export_mail_subject', ''),
-  );
-   $form['export']['orders']['mail']['uc_edi_order_export_mail_body'] = array(
-    '#type' => 'textarea',
-    '#title' => t('E-mail Message'),
-    '#disabled' => !(module_exists('mimemail')),
-    '#default_value' => variable_get('uc_edi_order_export_mail_body', ''),
-  );
-  $form['export']['orders']['uc_edi_order_export_method'] = array(
-    '#type' => 'radios',
-    '#title' => t('Export method'),
-    '#description' => t('The method used to export the order.'),
-    '#options' => array(
-      'checkout' => t('On checkout completion'),
-      'cron' => t('At a specified interval'),
-      'manual' => t('Manualy'),
-    ),
-    '#default_value' => variable_get('uc_edi_order_export_method', 'cron'),
-    '#ahah' => array(
-      'method' => 'replace',
-      'path' => 'admin/store/settings/edi/order-export-method-js',
-      'wrapper' => 'method-sub-wrapper',
-    ),
-  );
-  $form['export']['orders']['uc_edi_order_export_method_sub'] = uc_edi_order_export_method();
-  $form['export']['orders']['uc_edi_order_export_pattern'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Order export pattern'),
-    '#description' => t('This is the pattern used for each order in the export file.<br />Separate values by commas and use any order field keyword, i.e. !delivery_first_name.<br />Use: !_ to add a line break, !products to add the products, !delivery_name, !billing_name.<br />Add (#) to any key where # is the length you want the value to be.'),
-    '#default_value' => variable_get('uc_edi_order_export_pattern', '01, !billing_name(29), !order_id(6), !uid(10), !_, 02, !delivery_name(30), !delivery_street1(20), !delivery_street2(20), !_, 03, !delivery_city(15), !delivery_zone_code(2), !delivery_country_name(10), !delivery_postal_code(13), !_, 04, !delivery_phone(15), !spacer(15), !primary_email(41), !_, !products, 10, !billing_name(30), !billing_street1(30), !_, 11, !billing_street2(30), !billing_city(15), !billing_zone_code(2), !billing_country_name(20), !billing_postal_code(13), !_, 12, !billing_phone(15), !billing_first_name(15), !primary_email(41)'),
-  );
-  $form['export']['orders']['uc_edi_order_export_product_pattern'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Order product export pattern'),
-    '#description' => t('This is the pattern used for each order product in the export file.<br />Separate values by commas and use any product field keyword, i.e. !qty.<br />Use: !_ to add a line break, !# for the incremented order line number.'),
-    '#default_value' => variable_get('uc_edi_order_export_product_pattern', '05, !#(3), !spacer(3), !qty(11), EA, !price(16), !spacer(4), !model(15)'),
-  );
-  $form['export']['orders']['uc_edi_order_export_delimiter'] = array(
-    '#type' => 'select',
-    '#title' => t('Export pattern delimiter'),
-    '#options' => array(
-      '' => t('none'),
-      ',' => t('comma (,)'),
-      '|' => t('pipe (|)'),
-      '\t' => t('tab (\t)'),
-    ),
-    '#default_value' => variable_get('uc_edi_order_export_delimiter', '\t'),
-  );
-  $form['export']['orders']['uc_edi_order_export_next_batch_id'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Next order batch ID'),
-    '#description' => t('<b>DISABLED:</b> Adjusting this value may result in duplicate batch IDs. Adjustments must be made in the database.<br />The batch ID is incremented for every export and useful for tracking.'),
-    '#default_value' => variable_get('uc_edi_order_export_next_batch_id', 1000),
-    '#disabled' => TRUE,
-  );
-
-  $form = system_settings_form($form);
-
-  // We will call system_settings_form_submit() manually, so remove it for now.
-  unset($form['#submit']);
-  return $form;
-}
-
-/**
- * Returns the unrendered method sub form.
- */
-function uc_edi_order_export_method() {
-  // Retrieve variable values from $_POST or use the default.
-  $method = $_POST['uc_edi_order_export_method'] ? $_POST['uc_edi_order_export_method'] : variable_get('uc_edi_order_export_method', 'cron');
-  $frequency = $_POST['uc_edi_order_export_freq'] ? $_POST['uc_edi_order_export_freq'] : variable_get('uc_edi_order_export_freq', '1 day');
-  $status = $_POST['uc_edi_order_export_status'] ? $_POST['uc_edi_order_export_status'] : variable_get('uc_edi_order_export_status', 'edi_export');
-
-  // If the method has changed, alert the user to conditional action changnes.
-  if ($method != variable_get('uc_edi_order_export_method', 'cron')) {
-    if ($method == 'checkout') {
-      drupal_set_message(t('The <a href="!url1">Export the order</a> predicate will be enabled. Please verify your <a href="!url2">Conditional Actions configuration</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))), 'warning');
-    }
-    elseif (variable_get('uc_edi_order_export_method', 'cron') == 'checkout') {
-      drupal_set_message(t('The <a href="!url1">Export the order</a> predicate will be disabled. Please verify your <a href="!url2">Conditional Actions configuration</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))), 'warning');
-    }
-  }
-
-  // Create an array of order status options.
-  foreach (uc_order_status_list('general') as $uc_status) {
-    $options[$uc_status['id']] = $uc_status['title'];
-  }
-
-  // Build the default form.
-  $form['uc_edi_order_export_freq'] = array(
-    '#type' => 'select',
-    '#title' => t('Export frequency'),
-    '#description' => t('The frequency at which automatic exports should occur.'),
-    '#options' => array(
-      '1 second' => t('Every cron run'),
-      '1 hour' => t('Once an hour'),
-      '6 hours' => t('Every six hours'),
-      '12 hours' => t('Every twelve hours'),
-      '1 day' => t('Once a day'),
-    ),
-    '#default_value' => $frequency,
-  );
-  $form['uc_edi_order_export_status'] = array(
-    '#type' => 'select',
-    '#title' => t('Ready for export order status'),
-    '#description' => t('Select a status used to mark orders as ready for export.'),
-    '#options' => $options,
-    '#default_value' => $status,
-    '#ahah' => array(
-      'event' => 'change',
-      'method' => 'replace',
-      'path' => 'admin/store/settings/edi/order-export-method-js',
-      'wrapper' => 'method-sub-wrapper',
-    ),
-  );
-
-  // Generate the correct form based on the method.
-  switch ($method) {
-    // Export on checkout completion.
-    case 'checkout':
-      // Display help message to user.
-      $form['message'] = array(
-        '#value' => t('Exporting orders on checkout completion uses the <a href="!url1">Export the order</a> predicate for exporting orders. Please verify your <a href="!url2">Conditional Actions settings</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))),
-      );
-      // Hide unused form items.
-      $form['uc_edi_order_export_freq']['#type'] = 'hidden';
-      $form['uc_edi_order_export_status']['#type'] = 'hidden';
-      break;
-
-    // Export at a specified interval.
-    case 'cron':
-      // Nothing to do.
-      break;
-
-    // Export manually.
-    case 'manual':
-      // Display help message to user.
-      $form['message'] = array(
-        '#value' => t('Exporting orders manually can be accomplished using the <a href="!url">Manual EDI import/export form</a>.', array('!url' => url('admin/store/orders/edi'))),
-      );
-      // Hide unused form items.
-      $form['uc_edi_order_export_freq']['#type'] = 'hidden';
-      break;
-  }
-
-  // Validate Conditional Actions is configured correctly for the specified
-  // order export status.
-  if (!uc_edi_order_export_status_validate($method, $status)) {
-    form_set_error('uc_edi_order_export_status', t('A predicate must exist that sets the order status to that which is defined by the <strong>Ready for export order status</strong> field. See the <a href="!url">Export Configuration documentation</a>.', array('!url' => url('admin/help/uc_edi', array('fragment' => 'export-configuration')))));
-  }
-
-  // Add prefix and suffix elements.
-  $form += array(
-    '#prefix' => '<div id="method-sub-wrapper">',
-    '#suffix' => '</div>',
-  );
-
-  return $form;
-}
-
-/**
- * Returns the rendered method sub form.
- */
-function uc_edi_order_export_method_js() {
-  // Retrieve the unrendered frequency form.
-  $form = uc_edi_order_export_method();
-
-  // Remove #prefix and #suffix to avoid a duplicate wrapper.
-  unset($form['#prefix'], $form['#suffix']);
-
-  // Build and render the form, then return it in JSON format.
-  $form_state = array();
-  $form = form_builder($form['#name'], $form, $form_state);
-  $output = theme('status_messages', 'error');
-  $output .= theme('status_messages', 'warning');
-  $output .= drupal_render($form);
-  drupal_json(array('status' => TRUE, 'data' => $output));
-}
-
-/**
- * Handels validation of the general EDI settings form.
- *
- * @see uc_edi_settings_form()
- */
-function uc_edi_settings_form_validate($form, &$form_state) {
-  if (trim($form_state['values']['uc_edi_order_import_dir']) != '' &&
-      !is_dir($form_state['values']['uc_edi_order_import_dir'])) {
-    form_set_error('uc_edi_order_import_dir', t('You have specified a non-existent order import directory.'));
-  }
-  if (trim($form_state['values']['uc_edi_order_import_archive_dir']) != '' &&
-      !is_dir($form_state['values']['uc_edi_order_import_archive_dir'])) {
-    form_set_error('uc_edi_order_import_archive_dir', t('You have specified a non-existent order import archive directory.'));
-  }
-  if (trim($form_state['values']['uc_edi_order_export_dir']) != '' &&
-      !is_dir($form_state['values']['uc_edi_order_export_dir'])) {
-    form_set_error('uc_edi_order_export_dir', t('You have specified a non-existent order export directory.'));
-  }
-  if (trim($form_state['values']['uc_edi_order_export_archive_dir']) != '' &&
-      !is_dir($form_state['values']['uc_edi_order_export_archive_dir'])) {
-    form_set_error('uc_edi_order_export_archive_dir', t('You have specified a non-existent order export archive directory.'));
-  }
-  if (!valid_email_address($form_state['values']['uc_edi_order_export_mail_to']) &&
-      !empty($form_state['values']['uc_edi_order_export_mail_to']) &&
-      module_exists('mimemail')) {
-    form_set_error('uc_edi_order_export_mail_to', t('You have specified an invalid "to" e-mail address.'));
-  }
-  if (!valid_email_address($form_state['values']['uc_edi_order_export_mail_from']) &&
-      !empty($form_state['values']['uc_edi_order_export_mail_from']) &&
-      module_exists('mimemail')) {
-    form_set_error('uc_edi_order_export_mail_from', t('You have specified an invalid "from" e-mail address.'));
-  }
-}
-
-/**
- * Verify Conditional Actions is configured to work with Ubercart EDI.
- *
- * @param $method
- *   An export method.
- * @param $status
- *   An order status.
- *
- * @return boolean
- *   Returns FALSE if the $method requires that a Conditional Actions predicate
- *   set an orders status to $status and one does not exist, otherwise TRUE.
- */
-function uc_edi_order_export_status_validate($method, $status) {
-  // If orders are not exported at checkout.
-  if ($method != 'checkout') {
-    // Load all the module defined predicates into a temporary array.
-    $temp = module_invoke_all('ca_predicate');
-
-    // Assign a default weight if need be.
-    foreach ($temp as $key => $value) {
-      $temp[$key]['#pid'] = $key;
-      if (!isset($value['#weight'])) {
-        $temp[$key]['#weight'] = 0;
-      }
-    }
-
-    // Load and loop through all the database stored predicates.
-    $result = db_query("SELECT * FROM {ca_predicates}");
-    while ($predicate = db_fetch_array($result)) {
-      // Prepare the database data into a predicate.
-      $predicate = ca_prepare_db_predicate($predicate);
-
-      // Overrides the module defined predicate if it's been modified by a user.
-      $temp[$predicate['#pid']] = $predicate;
-    }
-
-    usort($temp, 'ca_weight_sort');
-
-    // Copy the temporary array of predicates into a keyed array.
-    $predicates = array();
-    foreach ($temp as $predicate) {
-      $predicates[$predicate['#pid']] = $predicate;
-    }
-
-    // Load and loop through all the database stored predicates.
-    foreach ($predicates as $predicate) {
-      // Loop through all predicate actions.
-      foreach ($predicate['#actions'] as $action) {
-        // Return true is a predicate is found that sets an orders status to
-        // the status passed in.
-        if ($action['#settings']['order_status'] == $status) {
-          return TRUE;
-        }
-      }
-    }
-
-    return FALSE;
-  }
-
-  return TRUE;
-}
-
-/**
- * Handler for submitting the settings form.
- */
-function uc_edi_settings_form_submit($form, &$form_state) {
-  // Call the default submit handler first.
-  system_settings_form_submit($form, $form_state);
-
-  // If the export method has changed from or to 'checkout'.
-  if ($form['export']['orders']['uc_edi_order_export_method']['#default_value'] != $form['export']['orders']['uc_edi_order_export_method']['#value'] &&
-     ($form['export']['orders']['uc_edi_order_export_method']['#default_value'] == 'checkout' || $form['export']['orders']['uc_edi_order_export_method']['#value'] == 'checkout')) {
-    // Load the order export predicate.
-    $predicate = ca_load_predicate('uc_edi_order_export');
-    $update = FALSE;
-
-    // Update the 'Export the order' predicate based on export method.
-    if ($form_state['values']['uc_edi_order_export_method'] == 'checkout') {
-      if ($predicate['#status'] == 0) {
-        $predicate['#status'] = 1;
-        $update = TRUE;
-      }
-    }
-    else {
-      if ($predicate['#status'] == 1) {
-        $predicate['#status'] = 0;
-        $update = TRUE;
-      }
-    }
-
-    // If manual predicate update was required.
-    if ($update) {
-      ca_save_predicate($predicate);
-    }
-
-    // Inform the user that the predicate was updated.
-    drupal_set_message(t('The <a href="!url1">Export the order</a> predicate has been updated. Please verify your <a href="!url2">Conditional Actions settings</a>.', array('!url1' => url('admin/store/ca/uc_edi_order_export/edit'), '!url2' => url('admin/store/ca'))), 'warning');
-  }
-}
-
-/**
- * Form builder for the manual import/export form.
- *
- * @see uc_edi_manual_form_order_import_submit()
- * @see uc_edi_manual_form_order_import_reset()
- * @see uc_edi_manual_form_order_export_submit()
- * @see uc_edi_manual_form_order_export_reset()
- * @ingroup forms
- */
-function uc_edi_manual_form() {
-  $form['import'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Order import details'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-
-  // Grab all valid files in the import directory.
-  $files = uc_edi_get_import_files(variable_get('uc_edi_order_import_dir', ''), variable_get('uc_edi_order_import_extension', 'edi'));
-
-  // Figure out how many seconds remain till the next import will run.
-  if (variable_get('uc_edi_order_import_freq', '1 second') != 'never') {
-    $elapsed = time() - variable_get('uc_edi_order_import_last', 0);
-    $needed = time() - strtotime(variable_get('uc_edi_order_import_freq', '1 second') . ' ago');
-    $seconds = $needed - $elapsed;
-  }
-  else {
-    $seconds = t('(auto import disabled) 0');
-  }
-
-  $form['import']['import_info'] = array(
-    '#value' => '<div><b>' . t('There are !count files ready to import in !seconds seconds:', array('!count' => count($files), '!seconds' => $seconds < 0 ? 0 : $seconds)) . '</b><br />' . implode(', ', $files) . '<p></p></div>',
-  );
-  $form['import']['import_now'] = array(
-    '#type' => 'submit',
-    '#submit' => array('uc_edi_manual_form_order_import_submit'),
-    '#value' => t('Import orders now'),
-  );
-  $form['import']['reset_import'] = array(
-    '#type' => 'submit',
-    '#submit' => array('uc_edi_manual_form_order_import_reset'),
-    '#value' => t('Reset import timer'),
-  );
-
-  // Retrieve orders ready for export from database.
-  $result = db_query("SELECT order_id FROM {uc_orders} WHERE order_status = '%s' ORDER BY order_id", variable_get('uc_edi_order_export_status', 'edi_export'));
-  $orders = array();
-  // Build export preview and keep count of orders.
-  while ($order = db_fetch_object($result)) {
-    $orders[] = $order->order_id;
-    $order = uc_order_load($order->order_id);
-    $preview .= uc_edi_generate_order_export($order);
-  }
-
-  $form['export'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Order export details'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-
-  // Number of orders ready for export.
-  $count = count($orders);
-  switch (variable_get('uc_edi_order_export_method', 'cron')) {
-    case 'checkout':
-      $message = t('Orders are configured to export on checkout completion. !count order(s) require manual export.', array('!count' => $count));
-      break;
-
-    case 'cron':
-      // Figure out how many seconds remain till the next export will run.
-      $elapsed = time() - variable_get('uc_edi_order_export_last', 0);
-      $needed = time() - strtotime(variable_get('uc_edi_order_export_freq', '1 day') . ' ago');
-      $seconds = $needed - $elapsed;
-      $message = t('Auto export configured to export !count orders in !seconds seconds:', array('!count' => $count, '!seconds' => $seconds < 0 ? 0 : $seconds));
-      break;
-
-    case 'manual':
-      $message = t('!count order(s) ready for manual export.', array('!count' => $count));
-      break;
-  }
-
-  $form['export']['export_info'] = array(
-    '#value' => '<div><b>' . $message . '</b><br />' . implode(', ', $orders) . '<p></p></div>',
-  );
-
-  // Display a fieldset with a preview of the export file.
-  $form['export']['export_preview'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Order export preview'),
-    '#collapsible' => TRUE,
-    '#collapsed' => TRUE,
-  );
-
-  if (count($orders) == 0) {
-    $preview = t('No orders awaiting export.');
-  }
-  elseif (empty($preview)) {
-    $preview = t('No output was generated. Check your order and product export patterns on the <a href="!url">Ubercart EDI settings</a> page.', array('!url' => url('admin/store/settings/edi')));
-  }
-  $form['export']['export_preview']['contents'] = array(
-    '#value' => '<div><pre>' . $preview . '</pre></div>',
-  );
-
-  $form['export']['export_now'] = array(
-    '#type' => 'submit',
-    '#submit' => array('uc_edi_manual_form_order_export_submit'),
-    '#value' => t('Export orders now'),
-  );
-  $form['export']['reset_export'] = array(
-    '#type' => 'submit',
-    '#submit' => array('uc_edi_manual_form_order_export_reset'),
-    '#value' => t('Reset export timer'),
-  );
-
-  return $form;
-}
-
-/**
- * Handles manual order import submissions.
- *
- * @see uc_edi_manual_form()
- */
-function uc_edi_manual_form_order_import_submit($form, &$form_state) {
-  uc_edi_import_orders();
-  drupal_set_message(t('Order import files have been processed.'));
-}
-
-/**
- * Handles resetting the order import timer.
- *
- * @see uc_edi_manual_form()
- */
-function uc_edi_manual_form_order_import_reset($form, &$form_state) {
-  variable_set('uc_edi_order_import_last', time());
-  drupal_set_message(t('Order import timer reset.'));
-}
-
-/**
- * Handles manual order export submissions.
- *
- * @see uc_edi_manual_form()
- */
-function uc_edi_manual_form_order_export_submit($form, &$form_state) {
-  // Export orders.
-   $filename = uc_edi_export_orders();
-
-  // If the export was successfull.
-  if ($filename) {
-    // Inform the user of a successfull export.
-    drupal_set_message(t('Order export file !file created.', array('!file' => $filename)));
-  }
-  else {
-    // Inform the user of an unsuccessfull export.
-    drupal_set_message(t('Problem creating the order export file. Check your EDI settings and directory permissions.'), 'error');
-  }
-}
-
-/**
- * Handles resetting the order export timer.
- *
- * @see uc_edi_manual_form()
- */
-function uc_edi_manual_form_order_export_reset($form, &$form_state) {
-  variable_set('uc_edi_order_export_last', time());
-  drupal_set_message(t('Order export timer reset.'));
-}
-
 /*******************************************************************************
  * Module and Helper Functions
  ******************************************************************************/
 
 /**
- * Creates a table with links for downloading and archiving export files.
- *
- * @return string
- *   An HTML table of order export files to be downloaded or archived if order
- *   export files were found, otherwise a default message explaining that no
- *   order export files were found.
- */
-function uc_edi_export_download() {
-  $output = '';
-
-  $files = file_scan_directory(variable_get('uc_edi_order_export_dir', ''), '.*\\.' . variable_get('uc_edi_order_export_extension', 'edi'), array('.', '..', 'CVS'), 0, FALSE);
-  $rows = array();
-  foreach ($files as $file) {
-    $rows[] = array($file->basename, t('<a href="!url">Download</a>', array('!url' => url('admin/store/edi/download/file/' . $file->basename))), t('<a href="!url">Archive</a>', array('!url' => url('admin/store/edi/download/archive/' . $file->basename))));
-  }
-  $header = array(t('Order export file'), array('data' => t('Actions'), 'colspan' => 2));
-  if (count($rows)) {
-    $output .= theme('table', $header, $rows);
-  }
-  else {
-    $output .= t('No order EDI export files were found in the export directory.');
-  }
-
-  return $output;
-}
-
-/**
- * Allows an order export file to be downloaded.
- *
- * @param $filename
- *   The name of the order export file to be downloaded.
- */
-function uc_edi_order_export_download_file($filename = '') {
-  $file = variable_get('uc_edi_order_export_dir', '') . '/' . $filename;
-
-  if (file_exists($file)) {
-    $data = fopen($file, 'rb');
-    ob_end_clean();
-
-    $headers = array(
-      'Content-Length:' . filesize($file),
-      'Content-Disposition: attachment; filename="' . basename($file) . '"',
-      'Content-Type: application/octet-stream'
-    );
-    foreach ($headers as $header) {
-      $header = preg_replace('/\r?\n(?!\t| )/', '', $header);
-      drupal_set_header($header);
-    }
-
-    while (!feof($data)) {
-      print fread($data, 1024);
-    }
-    fclose($data);
-    exit();
-  }
-  else {
-    drupal_not_found();
-  }
-}
-
-/**
- * Archives an order export file.
- *
- * @param $filename
- *   The name of the order export file to be archived.
- */
-function uc_edi_order_export_archive_file($filename = '') {
-  if (@rename(variable_get('uc_edi_order_export_dir', '') . '/' . $filename, variable_get('uc_edi_order_export_archive_dir', '') . '/' . $filename)) {
-    drupal_set_message(t('The selected order export file %file was archived successfully.', array('%file' => $filename)));
-  }
-  else {
-    drupal_set_message(t('Problem archiving the order export file. Check your EDI settings and directory permissions.'), 'error');
-  }
-
-  drupal_goto('admin/store/edi/download');
-}
-
-/**
  * Creates an export file containing $contents and calls delievery methods.
  *
  * @param $type
