PageRenderTime 5ms CodeModel.GetById 4ms app.highlight 58ms RepoModel.GetById 1ms app.codeStats 1ms

/modules/shopimporter/shopimporter.php

https://bitbucket.org/marcenuc/prestashop
PHP | 1506 lines | 1363 code | 72 blank | 71 comment | 229 complexity | bc544b36d103f7b97e4833eb6be5685b MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/*
   3* 2007-2012 PrestaShop
   4*
   5* NOTICE OF LICENSE
   6*
   7* This source file is subject to the Academic Free License (AFL 3.0)
   8* that is bundled with this package in the file LICENSE.txt.
   9* It is also available through the world-wide-web at this URL:
  10* http://opensource.org/licenses/afl-3.0.php
  11* If you did not receive a copy of the license and are unable to
  12* obtain it through the world-wide-web, please send an email
  13* to license@prestashop.com so we can send you a copy immediately.
  14*
  15* DISCLAIMER
  16*
  17* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18* versions in the future. If you wish to customize PrestaShop for your
  19* needs please refer to http://www.prestashop.com for more information.
  20*
  21*  @author PrestaShop SA <contact@prestashop.com>
  22*  @copyright  2007-2012 PrestaShop SA
  23*  @version  Release: $Revision$
  24*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  25*  International Registered Trademark & Property of PrestaShop SA
  26*/
  27
  28if (!defined('_PS_VERSION_'))
  29	exit;
  30
  31class shopimporter extends ImportModule
  32{
  33	public $supportedImports = array();
  34
  35	public function __construct()
  36	{
  37		$this->name = 'shopimporter';
  38		$this->tab = 'migration_tools';
  39		$this->version = '1.0';
  40		$this->author = 'PrestaShop';
  41		$this->need_instance = 0;
  42		$this->is_configurable = 1;
  43
  44		parent::__construct ();
  45
  46		$this->displayName = $this->l('Shop Importer');
  47		$this->description = $this->l('This module allows you to import your shop from another system into Prestashop.');
  48		$this->supportedImports = array(
  49									'language' => array('methodName' => 'getLangagues',
  50														'name' => $this->l('Language'),
  51														'className' => 'Language',
  52														'label' => $this->l('Import Languages'),
  53														'table' => 'lang',
  54														'identifier' => 'id_lang',
  55														'alterTable' => array('id_lang' => 'int(10)'),
  56														'info' => $this->l('New languages will automatically add translations.'),
  57														'defaultId' => 'PS_LANG_DEFAULT'
  58														),
  59									'currency' => array('methodName' => 'getCurrencies',
  60														'name' => $this->l('Currency'),
  61														'className' => 'Currency',
  62														'label' => $this->l('Import Currencies'),
  63														'table' => 'currency',
  64														'identifier' => 'id_currency',
  65														'alterTable' => array('id_currency' => 'int(10)'),
  66														'delete' => true,
  67														'defaultId' => 'PS_CURRENCY_DEFAULT'
  68														),
  69							/*
  70		'tax' => array('methodName' => 'getTaxes',
  71														'name' => $this->l('Taxes'),
  72														'className' => 'Tax',
  73														'label' => $this->l('Import Taxes'),
  74														'table' => 'tax',
  75														'identifier' => 'id_tax',
  76														'alterTable' => array('id_tax' => 'int(10)'),
  77														'delete' => true
  78														),
  79									'tax_rule' => array('methodName' => 'getTaxes rules',
  80														'name' => $this->l('Taxes rules'),
  81														'className' => 'TaxRule',
  82														'label' => $this->l('Import Taxes Rules'),
  83														'table' => 'tax_rules_group',
  84														'identifier' => 'id_tax',
  85														'alterTable' => array('id_tax_rules_group' => 'int(10)'),
  86														'delete' => true
  87														),
  88*/
  89									'zone' => array('methodName' => 'getZones',
  90														'name' => $this->l('Zone'),
  91														'className' => 'Zone',
  92														'label' => $this->l('Import Zones'),
  93														'table' => 'zone',
  94														'identifier' => 'id_zone',
  95														'alterTable' => array('id_zone' => 'int(10)'),
  96														'delete' => true
  97														),
  98									'country' => array('methodName' => 'getCountries',
  99														'name' => $this->l('Country'),
 100														'className' => 'Country',
 101														'label' => $this->l('Import Countries'),
 102														'table' => 'country',
 103														'identifier' => 'id_country',
 104														'foreign_key' => array('id_zone', 'id_currency'),
 105														'alterTable' => array('id_country' => 'int(10)'),
 106														'delete' => true,
 107														'defaultId' => 'PS_COUNTRY_DEFAULT'
 108														),
 109									'state' => array('methodName' => 'getStates',
 110														'name' => $this->l('State'),
 111														'className' => 'State',
 112														'label' => $this->l('Import States'),
 113														'table' => 'state',
 114														'identifier' => 'id_state',
 115														'foreign_key' => array('id_zone', 'id_country'),
 116														'alterTable' => array('id_state' => 'int(10)'),
 117														'delete' => true
 118														),
 119									'group' => array('methodName' => 'getGroups',
 120														'name' => $this->l('Group'),
 121														'className' => 'Group',
 122														'label' => $this->l('Import Groups'),
 123														'table' => 'group',
 124														'identifier' => 'id_group',
 125														'alterTable' => array('id_group' => 'int(10)'),
 126														'delete' => true,
 127														),
 128									'customer' => array('methodName' => 'getCustomers',
 129														'name' => $this->l('Customer'),
 130														'className' => 'Customer',
 131														'label' => $this->l('Import Customers'),
 132														'table' => 'customer',
 133														'identifier' => 'id_customer',
 134														'foreign_key' => array('id_group'),
 135														'alterTable' => array('id_customer' => 'int(10)', 'passwd' => 'varchar(100)'),
 136														'delete' => true,
 137														'association' => array(
 138															array(
 139																'table' => 'customer_group',
 140																'fields' => array('id_customer', 'id_group'),
 141																'matchTable' => array('customer', 'group'),
 142																)
 143															)
 144														),
 145									'address' => array('methodName' => 'getAddresses',
 146														'name' => $this->l('Address'),
 147														'className' => 'Address',
 148														'label' => $this->l('Import Addresses'),
 149														'table' => 'address',
 150														'identifier' => 'id_address',
 151														'foreign_key' => array('id_country', 'id_state', 'id_customer'),
 152														'alterTable' => array('id_address' => 'int(10)'),
 153														'delete' => true
 154														),
 155									'manufacturer' => array('methodName' => 'getManufacturers',
 156														'name' => $this->l('Manufacturer'),
 157														'className' => 'Manufacturer',
 158														'label' => $this->l('Import Manufacturers'),
 159														'table' => 'manufacturer',
 160														'identifier' => 'id_manufacturer',
 161														'delete' => true,
 162														'alterTable' => array('id_manufacturer' => 'int(10)'),
 163														'hasImage' => true
 164														),
 165									'supplier' => array('methodName' => 'getSuppliers',
 166														'name' => $this->l('Supplier'),
 167														'className' => 'Supplier',
 168														'label' => $this->l('Import Suppliers'),
 169														'table' => 'supplier',
 170														'identifier' => 'id_supplier',
 171														'delete' => true,
 172														'alterTable' => array('id_supplier' => 'int(10)'),
 173														'hasImage' => true
 174														),
 175									'category' => array('methodName' => 'getCategories',
 176														'name' => $this->l('Category'),
 177														'className' => 'Category',
 178														'label' => $this->l('Import Categories'),
 179														'table' => 'category',
 180														'identifier' => 'id_category',
 181														'alterTable' => array('id_category' => 'int(10)'),
 182														'delete' => true,
 183														'hasImage' => true,
 184														),
 185									'attributegroup' => array('methodName' => 'getAttributesGroups',
 186														'name' => $this->l('AttributeGroup'),
 187														'className' => 'AttributeGroup',
 188														'label' => $this->l('Import Attributes Groups'),
 189														'table' => 'attribute_group',
 190														'identifier' => 'id_attribute_group',
 191														'alterTable' => array('id_attribute_group' => 'int(10)'),
 192														'delete' => true
 193														),
 194									'attribute' => array('methodName' => 'getAttributes',
 195														'name' => $this->l('Attribute'),
 196														'className' => 'Attribute',
 197														'label' => $this->l('Import Attributes'),
 198														'table' => 'attribute',
 199														'identifier' => 'id_attribute',
 200														'alterTable' => array('id_attribute' => 'int(10)'),
 201														'foreign_key' => array('id_attribute_group'),
 202														'delete' => true
 203														),
 204									'product' => array('methodName' => 'getProducts',
 205														'name' => $this->l('Product'),
 206														'className' => 'Product',
 207														'label' => $this->l('Import Products'),
 208														'table' => 'product',
 209														'identifier' => 'id_product',
 210														'alterTable' => array('id_product' => 'int(10)'),
 211														'foreign_key' => array('id_category', 'id_manufacturer'),
 212														'delete' => true,
 213														'association' => array(
 214															array(
 215																'table' => 'category_product',
 216																'fields' => array('id_category', 'id_product'),
 217																'matchTable' =>  array('category', 'product')
 218																)
 219															),
 220														'hasImage' => true
 221														),
 222									'combination' => array('methodName' => 'getProductsCombination',
 223														'name' => $this->l('Combination'),
 224														'className' => 'Combination',
 225														'label' => $this->l('Import Products Combinations'),
 226														'table' => 'product_attribute',
 227														'identifier' => 'id_product_attribute',
 228														'alterTable' => array('id_product_attribute' => 'int(10)', 'id_product' => 'int(10)'),
 229														'foreign_key' => array('id_product'),
 230														'delete' => false,
 231														'association' => array(
 232															array(
 233																'table' => 'product_attribute_combination',
 234																'fields' => array('id_attribute', 'id_product_attribute'),
 235																'matchTable' =>  array('attribute', 'product_attribute')
 236																)
 237															)
 238														),
 239									'orderstate' => array('methodName' => 'getOrdersStates',
 240													 'name' => $this->l('Orders States'),
 241													 'className' => 'OrderState',
 242													 'label' => $this->l('Import Orders States'),
 243													 'table' => 'order_state',
 244													 'identifier' => 'id_order_state',
 245													 'alterTable' => array('id_order_state' => 'int(10)')
 246													 ),
 247									'cart' => array('methodName' => 'getOrders',
 248													 'name' => $this->l('Order'),
 249													 'className' => 'Cart',
 250													 'label' => $this->l('Import Orders'),
 251													 'table' => 'cart',
 252													 'identifier' => 'id_cart',
 253													 'foreign_key' => array('id_address_delivery', 'id_address_invoice', 'id_customer'),
 254													 'alterTable' => array('id_cart' => 'int(10)')
 255													 ),
 256									'orderhistory' => array('methodName' => 'getOrdersHistory',
 257													 'name' => $this->l('Order history'),
 258													 'className' => 'Order history',
 259													 'label' => $this->l('Import Order History'),
 260													 'table' => 'order_history',
 261													 'identifier' => 'id_order_history',
 262													 'foreign_key' => array('id_order', 'id_order_state'),
 263													 'alterTable' => array('id_order_history' => 'int(10)'),
 264													 'hidden' => true
 265													 ),
 266									'order' => array('methodName' => 'getOrders',
 267													 'name' => $this->l('Order'),
 268													 'className' => 'Order',
 269													 'label' => $this->l('Import Order History'),
 270													 'table' => 'orders',
 271													 'identifier' => 'id_order',
 272													 'alterTable' => array('id_order' => 'int(10)'),
 273													 'hidden' => true
 274													 )
 275									);
 276	}
 277
 278	public function install()
 279	{
 280		return parent::install();
 281	}
 282
 283	public function uninstall()
 284	{
 285		return parent::uninstall();
 286	}
 287
 288	public function getContent()
 289	{
 290		$exportModules = parent::getImportModulesOnDisk();
 291		//get installed module only
 292		foreach($exportModules as $key => $module)
 293			if ($module->name == $this->name || !(bool)$module->id)
 294				unset($exportModules[$key]);
 295		$html = '<script type="text/javascript">var globalAjaxShopImporterToken = "'.sha1(_COOKIE_KEY_.'ajaxShopImporter').'";</script>
 296		<script type="text/javascript" src="../modules/shopimporter/shopimporter.js"></script>
 297				<script src="'._PS_JS_DIR_.'jquery/jquery.scrollTo-1.4.2-min.js"></script>
 298				 <script type="text/javascript">
 299					var conf = new Array(); ';
 300		$i = 0;
 301		foreach($this->supportedImports as $import)
 302		{
 303			if(!array_key_exists('hidden', $import))
 304			$html .= 'conf['.$i.'] = new Array(\''.addslashes($import['methodName']).'\', \''.addslashes($import['label']).'\', \''.addslashes($import['className']).'\', \''.addslashes($import['name']).'\');';
 305			$i++;
 306		}
 307
 308		$html .= '	var notExist = "'.$this->l('is not available in this module').'";
 309					var databaseOk = "'.$this->l('Connection to the database OK').'";
 310					var wsOk = "'.$this->l('Connection to the web service OK').'";
 311					var showErrors = "'.$this->l('Show errors').'";
 312					var testImport = "'.$this->l('Test import process').'";
 313					var runImport = "'.$this->l('Run Import').'";
 314					var importHasErrors = "'.$this->l('Errors occurred during import. For more details click on "Show errors".').'"
 315					var importFinish = "'.$this->l('Import is complete.').'"
 316					var truncateTable = "'.$this->l('Remove data').'"
 317					var oneThing = "'.$this->l('Please choose one thing to import').'"
 318				</script>
 319				<style>
 320					.margin-form{padding: 0px 0px 1em 120px;width:300px;}
 321					label{width: 170px;}
 322					.import{background-color: #CCCCCC;border: 1px solid gray;margin: 0px 0px 10px;padding: 10px 15px;line-height: 20px;}
 323				</style>
 324				<fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" />'.$this->l('Import from another system').'</legend>
 325				<div class="warn" ><img src="../img/admin/warn2.png">
 326					'.$this->l('Before starting the import please backup your database. ').'
 327						<a href="index.php?tab=AdminBackup&token='.Tools::getAdminToken('AdminBackup'.(int)Tab::getIdFromClassName('AdminBackup').(int)$this->context->employee->id).'"">'.$this->l(' Click here to backup').'</a>
 328				</div>
 329				<br>
 330				<div style="float:right;width:450px" id="steps"></div>';
 331				if (sizeof($exportModules))
 332				{
 333				$html .= '
 334				<label>'.$this->l('Choose your import').' : </label>
 335				<div class="margin-form">
 336					<select name="import_module_name" id="import_module_name">
 337						<option value="0">---</option>';
 338
 339		foreach($exportModules as $key => $module)
 340			(($module->name != $this->name AND $module->id) ? $html .= '<option value="'.$module->name.'">'.$module->displayName.'</option>' : '' );
 341
 342		$html .= '</select><input type="submit" class="button" id="choose_module_name" value="'.$this->l('Choose').'">
 343				</div>';
 344				}
 345				else
 346					$html .= '<div class="warn" ><img src="../img/admin/warn2.png">'.$this->l('No import module installed').'</div>';
 347				$html .= '
 348					<div style="display:none;" class="error" id="connectionInformation"></div>
 349					<div id="config_connector"></div>
 350						<div class="margin-form">
 351						<input type="submit" name="displayOptions" id="displayOptions" class="button" value="'.$this->l('Next Step').'">
 352					</div>
 353					<hr>
 354					<div style="display:none" id="importOptions">
 355					<h2>'.$this->l('Import Options').'</h2>
 356					<div id="importOptionsYesNo">';
 357					foreach($this->supportedImports as $key => $import)
 358					{
 359						if(!array_key_exists('hidden', $import))
 360						$html .= '<label>'.$import['name'].' : </label>
 361									<div class="margin-form">
 362										<label class="t" for="'.$import['identifier'].'_on'.'"><img src="../img/admin/enabled.gif" alt="Yes" title="Yes"></label>
 363										<input type="radio" id="'.$import['identifier'].'_on'.'" name="'.$import['methodName'].'" class="'.$key.'" value="1" checked="checked">
 364										<label class="t" for="'.$import['identifier'].'_off'.'"><img src="../img/admin/disabled.gif" alt="No" title="No" style="margin-left: 10px;"></label>
 365										<input type="radio" id="'.$import['identifier'].'_off'.'" name="'.$import['methodName'].'" class="'.$key.'" value="0">
 366										'.(array_key_exists('delete', $import) ? '
 367										<label class="t"><img src="../img/admin/delete.gif" alt="Delete" title="Delete"></label>
 368										<input type="checkbox" class="truncateTable" id="'.$key.'" name="delete_'.$import['className'].'">' : '' ).
 369										(array_key_exists('hasImage', $import) ? '
 370										<label class="t"><img src="../img/admin/picture.gif" alt="Images" title="Images"></label>
 371										<input type="checkbox" class="importImages" id="'.$key.'" name="images_'.$import['className'].'">' : '' ).
 372										(array_key_exists('info', $import) ? '<p>'.$import['info'].'</p>' : '').'
 373									</div>';
 374					}
 375					$html .= '</div><hr>
 376					<h2>'.$this->l('Advanced Options').'</h2>
 377					<div class="warn" id="warnSkip" style="display:none"><img src="../img/admin/warn2.png">
 378					'.$this->l('This mode is dangerous').'
 379					</div>
 380					<label>'.$this->l('Import for every').' : </label>
 381							<div class="margin-form">
 382								<select name="nbr_import" id="nbr_import">
 383									<option value="10">10</option>
 384									<option value="50">50</option>
 385									<option value="100" selected="selected">100</option>
 386									<option value="200">200</option>
 387								</select>
 388								<p>'.$this->l('Select the number of occurrences for each query to import').'</p>
 389							</div>
 390					<label>'.$this->l('If errors occur').' : </label>
 391							<div class="margin-form">
 392								<label class="t"><img src="'.$this->_path.'img/stop.png"></label>
 393								<input type="radio" name="hasErrors" id="hasErrors" value="0" checked="checked">
 394								<label class="t">'.$this->l('Stop').'</label>
 395								<label class="t"><img src="'.$this->_path.'img/skip.png" style="margin-left: 10px;"></label>
 396								<input type="radio" name="hasErrors" id="hasErrors" value="1">
 397								<label class="t">'.$this->l('Skip').'</label>
 398								<label class="t"><img src="'.$this->_path.'img/force.gif" style="margin-left: 10px;"></label>
 399								<input type="radio" name="hasErrors" id="hasErrors" value="2">
 400								<label class="t">'.$this->l('Force').'</label>
 401								<p>'.$this->l('Stop: if there are errors with the data, import will not run.').'</p>
 402								<p>'.$this->l('Skip: if there are errors with the data, import will skip incorrect data.').'</p>
 403								<p>'.$this->l('Force: if there are errors with the data, import will replace incorrect data by generic data.').'</p>
 404							</div>
 405							<hr>
 406							<div style="display:none" id="specificOptions">
 407							<h2>'.$this->l('Specific Options').'</h2>
 408								<div style="display:none" class="error" id="specificOptionsErrors"></div>
 409								<div id="specificOptionsContent">
 410								</div>
 411							</div>
 412							<hr>
 413							<div class="margin-form">
 414							<input type="submit" class="button" name="checkAndSaveConfig" id="checkAndSaveConfig" value="'.$this->l('Next Step').'">
 415						</div>
 416					</div>
 417				</fieldset>';
 418		return $html;
 419	}
 420
 421	public function genericImport($className, $fields, $save = false)
 422	{
 423		$return = '';
 424		$json = array();
 425		$errors = array();
 426		$json['hasError'] = false;
 427		$json['datas'] = array_values($fields);
 428		$languages = array();
 429		$defaultLanguage = '';
 430		$table = $this->supportedImports[strtolower($className)]['table'];
 431
 432		$object = new $className();
 433		$rules = call_user_func(array($className, 'getValidationRules'), $className);
 434
 435		if ((sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang']) || Tools::isSubmit('syncLang') ||  Tools::isSubmit('syncCurrency')))
 436		{
 437			$moduleName = Tools::getValue('moduleName');
 438			if (Validate::isModuleName($moduleName) && Validate::file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
 439			{
 440				require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
 441				$importModule = new $moduleName();
 442				$importModule->server = Tools::getValue('server');
 443				$importModule->user = Tools::getValue('user');
 444				$importModule->passwd = Tools::getValue('password');
 445				$importModule->database = Tools::getValue('database');
 446				$importModule->prefix = Tools::getValue('prefix');
 447				$defaultLanguage = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
 448				$languages = $importModule->getLangagues(0);
 449				if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
 450				{
 451					$defaultIdLand = $importModule->getDefaultIdLang();
 452					$defaultLanguageImport = new Language(Language::getIdByIso($languages[$defaultIdLand]['iso_code']));
 453					if ($defaultLanguage->iso_code != $defaultLanguageImport->iso_code)
 454						$errors[] = $this->l('Default language doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultLanguage->name.' ?
 455											'.$importModule->displayName.' : '.$defaultLanguageImport->name.'<br>'.$this->l('Please change default language in your configuration');
 456				}
 457
 458				if (Tools::isSubmit('syncCurrency') || Tools::isSubmit('syncCurrencyWS'))
 459				{
 460					$defaultIdCurrency = $importModule->getDefaultIdCurrency();
 461					$currencies = $importModule->getCurrencies(0);
 462					if(!empty($currencies[$defaultIdCurrency]['iso_code']))
 463						$defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCode($currencies[$defaultIdCurrency]['iso_code']));
 464					else
 465						$defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCodeNum($currencies[$defaultIdCurrency]['iso_code_num']));
 466
 467					$defaultCurrency = new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'));
 468					if ($defaultCurrency->iso_code != $defaultCurrencyImport->iso_code)
 469						$errors[] = $this->l('Default currency doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultCurrency->name.' ? '.$importModule->displayName.' : '.$defaultCurrencyImport->name.'<br>'.$this->l('Please change default currency in your configuration');
 470				}
 471				if (!empty($errors))
 472					die('{"hasError" : true, "error" : '.Tools::jsonEncode($errors).'}');
 473			}
 474			else
 475				die('{"hasError" : true, "error" : ["FATAL ERROR"], "datas" : []}');
 476		}
 477
 478		foreach($fields as $key => $field)
 479		{
 480			$id = $this->supportedImports[strtolower($className)]['identifier'];
 481			//remove wrong fields (ex : id_toto in Customer)
 482			foreach($field as $name => $value)
 483				if (!array_key_exists($name, get_object_vars($object)) AND ($name != $id) AND ($name != 'association') AND ($name != 'images') AND (strtolower($className) != 'cart'))
 484					unset($field[$name]);
 485			$return = $this->validateRules($rules, $field, $className, $languages, $defaultLanguage);
 486			$fields[$key] = $field;
 487			if (!empty($return))
 488			{
 489				//skip mode
 490				if (Tools::getValue('hasErrors') == 1)
 491					unset($fields[$key]);
 492
 493				$errors[] = $return;
 494				array_unshift($errors[sizeof($errors)-1], $field[$id]);
 495			}
 496		}
 497		if (sizeof($errors) > 0)
 498		{
 499			$json['hasError'] = true;
 500			$json['error'] = $errors;
 501		}
 502
 503		if ($save || Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
 504		{
 505			//add language if not exist in prestashop
 506			if ($className == 'Language')
 507			{
 508				if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
 509					$add = true;
 510				else
 511					$add = false;
 512				$errors = $this->checkAndAddLang($fields, $add);
 513			}
 514			elseif ($className == 'Cart')
 515			{
 516				$this->saveOrders($fields);
 517			}
 518			else
 519			{
 520				$return = $this->saveObject($className, $fields);
 521				$this->cleanPositions($table);
 522				//insert association
 523				if (array_key_exists('association', $this->supportedImports[strtolower($className)]))
 524					$this->insertAssociation(strtolower($className), $fields);
 525				if (!empty($return))
 526				{
 527					$json['hasError'] = true;
 528					$json['error'] = $return;
 529				}
 530			}
 531			if ($className == 'Category' AND (sizeof($fields) != (int)Tools::getValue('nbr_import')))
 532				$this->updateCat();
 533		}
 534		if (sizeof($errors) > 0 AND is_array($errors))
 535		{
 536			$json['hasError'] = true;
 537			$json['error'] = $errors;
 538		}
 539		die(Tools::jsonEncode($json));
 540	}
 541	public function genericImportWS($className, $fields, $save = false)
 542	{
 543
 544		$return = '';
 545		$json = array();
 546		$errors = array();
 547		$json['hasError'] = false;
 548		$json['datas'] = array_values($fields);
 549		$languages = array();
 550		$defaultLanguage = '';
 551		$table = $this->supportedImports[strtolower($className)]['table'];
 552
 553		$object = new $className();
 554
 555		$rules = call_user_func(array($className, 'getValidationRules'), $className);
 556
 557
 558		if ((sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang']) || Tools::isSubmit('syncLangWS') ||  Tools::isSubmit('syncCurrency')))
 559		{
 560			$moduleName = Tools::getValue('moduleName');
 561			if (Validate::isModuleName($moduleName) && file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
 562			{
 563
 564				require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
 565				$importModule = new $moduleName();
 566
 567				$defaultLanguage = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
 568
 569				$languages = $importModule->getLangagues();
 570
 571				if (Tools::isSubmit('syncLangWS'))
 572				{
 573					$defaultIdLand = $importModule->getDefaultIdLang();
 574					$defaultLanguageImport = new Language(Language::getIdByIso($languages[$defaultIdLand]['iso_code']));
 575					if ($defaultLanguage->iso_code != $defaultLanguageImport->iso_code)
 576						$errors[] = $this->l('Default language doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultLanguage->name.' ?
 577											'.$importModule->displayName.' : '.$defaultLanguageImport->name.'<br>'.$this->l('Please change default language in your configuration');
 578				}
 579
 580				if (Tools::isSubmit('syncCurrency'))
 581				{
 582					$defaultIdCurrency = $importModule->getDefaultIdCurrency();
 583					$currencies = $importModule->getCurrencies();
 584					if (!empty($currencies[$defaultIdCurrency]['iso_code']))
 585						$defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCode($currencies[$defaultIdCurrency]['iso_code']));
 586					else
 587						$defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCodeNum($currencies[$defaultIdCurrency]['iso_code_num']));
 588
 589					$defaultCurrency = new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'));
 590					if ($defaultCurrency->iso_code != $defaultCurrencyImport->iso_code)
 591						$errors[] = $this->l('Default currency doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultCurrency->name.' ? '.$importModule->displayName.' : '.$defaultCurrencyImport->name.'<br>'.$this->l('Please change default currency in your configuration');
 592				}
 593				if (!empty($errors))
 594					die('{"hasError" : true, "error" : '.Tools::jsonEncode($errors).'}');
 595			}
 596			else
 597				die('{"hasError" : true, "error" : ["FATAL ERROR"], "datas" : []}');
 598		}
 599
 600		foreach($fields as $key => $field)
 601		{
 602			$id = $this->supportedImports[strtolower($className)]['identifier'];
 603			//remove wrong fields (ex : id_toto in Customer)
 604			foreach($field as $name => $value)
 605				if (!array_key_exists($name, get_object_vars($object)) AND ($name != $id) AND ($name != 'association') AND ($name != 'images') AND (strtolower($className) != 'cart'))
 606					unset($field[$name]);
 607			$return = $this->validateRules($rules, $field, $className, $languages, $defaultLanguage);
 608			$fields[$key] = $field;
 609			if (!empty($return))
 610			{
 611				//skip mode
 612				if (Tools::getValue('hasErrors') == 1)
 613					unset($fields[$key]);
 614
 615				$errors[] = $return;
 616				array_unshift($errors[sizeof($errors)-1], $field[$id]);
 617			}
 618		}
 619		if (sizeof($errors) > 0)
 620		{
 621			$json['hasError'] = true;
 622			$json['error'] = $errors;
 623		}
 624		if ($save || Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
 625		{
 626			//add language if not exist in prestashop
 627			if ($className == 'Language')
 628			{
 629				if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
 630					$add = true;
 631				else
 632					$add = false;
 633				$errors = $this->checkAndAddLang($fields, $add);
 634			}
 635			elseif ($className == 'Cart')
 636			{
 637				$this->saveOrders($fields);
 638			}
 639			else
 640			{
 641				$return = $this->saveObject($className, $fields);
 642				$this->cleanPositions($table);
 643				//insert association
 644				if (array_key_exists('association', $this->supportedImports[strtolower($className)]))
 645					$this->insertAssociation(strtolower($className), $fields);
 646				if (!empty($return))
 647				{
 648					$json['hasError'] = true;
 649					$json['error'] = $return;
 650				}
 651			}
 652			if ($className == 'Category' AND (sizeof($fields) != (int)Tools::getValue('nbr_import')))
 653				$this->updateCat();
 654		}
 655		if (sizeof($errors) > 0 AND is_array($errors))
 656		{
 657			$json['hasError'] = true;
 658			$json['error'] = $errors;
 659		}
 660		die(Tools::jsonEncode($json));
 661	}
 662
 663	private function saveObject($className, $items)
 664	{
 665		$return = array();
 666		$table = $this->supportedImports[strtolower($className)]['table'];
 667		//creating temporary fields for identifiers matching and password
 668		if (array_key_exists('alterTable', $this->supportedImports[strtolower($className)]))
 669			$this->alterTable(strtolower($className));
 670		$matchIdLang = $this->getMatchIdLang(1);
 671		foreach($items as $item)
 672		{
 673			$object = new $className;
 674			$id = $item[$this->supportedImports[strtolower($className)]['identifier']];
 675			if (array_key_exists('foreign_key', $this->supportedImports[strtolower($className)]))
 676				$this->replaceForeignKey($item, $table);
 677
 678			foreach($item as $key => $val)
 679			{
 680				if ($key == 'passwd')
 681				{
 682					$password = $val;
 683					$val = '------';
 684				}
 685				if (is_array($val) AND $key != 'images')
 686				{
 687					$tmp = array();
 688					foreach($matchIdLang as $k => $v)
 689						{
 690						if (array_key_exists($k, $val))
 691						{
 692							$tmp[$v] = $val[$k];
 693						}
 694				}
 695
 696					$object->$key = $tmp;
 697				}
 698				else
 699					$object->$key = $val;
 700			}
 701			if (!$object->save(false, false))
 702				$return[] = array($item[$this->supportedImports[strtolower($className)]['identifier']], $this->l('An error occurred when adding the object'));
 703			else
 704			{
 705				$this->saveMatchId(strtolower($className), (int)$object->id, (int)$id);
 706				if ($className == 'Customer')
 707					Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'customer SET `passwd_'.bqSQL(Tools::getValue('moduleName')).'` = \''.pSQL($password).'\' WHERE id_customer = '.(int)$object->id);
 708				if (array_key_exists('hasImage', $this->supportedImports[strtolower($className)]) AND Tools::isSubmit('images_'.$className))
 709					$this->copyImg($item, $className);
 710			}
 711		}
 712		return $return;
 713	}
 714
 715	private function saveOrders($items)
 716	{
 717		$this->saveObject('cart', $items);
 718		//import cart product
 719		$foreignKey = $this->getForeignKey('Cart', array('id_cart', 'id_product', 'id_product_attribute', 'id_customer','id_address_invoice', 'id_address_delivery'));
 720		foreach($items as &$item)
 721		{
 722			foreach($item['cart_products'] as $k => $cart_products)
 723			{
 724				foreach($cart_products as $key => $val)
 725					if (array_key_exists($key, $foreignKey))
 726						if (array_key_exists($val, $foreignKey[$key]))
 727							$item['cart_products'][$k][$key] = $foreignKey[$key][$val];
 728						else
 729							$item['cart_products'][$k][$key] = 0;
 730				Db::getInstance()->insert('cart_product', $item['cart_products'][$k]);
 731			}
 732			foreach($item['order_products'] as $k => $order_products)
 733			{
 734				foreach($order_products as $key => $val)
 735					if (array_key_exists($key, $foreignKey) || $key == 'product_id')
 736						//patch to correct a mistake naming column in the database
 737						if ($key == 'product_id')
 738							$item['order_products'][$k]['product_id'] =  $foreignKey['id_product'][$val];
 739						elseif (array_key_exists($val, $foreignKey[$key]))
 740							$item['order_products'][$k][$key] = $foreignKey[$key][$val];
 741						else
 742							$item['order_products'][$k][$key] = 0;
 743			}
 744		}
 745		//cart to order
 746		$this->cartToOrder($items, $foreignKey);
 747		$foreignKey = array_merge($this->getForeignKey('Cart', array('id_order', 'id_order_state')), $foreignKey);
 748		foreach($items as &$item)
 749		{
 750			//insert product in order detail
 751			foreach($item['order_products'] as $k => $order_products)
 752			{
 753				foreach($order_products as $key => $val)
 754					if (array_key_exists($key, $foreignKey))
 755						if (array_key_exists($val, $foreignKey[$key]))
 756							$item['order_products'][$k][$key] = $foreignKey[$key][$val];
 757						else
 758							$item['order_products'][$k][$key] = 0;
 759				Db::getInstance()->insert('order_detail', $item['order_products'][$k]);
 760			}
 761			//save order history
 762			foreach($item['order_history'] as $k => $order_history)
 763			{
 764				foreach($order_history as $key => $val)
 765					if (array_key_exists($key, $foreignKey))
 766						if (array_key_exists($val, $foreignKey[$key]))
 767							$item['order_history'][$k][$key] = $foreignKey[$key][$val];
 768						else
 769							$item['order_history'][$k][$key] = 0;
 770
 771				Db::getInstance()->insert('order_history', $item['order_history'][$k]);
 772			}
 773		}
 774	}
 775
 776	private function insertAssociation($table, $items)
 777	{
 778		foreach($this->supportedImports[$table]['association'] AS $association)
 779		{
 780			$associatFields = '';
 781			$associatFieldsName = implode('`, `', $association['fields']);
 782			$tableAssociation = $association['table'];
 783			$matchTable = $association['matchTable'];
 784			if (!empty($items))
 785			{
 786				$match = array();
 787				foreach($matchTable as $mTable)
 788				{
 789					$tmp = $this->getForeignKey($mTable, array('id_'.$mTable));
 790					if (array_key_exists('id_'.$mTable, $tmp))
 791						$match['id_'.$mTable] = $tmp['id_'.$mTable];
 792					else
 793						$match['id_'.$mTable] = $this->getDefaultId($table);
 794				}
 795				foreach($items AS $item)
 796					foreach($item AS $key => $val)
 797						if ($key == 'association' AND !empty($key))
 798							foreach($val[$tableAssociation] AS $k => $v)
 799							{
 800								$associatFields .= ' ('.((array_key_exists($k, $match[$association['fields'][0]])) ? (int)$match[$association['fields'][0]][$k] : '1').', ';
 801								$associatFields .= (int)$match[$association['fields'][1]][$v].'), ';
 802							}
 803				if ($associatFields != '')
 804					Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.bqSQL($tableAssociation).'` (`'.$associatFieldsName.'`) VALUES '.rtrim($associatFields, ', '));
 805			}
 806		}
 807	}
 808
 809	private function saveMatchId($className, $psId, $matchId)
 810	{
 811		$table = $this->supportedImports[$className]['table'];
 812		$moduleName = Tools::getValue('moduleName');
 813		$identifier = $this->supportedImports[$className]['identifier'];
 814		Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.bqSQL($table).'` SET `'.bqSQL($identifier).'_'.bqSQL($moduleName).'` =  '.(int)$matchId.' WHERE `'.bqSQL($identifier).'` = '.(int)$psId);
 815	}
 816
 817	private function getMatchId($className)
 818	{
 819		$table = $this->supportedImports[$className]['table'];
 820		$moduleName = Tools::getValue('moduleName');
 821		$identifier = $this->supportedImports[$className]['identifier'];
 822		$returns = Db::getInstance()->executeS('SELECT `'.bqSQL($identifier).'_'.bqSQL($moduleName).'`, `'.bqSQL($identifier).'` FROM `'._DB_PREFIX_.bqSQL($table).'` WHERE `'.bqSQL($identifier).'_'.bqSQL($moduleName).'` != 0 ');
 823		$match = array();
 824		foreach($returns as $return)
 825			$match[$return[$identifier.'_'.$moduleName]] = $return[$identifier];
 826		return $match;
 827	}
 828
 829	private function getDefaultId($table)
 830	{
 831		$defaultId = 1;
 832		if (array_key_exists('defaultId', $this->supportedImports[strtolower($table)]))
 833				$defaultId = Configuration::get($this->supportedImports[strtolower($table)]['defaultId']);
 834		return $defaultId;
 835	}
 836
 837	private function copyImg($item, $className)
 838	{
 839		require_once('../../images.inc.php');
 840		$identifier = $this->supportedImports[strtolower($className)]['identifier'];
 841		$matchId = $this->getMatchId(strtolower($className));
 842		$matchIdLang = $this->getMatchIdLang();
 843		switch($className)
 844		{
 845			default:
 846			case 'Product':
 847				$path = _PS_PROD_IMG_DIR_;
 848				$type = 'products';
 849			break;
 850			case 'Category':
 851				$path = _PS_CAT_IMG_DIR_;
 852				$type = 'categories';
 853			break;
 854			case 'Manufacturer':
 855				$path = _PS_MANU_IMG_DIR_;
 856				$type = 'manufacturers';
 857			break;
 858			case 'Supplier':
 859				$path = _PS_SUPP_IMG_DIR_;
 860				$type = 'suppliers';
 861			break;
 862		}
 863		$cover = 1;
 864		if (array_key_exists($item[$identifier], $matchId))
 865			if(array_key_exists('images', $item) && !is_null($item['images']))
 866			foreach($item['images'] as $key => $image)
 867			{
 868				$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'import');
 869					if (@copy(str_replace(' ', '%20', $image), $tmpfile))
 870				{
 871
 872					$imagesTypes = ImageType::getImagesTypes($type);
 873					ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'.jpg');
 874					if ($className == 'Product')
 875					{
 876						$image = new Image();
 877						$image->id_product = (int)($matchId[$item[$identifier]]);
 878						$image->cover = $cover;
 879						$image->position = Image::getHighestPosition((int)$matchId[$item[$identifier]]) + 1;
 880						$legend = array();
 881						foreach($item['name'] as $key => $val)
 882							if (array_key_exists($key, $matchIdLang))
 883								$legend[$matchIdLang[$key]] = Tools::link_rewrite($val);
 884							else
 885								$legend[Configuration::get('PS_LANG_DEFAULT')] = Tools::link_rewrite($val);
 886						$image->legend = $legend;
 887						$image->add();
 888						ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.(int)$image->id.'.jpg');
 889						foreach ($imagesTypes AS $k => $imageType)
 890							ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.(int)$image->id.'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']);
 891					}
 892					else
 893						foreach ($imagesTypes as $imageType)
 894							ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']);
 895				}
 896				else
 897					@unlink($tmpfile);
 898				@unlink($tmpfile);
 899				$cover = 0;
 900			}
 901
 902	}
 903
 904	private function replaceForeignKey(&$item, $table)
 905	{
 906		if ($table == 'product_attribute')
 907			$table2 = 'combination';
 908		else
 909			$table2 = $table;
 910
 911		$foreingKey = $this->supportedImports[$table2]['foreign_key'];
 912		$foreingKeyValue = $this->getForeignKey($table, $foreingKey);
 913		foreach($foreingKey as $key)
 914		{
 915			if ($table == 'product' AND $key == 'id_category')
 916				$key2 = 'id_category_default';
 917			else if ($table == 'customer' AND $key == 'id_group')
 918				$key2 = 'id_default_group';
 919			else
 920				$key2 = $key;
 921			if (array_key_exists($key, $foreingKeyValue) && $item[$key2] != 0)
 922				$item[$key2] = (array_key_exists($item[$key2], $foreingKeyValue[$key]) ? $item[$key2] = $foreingKeyValue[$key][$item[$key2]] : $item[$key2] = 0);
 923			else
 924				$item[$key2] = $this->getDefaultId($table);
 925		}
 926	}
 927
 928	private function alterTable($className)
 929	{
 930		$query ='';
 931		$queryTmp = '';
 932		$from = $this->supportedImports[$className]['table'];
 933		$result = array();
 934		$result = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.bqSQL($from).'`');
 935		if (!$result)
 936			$result = array();
 937		foreach ($this->supportedImports[$className]['alterTable'] AS $name => $type)
 938		{
 939			$moduleName = Tools::getValue('moduleName');
 940			Db::getInstance()->executeS("SHOW COLUMNS FROM `"._DB_PREFIX_.bqSQL($from)."` LIKE '".pSQL($name).'_'.pSQL($moduleName)."'");
 941			if (!Db::getInstance()->numRows() AND !array_key_exists($name.'_'.$moduleName, $result))
 942					$queryTmp .= ' ADD `'.$name.'_'.$moduleName.'` '.$type.' NOT NULL,';
 943		}
 944		if (!empty($queryTmp))
 945		{
 946			$query = 'ALTER TABLE  `'._DB_PREFIX_.bqSQL($from).'` ';
 947			$query .= rtrim($queryTmp, ',');
 948			Db::getInstance()->execute($query);
 949		}
 950	}
 951
 952	private function updateCat()
 953	{
 954		$moduleName = Tools::getValue('moduleName');
 955		Db::getInstance()->execute('UPDATE
 956									'._DB_PREFIX_.'category c
 957									INNER JOIN
 958									'._DB_PREFIX_.'category c2
 959									ON
 960									c.id_parent = c2.`id_category_'.bqSQL($moduleName).'`
 961									SET
 962									c.id_parent = c2.id_category
 963									WHERE c.`id_category_'.bqSQL($moduleName).'` != 0');
 964		$category = new Category();
 965		$cats = $category->getSimpleCategories((int)Configuration::get('PS_LANG_DEFAULT'));
 966		foreach($cats as $cat)
 967		{
 968			$cat = new Category((int)$cat['id_category']);
 969			$cat->level_depth = $cat->calcLevelDepth();
 970			$cat->update();
 971		}
 972	}
 973
 974	private function getForeignKey($className, $foreign_key = null)
 975	{
 976		$moduleName = Tools::getValue('moduleName');
 977		if (is_null($foreign_key))
 978			$foreign_key = $this->supportedImports[$className]['foreign_key'];
 979		$match = array();
 980		foreach($foreign_key AS $key)
 981		{
 982			if (in_array($key , array('id_address_invoice', 'id_address_delivery')))
 983				$key2 = 'id_address';
 984			elseif (in_array($key , array('id_category_default')))
 985				$key2 = 'id_category';
 986			else
 987				$key2 = $key;
 988			foreach($this->supportedImports AS $table => $conf)
 989				if ($conf['identifier'] == $key2)
 990					$from = $this->supportedImports[$table]['table'];
 991			$return = Db::getInstance()->executeS('SELECT `'.bqSQL($key2).'_'.bqSQL($moduleName).'`, `'.bqSQL($key2).'` FROM `'._DB_PREFIX_.bqSQL($from).'` WHERE `'.bqSQL($key2).'_'.bqSQL($moduleName).'` != 0');
 992			if (!empty($return))
 993				foreach($return AS $name => $val)
 994					$match[$key][$val[$key2.'_'.$moduleName]] = $val[$key2];
 995		}
 996		return $match;
 997	}
 998
 999	private function getForeignKeyLang($table)
1000	{
1001		$id = $this->supportedImports[$table]['identifier'];
1002		$moduleName = Tools::getValue('moduleName');
1003		$return = Db::getInstance()->executeS('SELECT `'.bqSQL($id).'_'.bqSQL($moduleName).'`, `'.bqSQL($id).'` FROM `'._DB_PREFIX_.bqSQL($table).'` WHERE `'.bqSQL($id).'_'.bqSQL($moduleName).'` != 0');
1004		$match = array();
1005		foreach($return AS $name => $val)
1006				$match[$val[$id.'_'.$moduleName]] = $val[$id];
1007		return $match;
1008	}
1009
1010	private function getMatchIdLang($order = 1)
1011	{
1012		$moduleName = Tools::getValue('moduleName');
1013		$return = Db::getInstance()->executeS('SELECT `id_lang`, `id_lang_'.bqSQL($moduleName).'` FROM `'._DB_PREFIX_.'lang'.'` WHERE `id_lang_'.bqSQL($moduleName).'` != 0');
1014		$match = array();
1015		foreach($return AS $name => $val)
1016			if ((bool)$order)
1017				$match[$val['id_lang_'.$moduleName]] = $val['id_lang'];
1018			else
1019				$match[$val['id_lang']] = $val['id_lang_'.$moduleName];
1020		return $match;
1021	}
1022
1023
1024	private function validateRules($rules, &$fields, $className, $languages, $defaultLanguage)
1025	{
1026		$returnErrors = array();
1027		$hasErrors = Tools::getValue('hasErrors');
1028		/* Checking for required fields */
1029		foreach ($rules['required'] AS $field)
1030			if (($value = $fields[$field]) == false AND (string)$value != '0')
1031				if ($hasErrors == 2)
1032				{
1033					if (array_key_exists($field, $rules['size']))
1034						$size = $rules['size'][$field];
1035					else
1036						$size = 1;
1037					$fields[$field] = $this->generateData($size, $rules['validate'][$field]);
1038				}
1039				else
1040					$returnErrors[] = sprintf(
1041						$this->l('The field %s is required.'),
1042						call_user_func(array($className, 'displayFieldName'), $field, $className)
1043					);
1044
1045		/* Checking for maximum fields sizes */
1046		foreach ($rules['size'] AS $field => $maxLength)
1047			if (array_key_exists($field, $fields) AND $field != 'passwd')
1048				if ($fields[$field] !== false AND Tools::strlen($fields[$field]) > $maxLength)
1049					if ($hasErrors == 2)
1050						$fields[$field] = substr($fields[$field], 0, $maxLength);
1051					else
1052						$returnErrors[] = sprintf(
1053							$this->l('The field %1$s is too long (%2$d chars max).'),
1054							call_user_func(array($className, 'displayFieldName'), $field, $className),
1055							$maxLength
1056						);
1057
1058		/* Checking for fields validity */
1059		foreach ($rules['validate'] AS $field => $function)
1060			if (array_key_exists($field, $fields))
1061				if (($value = $fields[$field]) !== false AND ($field != 'passwd'))
1062					if (!Validate::$function($value))
1063						if ($hasErrors == 2)
1064						{
1065							if (array_key_exists($field, $rules['size']))
1066								$size = $rules['size'][$field];
1067							else
1068								$size = 1;
1069							$fields[$field] = $this->generateData($size, $rules['validate'][$field]);
1070						}
1071						else
1072							$returnErrors[] = sprintf(
1073								$this->l('The field %s is invalid.'),
1074								call_user_func(array($className, 'displayFieldName'), $field, $className)
1075							);
1076
1077		if ((sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang'])))
1078		{
1079		$matchIdLang = $this->getMatchIdLang(0);
1080		/* Checking for multilingual required fields */
1081		foreach ($rules['requiredLang'] AS $fieldLang)
1082		{
1083			if (($empty = $fields[$fieldLang][$matchIdLang[$defaultLanguage->id]]) === false || empty($empty))
1084				if ($hasErrors == 2)
1085				{
1086					if (array_key_exists($fieldLang, $rules['sizeLang']))
1087						$size = $rules['sizeLang'][$fieldLang];
1088					else
1089						$size = 1;
1090					$fields[$fieldLang][$matchIdLang[$defaultLanguage->id]] = $this->generateData($size, $rules['validateLang'][$fieldLang]);
1091				}
1092				else
1093					$returnErrors[] = sprintf(
1094						$this->l('This field %1$s is required at least in %2$s'),
1095						call_user_func(array($className, 'displayFieldName'), $fieldLang, $className),
1096						$defaultLanguage->name
1097					);
1098		}
1099		/* Checking for maximum multilingual fields size */
1100		foreach ($rules['sizeLang'] AS $fieldLang => $maxLength)
1101			foreach ($languages AS $language)
1102				if (isset($fields[$fieldLang][$language['id_lang']]) && $fields[$fieldLang] !== false AND Tools::strlen($fields[$fieldLang][$language['id_lang']]) > $maxLength)
1103					if ($hasErrors == 2)
1104						$fields[$fieldLang] = substr($fields[$fieldLang], 0, $maxLength);
1105					else
1106						$returnErrors[] = sprintf(
1107							$this->l('This field %1$s (%2$s) is too long: %3$d chars max.'),
1108							call_user_func(array($className, 'displayFieldName'), $fieldLang, $className),
1109							$language['name'],
1110							$maxLength
1111						);
1112		foreach ($rules['validateLang'] AS $fieldLang => $function)
1113			{
1114			foreach ($languages AS $language)
1115			{
1116					if (array_key_exists($fieldLang, $fields) AND array_key_exists($language['id_lang'], $fields[$fieldLang]) AND ($value = $fields[$fieldLang][$language['id_lang']]) !== false AND !empty($value))
1117				{
1118					if (!Validate::$function($value))
1119						if ($hasErrors == 2)
1120						{
1121							if (array_key_exists($fieldLang, $rules['sizeLang']))
1122								$size = $rules['sizeLang'][$fieldLang];
1123							else
1124								$size = 1;
1125							$fields[$fieldLang][$language['id_lang']] = $this->generateData($size, $rules['validateLang'][$fieldLang]);
1126						}
1127						else
1128							$returnErrors[] = sprintf(
1129								$this->l('The field %1$s (%2$s) is invalid.'),
1130								call_user_func(array($className, 'displayFieldName'), $fieldLang, $className),
1131								$language['name']
1132							);
1133				}
1134			}
1135		}
1136		}
1137		return $returnErrors;
1138	}
1139
1140	private function validateRulesWS($rules, &$fields, $className, $languages, $defaultLanguage)
1141	{
1142		$returnErrors = array();
1143		$hasErrors = Tools::getValue('hasErrors');
1144		/* Checking for required fields */
1145		foreach ($rules['required'] AS $field)
1146			if (($value = $fields[$field]) == false AND (string)$value != '0')
1147				if ($hasErrors == 2)
1148				{
1149					if (array_key_exists($field, $rules['size']))
1150						$size = $rules['size'][$field];
1151					else
1152						$size = 1;
1153					$fields[$field] = $this->generateData($size, $rules['validate'][$field]);
1154				}
1155				else
1156					$returnErrors[] = sprintf(
1157						$this->l('The field %s is required.'),
1158						call_user_func(array($className, 'displayFieldName'), $field, $className)
1159					);
1160
1161		/* Checking for maximum fields sizes */
1162		foreach ($rules['size'] AS $field => $maxLength)
1163			if (array_key_exists($field, $fields) AND $field != 'passwd')
1164				if ($fields[$field] !== false AND Tools::strlen($fields[$field]) > $maxLength)
1165					if ($hasErrors == 2)
1166						$fields[$field] = substr($fields[$field], 0, $maxLength);
1167					else
1168						$returnErrors[] = sprintf(
1169							$this->l('The field %1$s is too long (%2$d chars max).'),
1170							call_user_func(array($className, 'displayFieldName'), $field, $className),
1171							$maxLength
1172						);
1173
1174		/* Checking for fields validity */
1175		foreach ($rules['validate'] AS $field => $function)
1176			if (array_key_exists($field, $fields))
1177				if (($value = $fields[$field]) !== false AND ($field != 'passwd'))
1178					if (!Validate::$function($value))
1179						if ($hasErrors == 2)
1180						{
1181							if (array_key_exists($field, $rules['size']))
1182								$size = $rules['size'][$field];
1183							else
1184								$size = 1;
1185							$fields[$field] = $this->generateData($size, $rules['validate'][$field]);
1186						}
1187						else
1188							$returnErrors[] = sprintf(
1189								$this->l('The field %s is invalid.'),
1190								call_user_func(array($className, 'displayFieldName'), $field, $className)
1191							);
1192
1193		return $returnErrors;
1194	}
1195	public function checkAndAddLang ($languages, $add = true)
1196	{
1197		$errors = '';
1198		$moduleName = Tools::getValue('moduleName');
1199		$this->alterTable('language');
1200		foreach($languages as $language)
1201		{
1202			$iso = $language['iso_code'];
1203			if (!Language::isInstalled($iso))
1204			{
1205				if ($add)
1206				{
1207					if (@fsockopen('www.prestashop.com', 80))
1208					{
1209						if ($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestasho…

Large files files are truncated, but you can click here to view the full file