#!/usr/bin/php
<?php
/**
 * This Script gets orders from OXID eShop and writes orderfiles. Each order one file called <ordernr>.csv.
 *
 * Lineformat is exactly as described in ERP/CSV documentation, just one difference: Only some fields (which needed)
 * are enclosed by double quotes "
 *
 * Example: Getting SID
 * http://testshops/EE/modules/erp/oxerpcsvexport.php?fnc=OXERPLogin&user=admin&pw=admin&version=2.2.0&shopid=1&langid=0
 *
 * Example: Getting ORDERS
 * http://testshops/EE/modules/erp/oxerpcsvexport.php?fnc=OXERPGetOrders&sid=2b53f75583dea05faf970b83726f6047&sSortFieldName=OXORDERNR&iStart=0&iCount=50
 *
 * Example: Getting ORDERARTICLE
 * http://testshops/EE/modules/erp/oxerpcsvexport.php?fnc=OXERPGetOrderArticle&sid=2b53f75583dea05faf970b83726f6047&id=c4bbb6f12015885300ff047b3a80ea9c&iStart=0&iCount=500
 *
 * @link http://www.oxid-esales.com
 * @package  ERP/CSV
 * @copyright © OXID eSales AG 2003-2009
 * @version 1.0
 *
 */

// URL to Shop
define ('ERPSCVURL', 'http://testshops/EE/modules/erp/oxerpcsvexport.php');

// Import- and Export path
define ('EXPORTPATH', '/htdocs/testshops/EE/export');
define ('IMPORTPATH', '/htdocs/testshops/EE/import');

// Admin user data
define ('ADMINUSER', 'admin');
define ('ADMINPASS', 'admin');

// Maximum orders per Script call and maximum articles per order
define ('MAX_ORDERS_PER_CALL', 1);
define ('MAX_ARTICLES_PER_ORDER', 50000);

// Subshop ID and Language
define ('SHOPID', '1');
define ('LANGID', '0');

// Path to cache file for highest order nr
define ('HIGHESTORDDERNRFILENAME', EXPORTPATH.'/highestordernr.txt');

/**
 * Logs in and gets Session ID (SID)
 *
 * @return string session id
 */
function getSID ()
{

    $sUrl = ERPSCVURL.'?fnc=OXERPLogin&user='.ADMINUSER.'&pw='.ADMINPASS.'&version=2.2.0&shopid='.SHOPID.'&langid='.LANGID;

    if ($fp = fopen ($sUrl, 'r')) {
        $sid = fgets($fp, 2048);
        fclose ($fp);
    }

    return $sid;
}

/**
 * Gets articles (= products) for a specfic order and returns it. Version line included.
 *
 * @param string $sSid       Session ID
 * @param string $sOrderOXID Order ID
 *
 * @return array $aOrders Array of product information
 */
function getOrderArticles ($sSid, $sOrderOXID)
{

    $sUrl = ERPSCVURL.'?fnc=OXERPGetOrderArticle&sid='.$sSid.'&id='.$sOrderOXID.'&iStart=0&iCount='.MAX_ARTICLES_PER_ORDER;

    $aOrders = array();
    if ($fp = fopen ($sUrl, 'r')) {
        while ($aOrders[] = fgetcsv ($fp, 4096, ';', '"') ) {
        }
        fclose ($fp);
    }

    return $aOrders;

}

/**
 * Writes (highest) fetched ordernr
 *
 * @param integer $iOrdernr Order number
 *
 * @return nothing
 */
function writeHighestOrderNr ($iOrdernr)
{

    if ($fp = fopen (HIGHESTORDDERNRFILENAME, 'w')) {
        fputs($fp, $iOrdernr);
    }
    fclose($fp);
}

/**
 * Get highest order number
 *
 * @return integer $iOrderNr ordernumber
 */
function getHighestOrderNr ()
{

    $iOrderNr = 0;

    if (file_exists(HIGHESTORDDERNRFILENAME)) {
        if ($fp = fopen (HIGHESTORDDERNRFILENAME, 'r')) {
            $iOrderNr = fgets ($fp, 16);
            fclose($fp);
        }
    }

    return $iOrderNr;
}


/**
 * Writes all collected data which belongs to one order into one file <ordernr>.csv
 *
 * @param array $aOrder         Array of order information (without version line)
 * @param array $aOrderarticles Array of arrays of products (containing version line)
 *
 * @return integer $iOrdernr Order number of written order. NULL if no success in writing order
 */
function writeOrder ($aOrder, $aOrderarticles)
{

    $iOrdernr = $aOrder[5];
    $filename = EXPORTPATH.'/'.$iOrdernr.'.csv';

    if ($fp = fopen ($filename, 'w')) {

        // Version line:
        fputcsv ($fp, $aOrderarticles[0], ';');
        fputcsv ($fp, $aOrder, ';');

        foreach ($aOrderarticles as $name => $value) {
            if ($value[0] == "R") {
                fputcsv($fp, $value, ';');
            }
        }
        fclose($fp);
    } else {
        $iOrdernr = null;
    }

    return $iOrdernr;

}

/**
 * Writes all orders, beginning from last not written order into files.
 *
 * @param string $sSid Session ID
 *
 * @return nothing
 */
function writeOrders ($sSid)
{

    $iStartordernr = getHighestOrderNr ();

    $sUrl = ERPSCVURL.'?fnc=OXERPGetOrders&sid='.$sSid.'&sSortFieldName=OXORDERNR&iStart='.$iStartordernr.'&iCount='.MAX_ORDERS_PER_CALL;

    if ($fp = fopen ($sUrl, 'r')) {
        while ($aOrder = fgetcsv ($fp, 4096, ';', '"') ) {
            if ($aOrder[0] != "V") {
                $sOrderOXID = $aOrder[1];

                $aOrderArticles = getOrderArticles ($sSid, $sOrderOXID);

                $lastordernr = writeOrder ($aOrder, $aOrderArticles);
            }
        }
        fclose ($fp);

        writeHighestOrderNr ($lastordernr);
    }
}


WriteOrders(GetSID());


