* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 1.4 $
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
// Security
if (!defined('_PS_VERSION_'))
exit;
// Loading eBay Class Request
if (file_exists(dirname(__FILE__).'/eBayRequest.php'))
require_once(dirname(__FILE__).'/eBayRequest.php');
// Checking compatibility with older PrestaShop and fixing it
if (!defined('_MYSQL_ENGINE_'))
define('_MYSQL_ENGINE_', 'MyISAM');
class Ebay extends Module
{
private $_html = '';
private $_postErrors = array();
private $_shippingMethod = array();
private $_webserviceTestResult = '';
private $_webserviceError = '';
private $_fieldsList = array();
private $_moduleName = 'ebay';
private $id_lang;
/******************************************************************/
/** Construct Method **********************************************/
/******************************************************************/
public function __construct()
{
$this->name = 'ebay';
$this->tab = 'market_place';
$this->version = '1.3.5';
$this->author = 'PrestaShop';
parent::__construct ();
$this->displayName = $this->l('eBay');
$this->description = $this->l('Open your shop on the eBay market place !');
$this->id_lang = Language::getIdByIso('fr');
// Check the country and ask the bypass if not 'fr'
if (strtolower($this->context->country->iso_code) != 'fr' && !isset($this->context->cookie->ebay_country_default_fr))
{
$this->warning = $this->l('eBay module currently works only for eBay.fr');
return false;
}
// Checking Extension
if (!extension_loaded('curl') || !ini_get('allow_url_fopen'))
{
if (!extension_loaded('curl') && !ini_get('allow_url_fopen'))
$this->warning = $this->l('You must enable cURL extension and allow_url_fopen option on your server if you want to use this module.');
else if (!extension_loaded('curl'))
$this->warning = $this->l('You must enable cURL extension on your server if you want to use this module.');
else if (!ini_get('allow_url_fopen'))
$this->warning = $this->l('You must enable allow_url_fopen option on your server if you want to use this module.');
return false;
}
// Checking compatibility with older PrestaShop and fixing it
if (!Configuration::get('PS_SHOP_DOMAIN'))
Configuration::updateValue('PS_SHOP_DOMAIN', $_SERVER['HTTP_HOST']);
// Generate eBay Security Token if not exists
if (!Configuration::get('EBAY_SECURITY_TOKEN'))
Configuration::updateValue('EBAY_SECURITY_TOKEN', Tools::passwdGen(30));
// For 1.4.3 and less compatibility
$updateConfig = array('PS_OS_CHEQUE' => 1, 'PS_OS_PAYMENT' => 2, 'PS_OS_PREPARATION' => 3, 'PS_OS_SHIPPING' => 4, 'PS_OS_DELIVERED' => 5, 'PS_OS_CANCELED' => 6,
'PS_OS_REFUND' => 7, 'PS_OS_ERROR' => 8, 'PS_OS_OUTOFSTOCK' => 9, 'PS_OS_BANKWIRE' => 10, 'PS_OS_PAYPAL' => 11, 'PS_OS_WS_PAYMENT' => 12);
foreach ($updateConfig as $u => $v)
if (!Configuration::get($u) || (int)Configuration::get($u) < 1)
{
if (defined('_'.$u.'_') && (int)constant('_'.$u.'_') > 0)
Configuration::updateValue($u, constant('_'.$u.'_'));
else
Configuration::updateValue($u, $v);
}
// Check if installed
if (self::isInstalled($this->name))
{
// Upgrade eBay module
if (Configuration::get('EBAY_VERSION') != $this->version)
$this->upgrade();
// Generate warnings
if (!Configuration::get('EBAY_API_TOKEN'))
$this->warning = $this->l('You must register your module on eBay.');
// Loading Shipping Method
$this->loadShippingMethod();
// Warning uninstall
$this->confirmUninstall = $this->l('Are you sure you want uninstall this module ? All your configuration will be lost.');
}
}
public function loadShippingMethod()
{
// Shipping methods
$this->_shippingMethod = array(
7104 => array('description' => 'Colissimo', 'shippingService' => 'FR_ColiposteColissimo', 'shippingServiceID' => '7104'),
7112 => array('description' => 'Ecopli', 'shippingService' => 'FR_Ecopli', 'shippingServiceID' => '7112'),
57104 => array('description' => 'La Poste - Courrier International Prioritaire', 'shippingService' => 'FR_LaPosteInternationalPriorityCourier', 'shippingServiceID' => '57104'),
7101 => array('description' => 'Lettre', 'shippingService' => 'FR_PostOfficeLetter', 'shippingServiceID' => '7101'),
57105 => array('description' => 'La Poste - Courrier International Economique', 'shippingService' => 'FR_LaPosteInternationalEconomyCourier', 'shippingServiceID' => '57105'),
57106 => array('description' => 'La Poste - Colissimo International', 'shippingService' => 'FR_LaPosteColissimoInternational', 'shippingServiceID' => '57106'),
7102 => array('description' => 'Lettre avec suivi', 'shippingService' => 'FR_PostOfficeLetterFollowed', 'shippingServiceID' => '7102'),
57107 => array('description' => 'La Poste - Colis Economique International', 'shippingService' => 'FR_LaPosteColisEconomiqueInternational', 'shippingServiceID' => '57107'),
7103 => array('description' => 'Lettre recommandée', 'shippingService' => 'FR_PostOfficeLetterRecommended', 'shippingServiceID' => '7103'),
7121 => array('description' => 'Lettre Max', 'shippingService' => 'FR_LaPosteLetterMax', 'shippingServiceID' => '7121'),
7113 => array('description' => 'Coliéco', 'shippingService' => 'FR_Colieco', 'shippingServiceID' => '7113'),
57108 => array('description' => 'La Poste - Colissimo Emballage International', 'shippingService' => 'FR_LaPosteColissimoEmballageInternational', 'shippingServiceID' => '57108'),
57114 => array('description' => 'Chronopost Express International', 'shippingService' => 'FR_ChronopostExpressInternational', 'shippingServiceID' => '57114'),
7106 => array('description' => 'Colissimo Recommandé', 'shippingService' => 'FR_ColiposteColissimoRecommended', 'shippingServiceID' => '7106'),
57109 => array('description' => 'Chronopost Classic International', 'shippingService' => 'FR_ChronopostClassicInternational', 'shippingServiceID' => '57109'),
57110 => array('description' => 'Chronopost Premium International', 'shippingService' => 'FR_ChronopostPremiumInternational', 'shippingServiceID' => '57110'),
7117 => array('description' => 'Chronopost - Chrono Relais', 'shippingService' => 'FR_ChronopostChronoRelais', 'shippingServiceID' => '7117'),
57111 => array('description' => 'UPS Standard', 'shippingService' => 'FR_UPSStandardInternational', 'shippingServiceID' => '57111'),
7111 => array('description' => 'Autre mode d\'envoi de courrier', 'shippingService' => 'FR_Autre', 'shippingServiceID' => '7111'),
57112 => array('description' => 'UPS Express', 'shippingService' => 'FR_UPSExpressInternational', 'shippingServiceID' => '57112'),
7114 => array('description' => 'Autre mode d\'envoi de colis', 'shippingService' => 'FR_AuteModeDenvoiDeColis', 'shippingServiceID' => '7114'),
57113 => array('description' => 'DHL', 'shippingService' => 'FR_DHLInternational', 'shippingServiceID' => '57113'),
57101 => array('description' => 'Frais de livraison internationale fixes', 'shippingService' => 'FR_StandardInternational', 'shippingServiceID' => '57101'),
7116 => array('description' => 'Chronopost', 'shippingService' => 'FR_Chronopost', 'shippingServiceID' => '7116'),
57102 => array('description' => 'Frais fixes pour livraison internationale express', 'shippingService' => 'FR_ExpeditedInternational', 'shippingServiceID' => '57102'),
57103 => array('description' => 'Autres livraisons internationales (voir description)', 'shippingService' => 'FR_OtherInternational', 'shippingServiceID' => '57103'),
7118 => array('description' => 'Chrono 10', 'shippingService' => 'FR_Chrono10', 'shippingServiceID' => '7118'),
7119 => array('description' => 'Chrono 13', 'shippingService' => 'FR_Chrono13', 'shippingServiceID' => '7119'),
7120 => array('description' => 'Chrono 18', 'shippingService' => 'FR_Chrono18', 'shippingServiceID' => '7120'),
7105 => array('description' => 'Coliposte - Colissimo Direct', 'shippingService' => 'FR_ColiposteColissimoDirect', 'shippingServiceID' => '7105'),
7107 => array('description' => 'Chronoposte - Chrono Classic International', 'shippingService' => 'FR_ChronoposteInternationalClassic', 'shippingServiceID' => '7107'),
7108 => array('description' => 'DHL - Express Europack', 'shippingService' => 'FR_DHLExpressEuropack', 'shippingServiceID' => '7108'),
7109 => array('description' => 'UPS - Standard', 'shippingService' => 'FR_UPSStandard', 'shippingServiceID' => '7109'),
);
}
/******************************************************************/
/** Install / Uninstall Methods ***********************************/
/******************************************************************/
public function install()
{
// Install SQL
include(dirname(__FILE__).'/sql-install.php');
foreach ($sql as $s)
if (!Db::getInstance()->execute($s))
return false;
// Install Module
if (!parent::install() ||
!$this->registerHook('addproduct') ||
!$this->registerHook('updateproduct') ||
!$this->registerHook('updateProductAttribute') ||
!$this->registerHook('deleteproduct') ||
!$this->registerHook('newOrder') ||
!$this->registerHook('backOfficeTop') ||
!$this->registerHook('backOfficeFooter') ||
!$this->registerHook('header') ||
!$this->registerHook('updateOrderStatus'))
return false;
// Generate Product Template
$content = file_get_contents(dirname(__FILE__).'/template/ebay.tpl');
$content = str_replace('{SHOP_NAME}', Configuration::get('PS_SHOP_NAME'), $content);
$content = str_replace('{SHOP_URL}', 'http://'.Configuration::get('PS_SHOP_DOMAIN').'/'.__PS_BASE_URI__.'/', $content);
$content = str_replace('{MODULE_URL}', 'http://'.Configuration::get('PS_SHOP_DOMAIN').'/'.__PS_BASE_URI__.'/modules/ebay/', $content);
Configuration::updateValue('EBAY_PRODUCT_TEMPLATE', '');
Configuration::updateValue('EBAY_PRODUCT_TEMPLATE', $content, true);
// Init
Configuration::updateValue('EBAY_VERSION', $this->version);
return true;
}
public function uninstall()
{
// Uninstall Config
foreach ($this->_fieldsList as $keyConfiguration => $name)
if (!Configuration::deleteByName($keyConfiguration))
return false;
// Uninstall SQL
include(dirname(__FILE__).'/sql-uninstall.php');
foreach ($sql as $s)
if (!Db::getInstance()->execute($s))
return false;
Configuration::deleteByName('EBAY_API_SESSION');
Configuration::deleteByName('EBAY_API_USERNAME');
Configuration::deleteByName('EBAY_API_TOKEN');
Configuration::deleteByName('EBAY_IDENTIFIER');
Configuration::deleteByName('EBAY_SHOP');
Configuration::deleteByName('EBAY_PAYPAL_EMAIL');
Configuration::deleteByName('EBAY_SHIPPING_CARRIER_ID');
Configuration::deleteByName('EBAY_SHIPPING_COST');
Configuration::deleteByName('EBAY_SHIPPING_COST_CURRENCY');
Configuration::deleteByName('EBAY_SHOP_POSTALCODE');
Configuration::deleteByName('EBAY_CATEGORY_LOADED');
Configuration::deleteByName('EBAY_CATEGORY_LOADED_DATE');
Configuration::deleteByName('EBAY_PRODUCT_TEMPLATE');
Configuration::deleteByName('EBAY_SYNC_MODE');
Configuration::deleteByName('EBAY_ORDER_LAST_UPDATE');
Configuration::deleteByName('EBAY_VERSION');
Configuration::deleteByName('EBAY_SECURITY_TOKEN');
// Uninstall Module
if (!parent::uninstall() ||
!$this->unregisterHook('addproduct') ||
!$this->unregisterHook('updateproduct') ||
!$this->unregisterHook('updateProductAttribute') ||
!$this->unregisterHook('deleteproduct') ||
!$this->unregisterHook('newOrder') ||
!$this->unregisterHook('backOfficeTop') ||
!$this->unregisterHook('backOfficeFooter') ||
!$this->unregisterHook('header') ||
!$this->unregisterHook('updateOrderStatus'))
return false;
// Clean Cookie
$this->context->cookie->eBaySession = '';
$this->context->cookie->eBayUsername = '';
return true;
}
public function upgrade()
{
$version = Configuration::get('EBAY_VERSION');
if ($version == '1.1' || empty($version))
{
// Upgrade SQL
include(dirname(__FILE__).'/sql-upgrade-1-2.php');
foreach ($sql as $s)
if (!Db::getInstance()->execute($s))
return false;
Configuration::updateValue('EBAY_VERSION', $this->version);
}
}
/******************************************************************/
/** Hook Methods **************************************************/
/******************************************************************/
public function hookNewOrder($params)
{
if ((int)$params['cart']->id < 1)
return false;
$sql = '`id_product` IN (SELECT `id_product` FROM `'._DB_PREFIX_.'cart_product` WHERE `id_cart` = '.(int)$params['cart']->id.')';
if (Configuration::get('EBAY_SYNC_MODE') == 'A')
{
// Retrieve product list for eBay (which have matched categories) AND Send each product on eBay
$productsList = Db::getInstance()->executeS('SELECT `id_product` FROM `'._DB_PREFIX_.'product` WHERE '.$sql.' AND `active` = 1 AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0)');
foreach ($productList as $k => $v)
$productList[$k]['noPriceUpdate'] = 1;
if ($productsList)
$this->_syncProducts($productsList);
}
else if (Configuration::get('EBAY_SYNC_MODE') == 'B')
{
// Select the sync Categories and Retrieve product list for eBay (which have matched and sync categories) AND Send each product on eBay
$productsList = Db::getInstance()->executeS('SELECT `id_product` FROM `'._DB_PREFIX_.'product` WHERE '.$sql.' AND `active` = 1 AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0 AND `sync` = 1)');
foreach ($productList as $k => $v)
$productList[$k]['noPriceUpdate'] = 1;
if ($productsList)
$this->_syncProducts($productsList);
}
}
public function hookaddproduct($params)
{
if (!isset($params['product']->id))
return false;
$id_product = $params['product']->id;
if ((int)$id_product < 1)
return false;
if (Configuration::get('EBAY_SYNC_MODE') == 'A')
{
// Retrieve product list for eBay (which have matched categories) AND Send each product on eBay
$productsList = Db::getInstance()->executeS('SELECT `id_product` FROM `'._DB_PREFIX_.'product` WHERE `id_product` = '.(int)$id_product.' AND `active` = 1 AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0)');
if ($productsList)
$this->_syncProducts($productsList);
}
else if (Configuration::get('EBAY_SYNC_MODE') == 'B')
{
// Select the sync Categories and Retrieve product list for eBay (which have matched and sync categories) AND Send each product on eBay
$productsList = Db::getInstance()->executeS('SELECT `id_product` FROM `'._DB_PREFIX_.'product` WHERE `id_product` = '.(int)$id_product.' AND `active` = 1 AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0 AND `sync` = 1)');
if ($productsList)
$this->_syncProducts($productsList);
}
}
public function hookbackOfficeTop($params)
{
// Check if the module is configured
if (!Configuration::get('EBAY_PAYPAL_EMAIL'))
return false;
// Fix hook update product attribute
$this->hookupdateProductAttributeEbay();
// If no update yet
if (!Configuration::get('EBAY_ORDER_LAST_UPDATE'))
Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d').'T'.date('H:i:s').'.000Z');
// init Var
$dateNew = date('Y-m-d').'T'.date('H:i:s').'.000Z';
if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')).'T'.date('H:i:s', strtotime('-30 minutes')).'.000Z')
{
// Lock
Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', $dateNew);
// eBay Request
$ebay = new eBayRequest();
$page = 1;
$orderList = array();
$orderCount = 0;
$orderCountTmp = 100;
while ($orderCountTmp == 100 && $page < 10)
{
$orderListTmp = $ebay->getOrders(date('Y-m-d', strtotime('-30 days')).'T'.date('H:i:s', strtotime('-30 days')).'.000Z', $dateNew, $page);
$orderCountTmp = count($orderListTmp);
$orderList = array_merge((array)$orderList, (array)$orderListTmp);
$orderCount += $orderCountTmp;
$page++;
}
if ($orderList)
{
foreach ($orderList as $korder => $order)
{
if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list']))
{
if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `'._DB_PREFIX_.'ebay_order` WHERE `id_order_ref` = \''.pSQL($order['id_order_ref']).'\''))
{
// Check for empty name
$order['firstname'] = trim($order['firstname']);
$order['familyname'] = trim($order['familyname']);
if (empty($order['familyname']))
$order['familyname'] = $order['firstname'];
if (empty($order['firstname']))
$order['firstname'] = $order['familyname'];
if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone']))
$order['phone'] = '0100000000';
if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname']))
{
// Getting the customer
$id_customer = (int)Db::getInstance()->getValue('SELECT `id_customer` FROM `'._DB_PREFIX_.'customer` WHERE `active` = 1 AND `email` = \''.pSQL($order['email']).'\' AND `deleted` = 0'.(substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
// Add customer if he doesn't exist
if ($id_customer < 1)
{
$customer = new Customer();
$customer->id_gender = 0;
$customer->id_default_group = 1;
$customer->secure_key = md5(uniqid(rand(), true));
$customer->email = $order['email'];
$customer->passwd = md5(pSQL(_COOKIE_KEY_.rand()));
$customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
$customer->newsletter = 0;
$customer->lastname = pSQL($order['familyname']);
$customer->firstname = pSQL($order['firstname']);
$customer->active = 1;
$customer->add();
$id_customer = $customer->id;
}
// Search if address exists
$id_address = (int)Db::getInstance()->getValue('SELECT `id_address` FROM `'._DB_PREFIX_.'address` WHERE `id_customer` = '.(int)$id_customer.' AND `alias` = \'eBay\'');
if ($id_address > 0)
$address = new Address((int)$id_address);
else
{
$address = new Address();
$address->id_customer = (int)$id_customer;
}
$address->id_country = (int)Country::getByIso($order['country_iso_code']);
$address->alias = 'eBay';
$address->lastname = pSQL($order['familyname']);
$address->firstname = pSQL($order['firstname']);
$address->address1 = pSQL($order['address1']);
$address->address2 = pSQL($order['address2']);
$address->postcode = pSQL($order['postalcode']);
$address->city = pSQL($order['city']);
$address->phone = pSQL($order['phone']);
$address->active = 1;
if ($id_address > 0 && Validate::isLoadedObject($address))
$address->update();
else
$address->add();
$id_address = $address->id;
$flag = 1;
foreach ($order['product_list'] as $product)
{
if ((int)$product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `'._DB_PREFIX_.'product` WHERE `id_product` = '.(int)$product['id_product']))
$flag = 0;
if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `'._DB_PREFIX_.'product_attribute` WHERE `id_product` = '.(int)$product['id_product'].' AND `id_product_attribute` = '.(int)$product['id_product_attribute']))
$flag = 0;
}
if ($flag == 1)
{
$cartNbProducts = 0;
$cartAdd = new Cart();
$cartAdd->id_customer = $id_customer;
$cartAdd->id_address_invoice = $id_address;
$cartAdd->id_address_delivery = $id_address;
$cartAdd->id_carrier = 0;
$cartAdd->id_lang = $this->id_lang;
$cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
$cartAdd->recyclable = 0;
$cartAdd->gift = 0;
$cartAdd->add();
foreach ($order['product_list'] as $product)
if ($cartAdd->updateQty((int)($product['quantity']), (int)($product['id_product']), ((isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0) ? $product['id_product_attribute'] : NULL)))
$cartNbProducts++;
$cartAdd->update();
// Check number of products in the cart
if ($cartNbProducts > 0 && !Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `'._DB_PREFIX_.'ebay_order` WHERE `id_order_ref` = \''.pSQL($order['id_order_ref']).'\''))
{
// Fix on sending e-mail
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = '.(int)$id_customer);
$customerClear = new Customer();
if (method_exists($customerClear, 'clearCache'))
$customerClear->clearCache(true);
// Validate order
$paiement = new eBayPayment();
$paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay '.$order['payment_method'].' '.$order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency));
$id_order = $paiement->currentOrder;
// Fix on date
Db::getInstance()->autoExecute(_DB_PREFIX_.'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = '.(int)$id_order);
// Fix on sending e-mail
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = '.(int)$id_customer);
// Update price (because of possibility of price impact)
foreach ($order['product_list'] as $product)
{
$tax_rate = Db::getInstance()->getValue('SELECT `tax_rate` FROM `'._DB_PREFIX_.'order_detail` WHERE `id_order` = '.(int)$id_order.' AND `product_id` = '.(int)$product['id_product'].' AND `product_attribute_id` = '.(int)$product['id_product_attribute']);
Db::getInstance()->autoExecute(_DB_PREFIX_.'order_detail', array('product_price' => floatval($product['price'] / (1 + ($tax_rate / 100))), 'reduction_percent' => 0), 'UPDATE', '`id_order` = '.(int)$id_order.' AND `product_id` = '.(int)$product['id_product'].' AND `product_attribute_id` = '.(int)$product['id_product_attribute']);
}
$updateOrder = array(
'total_paid' => floatval($order['amount']),
'total_paid_real' => floatval($order['amount']),
'total_products' => floatval(Db::getInstance()->getValue('SELECT SUM(`product_price`) FROM `'._DB_PREFIX_.'order_detail` WHERE `id_order` = '.(int)$id_order)),
'total_products_wt' => floatval($order['amount'] - $order['shippingServiceCost']),
'total_shipping' => floatval($order['shippingServiceCost']),
);
Db::getInstance()->autoExecute(_DB_PREFIX_.'orders', $updateOrder, 'UPDATE', '`id_order` = '.(int)$id_order);
// Register the ebay order ref
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int)$id_order), 'INSERT');
}
else
{
$cartAdd->delete();
$orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)');
}
}
else
$orderList[$korder]['errors'][] = $this->l('Could not found products in database');
}
else
$orderList[$korder]['errors'][] = $this->l('Invalid e-mail');
}
else
$orderList[$korder]['errors'][] = $this->l('Order already imported');
}
else
$orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching');
}
file_put_contents(dirname(__FILE__).'/log/orders.php', "hookaddproduct($params); }
public function hookupdateProductAttribute($params) { }
public function hookupdateProductAttributeEbay()
{
if (isset($_POST['submitProductAttribute']) && isset($_POST['id_product_attribute']))
{
$params = array();
$params['id_product_attribute'] = (int)$_POST['id_product_attribute'];
if ($params['id_product_attribute'] > 0)
{
$id_product = Db::getInstance()->getValue('SELECT `id_product` FROM `'._DB_PREFIX_.'product_attribute` WHERE `id_product_attribute` = '.(int)$params['id_product_attribute']);
$params['product'] = new Product($id_product);
$this->hookaddproduct($params);
}
}
}
public function hookdeleteproduct($params) { $this->hookaddproduct($params); }
public function hookheader($params) { $this->hookbackOfficeTop($params); }
public function hookbackOfficeFooter($params) { $this->hookbackOfficeTop($params); }
/******************************************************************/
/** Main Form Methods *********************************************/
/******************************************************************/
public function getContent()
{
$this->_html .= '
' . $this->l('eBay').'
';
// Checking Country
if (Tools::getValue('ebay_country_default_fr') == 'ok')
$this->context->cookie->ebay_country_default_fr = true;
if (strtolower($this->context->country->iso_code) != 'fr' && !isset($this->context->cookie->ebay_country_default_fr))
return $this->_html.$this->displayError($this->l('eBay module currently works only for eBay.fr').'. '.$this->l('Continue anyway ?').'');
// Checking Extension
if (!extension_loaded('curl') || !ini_get('allow_url_fopen'))
{
if (!extension_loaded('curl') && !ini_get('allow_url_fopen'))
return $this->_html.$this->displayError($this->l('You must enable cURL extension and allow_url_fopen option on your server if you want to use this module.'));
else if (!extension_loaded('curl'))
return $this->_html.$this->displayError($this->l('You must enable cURL extension on your server if you want to use this module.'));
else if (!ini_get('allow_url_fopen'))
return $this->_html.$this->displayError($this->l('You must enable allow_url_fopen option on your server if you want to use this module.'));
}
// If isset Post Var, post process else display form
if (!empty($_POST) && (Tools::isSubmit('submitSave') || Tools::isSubmit('submitSave1') || Tools::isSubmit('submitSave2')))
{
$this->_postValidation();
if (!sizeof($this->_postErrors))
$this->_postProcess();
else
foreach ($this->_postErrors AS $err)
$this->_html .= '
'.$err.'
';
}
$this->_displayForm();
return $this->_html;
}
private function _displayForm()
{
// Test alert
$alert = array();
if (!Configuration::get('EBAY_API_TOKEN'))
$alert['registration'] = 1;
if (!ini_get('allow_url_fopen'))
$alert['allowurlfopen'] = 1;
if (!extension_loaded('curl'))
$alert['curl'] = 1;
// Displaying Information from Prestashop
$stream_context = @stream_context_create(array('http' => array('method'=>"GET", 'timeout' => 2)));
$prestashopContent = @file_get_contents('http://www.prestashop.com/partner/modules/ebay.php?version='.$this->version.'&shop='.urlencode(Configuration::get('PS_SHOP_NAME')).'®istered='.($alert['registration'] == 1 ? 'no' : 'yes').'&url='.urlencode($_SERVER['HTTP_HOST']).'&iso_country='.$isoCountry.'&iso_lang='.Tools::strtolower($isoUser).'&id_lang='.(int)$this->context->language->id.'&email='.urlencode(Configuration::get('PS_SHOP_EMAIL')).'&security='.md5(Configuration::get('PS_SHOP_EMAIL')._COOKIE_IV_), false, $stream_context);
if (!Validate::isCleanHtml($prestashopContent))
$prestashopContent = '';
// Displaying page
$this->_html .= '
';
if (!Configuration::get('EBAY_API_TOKEN'))
$this->_html .= $this->_displayFormRegister();
else
$this->_html .= $this->_displayFormConfig();
}
private function _postValidation()
{
if (!Configuration::get('EBAY_API_TOKEN'))
$this->_postValidationRegister();
else if (Tools::getValue('section') == 'parameters')
$this->_postValidationParameters();
else if (Tools::getValue('section') == 'category')
$this->_postValidationCategory();
else if (Tools::getValue('section') == 'template')
$this->_postValidationTemplateManager();
else if (Tools::getValue('section') == 'sync')
$this->_postValidationEbaySync();
}
private function _postProcess()
{
if (!Configuration::get('EBAY_API_TOKEN'))
$this->_postProcessRegister();
else if (Tools::getValue('section') == 'parameters')
$this->_postProcessParameters();
else if (Tools::getValue('section') == 'category')
$this->_postProcessCategory();
else if (Tools::getValue('section') == 'template')
$this->_postProcessTemplateManager();
else if (Tools::getValue('section') == 'sync')
$this->_postProcessEbaySync();
}
/******************************************************************/
/** Register Form Config Methods **********************************/
/******************************************************************/
private function _displayFormRegister()
{
$ebay = new eBayRequest();
if (!empty($this->context->cookie->eBaySession) && isset($_GET['action']) && $_GET['action'] == 'logged')
{
if (isset($_POST['eBayUsername']))
{
$this->context->cookie->eBayUsername = $_POST['eBayUsername'];
Configuration::updateValue('EBAY_API_USERNAME', $_POST['eBayUsername']);
}
$ebay->session = $this->context->cookie->eBaySession;
$ebay->username = $this->context->cookie->eBayUsername;
$html = '
';
$html .= '';
}
else
{
if (empty($this->context->cookie->eBaySession))
{
$ebay->login();
$this->context->cookie->eBaySession = $ebay->session;
Configuration::updateValue('EBAY_API_SESSION', $ebay->session);
}
$html = '
';
}
return $html;
}
private function _postValidationRegister()
{
}
private function _postProcessRegister()
{
}
/******************************************************************/
/** Parameters Form Config Methods ********************************/
/******************************************************************/
private function _displayFormConfig()
{
$html = '
1. '.$this->l('Parameters').'
2. '.$this->l('Categories settings').'
3. '.$this->l('Template manager').'
4. '.$this->l('eBay Sync').'
5. '.$this->l('Orders history').'
6. '.$this->l('Help').'
'.$this->_displayFormParameters().'
'.$this->_displayFormCategory().'
'.$this->_displayFormTemplateManager().'
'.$this->_displayFormEbaySync().'
'.$this->_displayOrdersHistory().'
'.$this->_displayHelp().'
';
if (isset($_GET['id_tab']))
$html .= '';
return $html;
}
private function _displayFormParameters()
{
// Loading config currency
$configCurrency = new Currency((int)(Configuration::get('PS_CURRENCY_DEFAULT')));
// Display Form
$html = '';
if (!Configuration::get('EBAY_CATEGORY_LOADED'))
{
$html .= '
';
}
return $html;
}
private function _postValidationParameters()
{
// Check configuration values
if (Tools::getValue('ebay_identifier') == NULL)
$this->_postErrors[] = $this->l('Your eBay identifier account is not specified or is invalid');
if (Tools::getValue('ebay_paypal_email') == NULL OR !Validate::isEmail(Tools::getValue('ebay_paypal_email')))
$this->_postErrors[] = $this->l('Your Paypal E-mail account is not specified or is invalid');
if (Tools::getValue('ebay_shipping_cost') == '' OR !is_numeric(Tools::getValue('ebay_shipping_cost')))
$this->_postErrors[] = $this->l('Your shipping cost is not specified or is invalid');
if (Tools::getValue('ebay_shop_postalcode') == '' OR !Validate::isPostCode(Tools::getValue('ebay_shop_postalcode')))
$this->_postErrors[] = $this->l('Your shop\'s postal code is not specified or is invalid');
}
private function _postProcessParameters()
{
// Saving new configurations
if (Configuration::updateValue('EBAY_PAYPAL_EMAIL', pSQL(Tools::getValue('ebay_paypal_email'))) &&
Configuration::updateValue('EBAY_IDENTIFIER', pSQL(Tools::getValue('ebay_identifier'))) &&
Configuration::updateValue('EBAY_SHOP', pSQL(Tools::getValue('ebay_shop'))) &&
Configuration::updateValue('EBAY_SHIPPING_COST', (float)(Tools::getValue('ebay_shipping_cost'))) &&
Configuration::updateValue('EBAY_SHIPPING_COST_CURRENCY', (int)(Configuration::get('PS_CURRENCY_DEFAULT'))) &&
Configuration::updateValue('EBAY_SHIPPING_CARRIER_ID', pSQL(Tools::getValue('ebay_shipping_carrier_id'))) &&
Configuration::updateValue('EBAY_SHOP_POSTALCODE', pSQL(Tools::getValue('ebay_shop_postalcode'))))
$this->_html .= $this->displayConfirmation($this->l('Settings updated'));
else
$this->_html .= $this->displayError($this->l('Settings failed'));
}
/******************************************************************/
/** Category Form Config Methods **********************************/
/******************************************************************/
private function _getChildCategories($categories, $id, $path = array(), $pathAdd = '')
{
$categoryTmp = array();
$categoryTab = array();
if ($pathAdd != '')
$path[] = $pathAdd;
if (isset($categories[$id]))
foreach ($categories[$id] as $idc => $cc)
{
$name = '';
if ($path)
foreach ($path as $p)
$name .= $p.' > ';
$name .= $cc['infos']['name'];
$categoryTab[] = array('id_category' => $cc['infos']['id_category'], 'name' => $name);
$categoryTmp = $this->_getChildCategories($categories, $idc, $path, $cc['infos']['name']);
$categoryTab = array_merge($categoryTab, $categoryTmp);
}
return $categoryTab;
}
private function _displayFormCategory()
{
// Check if the module is configured
if (!Configuration::get('EBAY_PAYPAL_EMAIL'))
return '
'.$this->l('You have to configure "General Settings" tab before using this tab.').'
';
// Load categories only if necessary
if (Db::getInstance()->getValue('SELECT COUNT(`id_ebay_category_configuration`) FROM `'._DB_PREFIX_.'ebay_category_configuration`') >= 1 && Tools::getValue('section') != 'category')
return '
'.$this->l('Your categories have already been configured.').'
';
// Display eBay Categories
if (!Configuration::get('EBAY_CATEGORY_LOADED'))
{
$ebay = new eBayRequest();
$ebay->saveCategories();
Configuration::updateValue('EBAY_CATEGORY_LOADED', 1);
Configuration::updateValue('EBAY_CATEGORY_LOADED_DATE', date('Y-m-d H:i:s'));
}
// Loading categories
$categoryConfigList = array();
$categoryConfigListTmp = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'ebay_category_configuration`');
foreach ($categoryConfigListTmp as $c)
$categoryConfigList[$c['id_category']] = $c;
$categoryList = $this->_getChildCategories(Category::getCategories($this->context->language->id), 0);
$eBayCategoryList = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'ebay_category` WHERE `id_category_ref` = `id_category_ref_parent`');
// Display header
$html = '
'.$this->l('To export your products on eBay, you have to associate each one of your shop categories to an eBay category. You can also define an impact of your price on eBay.').'
'.$this->l('Beware : Only product default categories are used for this configuration.').'
';
return $html;
}
private function _postValidationCategory()
{
}
private function _postProcessCategory()
{
// Init Var
$date = date('Y-m-d H:i:s');
$services = Tools::getValue('service');
if (Tools::getValue('action') == 'suggestCategories')
{
// Loading categories
$ebay = new eBayRequest();
$categoryConfigList = array();
$categoryConfigListTmp = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'ebay_category_configuration`');
foreach ($categoryConfigListTmp as $c)
$categoryConfigList[$c['id_category']] = $c;
$categoryList = Db::getInstance()->executeS('SELECT `id_category`, `name` FROM `'._DB_PREFIX_.'category_lang` WHERE `id_lang` = '.(int)$this->id_lang.$this->context->shop->addSqlRestrictionOnLang('cl'));
foreach ($categoryList as $k => $c)
if (!isset($categoryConfigList[$c['id_category']]))
{
$productTest = Db::getInstance()->getRow('
SELECT pl.`name`, pl.`description`
FROM `'._DB_PREFIX_.'product` p LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.`id_product` = p.`id_product` AND pl.`id_lang` = '.(int)$this->id_lang.$this->context->shop->addSqlRestrictionOnLang('pl').')
WHERE `id_category_default` = '.(int)$c['id_category']);
$id_category_ref_suggested = $ebay->getSuggestedCategories($c['name'].' '.$productTest['name']);
$id_ebay_category_suggested = Db::getInstance()->getValue('SELECT `id_ebay_category` FROM `'._DB_PREFIX_.'ebay_category` WHERE `id_category_ref` = '.(int)$id_category_ref_suggested);
if ((int)$id_ebay_category_suggested > 0)
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_category_configuration', array('id_country' => 8, 'id_ebay_category' => (int)$id_ebay_category_suggested, 'id_category' => (int)$c['id_category'], 'percent' => 0, 'date_add' => pSQL($date), 'date_upd' => pSQL($date)), 'INSERT');
}
$this->_html .= $this->displayConfirmation($this->l('Settings updated'));
return true;
}
// Sort post datas
$postValue = array();
foreach ($_POST as $k => $v)
{
if (strlen($k) > 8 && substr($k, 0, 8) == 'category')
$postValue[substr($k, 8, strlen($k) - 8)]['id_ebay_category'] = $v;
if (strlen($k) > 7 && substr($k, 0, 7) == 'percent')
$postValue[substr($k, 7, strlen($k) - 7)]['percent'] = $v;
}
// Insert and update configuration
foreach ($postValue as $id_category => $tab)
{
$arraySQL = array();
$date = date('Y-m-d H:i:s');
if ($tab['id_ebay_category'])
$arraySQL = array('id_country' => 8, 'id_ebay_category' => (int)$tab['id_ebay_category'], 'id_category' => (int)$id_category, 'percent' => pSQL($tab['percent']), 'date_upd' => pSQL($date));
$id_ebay_category_configuration = Db::getInstance()->getValue('SELECT `id_ebay_category_configuration` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` = '.(int)$id_category);
if ($id_ebay_category_configuration > 0)
{
if ($arraySQL)
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_category_configuration', $arraySQL, 'UPDATE', '`id_category` = '.(int)$id_category);
else
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` = '.(int)$id_category);
}
elseif ($arraySQL)
{
$arraySQL['date_add'] = $date;
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_category_configuration', $arraySQL, 'INSERT');
}
}
$this->_html .= $this->displayConfirmation($this->l('Settings updated'));
}
/******************************************************************/
/** Template Manager Form Config Methods **************************/
/******************************************************************/
private function _displayFormTemplateManager()
{
// Check if the module is configured
if (!Configuration::get('EBAY_PAYPAL_EMAIL'))
return '
'.$this->l('You have to configure "General Settings" tab before using this tab.').'
';
$iso = $context->language->iso_code;
$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
$ad = dirname($_SERVER["PHP_SELF"]);
// Display Form
$forbiddenJs = array('textarea', 'script', 'onmousedown', 'onmousemove', 'onmmouseup', 'onmouseover', 'onmouseout', 'onload', 'onunload', 'onfocus', 'onblur', 'onchange', 'onsubmit', 'ondblclick', 'onclick', 'onkeydown', 'onkeyup', 'onkeypress', 'onmouseenter', 'onmouseleave', 'onerror');
$html = '';
return $html;
}
private function _postValidationTemplateManager()
{
}
private function _postProcessTemplateManager()
{
// Saving new configurations
if (Configuration::updateValue('EBAY_PRODUCT_TEMPLATE', Tools::getValue('ebay_product_template'), true))
$this->_html .= $this->displayConfirmation($this->l('Settings updated'));
else
$this->_html .= $this->displayError($this->l('Settings failed'));
}
/******************************************************************/
/** Ebay Sync Form Config Methods **************************/
/******************************************************************/
private function _displayFormEbaySync()
{
// Check if the module is configured
if (!Configuration::get('EBAY_PAYPAL_EMAIL'))
return '
'.$this->l('You have to configure "General Settings" tab before using this tab.').'
';
if (Db::getInstance()->getValue('SELECT COUNT(`id_ebay_category_configuration`) as nb FROM `'._DB_PREFIX_.'ebay_category_configuration`') < 1)
return '
'.$this->l('You have to configure "Categories Settings" tab before using this tab.').'
';
$nbProductsModeA = Db::getInstance()->getValue('
SELECT COUNT(`id_product`) as nb
FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_ebay_category` > 0)');
$nbProductsModeB = Db::getInstance()->getValue('
SELECT COUNT(`id_product`) as nb
FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_ebay_category` > 0 AND `sync` = 1)');
$nbProducts = $nbProductsModeA;
if (Configuration::get('EBAY_SYNC_MODE') == 'B')
$nbProducts = $nbProductsModeB;
// Display Form
$html = '
';
return $html;
}
private function _postValidationEbaySync()
{
}
private function _postProcessEbaySync()
{
// Update Sync Option
Configuration::updateValue('EBAY_SYNC_OPTION_RESYNC', (Tools::getValue('ebay_sync_option_resync') == 1 ? 1 : 0));
// Empty error result
Configuration::updateValue('EBAY_SYNC_LAST_PRODUCT', 0);
@unlink(dirname(__FILE__).'/log/syncError.php');
if ($_POST['ebay_sync_mode'] == 'A')
{
// Update Sync Mod
Configuration::updateValue('EBAY_SYNC_MODE', 'A');
}
else
{
// Update Sync Mod
Configuration::updateValue('EBAY_SYNC_MODE', 'B');
// Select the sync Categories and Retrieve product list for eBay (which have matched and sync categories)
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_category_configuration', array('sync' => 0), 'UPDATE', '');
foreach ($_POST['category'] as $id_category)
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_category_configuration', array('sync' => 1), 'UPDATE', '`id_category` = '.(int)$id_category);
}
}
public function ajaxProductSync()
{
$whereOption1 = 'AND `id_product` NOT IN (SELECT `id_product` FROM `'._DB_PREFIX_.'ebay_product`)';
if (Configuration::get('EBAY_SYNC_MODE') == 'A')
{
// Retrieve total nb products for eBay (which have matched categories)
$nbProductsTotal = Db::getInstance()->getValue('
SELECT COUNT(`id_product`)
FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0)');
// Retrieve products list for eBay (which have matched categories)
$productsList = Db::getInstance()->executeS('
SELECT `id_product` FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0)
'.(Tools::getValue('option') == 1 ? $whereOption1 : '').'
AND `id_product` > '.(int)Configuration::get('EBAY_SYNC_LAST_PRODUCT').'
ORDER BY `id_product`
LIMIT 1');
// How Many Product Less ?
$nbProductsLess = Db::getInstance()->getValue('
SELECT COUNT(`id_product`) FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0)
'.(Tools::getValue('option') == 1 ? $whereOption1 : '').'
AND `id_product` > '.(int)Configuration::get('EBAY_SYNC_LAST_PRODUCT'));
}
else
{
// Retrieve total nb products for eBay (which have matched categories)
$nbProductsTotal = Db::getInstance()->getValue('
SELECT COUNT(`id_product`)
FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0 AND `sync` = 1)');
// Retrieve products list for eBay (which have matched categories)
$productsList = Db::getInstance()->executeS('
SELECT `id_product` FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0 AND `sync` = 1)
'.(Tools::getValue('option') == 1 ? $whereOption1 : '').'
AND `id_product` > '.(int)Configuration::get('EBAY_SYNC_LAST_PRODUCT').'
ORDER BY `id_product`
LIMIT 1');
// How Many Product Less ?
$nbProductsLess = Db::getInstance()->getValue('
SELECT COUNT(`id_product`) FROM `'._DB_PREFIX_.'product`
WHERE `quantity` > 0 AND `active` = 1
AND `id_category_default` IN (SELECT `id_category` FROM `'._DB_PREFIX_.'ebay_category_configuration` WHERE `id_category` > 0 AND `id_ebay_category` > 0 AND `sync` = 1)
'.(Tools::getValue('option') == 1 ? $whereOption1 : '').'
AND `id_product` > '.(int)Configuration::get('EBAY_SYNC_LAST_PRODUCT'));
}
// Send each product on eBay
if (count($productsList) >= 1)
{
// Save the last product
Configuration::updateValue('EBAY_SYNC_LAST_PRODUCT', (int)$productsList[0]['id_product']);
// Sync product
$this->_syncProducts($productsList);
echo 'KO|
NB : L’outil « Gestionnaire de Ventes Pro » vous permet d’automatiser un certain nombre de ses tâches de relation client et ainsi de vous faire gagner du temps. Souscrire au Gestionnaire de ventes Pro
';
}
public function displayInfoByCart()
{
}
private function _displayFormProduct() { }
private function _displayFormAssociation() { }
}