Zen Cart Logo
Forums / Addon Shipping Modules / Help with a osc converted shipping module

Help with a osc converted shipping module

Locked

Views: 1,181

Results 1 to 3 of 3
This thread is locked. New replies are disabled.
3 Sep 2010, 1:30 AM
#1
frilansreklam avatar

frilansreklam

New Zenner

Join Date:
Sep 2008
Location:
Sweden
Posts:
99
Plugin Contributions:
1

Help with a osc converted shipping module

I have worked on a convertion of an osc shipping module and all looks fine but it not sending the last xml information.

the module first import different shipping companys prices and that works fine. It is calculated from an extra box size code (not neded).

the customer check the prefered shipping and go to checkout.

all still work fine and the correct shipping is stored.

But nothing is registred at the administration page at the shipping company.

So if someone can se what I can't see I would be very happy because this module has been unfinnished for a long time.

3 Sep 2010, 1:32 AM
#2
frilansreklam avatar

frilansreklam

New Zenner

Join Date:
Sep 2008
Location:
Sweden
Posts:
99
Plugin Contributions:
1

Re: Help with a osc converted shipping module

This is the code:

function quote($method = '') {
global $language, $order, $shipping_num_boxes, $db;

// On lacking SimpleXML
  if (!class_exists('SimpleXMLElement') || !function_exists('curl_init')) {
    
  // Halt
    return $this->fallback('PHP-komponenten SimpleXML saknas.');
  }
  
// On lacking server capabilities
  if (MODULE_SHIPPING_FRAKTJAKT_HTTP_METHOD == 'fopen' && ini_get('allow_url_fopen') < 1) {
    
  // Halt
    return $this->fallback('PHP fopen tillåter inte externa anslutningar. Använd kommunikationsmetod libcurl istället.');
  }
  
// On lacking server capabilities
  if (MODULE_SHIPPING_FRAKTJAKT_HTTP_METHOD == 'libcurl' && !function_exists('curl_init')) {
    
  // Halt
    return $this->fallback('PHP-komponenten cURL saknas. Använd kommunikationsmetod fopen istället.');
  }
  
// On unsupported standard currency
$min_kod = $db->Execute("select code from ". TABLE_CURRENCIES ." where code='SEK';");
	if ($min_kod->EOF) {

    
  // Halt
    return $this->fallback('Standardvalutan i osCommerce stöds ej. Sätt standardvaluta till SEK.');
  }
  $def_curr = $db->Execute("select configuration_value from ". TABLE_CONFIGURATION ." where configuration_key='DEFAULT_CURRENCY' and configuration_value='SEK';");
if ($def_curr->EOF) {

    
  // Halt
    return $this->fallback('Standardvalutan i osCommerce stöds ej. Sätt standardvaluta till SEK.');
  }
  
// Build XML
  $this->debug[] = 'Building query XML.';
  $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
       . '<shipment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . "\r\n"
       . '  <value>'. round($order->info['subtotal'] + $order->info['tax'], 2) .'</value>' . "\r\n"
       . '  <consignor>' . "\r\n"
       . '    <id>'. MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_ID .'</id>' . "\r\n"
       . '    <key>'. MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_PASSWORD .'</key>' . "\r\n"
       . '    <currency>'. $order->info['currency'] .'</currency>' . "\r\n"
       . '    <language>'. $this->get_iso_language($language) .'</language>' . "\r\n"
       . '  </consignor>' . "\r\n"
       . '  <parcels>' . "\r\n";
  
// Go through every product
  foreach ($order->products as $product) {
  
  // If product itself should be sent as an own package
    if ($product['own_package'] == '1') {
      
    // Twist and turn the item for best fit with other items in same package
      $dimensions = array($product['width'], $product['height'], $product['length']);
      rsort($dimensions, SORT_NUMERIC); // Sort $dimensions by highest to lowest
      
    // For each quantity
      for($i=0; $i < $product['qty']; $i++) {
        
      // Write the package to XML
        $xml .= '    <parcel>' . "\r\n"
              . '      <weight>'. $product['weight'] .'</weight>' . "\r\n"
              . '      <length>'. $dimensions[0] .'</length>' . "\r\n"
              . '      <width>'. $dimensions[1] .'</width>' . "\r\n"
              . '      <height>'. $dimensions[2] .'</height>' . "\r\n"
              . '    </parcel>' . "\r\n";
      }
    
  // Or if this item should be sent among the others
    } else {
      
    // Twist and turn the item for best fit with other items in same package
      $dimensions = array($product['width'], $product['height'], $product['length']);
      rsort($dimensions, SORT_NUMERIC); // Sort $dimensions by highest to lowest
      
    // For each quantity
      for($i=0; $i < $product['qty']; $i++) {
      
      // Add item to package with other items
        $shipping_num_items++;
        $shipping_weight += $product['weight'];
        if ($dimensions[0] > $shipping_length) $shipping_length = $dimensions[0]; // This is the longest side, we will treat it as length.
        if ($dimensions[1] > $shipping_width) $shipping_width = $dimensions[1]; // This is the 2nd longest side, we will treat it as width.
        $shipping_height += $dimensions[2]; // This is the shortest side, we will treat it as height and place it above previous item(s).
      }
    }
  }
  
// Write package with various items to XML
  if ($shipping_num_items > 0) {
    $xml .= '    <parcel>' . "\r\n"
          . '      <weight>'. $shipping_weight .'</weight>' . "\r\n"
          . '      <length>'. $shipping_length .'</length>' . "\r\n"
          . '      <width>'. $shipping_width .'</width>' . "\r\n"
          . '      <height>'. $shipping_height .'</height>' . "\r\n"
          . '    </parcel>' . "\r\n";
  }
  
// Continue writing XML
  $xml .= '  </parcels>' . "\r\n"
        . '  <address>' . "\r\n"
        . '    <street_address_1>'. $order->delivery['street_address'] .'</street_address_1>' . "\r\n"
        . '    <street_address_2></street_address_2>' . "\r\n"
        . '    <postal_code>'. $order->delivery['postcode'] .'</postal_code>' . "\r\n"
        . '    <city_name>'. $order->delivery['city'] .'</city_name>' . "\r\n"
        . '    <residential>1</residential>' . "\r\n"
        . '    <country_code>'. $order->delivery['country']['iso_code_2'] .'</country_code>' . "\r\n"
        . '    <country_subdivision_code>F</country_subdivision_code>' . "\r\n"
        . '  </address>' . "\r\n"
        . '</shipment>' . "\r\n";
  
  $this->debug[] = "\r\n". $xml . "\r\n";
  
  if ($_SESSION['fraktjakt_api']['query_xml'] != $xml || empty($_SESSION['fraktjakt_api']['query_response_xml'])) {
    
  // Define the API URL
    $api_url = $this->api_server . '/fraktjakt/query_xml';
    $this->debug[] = 'Setting API URL to '. $api_url .'.';
    
  // Set HTTP request headers
    $httpHeaders = array(
    // BOF: PHP bug #47906 circumvention (<http://bugs.php.net/bug.php?id=47906>)
      "Expect: ", // Disable the 100-continue header
    // EOF: PHP bug #47906 circumvention
      "Accept-Charset: UTF-8",
      "Content-type: application/x-www-form-urlencoded"
    );
    $this->debug[] = "Setting HTTP request headers to:\r\n   " . implode("\r\n   ", $httpHeaders) ."\r\n\r\n";
    
  // Build HTTP POST parameters
    $httpPostParams = array(
      'md5_checksum' => md5($xml),
      'xml' => utf8_encode($xml)
    );
    $this->debug[] = 'Setting '. count($httpPostParams) .' post parameters ('. implode(', ', array_keys($httpPostParams)) .').';
    
  // Cache query xml
    $this->debug[] = 'Caching XML query incase it will be used again.';
    $_SESSION['fraktjakt_api']['query_xml'] = $xml;
    
  // Contact remote API and get data
    $_SESSION['fraktjakt_api']['query_response_xml'] = $this->http_post($api_url, $httpHeaders, $httpPostParams);

  } else {
    
    $this->debug[] = 'Using cached data instead of new API connection.';      
  }
  
// On no data
  if (empty($_SESSION['fraktjakt_api']['query_response_xml'])) {
    
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Query Error');
    
  // Send technical e-mail report to fraktjakt
    $this->send_report($this->report_email, 'Fraktjakt Query Error');
    
  // Halt
    return $this->fallback('Anslutning till Fraktjakt API misslyckades, vänligen försök igen senare.');
  }
  
// Treat libxml errors internally instead
  libxml_use_internal_errors(true);
  
// Create a SimpleXMLElement object
  $objXML = simplexml_load_string($_SESSION['fraktjakt_api']['query_response_xml']);
  
// On XML class error
  if (!objXML || libxml_get_errors()) {
  
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Query Error');
    
  // Send technical e-mail report to fraktjakt
    $this->send_report($this->report_email, 'Fraktjakt Query Error');
    
  // Halt
    return $this->fallback('Ogiltig XML nod. Felaktig svarskod?');
  }

// On no shipment node
  if (utf8_decode($objXML->getName()) != 'shipment') {
  
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Query Error');
    
  // Send technical e-mail report to fraktjakt
    $this->send_report($this->report_email, 'Fraktjakt Query Error');
    
  // Halt
    return $this->fallback('Ogiltig XML nod. Felaktig svarskod?');
  }
  
// On error
  if (trim(utf8_decode($objXML->error_message)) != '') {
    
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Query Error');
    
  // Halt
    return $this->fallback(utf8_decode($objXML->error_message));
  }
  
// On no methods
  if (empty($objXML->shipping_products)) {
    
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Query Error');
    
  // Send technical e-mail report to fraktjakt
    $this->send_report($this->report_email, 'Fraktjakt Query Error');
    
  // Halt
    if (MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS == 'Ja') {
      return $this->fallback('Inga metodval att lista.');
    } else {
      return $this->fallback();
    }
  }
  
// On debug
  if ($method == '' && MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS == 'Ja') {
    
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Query Debug');
  }
  
// Go through every option
  foreach ($objXML->shipping_products->children() as $option) {
    
    $gross = utf8_decode($option->price) * $shipping_num_boxes;
    
  // Should option be output?
    if ($method == '' || $method == trim(utf8_decode($objXML->id)) .'-'. trim(utf8_decode($option->id))) {
    
    // Build output option variable
      $shipping_methods[] = array(
        'id' => trim(utf8_decode($objXML->id)) .'-'. trim(utf8_decode($option->id)),
        'title' => (($method != '') ? utf8_decode($option->description) : utf8_decode($option->description) . '<font color="#666666">' . (($option->agent_info != '') ? '<br />   ' . MODULE_SHIPPING_FRAKTJAKT_AGENT . '<a href="'. utf8_decode($option->agent_link) .'" target="_blank" style="color: #666666;">' . utf8_decode($option->agent_info) .'</a>' : false) . (($option->arrival_time != '') ? '<br />   '. MODULE_SHIPPING_FRAKTJAKT_ARRIVAL_TIME . utf8_decode($option->arrival_time) : false) . '</font>'),
        'cost' => $gross
      );
    }
  }
  
  if ($method != '') {
    $output_string = ((MODULE_SHIPPING_FRAKTJAKT_ICON == '') ? $this->moduleinfo['name'] : false);
  } else {
    $output_string = $this->moduleinfo['name'];
    $output_string .= ((MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS == 'Ja') ? ' #' . utf8_decode($objXML->id) : false);
    $output_string .= ((MODULE_SHIPPING_FRAKTJAKT_TEST_MODE == 'Ja') ? ' [TEST]' : false);
    $output_string .= ((MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS == 'Ja' && trim($objXML->warning) != '') ? ' (Varning:' . utf8_decode($objXML->warning) . ')' : false);
  }
  
// Get tax rate
  if (MODULE_SHIPPING_FRAKTJAKT_TAX_TYPE == 'Standard') {
    if ($this->tax_class > 0) {
      $tax_rate = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
    }
  } else {
    $tax_rate = $this->get_proportional_tax_rate();
  }
  
// Output
  return array(
    'id' => $this->code,
    'icon' => (MODULE_SHIPPING_FRAKTJAKT_ICON != '') ? zen_image(MODULE_SHIPPING_FRAKTJAKT_ICON, $this->moduleinfo['name'] . ((MODULE_SHIPPING_FRAKTJAKT_TEST_MODE == 'Ja') ? ' [TEST]' : false)) : false,
    'module' => $output_string,
    'methods' => $shipping_methods,
    'tax' => $tax_rate
  );
}

function after_process() {
  global $db, $language, $order, $shipping, $insert_id;
  
// Rensning av cache
  $_SESSION['fraktjakt_api']['query_xml'] = '';
  
// Extract query id and product/method id
  list($shipment_id, $shipping_product_id) = explode('-', substr($_SESSION['shipping']['id'], strpos($_SESSION['shipping']['id'], '_')+1));
  
// Halt on fallback method
  if ($shipping_product_id == 'fallback') return;
  
// Build XML
  $this->debug[] = 'Building order XML.';
  $xml =   '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
         . '<order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . "\r\n"
         . '  <consignor>' . "\r\n"
         . '    <id>'. MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_ID .'</id>' . "\r\n"
         . '    <key>'. MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_PASSWORD .'</key>' . "\r\n"
         . '    <currency>'. $order->info['currency'] .'</currency>' . "\r\n"
         . '    <language>'. $this->get_iso_language($language) .'</language>' . "\r\n"
         . '  </consignor>' . "\r\n"
         . '  <shipment_id>'. $shipment_id .'</shipment_id>' . "\r\n"
         . '  <shipping_product_id>'. $shipping_product_id .'</shipping_product_id>' . "\r\n"
         . '  <reference>osCommerce order #'. $insert_id .'</reference>' . "\r\n"
         . '  <commodities>' . "\r\n";
  foreach ($order->products as $product) {
  $xml .=  '    <commodity>' . "\r\n"
         . '      <name>'. $product['name'] .'</name>' . "\r\n"
         . '      <quantity>'. $product['qty'] .'</quantity>' . "\r\n"
         . '      <taric>'. $product['taric_code'] .'</taric>' . "\r\n"
         . '      <quantity_units>EA</quantity_units>' . "\r\n"
         . '      <description></description>' . "\r\n"
         . '      <country_of_manufacture>'. $product['country_of_manufacture'] .'</country_of_manufacture>' . "\r\n"
         . '      <weight>'. $product['weight'] .'</weight>' . "\r\n"
         . '      <unit_price>'. round($product['final_price'], 2) .'</unit_price>' . "\r\n"
         . '    </commodity>' . "\r\n";
  }
  $xml .=  '  </commodities>' . "\r\n"
         . '  <recipient>' . "\r\n"
         . '    <company_to>'. $order->delivery['company'] .'</company_to>' . "\r\n"
         . '    <name_to>'. trim($order->delivery['firstname'] . ' ' . $order->delivery['lastname']) .'</name_to>' . "\r\n"
         . '    <telephone_to>'. $order->customer['telephone'] .'</telephone_to>' . "\r\n"
         . '    <email_to>'. $order->customer['email_address'] .'</email_to>' . "\r\n"
         . '  </recipient>' . "\r\n"
         . '</order>' . "\r\n";
  
  $this->debug[] = "\r\n". $xml . "\r\n";
  
// Define the API URL
  $api_url = $this->api_server . '/orders/order_xml';
  $this->debug[] = "Setting API URL to ". $api_url . '.';
  
// Set HTTP request headers
  $httpHeaders = array(
  // BOF: PHP bug #47906 circumvention (<http://bugs.php.net/bug.php?id=47906>)
    "Expect: ", // Disable the 100-continue header
  // EOF: PHP bug #47906 circumvention
    "Accept-Charset: UTF-8",
    "Content-type: application/x-www-form-urlencoded"
  );
  $this->debug[] = "Setting HTTP request headers to:\r\n   " . implode("\r\n   ", $httpHeaders) ."\r\n\r\n";
  
// Build HTTP POST parameters
  $httpPostParams = array(
    'md5_checksum' => md5($xml),
    'xml' => utf8_encode($xml)
  );
  $this->debug[] = 'Setting '. count($httpPostParams) .' post parameters ('. implode(', ', array_keys($httpPostParams)) .').';
  
// Contact remote API and send data
  $response_xml = $this->http_post($this->api_server . '/orders/order_xml', $httpHeaders, $httpPostParams);
  
// Treat libxml errors internally instead
  libxml_use_internal_errors(true);
  
// Create a SimpleXMLElement object
  $objXML = simplexml_load_string($response_xml);
  
// On XML class errors
  if (!$objXML || libxml_get_errors()) {
    
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Order Error');
    
  // Send technical e-mail report to fraktjakt
    $this->send_report($this->report_email, 'Fraktjakt Order Error');
    
    return;
  }
  
// On invalid XML or returned error
  if (utf8_decode($objXML->getName()) != 'result' || utf8_decode($objXML->error) != '') {
  
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Order Error');
    
  // Send technical e-mail report to fraktjakt
    $this->send_report($this->report_email, 'Fraktjakt Order Error');
    
    return;
  }
  
// On warning
  if (trim(utf8_decode($objXML->warning)) != '') {
  
  if (MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS == 'Ja') {
  
    // Send technical e-mail report
      $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Order Warning');
      
      return;
    }
  }
  
// on debug
  if (MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS == 'Ja') {
  
  // Send technical e-mail report
    $this->send_report(MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL, 'Fraktjakt Order Debug');
  }
}

function send_report($recipient, $subject) {
  
// Send technical e-mail report
  if (MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL != '') {
    
  // Create mail object
  // $message = new email(array('X-Mailer: PHPMailer [version 1.73] via Zen Cart'));
    
  // Prepare mail mody
    $body = (
      "Versions:\r\n" .
      "- " . $_SERVER['SERVER_SOFTWARE'] ."\r\n" .
      "- PHP: " . phpversion() . "\r\n" . 
      "- cURL: " . $curl_ver['version'] . ' (' . implode(', ', curl_version()) . ')' ."\r\n" .
      "- SimpleXML: " . phpversion('SimpleXML') . "\r\n\r\n" .
      "Configuration:\r\n" .
      "- allow_url_fopen: " . ini_get('allow_url_fopen') . "\r\n\r\n" .
      "--------------------------------------------\r\n\r\n" .
      "Script debug data:\r\n\r\n" .
      "  " . @implode("\r\n  ", $this->debug) . "\r\n"
    );

// $message->add_text($body);

  // Send mail
  //  $message->build_message();
   // $message->send($recipient, $recipient, STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, $subject);
  }
}

function fallback($error_message='') {
  global $db, $order, $shipping_weight, $shipping_num_boxes;
  
  $this->debug[] = 'Executing fallback function.';
  
  if ($order->delivery['country']['iso_code_2'] == 'SE') {
    
  // Shipping within Sweden
    $shipping_table = MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_DOMESTIC;
    
  } else {
    
    if (in_array($order->delivery['country']['iso_code_2'], explode(',', 'AT,BE,CH,DK,ES,GB,FR,DE,GL,GR,IL,IS,IE,IT,NO,NL,PL,FI,PT'))) {
      
    // Shipping outside Sweden - Within Europe
      $shipping_table = MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_EUROPE;
      
    } else {
      
    // Shipping outside Sweden - Outside Europe
      $shipping_table = MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_WORLD;
    }
  }
  
// Calculate cost
  $gross = $this->calculate_table_cost($shipping_table, ($shipping_weight)) * $shipping_num_boxes + MODULE_SHIPPING_POSTEN_INRIKESPAKET_HANDLING;
  
// Get tax rate
  if (MODULE_SHIPPING_FRAKTJAKT_TAX_TYPE == 'Standard') {
    if ($this->tax_class > 0) {
      $tax_rate = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
    }
  } else {
    $tax_rate = $this->get_proportional_tax_rate();
  }
3 Sep 2010, 1:32 AM
#3
frilansreklam avatar

frilansreklam

New Zenner

Join Date:
Sep 2008
Location:
Sweden
Posts:
99
Plugin Contributions:
1

Re: Help with a osc converted shipping module

// Return the options
return array(
'id' => $this->code,
'icon' => false,
'module' => $this->moduleinfo['name'] . ((MODULE_SHIPPING_FRAKTJAKT_TEST_MODE == 'Ja') ? ' [TEST]' : false) . ' (Fel: '. $error_message .')',
'methods' => array(
array(
'id' => 'fallback',
'title' => MODULE_SHIPPING_FRAKTJAKT_FALLBACK_METHOD_NAME,
'cost' => $gross
)
),
'tax' => $tax_rate
);
}

function get_iso_language($language) {
  switch ($language) {
    case 'english':
      return 'en';
    case 'svenska':
    case 'swedish':
      return 'sv';
    default:
      return 'en';
  }
}

function get_proportional_tax_rate() {

// Give access to global variables
  global $order;
  
// Step through every product in shopping cart
  foreach ($order->products as $product) {
    
  // Summarize the total gross cost for all products, no matter which tax groups
    $products_gross_total += $product['qty'] * $product['final_price'];
    
  // Summarize the total gross cost for all products, no matter which tax groups
    $products_tax_total += $product['qty'] * $product['final_price'] * $product['tax'] / 100;
  }
  
// Return proportional tax rate
  return $products_tax_total / $products_gross_total * 100;
}

function calculate_table_cost($table, $weight) {
  
// Split weight table
  $table = array_reverse(explode("|" , $table));
  
// Step through every class entry
  foreach ($table as $entry) {
    $entry = explode(':', $entry);
    
    // Set cost
      if ($weight <= $entry[0]) $this_cost = $entry[1];
  }
  return $this_cost;
}

function http_post($url, $headers='', $postfields) {

// Using fopen()
  if (MODULE_SHIPPING_FRAKTJAKT_HTTP_METHOD == 'fopen') {
  
    if (is_array($postfields)) {
      foreach ($postfields as $key => $value) {
        $postfields[$key] = $key .'='. urlencode($value);
      }
      $postfields = implode('&', $postfields); 
    }
    
    $params = array(
      'http' => array(
        'method' => 'POST',
        'content' => $postfields,
        'header' => @implode("\r\n", $headers),
      )
    );
      
    while ($response == false && $tries < 2) {
    
      $this->debug[] = '[fopen] Connecting to ' . $url .' at '. date('H:i:s') . '.';
      
      $ctx = @stream_context_create($params);
      $fp = @fopen($url, 'rb', false, $ctx);
      $response = @stream_get_contents($fp);
      
      $this->debug[] = '[fopen] ' . ((!$response) ? 'No response data at '. date('H:i:s') .'('. curl_error() .')' : "Got the following HTTP response at ". date('H:i:s') .":\r\n\r\n" . utf8_decode($response) ."\r\n\r\n");
      
      $tries++;
    }
    return $response;
    
// Using libcurl
  } else {
  
  // BOF: PHP bug #27040 circumvention (<http://bugs.php.net/bug.php?id=27040>)
  // Solution for known bug where CURLOPT_POSTFIELDS doesnt work with arrays
    if (is_array($postfields)) {
      foreach ($postfields as $key => $value) {
        $postfields[$key] = $key .'='. urlencode($value);
      }
      $postfields = implode('&', $postfields);
    }
  // EOF: PHP bug #27040 circumvention
    
    while ($response == false && $tries < 2) {
    
      $this->debug[] = '[cURL] Connecting to '. $url .' at '. date('H:i:s') .'.';
      
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_FAILONERROR, false); // fail on errors
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // allow redirects
      curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); // forces a non-cached connection
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set http headers
      curl_setopt($ch, CURLOPT_POST, true); // initialize post method
      curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); // variables to post
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
      curl_setopt($ch, CURLOPT_TIMEOUT, 30); // timeout after 30s
      $response = curl_exec($ch);
      
      $this->debug[] = '[cURL] ' . ((!$response) ? 'No response data at '. date('H:i:s') .'('. curl_error() .')' : "Got the following HTTP response at ". date('H:i:s') .":\r\n\r\n" . utf8_decode($response) ."\r\n\r\n");
      
      curl_close($ch);
      $tries++;
    }
    return $response;
  }
}
 function check() {
  global $db;
  if (!isset($this->_check)) {
    $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_FRAKTJAKT_STATUS'");
    $this->_check = $check_query->RecordCount();
  }
  return $this->_check;
}
    
function install() {
	global $db;
  $this->remove();
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Tjänsten aktiverad?', 'MODULE_SHIPPING_FRAKTJAKT_STATUS', 'Ja', 'Vill du hämta priser för frakt från Fraktjakt.se?', '6', '0', 'zen_cfg_select_option(array(\'Ja\', \'Nej\'), ', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Ikon', 'MODULE_SHIPPING_FRAKTJAKT_ICON', '', 'Om du vill visa en ikon istället för ett textalternativ, ange webbsökväg ex. /images/myicon.gif', '6', '1', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Fraktjakt användarnamn', 'MODULE_SHIPPING_FRAKTJAKT_USERNAME', '', 'Ange användarnamn till adminpanelen hos Fraktjakt.', '6', '2', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Fraktjakt lösenord', 'MODULE_SHIPPING_FRAKTJAKT_PASSWORD', '', 'Ange lösenord till adminpanelen hos Fraktjakt.', '6', '3', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Fraktjakt Consignor ID', 'MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_ID', '', 'Ange ditt id för Fraktjakt API.', '6', '4', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Fraktjakt Consignor Key', 'MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_PASSWORD', '', 'Ange ditt lösenord för API.', '6', '5', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Testläge', 'MODULE_SHIPPING_FRAKTJAKT_TEST_MODE', 'Ja', 'Vill du köra mot Fraktjakts testserver? (Kräver separat konto på testserver)', '6', '6', 'zen_cfg_select_option(array(\'Ja\', \'Nej\'), ', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Kommunikationsmetod', 'MODULE_SHIPPING_FRAKTJAKT_HTTP_METHOD', 'libcurl', 'Ange önskad serverkomponent för kommunicering.', '6', '0', 'zen_cfg_select_option(array(\'fopen\', \'libcurl\'), ', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Felsökningsläge?', 'MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS', 'Ja', 'Vill du köra i felsökningsläge? Rapporter kommer att skickas till dig via e-post vid varje API anslutning. Om du inte kör felsökningsläge kommer endast felrapporteringar skickas via e-post.', '6', '7', 'zen_cfg_select_option(array(\'Ja\', \'Nej\'), ', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('E-postadress för rapporter', 'MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL', '', 'Ange en mottagaradress för tekniska rapporteringar.', '6', '8', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Pristabell för reservutväg vid inrikes sändning', 'MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_DOMESTIC', '3:112|5:128|10:168|15:204|20:236', '', '6', '9', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Pristabell för reservutväg vid utrikes sändning inom Europa', 'MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_EUROPE', '3:210|5:250|10:350|15:450|20:550|25:650|30:750', '', '6', '10', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Pristabell för reservutväg vid utrikes sändning utanför Europa', 'MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_WORLD', '3:321|5:435|10:720|15:1005|20:1290|25:1575|30:1860', '', '6', '11', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Momsfunktion', 'MODULE_SHIPPING_FRAKTJAKT_TAX_TYPE', 'Variabel', 'Ange önskad momsfunktion ex. Standard för att själv ange momsklass nedan eller Variabel för att frakten regelriktigt skall ärva momsen från varorna (OBS! kräver TiM\'s ordertotal-moduler).', '6', '12', 'zen_cfg_select_option(array(\'Standard\', \'Variabel\'), ', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Momsklass', 'MODULE_SHIPPING_FRAKTJAKT_TAX_CLASS', '0', 'Ange momsklass för fraktavgiften.', '6', '13', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");
  $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sortering', 'MODULE_SHIPPING_FRAKTJAKT_SORT_ORDER', '0', 'Ange plats i modulernas sorteringsordning.', '6', '14', now())");
}

function remove() {
	global $db;
  $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
}

function keys() {
  return array (
    'MODULE_SHIPPING_FRAKTJAKT_STATUS',
    'MODULE_SHIPPING_FRAKTJAKT_ICON',
    'MODULE_SHIPPING_FRAKTJAKT_USERNAME',
    'MODULE_SHIPPING_FRAKTJAKT_PASSWORD',
    'MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_ID',
    'MODULE_SHIPPING_FRAKTJAKT_CONSIGNOR_PASSWORD',
    'MODULE_SHIPPING_FRAKTJAKT_TEST_MODE',
    'MODULE_SHIPPING_FRAKTJAKT_HTTP_METHOD',
    'MODULE_SHIPPING_FRAKTJAKT_DEBUG_STATUS',
    'MODULE_SHIPPING_FRAKTJAKT_REPORT_EMAIL',
    'MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_DOMESTIC',
    'MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_EUROPE',
    'MODULE_SHIPPING_FRAKTJAKT_SHIPIPNG_TABLE_WORLD',
    'MODULE_SHIPPING_FRAKTJAKT_TAX_TYPE',
    'MODULE_SHIPPING_FRAKTJAKT_TAX_CLASS',
    'MODULE_SHIPPING_FRAKTJAKT_SORT_ORDER'
  );
}

}

?>