You are here

commerce_ups.module in Commerce UPS 7

Same filename and directory in other branches
  1. 8.3 commerce_ups.module
  2. 7.2 commerce_ups.module

File

commerce_ups.module
View source
<?php

/**
 * @file
 * Handles main functionality for Commerce UPS module.
 */
require 'commerce_ups.xml.inc';
function commerce_ups_menu() {
  $items = array();
  $items['admin/commerce/config/shipping/methods/ups/edit'] = array(
    'title' => 'Edit',
    'description' => 'Configure the UPS shipping method.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'commerce_ups_settings_form',
    ),
    'access arguments' => array(
      'administer shipping',
    ),
    'file' => 'commerce_ups.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
    'weight' => 0,
  );
  return $items;
}

/**
 * Implements hook_commerce_shipping_method_info().
 */
function commerce_ups_commerce_shipping_method_info() {
  $shipping_methods = array();
  $shipping_methods['ups'] = array(
    'title' => t('UPS'),
    'description' => t('Quote rates from UPS'),
  );
  return $shipping_methods;
}

/**
 * Implements hook_commerce_shipping_service_info().
 */
function commerce_ups_commerce_shipping_service_info() {
  $shipping_services = array();
  $available_services = _commerce_ups_service_list();
  $selected_services = variable_get('commerce_ups_services', array());
  foreach ($selected_services as $id => $val) {
    if ($val != 0) {

      // if you find a selected one...
      $service = $available_services[$id];
      $shipping_services[$service['slug']] = array(
        'title' => t($service['title']),
        'description' => t($service['description']),
        'display_title' => t($service['title']),
        'shipping_method' => 'ups',
        'price_component' => 'shipping',
        'callbacks' => array(
          'rate' => 'commerce_ups_service_rate_order',
        ),
      );
    }
  }
  return $shipping_services;
}

/**
 * Shipping service callback: returns a base price array for a shipping service
 * calculated for the given order.
 */
function commerce_ups_service_rate_order($shipping_service, $order) {

  // First attempt to recover cached shipping rates for the current order.
  $rates = commerce_shipping_rates_cache_get('ups', $order, variable_get('commerce_ups_rates_timeout', 0));

  // If no rates were recovered from the cache or the cached rates are over one minute old...
  if (!$rates) {
    $rates = array();

    // Build the rate request for the current order. This returns XML.
    $rate_request_xml = commerce_ups_build_rate_request($order);

    // If we got a valid rate request object back...
    if ($rate_request_xml) {

      // Submit the API request to UPS.
      $response = commerce_ups_api_request($rate_request_xml, t('Requesting shipping rates for Order @order_number', array(
        '@order_number' => $order->order_number,
      )));
      if (!empty($response)) {

        // Parse the response to cache all requested rates for the current order.
        foreach ($response->RatedShipment as $rate) {

          // Extract the service name and price information from the rate object.
          $service_name = commerce_ups_commerce_shipping_service_name((string) $rate->Service->Code);
          $decimal = (string) $rate->TotalCharges->MonetaryValue;
          $currency_code = (string) $rate->TotalCharges->CurrencyCode;

          // Add an item to the rates array for the current service.
          $rates[$service_name] = array(
            'amount' => commerce_currency_decimal_to_amount($decimal, $currency_code),
            'currency_code' => $currency_code,
            'data' => array(),
          );
        }

        // Cache the calculated rates for subsequent requests.
        commerce_shipping_rates_cache_set('ups', $order, $rates);
      }
    }
  }

  // Return the rate for the requested service or FALSE if not found.
  return isset($rates[$shipping_service['name']]) ? $rates[$shipping_service['name']] : FALSE;
}

/**
 * Implements hook_commerce_shipping_service_rate_options_alter().
 */
function commerce_ups_commerce_shipping_service_rate_options_alter(&$options, $order) {

  // If the display UPS logo next to UPS services is enabled in settings,
  // loop through the shipping options and add the UPS logo to UPS services.
  if (variable_get('commerce_ups_show_logo', FALSE)) {
    $image = drupal_get_path('module', 'commerce_ups') . '/images/ups-logo.png';
    if (file_exists($image)) {
      foreach ($options as $key => &$option) {
        if (preg_match('/^ups_/', $key)) {
          $option = theme('image', array(
            'path' => $image,
            'width' => '16px',
          )) . ' ' . $option;
        }
      }
    }
  }
}

/**
 * Convenience function to get UPS codes for their services.
 */
function _commerce_ups_service_list() {
  $services = array(
    // Domestic services
    '03' => array(
      'title' => t('UPS Ground'),
      'description' => t('Ground Delivery'),
    ),
    '01' => array(
      'title' => t('UPS Next Day Air'),
      'description' => t('Next Day Air'),
    ),
    '13' => array(
      'title' => t('UPS Next Day Air Saver'),
      'description' => t('Next Day Air Saver'),
    ),
    '14' => array(
      'title' => t('UPS Next Day Early A.M.'),
      'description' => t('Next Day Early A.M.'),
    ),
    '02' => array(
      'title' => t('UPS 2nd Day Air'),
      'description' => t('2nd Day Air'),
    ),
    '59' => array(
      'title' => t('UPS 2nd Day Air A.M.'),
      'description' => t('2nd Day Air A.M.'),
    ),
    '12' => array(
      'title' => t('UPS 3 Day Select'),
      'description' => t('3 Day Select'),
    ),
    // International services
    '11' => array(
      'title' => t('UPS Standard'),
      'description' => t('International Standard'),
    ),
    '07' => array(
      'title' => t('UPS Worldwide Express'),
      'description' => t('Worldwide Express'),
    ),
    '08' => array(
      'title' => t('UPS Worldwide Expedited'),
      'description' => t('Worldwide Expedited'),
    ),
    '54' => array(
      'title' => t('UPS Worldwide Express Plus'),
      'description' => t('Worldwide Express Plus'),
    ),
    '65' => array(
      'title' => t('UPS Worldwide Saver'),
      'description' => t('Worldwide Saver'),
    ),
  );

  /* Make a unique ID to identify the service by */
  foreach ($services as $key => $service) {
    $service['slug'] = str_replace(' ', '_', drupal_strtolower($service['title']));
    $services[$key] = $service;
  }
  return $services;
}

/**
 * Convenience function to get UPS codes for their package types.
 */
function _commerce_ups_packaging_types() {
  return array(
    // Customer Supplied Page is first so it will be the default
    '02' => t('Customer Supplied Package'),
    '01' => t('UPS Letter'),
    '03' => t('Tube'),
    '04' => t('PAK'),
    '21' => t('UPS Express Box'),
    '24' => t('UPS 25KG Box'),
    '25' => t('UPS 10KG Box'),
    '30' => t('Pallet'),
    '2a' => t('Small Express Box'),
    '2b' => t('Medium Express Box'),
    '2c' => t('Large Express Box'),
  );
}
function _commerce_ups_pickup_types() {
  return array(
    '06' => 'One Time Pickup',
    '01' => 'Daily Pickup',
    '03' => 'Customer Counter',
    '07' => 'On Call Air',
    '19' => 'Letter Center',
    '20' => 'Air Service Center',
  );
}
function commerce_ups_commerce_shipping_service_name($service_code) {
  $service_names = _commerce_ups_service_list();
  return $service_names[$service_code]['slug'];
}

/**
 * Encrypt a specified value.
 */
function commerce_ups_encrypt($value) {
  return aes_encrypt($value);
}

/**
 * Decrypt all api variables in one function call. 
 */
function commerce_ups_decrypt_vars($include_password) {
  $user_vars = array();
  $encrypted = variable_get('commerce_ups_encrypt', FALSE) && function_exists('aes_decrypt');
  $user_vars['ups_accountid'] = variable_get('commerce_ups_account_id', '');
  $user_vars['ups_userid'] = variable_get('commerce_ups_user_id', '');
  $user_vars['ups_accesskey'] = variable_get('commerce_ups_access_key', '');
  if ($include_password) {
    $user_vars['ups_password'] = variable_get('commerce_ups_password', '');
  }
  if ($encrypted) {
    $user_vars['ups_accountid'] = aes_decrypt($user_vars['ups_accountid']);
    $user_vars['ups_userid'] = aes_decrypt($user_vars['ups_userid']);
    $user_vars['ups_accesskey'] = aes_decrypt($user_vars['ups_accesskey']);
    if ($include_password) {
      $user_vars['ups_password'] = aes_decrypt($user_vars['ups_password']);
    }
  }
  return $user_vars;
}

/**
 * Check whether encryption is available.
 */
function commerce_ups_encryption_available($options = array()) {
  $defaults = array(
    'check_config' => TRUE,
    'display_errors' => FALSE,
    'display_warnings' => FALSE,
    'display_all' => FALSE,
    'fail_threshold' => 'warnings',
  );
  $options = array_merge($defaults, $options);
  extract($options);
  $errors = array();
  $warnings = array();
  if (!module_exists('aes')) {
    $errors[] = 'AES Encryption module is not installed.';
  }
  elseif ($check_config) {
    if (!variable_get('aes_key_path', FALSE) || variable_get('aes_key_storage_method', FALSE) != 'File') {
      $warnings[] = 'AES Encryption is installed but not configured securely. Please go ' . l('configure AES Encryption to use file storage', 'admin/settings/aes') . ' to enable encryption for UPS credentials.';
    }
  }
  if ($display_errors || $display_all) {
    foreach ($errors as $msg) {
      drupal_set_message(filter_xss(t($msg)), 'error', FALSE);
    }
  }
  if ($display_warnings || $display_all) {
    foreach ($warnings as $msg) {
      drupal_set_message(filter_xss(t($msg)), 'warning', FALSE);
    }
  }
  switch ($fail_threshold) {
    case 'errors':
      if (empty($errors)) {
        return TRUE;
      }
    case 'warnings':
      if (empty($errors) && empty($warnings)) {
        return TRUE;
      }
  }
}

Functions

Namesort descending Description
commerce_ups_commerce_shipping_method_info Implements hook_commerce_shipping_method_info().
commerce_ups_commerce_shipping_service_info Implements hook_commerce_shipping_service_info().
commerce_ups_commerce_shipping_service_name
commerce_ups_commerce_shipping_service_rate_options_alter Implements hook_commerce_shipping_service_rate_options_alter().
commerce_ups_decrypt_vars Decrypt all api variables in one function call.
commerce_ups_encrypt Encrypt a specified value.
commerce_ups_encryption_available Check whether encryption is available.
commerce_ups_menu
commerce_ups_service_rate_order Shipping service callback: returns a base price array for a shipping service calculated for the given order.
_commerce_ups_packaging_types Convenience function to get UPS codes for their package types.
_commerce_ups_pickup_types
_commerce_ups_service_list Convenience function to get UPS codes for their services.