Benutzer-Werkzeuge

Webseiten-Werkzeuge


fakturama:zencart-connector

ZenCart Connector

fakturama-zencart_connector.php
<?php
 
/*
 * Fakturama - Free Invoicing Software - http://fakturama.sebulli.com
 * 
 * 
 * Web shop connector script
 * Date: 28.JAN.2014
 * 
 * This version is compatible to the same version of Fakturama
 *
 *
 * 
 * Copyright (C) 2014 Christian Kvasny
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * 01.2.2014 by Chris
 * code cleanup
 * fix empty contact id (change cid -> id)
 * change $check_orders_query from .... AND (o.orders_status = '1' " .... to .... AND (o.orders_status > '0' "
 * do status update without statusmessage must exist
 *
 * 28.1.2014 by Chris
 * change tablename with constants which are defined in database_tables.php
 * change rawurlencode to str_replace for replace space in image names
 * fix countries query .TABLE_COUNTRIES. " countries ON ..."
 * 
 * 10.11.2014 by NoBBi
 * fix: $file = getcwd().'/tmp/gets.txt';
 * please create a tmp-dir with read-create in active path before!
 *  
 */
 
define ('FAKTURAMA_CONNECTOR_VERSION', '1.6.3_20140201');
define ('FAKTURAMA_WEBSHOP', 'ZENCART-PRO');
// Character Set of the web shop. This is used to send notification comments.
define ('FAKTURAMA_WEBSHOP_CHARSET', 'UTF-8');
define ('IS_ADMIN_FLAG', true);
 
// Only for debugging. All the data is encrypted.
//define ('ENCRYPT_DATA',true);	
// Set header to UTF-8
header ("Content-Type: text/html; charset=utf-8");
 
// Set the level of error reporting
error_reporting (E_ALL & ~E_NOTICE);
 
// Use $HTTP_POST_VARS instead of $_POST in older environments
if (PHP_VERSION < 5.0) {
    exit ('PHP Version must be >= 5.0');
}
 
// Include application configuration parameters
require('includes/configure.php');
 
// init and database stuff
require(DIR_WS_FUNCTIONS . 'html_output.php');
require(DIR_FS_CATALOG . DIR_WS_FUNCTIONS . 'functions_email.php');
require(DIR_FS_CATALOG . DIR_WS_FUNCTIONS . 'sessions.php');
require(DIR_FS_CATALOG . DIR_WS_FUNCTIONS . 'password_funcs.php');
require(DIR_FS_CATALOG . DIR_WS_INCLUDES . 'filenames.php');
require(DIR_FS_CATALOG . DIR_WS_INCLUDES . 'database_tables.php');
require(DIR_FS_CATALOG . DIR_WS_INCLUDES . 'version.php');
require(DIR_FS_CATALOG . DIR_WS_CLASSES . 'class.base.php');
require(DIR_FS_CATALOG . DIR_WS_CLASSES . 'db/' . DB_TYPE . '/query_factory.php');
$db = new queryFactory();
$db->connect (DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
 
require(DIR_WS_FUNCTIONS . 'general.php');
 
// set php_self in the local scope
$PHP_SELF = $_SERVER['PHP_SELF'];
 
// include the database functions
require(DIR_WS_FUNCTIONS . 'database.php');
 
// set application wide parameters
$configuration_query = "SELECT configuration_key AS cfgKey, configuration_value AS cfgValue FROM " .TABLE_CONFIGURATION;
$configuration = $db->Execute ($configuration_query);
while (!$configuration->EOF) {
    define ($configuration->fields['cfgKey'], $configuration->fields['cfgValue']);
    $configuration_array[$configuration->fields['cfgKey']] = $configuration->fields['cfgValue'];
    $configuration->MoveNext ();
}
 
// Encrypt the data
function my_encrypt ($s)
{
    // Replace all characters
    if (defined ('ENCRYPT_DATA')) {
        $s = preg_replace ("/[a-z]/", "x", $s);
        $s = preg_replace ("/[A-Z]/", "X", $s);
        $s = preg_replace ("/[0-9]/", "0", $s);
    }
    return $s;
}
 
// Remove invalid XML Characters
function stripInvalidXml ($value)
{
    $ret = "";
    $current = "";
    if (empty ($value))
        return $ret;
 
    $length = strlen ($value);
    for ($i = 0; $i < $length; $i++) {
        $current = ord ($value{$i});
        if (($current == 0x9) ||
                ($current == 0xA) ||
                ($current == 0xD) ||
                (($current >= 0x20) && ($current <= 0xD7FF)) ||
                (($current >= 0xE000) && ($current <= 0xFFFD)) ||
                (($current >= 0x10000) && ($current <= 0x10FFFF))) {
            $ret .= chr ($current);
        } else {
            $ret .= " ";
        }
    }
    return $ret;
}
 
// Convert a string to proper UTF-8
function convertToUTF8 ($s)
{
    if (!mb_check_encoding ($s, 'UTF-8') OR !($s === mb_convert_encoding (mb_convert_encoding ($s, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32'))) {
        $s = mb_convert_encoding ($s, 'UTF-8');
    }
    return $s;
}
 
// Convert a string to UTF-8 and encode the special characters
function my_encode ($s)
{
    // Convert to UTF-8
    $s = convertToUTF8 ($s);
 
    // Strip all HTML Tags
    $s = strip_tags ($s);
 
    // Encrypt the data
    $s = my_encrypt ($s);
 
    // Convert entities like &uuml; to ü
    $s = html_entity_decode ($s, ENT_COMPAT, 'UTF-8');
 
    // Replace special characters
    $s = htmlspecialchars ($s, ENT_COMPAT, 'UTF-8');
 
    // Remove invalid characters
    $s = stripInvalidXml ($s);
    return $s;
}
 
// Exit with error message
function exit_with_error ($err)
{
    echo (" <error>" . $err . "</error>\n");
    echo ("</webshopexport>\n");
    exit ();
}
 
// Keep the BR-tags
function my_clean_nl ($s)
{
    // Keep the BR-tags
    //$s = str_replace("\n", "<br />", $s);
    // remove the carriage return
    $s = str_replace ("\r", "", $s);
    // remove non breakable spaces return
    $s = str_replace ("\xC2\xA0", " ", $s);
    $s = trim ($s);
    return $s;
}
 
class order
{
 
    var $info, $totals, $products, $customer, $delivery, $billing;
 
    function __construct ($order_id)
    {
        $this->info = array ();
        $this->totals = array ();
        $this->products = array ();
        $this->customer = array ();
        $this->delivery = array ();
        $this->billing = array ();
 
        $this->query ($order_id);
    }
 
    function query ($order_id)
    {
        global $db;
 
        $order_query = "SELECT
		customers_id, customers_name, customers_company, customers_street_address,
		customers_suburb, customers_city, customers_postcode, customers_state,
		customers_country, customers_telephone, customers_email_address, customers_address_format_id,
		delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city,
		delivery_postcode, delivery_state, delivery_country, delivery_address_format_id,
		billing_name, billing_company, billing_street_address, billing_suburb, billing_city, billing_postcode,
		billing_state, billing_country, billing_address_format_id, payment_method,
		cc_type, cc_owner, cc_number, cc_expires, currency, currency_value, date_purchased,
		orders_status, last_modified
		FROM "
		.TABLE_ORDERS.
		" WHERE
		orders_id = '" . (int) $order_id . "'";
 
        $order = $db->Execute ($order_query);
        $totals_query = "SELECT
		title, text
		FROM "
		.TABLE_ORDERS_TOTAL.
		" WHERE
		orders_id = '" . (int) $order_id . "'
		ORDER BY
		sort_order";
 
        $totals = $db->Execute ($totals_query);
        while (!$totals->EOF) {
            $this->totals[] = array ('title' => $totals->fields['title'], 'text' => $totals->fields['text']);
            $totals->MoveNext ();
        }
 
        $this->info = array ('currency' => $order->fields['currency'],
            'currency_value' => $order->fields['currency_value'],
            'payment_method' => $order->fields['payment_method'],
            'payment_class' => $order->fields['payment_class'],
            'cc_type' => $order->fields['cc_type'],
            'cc_owner' => $order->fields['cc_owner'],
            'cc_number' => $order->fields['cc_number'],
            'cc_expires' => $order->fields['cc_expires'],
            'date_purchased' => $order->fields['date_purchased'],
            'orders_status' => $order->fields['orders_status'],
            'language' => $order->fields['language'],
            'last_modified' => $order->fields['last_modified']);
 
        $this->info['language'] = FAKTURAMA_LANGUAGE;
 
        $this->customer = array (
            'id' => $order->fields['customers_id'],
            'firstname' => "",
            'lastname' => $order->fields['customers_name'],
            'name' => $order->fields['customers_name'],
            'company' => $order->fields['customers_company'],
            'street_address' => $order->fields['customers_street_address'],
            'suburb' => $order->fields['customers_suburb'],
            'city' => $order->fields['customers_city'],
            'postcode' => $order->fields['customers_postcode'],
            'state' => $order->fields['customers_state'],
            'country' => $order->fields['customers_country'],
            'format_id' => $order->fields['customers_address_format_id'],
            'telephone' => $order->fields['customers_telephone'],
            'email_address' => $order->fields['customers_email_address']);
 
        $this->delivery = array ('name' => $order->fields['delivery_name'],
            'firstname' => "",
            'lastname' => $order->fields['delivery_name'],
            'gender' => "",
            'company' => $order->fields['delivery_company'],
            'street_address' => $order->fields['delivery_street_address'],
            'suburb' => $order->fields['delivery_suburb'],
            'city' => $order->fields['delivery_city'],
            'postcode' => $order->fields['delivery_postcode'],
            'state' => $order->fields['delivery_state'],
            'country' => $order->fields['delivery_country'],
            'format_id' => $order->fields['delivery_address_format_id']);
 
        $this->billing = array ('name' => $order->fields['billing_name'],
            'firstname' => "",
            'lastname' => $order->fields['billing_name'],
            'gender' => "",
            'company' => $order->fields['billing_company'],
            'street_address' => $order->fields['billing_street_address'],
            'suburb' => $order->fields['billing_suburb'],
            'city' => $order->fields['billing_city'],
            'postcode' => $order->fields['billing_postcode'],
            'state' => $order->fields['billing_state'],
            'country' => $order->fields['billing_country'],
            'format_id' => $order->fields['billing_address_format_id']);
 
        $customers_id = $this->customer['id'];
        $firstandlastname = $this->customer['firstname'] . " " . $this->customer['lastname'] . "-";
 
        if ($this->delivery['name'] == " ") {
            $this->delivery = $this->customer;
        }
 
        $orders_address_query = "SELECT
		customers_id, entry_gender, entry_firstname, entry_lastname, entry_country_id, entry_zone_id
		FROM "
		.TABLE_ADDRESS_BOOK.
		" WHERE
		customers_id = '" . (int) $customers_id . "'";
 
        $orders_address = $db->Execute ($orders_address_query);
        while (!$orders_address->EOF) {
            $firstandlastname = $orders_address->fields['entry_firstname'] . " " . $orders_address->fields['entry_lastname'];
 
            $customer_entry_country_id = $orders_address->fields['entry_country_id'];
            $customer_entry_zone_id = $orders_address->fields['entry_zone_id'];
 
            if ($firstandlastname == $this->billing['name']) {
                $this->billing['firstname'] = $orders_address->fields['entry_firstname'];
                $this->billing['lastname'] = $orders_address->fields['entry_lastname'];
                $this->billing['gender'] = $orders_address->fields['entry_gender'];
            }
            if ($firstandlastname == $this->delivery['name']) {
                $this->delivery['firstname'] = $orders_address->fields['entry_firstname'];
                $this->delivery['lastname'] = $orders_address->fields['entry_lastname'];
                $this->delivery['gender'] = $orders_address->fields['entry_gender'];
            }
 
 
            $orders_address->MoveNext ();
        }
 
        //start with a default value
        $customer_geo_zone = 1;
 
        // Get the geozone if only the country matches
        $geo_zone_query = "SELECT
		geo_zone_id, zone_country_id, zone_id 
		FROM "
		.TABLE_ZONES_TO_GEO_ZONES.
		" WHERE
		zone_country_id = '" . (int) $customer_entry_country_id . "'";
        $geo_zone_line = $db->Execute ($geo_zone_query);
        while (!$geo_zone_line->EOF) {
            if ($geo_zone_line->fields['geo_zone_id'] > 0)
                $customer_geo_zone = $geo_zone_line->fields['geo_zone_id'];
            $geo_zone_line->MoveNext ();
        }
 
        // Get the geozone if only the country and the zone matches
        $geo_zone_query = "SELECT
		geo_zone_id, zone_country_id, zone_id 
		FROM "
		.TABLE_ZONES_TO_GEO_ZONES.
		" WHERE
		((zone_country_id = '" . (int) $customer_entry_country_id . "') AND (zone_id = '" . (int) $customer_entry_zone_id . "'))";
        $geo_zone_line = $db->Execute ($geo_zone_query);
        while (!$geo_zone_line->EOF) {
            if ($geo_zone_line->fields['geo_zone_id'] > 0)
                $customer_geo_zone = $geo_zone_line->fields['geo_zone_id'];
            $geo_zone_line->MoveNext ();
        }
 
        $index = 0;
        $orders_products_query = "SELECT
		tax.tax_description, ordprod.orders_products_id, ordprod.products_name,ordprod.products_id,
		ordprod.products_model, ordprod.products_price, ordprod.products_tax,
		ordprod.products_quantity, ordprod.final_price
		FROM "
		.TABLE_ORDERS_PRODUCTS. " ordprod
		LEFT JOIN "
		.TABLE_PRODUCTS. " prod ON (prod.products_id = ordprod.products_id) 
		LEFT JOIN "
		.TABLE_TAX_RATES. " tax ON ((prod.products_tax_class_id = tax.tax_class_id) AND (tax.tax_zone_id = '" . (int) $customer_geo_zone . "'))
		LEFT JOIN "
		.TABLE_LANGUAGES. " langu ON (langu.code = '" . DEFAULT_LANGUAGE . "')
		WHERE
		ordprod.orders_id = '" . (int) $order_id . "'";
 
        $orders_products = $db->Execute ($orders_products_query);
        while (!$orders_products->EOF) {
            $this->products[$index] = array (
                'id' => $orders_products->fields['orders_products_id'],
                'qty' => $orders_products->fields['products_quantity'],
                'name' => $orders_products->fields['products_name'],
                'products_id' => $orders_products->fields['products_id'],
                'ean' => $orders_products->fields['products_ean'],
                'model' => $orders_products->fields['products_model'],
                'tax' => $orders_products->fields['products_tax'],
                'tax_description' => $orders_products->fields['tax_description'],
                'price' => $orders_products->fields['products_price'],
                'products_vpe_name' => $orders_products->fields['products_vpe_name'],
                'final_price' => $orders_products->fields['final_price']);
 
 
            $category_query = "SELECT
		cat_desc.categories_name, langu.code , cat_desc.categories_id , prod_cat.products_id
		FROM "
		.TABLE_CATEGORIES_DESCRIPTION. " cat_desc
		LEFT JOIN "
		.TABLE_PRODUCTS_TO_CATEGORIES. " prod_cat ON (prod_cat.categories_id = cat_desc.categories_id)
		LEFT JOIN "
		.TABLE_LANGUAGES. " langu ON (langu.languages_id = cat_desc.language_id)
		WHERE 
		prod_cat.products_id = '" . (int) $orders_products->fields['products_id'] . "'
		AND langu.code ='" . DEFAULT_LANGUAGE . "'";
 
            $category = "";
            $orders_category = $db->Execute ($category_query);
 
            if (!$orders_category->EOF) {
                $category = $orders_category->fields['categories_name'];
            }
 
            $this->products[$index]['category'] = $category;
 
            $subindex = 0;
            $attributes_query = "SELECT
		products_options, products_options_values, options_values_price, price_prefix
		FROM "
		.TABLE_ORDERS_PRODUCTS_ATTRIBUTES.
		" WHERE 
		orders_id = '" . (int) $order_id . "' 
		AND orders_products_id = '" . (int) $orders_products->fields['orders_products_id'] . "'";
 
            $attributes = $db->Execute ($attributes_query);
            if ($attributes->RecordCount ()) {
                while (!$attributes->EOF) {
                    $this->products[$index]['attributes'][$subindex] = array ('option' => $attributes->fields['products_options'],
                        'value' => $attributes->fields['products_options_values'],
                        'prefix' => $attributes->fields['price_prefix'],
                        'price' => $attributes->fields['options_values_price']);
                    $subindex++;
                    $attributes->MoveNext ();
                }
            }
            $index++;
            $orders_products->MoveNext ();
        }
    }
 
}
 
// load the installed payment module
if (defined ('MODULE_PAYMENT_INSTALLED') && zen_not_null (MODULE_PAYMENT_INSTALLED)) {
    $modules_payment = explode (';', MODULE_PAYMENT_INSTALLED);
    $include_modules_payment = array ();
 
    if ((zen_not_null ($module)) && (in_array ($module . '.' . substr ($PHP_SELF, (strrpos ($PHP_SELF, '.') + 1)), $modules_payment))) {
        $selected_module = $module;
 
        $include_modules_payment[] = array ('class' => $module, 'file' => $module . '.php');
    } else {
        reset ($modules_payment);
        while (list(, $value) = each ($modules_payment)) {
            $class = substr ($value, 0, strrpos ($value, '.'));
            $include_modules_payment[] = array ('class' => $class, 'file' => $value);
        }
    }
}
 
// load the installed shipping module
if (defined ('MODULE_SHIPPING_INSTALLED') && zen_not_null (MODULE_SHIPPING_INSTALLED)) {
    $modules_shipping = explode (';', MODULE_SHIPPING_INSTALLED);
 
    $include_modules_shipping = array ();
 
    if ((zen_not_null ($module)) && (in_array ($module . '.' . substr ($PHP_SELF, (strrpos ($PHP_SELF, '.') + 1)), $modules_shipping))) {
        $selected_module = $module;
        $include_modules_shipping[] = array ('class' => $module, 'file' => $module . '.php');
    } else {
        reset ($modules_shipping);
        while (list(, $value) = each ($modules_shipping)) {
            $class = substr ($value, 0, strrpos ($value, '.'));
            $include_modules_shipping[] = array ('class' => $class, 'file' => $value);
        }
    }
}
 
// search all languages for the payment method
$languages_query = "SELECT
    directory
    FROM " .TABLE_LANGUAGES;
$languages = $db->Execute ($languages_query);
 
while (!$languages->EOF) {
    for ($i = 0, $n = sizeof ($include_modules_payment); $i < $n; $i++) {
        $filename = DIR_FS_CATALOG . DIR_WS_LANGUAGES . $languages->fields['directory'] . '/modules/payment/' . $include_modules_payment[$i]['file'];
        if (file_exists ($filename)) {
            $paymentfile = fopen ($filename, 'r');
            while (!feof ($paymentfile)) {
                $zeile = fgets ($paymentfile, 1024);
                $pos1 = strpos ($zeile, "('MODULE_PAYMENT_");
                $pos2 = strpos ($zeile, "_TEXT_TITLE'");
                if (($pos1 > 0) && ($pos2 > 0)) {
                    $paymenttext = substr ($zeile, $pos2 + 13);
                    $paymenttext = substr ($paymenttext, strpos ($paymenttext, "'") + 1);
                    $paymenttext = substr ($paymenttext, 0, strrpos ($paymenttext, "'"));
                    $paymenttext = trim ($paymenttext);
                    if ($paymenttext) {
                        $paymentsynonym[$paymenttext] = $include_modules_payment[$i]['class'];
                    }
                }
            }
            fclose ($paymentfile);
        }
    }
    $languages->MoveNext ();
}
 
$languages->Move (0);
while (!$languages->EOF) {
    for ($i = 0, $n = sizeof ($include_modules_shipping); $i < $n; $i++) {
        $filename = DIR_FS_CATALOG . DIR_WS_LANGUAGES . $languages->fields['directory'] . '/modules/shipping/' . $include_modules_shipping[$i]['file'];
        if (file_exists ($filename)) {
            $shippingfile = fopen ($filename, 'r');
            while (!feof ($shippingfile)) {
                $zeile = fgets ($shippingfile, 1024);
                $pos1 = strpos ($zeile, "('MODULE_SHIPPING_");
                $pos2 = strpos ($zeile, "_TEXT_TITLE'");
                if (($pos1 > 0) && ($pos2 > 0)) {
                    $shippingtext = substr ($zeile, $pos2 + 13);
                    $shippingtext = substr ($shippingtext, strpos ($shippingtext, "'") + 1);
                    $shippingtext = substr ($shippingtext, 0, strrpos ($shippingtext, "'"));
                    $shippingtext = trim ($shippingtext);
                    if ($shippingtext)
                        $shippingssynonym[$shippingtext] = $include_modules_shipping[$i]['class'];
                }
            }
            fclose ($shippingfile);
        }
    }
    $languages->MoveNext ();
}
 
// parse POST parameters
$getshipped = (isset ($_POST['getshipped']) ? $_POST['getshipped'] : '');
$action = (isset ($_POST['action']) ? $_POST['action'] : '');
$orderstosync = (isset ($_POST['setstate']) ? $_POST['setstate'] : '{}');
$maxproducts = (isset ($_POST['maxproducts']) ? $_POST['maxproducts'] : '');
$lasttime = (isset ($_POST['lasttime']) ? $_POST['lasttime'] : '');
 
// $orderstosync = '{4=3*Alles OK}';
 
writeLog($orderstosync);
 
$orderstosync = substr ($orderstosync, 0, -1);
$orderstosync = substr ($orderstosync, 1);
$orderstosync = explode (",", $orderstosync);
 
 
$username = zen_db_prepare_input ($_POST['username']);
$password = zen_db_prepare_input ($_POST['password']);
 
function writeLog ($txt)
{
// set file to write
    $file = getcwd().'/tmp/gets.txt';
 
    if (is_array($txt))
	$txt = implode($txt);
 
    if (strlen($txt) == 0 ) return;
    file_put_contents($file, $txt ."\n", FILE_APPEND);
 
}
 
// generate header of response
echo ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
echo ("<webshopexport version=\"" . FAKTURAMA_CONNECTOR_VERSION . "\" >\n");
 
echo ("<phpversion>");
echo (phpversion ());
echo ("</phpversion>\n");
echo ("<webshop ");
 
echo ("shop=\"" . PROJECT_VERSION_NAME . " " . PROJECT_VERSION_MAJOR . "." . PROJECT_VERSION_MINOR . "\" ");
echo ("url=\"" . my_encrypt (HTTP_CATALOG_SERVER) . "\"");
echo ("></webshop>\n");
 
// does action start with "get" ?
if (strncmp ($action, "get", 3) == 0) {
    // does the action contains one of the following keys:
    $action_getproducts = strpos ($action, "products");
    $action_getorders = strpos ($action, "orders");
    $action_getcontacts = strpos ($action, "contacts");
}
 
// parse the GETSHIPPED parameter for the time interval
$getshipped = strtolower ($getshipped);
 
if (preg_match ('/\d+/', $getshipped, $matches)) {
    $getshipped_number = $matches[0];
}
 
if (preg_match ('/month|day|week|year|ever/', $getshipped, $matches)) {
    $getshipped_datetype = $matches[0];
}
 
if (($getshipped_number > 0) && ($getshipped_datetype))
    $getshipped_condition = " or ( DATE_SUB(CURDATE(),INTERVAL " . $getshipped_number . " " . $getshipped_datetype . " ) <= o.date_purchased) ";
 
if ($getshipped_datetype == 'ever')
    $getshipped_condition = " or TRUE";
 
if (!defined ('DEFAULT_LANGUAGE')) {
    $lng = $db->Execute ("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = '" . DEFAULT_LANGUAGE . "'");
    if ($lng) {
        $lng = $lng->fields['configuration_value'];
        define ('DEFAULT_LANGUAGE', $lng);
    } else {
        exit_with_error ('DEFAULT_LANGUAGE not defined');
    }
}
 
$language_query = 'SELECT
	code, directory
	FROM '
	.TABLE_LANGUAGES.
	' WHERE
	code = "' . DEFAULT_LANGUAGE . '"';
 
$languages = $db->Execute ($language_query);
if ($languages->RecordCount () != 1)
    exit_with_error ('Language ' . DEFAULT_LANGUAGE . ' not found');
 
$_SESSION['language'] = $languages->fields['directory'];
 
// include the language translations
require_once(DIR_WS_LANGUAGES . $languages->fields['directory'] . '.php');
require_once(DIR_WS_LANGUAGES . $languages->fields['directory'] . '/orders.php');
 
$admin_valid = 0;
 
// Get the admins from the database
// require('../includes/functions/password_funcs.php');
$admin_query = '
    SELECT admin_id,admin_name, admin_pass
    FROM ' .TABLE_ADMIN. '
    WHERE
    admin_name  = "' . $username . '"';
 
// Verify password
$admin = $db->Execute ($admin_query);
if ($admin->RecordCount () == 1)
    if (zen_validate_password ($password, $admin->fields['admin_pass']))
        $admin_valid = 1;
 
 
// No admin with valid password found
if ($admin_valid != 1)
    exit_with_error ('Invalid username or password');
 
// update the shop values
foreach ($orderstosync as $ordertosync) {
    list($orders_id_tosync, $orders_status_tosync) = explode ("=", trim ($ordertosync));
 
    if ($orders_status_tosync == 'pending')
        $orders_status_tosync = 1;
    if ($orders_status_tosync == 'processing')
        $orders_status_tosync = 2;
    if ($orders_status_tosync == 'shipped')
        $orders_status_tosync = 3;
    $customer_notified = 0;
    // Notify the customer
    $notify_comments = '';
    // Is there a comment ?
    if (strlen ($orders_status_tosync) > 1) {
        $notify_comments = substr ($orders_status_tosync, 1);
    }
    if (substr ($notify_comments, 0, 1) == "*") {
 
        // First character is the new status
        $orders_status_tosync = substr ($orders_status_tosync, 0, 1);
        // Remove the "*"
        $notify_comments = substr ($notify_comments, 1);
        // Replace the &comma;
        $notify_comments = str_replace ('&comma;', ",", $notify_comments);
        // Replace the &equal;
        $notify_comments = str_replace ('&equal;', "=", $notify_comments);
 
        // Convert it into the correct character encoding
        if (function_exists ('iconv'))
            $notify_comments = iconv ("UTF-8", FAKTURAMA_WEBSHOP_CHARSET . "//TRANSLIT", $notify_comments);
 
        $notify_comments_mail = $notify_comments;
        //exit_with_error($notify_comments_mail);
 
        $order = new order ($orders_id_tosync);
        $lang_query = "select languages_id from " .TABLE_LANGUAGES. " where directory = '" . $order->info['language'] . "'";
        $lang = $db->Execute ($lang_query);
        $lang = $lang->fields['languages_id'];
 
        if (!isset ($lang))
            $lang = 1;
        $orders_statuses = array ();
        $orders_status_array = array ();
        $orders_status_query = "select orders_status_id, orders_status_name from " .TABLE_ORDERS_STATUS. " where language_id = '" . $lang . "'";
        $orders_status = $db->Execute ($orders_status_query);
        while (!$orders_status->EOF) {
            $orders_statuses[] = array ('id' => $orders_status->fields['orders_status_id'], 'text' => $orders_status->fields['orders_status_name']);
            $orders_status_array[$orders_status->fields['orders_status_id']] = $orders_status->fields['orders_status_name'];
            $orders_status->MoveNext ();
        }
 
        $email_valid = 1;
        if (empty ($order->customer['email_address']))
            $email_valid = 0;
 
        if (!empty ($notify_comments_mail))
            $notify_comments_mail .= "\n\n";
 
        $email = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $orders_id_tosync . "\n" . EMAIL_TEXT_INVOICE_URL . ' ' . zen_catalog_href_link (FILENAME_CATALOG_ACCOUNT_HISTORY_INFO . ".php", 'order_id=' . $orders_id_tosync, 'SSL') . "\n" . EMAIL_TEXT_DATE_ORDERED . ' ' . zen_date_long ($order->info['date_purchased']) . "\n\n" . $notify_comments_mail . sprintf (EMAIL_TEXT_STATUS_UPDATED, $orders_status_array[$orders_status_tosync]);
 
        if ($email_valid) {
            require(DIR_FS_CATALOG . DIR_WS_CLASSES . 'class.phpmailer.php');
            require(DIR_FS_CATALOG . DIR_WS_CLASSES . 'class.notifier.php');
            $zco_notifier = new notifier();
            zen_mail ($order->customer['name'], $order->customer['email_address'], EMAIL_TEXT_SUBJECT, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
            $customer_notified = 1;
        } else {
            echo (" <error>" . 'No valid email' . "</error>\n");
        }
    }
 
    if (($orders_id_tosync > 0) && ($orders_status_tosync >=1) && ($orders_status_tosync <=3)) {
        $db->Execute ("UPDATE
	    " . TABLE_ORDERS . "
	    SET
	    orders_status = '" . $orders_status_tosync . "'
	    WHERE
	    orders_id = '" . (int) $orders_id_tosync . "'
	");
        $db->Execute ("INSERT INTO
	    " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments)
	    VALUES ('" . (int) $orders_id_tosync . "', '" . $orders_status_tosync . "',
	    now(), '" . $customer_notified . "', '" . $notify_comments . "')");
    }
}
 
// generate list of all products	
if ($action_getproducts) {
    $imagepath = DIR_WS_CATALOG . DIR_WS_IMAGES;
    $fs_imagepath = DIR_FS_CATALOG_IMAGES;
    echo (" <products imagepath=\"" . my_encrypt ($imagepath) . "\">\n");
 
    $products_short_description_query = '';
 
    // Limit the query to maxproducts
    $productslimit_query = "";
    if ($maxproducts > 0) {
        $productslimit_query = " LIMIT " . $maxproducts;
    }
 
    // Limit the query to maxproducts
    $lasttime_query = "";
    if ($lasttime > 0) {
        $lasttime_query = " AND ( prod.products_last_modified > '" . $lasttime . "') ";
    }
 
    $products_query = "SELECT
	prod_desc.products_name, prod_desc.products_description " . $products_short_description_query . ",
	prod.products_model, prod.products_image, products_quantity, prod.products_id, prod.products_price,	
	prod.products_price,
	cat_desc.categories_name,
	countries.countries_id,
	tax.tax_rate, tax.tax_description
	FROM "
	.TABLE_PRODUCTS_DESCRIPTION. " prod_desc
	LEFT JOIN "
	.TABLE_PRODUCTS. " prod ON (prod.products_id = prod_desc.products_id) 
	LEFT JOIN "
	.TABLE_LANGUAGES. " langu ON (langu.languages_id = prod_desc.language_id) 
	LEFT JOIN "
	.TABLE_PRODUCTS_TO_CATEGORIES. " prod_cat ON (prod_cat.products_id = prod.products_id)
	LEFT JOIN "
	.TABLE_CATEGORIES_DESCRIPTION. " cat_desc ON (prod_cat.categories_id = cat_desc.categories_id) AND  (cat_desc.language_id  = langu.languages_id )
	LEFT JOIN "
	.TABLE_COUNTRIES. " countries ON  (countries.countries_id = '" . STORE_COUNTRY . "')
	LEFT JOIN "
	.TABLE_ZONES_TO_GEO_ZONES. " z2geozones ON (countries.countries_id = z2geozones.zone_country_id)
	LEFT JOIN "
	.TABLE_TAX_RATES. " tax ON (prod.products_tax_class_id = tax.tax_class_id) AND (z2geozones.geo_zone_id = tax.tax_zone_id)
	WHERE
	(langu.code = '" . DEFAULT_LANGUAGE . "') AND (prod.products_status = '1')
	" . $lasttime_query . "
	" . $productslimit_query . "";
 
    $last_products_model_name = "";
    $products = $db->Execute ($products_query);
    while (!$products->EOF) {
        $products_model_name = $products->fields['products_model'] . $products->fields['products_name'];
        if ($last_products_model_name != $products_model_name) {
            $products->fields['products_short_description'] = $products->fields['products_description'];
 
            echo ("  <product ");
            echo ("gross=\"" . my_encrypt (number_format ($products->fields['products_price'] * (1 + $products->fields['tax_rate'] / 100), 2)) . "\" " );
            echo ("vatpercent=\"" . my_encrypt (number_format ($products->fields['tax_rate'], 2)) . "\" " );
            echo ("quantity=\"" . my_encrypt ($products->fields['products_quantity']) . "\" " );
            echo ("id=\"" . my_encrypt ($products->fields['products_id']) . "\" " );
            echo (">\n");
            echo ("   <model>" . my_encode ($products->fields['products_model']) . "</model>\n");
            echo ("   <ean></ean>\n");
            echo ("   <name>" . my_encode ($products->fields['products_name']) . "</name>\n");
            echo ("   <category>" . my_encode ($products->fields['categories_name']) . "</category>\n");
            echo ("   <qunit>" . my_encode ($products->fields['products_vpe_name']) . "</qunit>\n");
            echo ("   <vatname>" . my_encode ($products->fields['tax_description']) . "</vatname>\n");
            echo ("   <short_description>" . my_clean_nl (my_encode ($products->fields['products_short_description'])) . "</short_description>\n");
 
            // Use the image only, if it exists	
            if (file_exists ($fs_imagepath . $products->fields['products_image']))
                echo ("   <image>" . str_replace (" ", "%20", my_encrypt ($products->fields['products_image'])) . "</image>\n");
 
            echo ("  </product>\n\n");
        }
 
        $last_products_model_name = $products_model_name;
        $products->MoveNext ();
    }
    echo (" </products>\n\n\n\n");
}
 
// generate list of all orders	
if ($action_getorders) {
    $check_orders_query = "SELECT
	    o.orders_id, o.orders_status, ot.text AS order_total
	    FROM "
	    .TABLE_ORDERS. " o
	    LEFT JOIN "
	    .TABLE_ORDERS_TOTAL. " ot ON (o.orders_id = ot.orders_id)
	    WHERE
	    ot.class = 'ot_total' 
	    AND (o.orders_status > '0' " . $getshipped_condition . "  )
	    ORDER BY 
	    o.orders_id DESC";
 
    echo (" <orders>\n");
 
    $check_orders = $db->Execute ($check_orders_query);
    while (!$check_orders->EOF) {
 
        $oID = $check_orders->fields['orders_id'];
        $order = new order ($oID);
        $payment_class = $paymentsynonym[$order->info['payment_method']];
 
        $payment_text = $payment_class;
 
        if ($payment_class == 'cod')
            $payment_text = 'cod';
        if ($payment_class == 'moneyorder')
            $payment_text = 'prepayment';
        if ($payment_class == 'cc')
            $payment_text = 'creditcard';
        if ($payment_class == 'authorizenet_cc_aim')
            $payment_text = 'creditcard';
        if ($payment_class == 'authorizenet_cc_sim')
            $payment_text = 'creditcard';
        if ($payment_class == 'chronopay')
            $payment_text = 'chronopay.com';
        if ($payment_class == 'ipayment_cc')
            $payment_text = 'ipayment.de';
        if ($payment_class == 'nochex')
            $payment_text = 'nochex.com';
        if ($payment_class == 'paypal_direct')
            $payment_text = 'paypal.com';
        if ($payment_class == 'paypal_express')
            $payment_text = 'paypal.com';
        if ($payment_class == 'paypal_standard')
            $payment_text = 'paypal.com';
        if ($payment_class == 'paypal_uk_direct')
            $payment_text = 'paypal.com';
        if ($payment_class == 'paypal_uk_express')
            $payment_text = 'paypal.com';
        if ($payment_class == 'pm2checkout')
            $payment_text = '2checkout.com';
        if ($payment_class == 'psigate')
            $payment_text = 'psigate.com';
        if ($payment_class == 'secpay')
            $payment_text = 'secpay.com';
        if ($payment_class == 'sofortueberweisung_direct')
            $payment_text = 'payment-networt.com';
        if ($payment_class == 'worldpay_junior')
            $payment_text = 'bsworldpay.com';
 
        $orders_history_query = "SELECT
		orders_status_id, date_added, comments
		FROM "
		.TABLE_ORDERS_STATUS_HISTORY.
		" WHERE
		orders_id = '" . zen_db_input ($oID) . "'
		ORDER BY
		date_added";
 
        // if entry is empty, use entry from customers data or from delivery data
        if (empty ($order->billing['telephone']) && !empty ($order->customer['telephone']))
            $order->billing['telephone'] = $order->customer['telephone'];
        if (empty ($order->billing['telephone']) && !empty ($order->delivery['telephone']))
            $order->billing['telephone'] = $order->delivery['telephone'];
 
        // if entry is empty, use entry from customers data or from delivery data
        if (empty ($order->billing['email_address']) && !empty ($order->customer['email_address']))
            $order->billing['email_address'] = $order->customer['email_address'];
        if (empty ($order->billing['email_address']) && !empty ($order->delivery['email_address']))
            $order->billing['email_address'] = $order->delivery['email_address'];
 
        echo ("  <order id=\"" . my_encrypt ($oID) . "\" date=\"" . my_encrypt ($order->info['date_purchased']) . "\" ");
 
        if ($order->info['orders_status'] == 1)
            $order_status_text = "pending";
        if ($order->info['orders_status'] == 2)
            $order_status_text = "processing";
        if ($order->info['orders_status'] == 3)
            $order_status_text = "shipped";
 
        $total = 0.0;
        if (preg_match ("/[0-9]+\.[0-9]+/", str_replace (",", ".", strip_tags ($check_orders->fields['order_total'])), $matches))
            $total = $matches[0];
 
        echo ("currency=\"" . $order->info['currency'] . "\" ");
        echo ("currency_value=\"" . $order->info['currency_value'] . "\" ");
        echo ("status=\"" . my_encode ($order_status_text) . "\" ");
        echo (">\n");
 
        //echo ('    <cc_type>'.$order->info['cc_type'].'</cc_type>'."\n");
        //echo ('    <cc_owner>'.$order->info['cc_owner'].'</cc_owner>'."\n");
        //echo ('    <cc_number>'.$order->info['cc_number'].'</cc_number>'."\n");
        //echo ('    <cc_expires>'.$order->info['cc_expires'].'</cc_expires>'."\n");
        //echo ('    <last_modified>'.$order->info['last_modified'].'</last_modified>'."\n");
 
        echo ("   <contact ");
        echo ("id=\"" . my_encode ($order->customer['id']) . "\">\n");
        echo ("    <gender>" . my_encode ($order->billing['gender']) . "</gender>\n");
        echo ("    <firstname>" . my_encode ($order->billing['firstname']) . "</firstname>\n");
        echo ("    <lastname>" . my_encode ($order->billing['lastname']) . "</lastname>\n");
        echo ("    <company>" . my_encode ($order->billing['company']) . "</company>\n");
        echo ("    <street>" . my_encode ($order->billing['street_address']) . "</street>\n");
        echo ("    <zip>" . my_encode ($order->billing['postcode']) . "</zip>\n");
        echo ("    <city>" . my_encode ($order->billing['city']) . "</city>\n");
        echo ("    <country>" . my_encode ($order->billing['country']) . "</country>\n");
        echo ("    <delivery_gender>" . my_encode ($order->delivery['gender']) . "</delivery_gender>\n");
        echo ("    <delivery_firstname>" . my_encode ($order->delivery['firstname']) . "</delivery_firstname>\n");
        echo ("    <delivery_lastname>" . my_encode ($order->delivery['lastname']) . "</delivery_lastname>\n");
        echo ("    <delivery_company>" . my_encode ($order->delivery['company']) . "</delivery_company>\n");
        echo ("    <delivery_street>" . my_encode ($order->delivery['street_address']) . "</delivery_street>\n");
        echo ("    <delivery_zip>" . my_encode ($order->delivery['postcode']) . "</delivery_zip>\n");
        echo ("    <delivery_city>" . my_encode ($order->delivery['city']) . "</delivery_city>\n");
        echo ("    <delivery_country>" . my_encode ($order->delivery['country']) . "</delivery_country>\n");
        echo ("    <phone>" . my_encode ($order->billing['telephone']) . "</phone>\n");
        echo ("    <email>" . my_encode ($order->billing['email_address']) . "</email>\n");
        echo ("   </contact>\n");
 
        $orders_history = $db->Execute ($orders_history_query);
        while (!$orders_history->EOF) {
            if (strlen (trim ($orders_history->fields['comments']))) {
                echo ("    <comment date=\"" . $orders_history->fields['date_added'] . "\">");
                echo ( my_encode (nl2br (zen_db_output ($orders_history->fields['comments']))));
                echo ("</comment>\n");
            }
            $orders_history->MoveNext ();
        }
 
        foreach ($order->products as $product) {
            $orders_tax_query = "SELECT
		    tax_rate, tax_description
		    FROM "
		    .TABLE_TAX_RATES.
		    " WHERE
		    tax_class_id = '" . $tax_class . "'";
 
            $taxs = $db->Execute ($orders_tax_query);
            if (!$taxs->EOF) {
                $shipping_tax = $taxs->fields['tax_rate'];
                $shipping_tax_name = $taxs->fields['tax_description'];
            }
 
            echo ("   <item ");
            echo ("productid=\"" . my_encode ($product['products_id']) . "\" ");
            echo ("quantity=\"" . my_encrypt ($product['qty']) . "\" ");
 
            echo ("gross=\"" . my_encrypt (number_format ($product['price'] * (1 + $product['tax'] / 100), 2)) . "\" ");
 
            echo ("vatpercent=\"" . my_encrypt (number_format ($product['tax'], 2)) . "\">\n");
            echo ("    <model>");
            if (!empty ($product['model']))
                echo (my_encode ($product['model']));
            else
                echo (my_encode ($product['name']));
            echo ("</model>\n");
            echo ("    <ean></ean>\n");
            echo ("    <name>" . my_encode ($product['name'])) . "</name>\n";
            echo ("    <category>" . my_encode ($product['category']) . "</category>\n");
            echo ("    <qunit>" . my_encode ($product['products_vpe_name']) . "</qunit>\n");
            echo ("    <vatname>" . my_encode ($product['tax_description']) . "</vatname>\n");
 
            // Export the product attributes
            if ($product['attributes']) {
                $subindex = 0;
                foreach ($product['attributes'] as $attribute) {
                    echo ("    <attribute ");
                    echo ("prefix=\"" . my_encode ($product['attributes'][$subindex]['prefix']) . "\" ");
                    echo ("price=\"" . my_encode ($product['attributes'][$subindex]['price']) . "\"");
                    echo (">\n");
                    echo ("     <option>" . my_encode ($product['attributes'][$subindex]['option']) . "</option>\n");
                    echo ("     <value>" . my_encode ($product['attributes'][$subindex]['value']) . "</value>\n");
                    echo ("    </attribute>\n");
 
                    $subindex++;
                }
            }
 
            echo ("   </item>\n");
        }
        // Get the shipping
        $totals_query = "SELECT
		title, text, class
		FROM "
		.TABLE_ORDERS_TOTAL.
		" WHERE
		orders_id = '" . (int) $oID . "'
		AND class = 'ot_shipping'
		ORDER BY
		sort_order";
 
        $shipping_title = "";
        $shipping_text = "";
        $totals = $db->Execute ($totals_query);
        if (!$totals->EOF) {
            $shipping_title = $totals->fields['title'];
            $shipping_text = $totals->fields['text'];
        }
 
        // delete last character, if it is a ":"
        if (substr ($shipping_title, -1, 1) == ':')
            $shipping_title = substr ($shipping_title, 0, -1);
 
        if (strrpos ($shipping_title, '('))
            $shipping_title = trim (substr ($shipping_title, 0, strrpos ($shipping_title, '(')));
 
        $shipping_tax = 0.0;
        $shipping_tax_name = "";
        $shipping_class = $shippingssynonym[$shipping_title];
        if (!empty ($shipping_class)) {
            $configkey = 'MODULE_SHIPPING_' . strtoupper ($shipping_class) . '_TAX_CLASS';
            $tax_class = $configuration_array[$configkey];
            $orders_tax_query = "SELECT
			tax_rate, tax_description
			FROM "
			.TABLE_TAX_RATES.
			" WHERE
			tax_class_id = '" . $tax_class . "'";
 
            $taxs = $db->Execute ($orders_tax_query);
            if (!$taxs->EOF) {
                $shipping_tax = $taxs->fields['tax_rate'];
                $shipping_tax_name = $taxs->fields['tax_description'];
            }
        }
 
        $shipping_value = 0.0;
        if (preg_match ("/[0-9]+\.[0-9]+/", str_replace (",", ".", $shipping_text), $matches))
            $shipping_value = $matches[0];
 
        // Get the COD fee
        $totals_query = "SELECT
		title, text, class
		FROM "
		.TABLE_ORDERS_TOTAL.
		" WHERE
		orders_id = '" . (int) $oID . "'
		AND class = 'ot_cod_fee'
		ORDER BY
		sort_order";
 
        $cod_fee_text = "";
        $totals = $db->Execute ($totals_query);
        if (!$totals->EOF) {
            $cod_fee_text = $totals->fields['text'];
        }
        $cod_fee_value = 0.0;
        if (preg_match ("/[0-9]+\.[0-9]+/", str_replace (",", ".", $cod_fee_text), $matches))
            $cod_fee_value = $matches[0];
 
        // Workaround: add the COD fee to the shipping value
        $shipping_value += $cod_fee_value;
 
        echo ("   <shipping ");
        echo ("gross=\"" . my_encrypt (number_format ($shipping_value, 2)) . "\" ");
        //echo ("net=\"" .number_format( $shipping_value / ( 1 + $shipping_tax/100), 2)."\" ");
        echo ("vatpercent=\"" . my_encrypt (number_format ($shipping_tax, 2)) . "\">\n");
        echo ("    <name>" . my_encode ($shipping_title) . "</name>\n");
        echo ("    <vatname>" . my_encode ($shipping_tax_name) . "</vatname>\n");
        echo ("   </shipping>\n");
 
        echo ("   <payment ");
        echo ("type=\"" . my_encode ($payment_text) . "\" ");
        echo ("total=\"" . my_encrypt (number_format ($total, 2)) . "\">\n");
        echo ("    <name>" . my_encode ($order->info['payment_method']) . "</name>\n");
        echo ("   </payment>\n");
 
        echo ("  </order>\n\n");
 
        $check_orders->MoveNext ();
    }
    echo (" </orders>\n");
}
 
if ($action_getcontacts) {
    writeLog ("Request for Contacts found. But not implemented.");
}
 
echo ("</webshopexport>\n");
?>
fakturama/zencart-connector.txt · Zuletzt geändert: 2017/01/10 15:56 von Admin