protected function addressImportOne($info, $force_ids, $validateOnly = false) { AdminImportController::setDefaultValues($info); if ($force_ids && isset($info['id']) && (int) $info['id']) { $address = new Address((int) $info['id']); } else { if (array_key_exists('id', $info) && (int) $info['id'] && Address::addressExists((int) $info['id'])) { $address = new Address((int) $info['id']); } else { $address = new Address(); } } AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $address); if (isset($address->country) && is_numeric($address->country)) { if (Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), (int) $address->country)) { $address->id_country = (int) $address->country; } } elseif (isset($address->country) && is_string($address->country) && !empty($address->country)) { if ($id_country = Country::getIdByName(null, $address->country)) { $address->id_country = (int) $id_country; } else { $country = new Country(); $country->active = 1; $country->name = AdminImportController::createMultiLangField($address->country); $country->id_zone = 0; // Default zone for country to create $country->iso_code = Tools::strtoupper(Tools::substr($address->country, 0, 2)); // Default iso for country to create $country->contains_states = 0; // Default value for country to create $lang_field_error = $country->validateFieldsLang(UNFRIENDLY_ERROR, true); if (($field_error = $country->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $country->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $country->add()) { $address->id_country = (int) $country->id; } else { if (!$validateOnly) { $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT'); $this->errors[] = sprintf($this->trans('%s cannot be saved', array(), 'Admin.Parameters.Notification'), $country->name[$default_language_id]); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } } if (isset($address->state) && is_numeric($address->state)) { if (State::getNameById((int) $address->state)) { $address->id_state = (int) $address->state; } } elseif (isset($address->state) && is_string($address->state) && !empty($address->state)) { if ($id_state = State::getIdByName($address->state)) { $address->id_state = (int) $id_state; } else { $state = new State(); $state->active = 1; $state->name = $address->state; $state->id_country = isset($country->id) ? (int) $country->id : 0; $state->id_zone = 0; // Default zone for state to create $state->iso_code = Tools::strtoupper(Tools::substr($address->state, 0, 2)); // Default iso for state to create $state->tax_behavior = 0; if (($field_error = $state->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $state->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $state->add()) { $address->id_state = (int) $state->id; } else { if (!$validateOnly) { $this->errors[] = sprintf($this->trans('%s cannot be saved', array(), 'Admin.Parameters.Notification'), $state->name); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } } if (isset($address->customer_email) && !empty($address->customer_email)) { if (Validate::isEmail($address->customer_email)) { // a customer could exists in different shop $customer_list = Customer::getCustomersByEmail($address->customer_email); if (count($customer_list) == 0) { $this->errors[] = sprintf(Tools::displayError('%1$s does not exist in database %2$s (ID: %3$s), and therefore cannot be ' . ($validateOnly ? 'validated' : 'saved')), Db::getInstance()->getMsgError(), $address->customer_email, isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); } } else { $this->errors[] = sprintf($this->trans('"%s" is not a valid email address.', array(), 'Admin.Parameters.Notification'), $address->customer_email); return; } } elseif (isset($address->id_customer) && !empty($address->id_customer)) { if (Customer::customerIdExistsStatic((int) $address->id_customer)) { $customer = new Customer((int) $address->id_customer); // a customer could exists in different shop $customer_list = Customer::getCustomersByEmail($customer->email); if (count($customer_list) == 0) { $this->errors[] = sprintf(Tools::displayError('%1$s does not exist in database %2$s (ID: %3$s), and therefore cannot be ' . ($validateOnly ? 'validated' : 'saved')), Db::getInstance()->getMsgError(), $customer->email, (int) $address->id_customer); } } else { $this->errors[] = sprintf(Tools::displayError('The customer ID #%d does not exist in the database, and therefore cannot be ' . ($validateOnly ? 'validated' : 'saved')), $address->id_customer); } } else { $customer_list = array(); $address->id_customer = 0; } if (isset($address->manufacturer) && is_numeric($address->manufacturer) && Manufacturer::manufacturerExists((int) $address->manufacturer)) { $address->id_manufacturer = (int) $address->manufacturer; } elseif (isset($address->manufacturer) && is_string($address->manufacturer) && !empty($address->manufacturer)) { if ($manufacturerId = Manufacturer::getIdByName($address->manufacturer)) { $address->id_manufacturer = $manufacturerId; } else { $manufacturer = new Manufacturer(); $manufacturer->name = $address->manufacturer; if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $manufacturer->add()) { $address->id_manufacturer = (int) $manufacturer->id; } else { if (!$validateOnly) { $this->errors[] = Db::getInstance()->getMsgError() . ' ' . sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null'); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } } if (isset($address->supplier) && is_numeric($address->supplier) && Supplier::supplierExists((int) $address->supplier)) { $address->id_supplier = (int) $address->supplier; } elseif (isset($address->supplier) && is_string($address->supplier) && !empty($address->supplier)) { if ($supplierId = Supplier::getIdByName($address->supplier)) { $address->id_supplier = $supplierId; } else { $supplier = new Supplier(); $supplier->name = $address->supplier; if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $supplier->add()) { $address->id_supplier = (int) $supplier->id; } else { if (!$validateOnly) { $this->errors[] = Db::getInstance()->getMsgError() . ' ' . sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null'); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } } $res = false; if (($field_error = $address->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $address->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $address->force_id = (bool) $force_ids; if (isset($customer_list) && count($customer_list) > 0) { $filter_list = array(); foreach ($customer_list as $customer) { if (in_array($customer['id_customer'], $filter_list)) { continue; } $filter_list[] = $customer['id_customer']; $address->id_customer = $customer['id_customer']; } } if ($address->id && $address->addressExists($address->id)) { $res = $validateOnly || $address->update(); } if (!$res) { $res = $validateOnly || $address->add(); } } if (!$res) { if (!$validateOnly) { $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $info['alias'], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); } if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } }
public function addressImport() { $this->receiveTab(); $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT'); $handle = $this->openCsvFile(); self::setLocale(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) { if (Tools::getValue('convert')) { $line = $this->utf8_encode_array($line); } $info = self::getMaskedRow($line); self::setDefaultValues($info); $address = new Address(); self::array_walk($info, array('AdminImport', 'fillInfo'), $address); if (isset($address->country) and is_numeric($address->country)) { if (Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), (int) $address->country)) { $address->id_country = (int) $address->country; } } elseif (isset($address->country) and is_string($address->country) and !empty($address->country)) { if ($id_country = Country::getIdByName(NULL, $address->country)) { $address->id_country = (int) $id_country; } else { $country = new Country(); $country->active = 1; $country->name = self::createMultiLangField($address->country); $country->id_zone = 0; // Default zone for country to create $country->iso_code = strtoupper(substr($address->country, 0, 2)); // Default iso for country to create $country->contains_states = 0; // Default value for country to create $langFieldError = $country->validateFieldsLang(UNFRIENDLY_ERROR, true); if (($fieldError = $country->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $country->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $country->add()) { $address->id_country = (int) $country->id; } else { $this->_errors[] = $country->name[$defaultLanguageId] . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } } if (isset($address->state) and is_numeric($address->state)) { if (State::getNameById((int) $address->state)) { $address->id_state = (int) $address->state; } } elseif (isset($address->state) and is_string($address->state) and !empty($address->state)) { if ($id_state = State::getIdByName($address->state)) { $address->id_state = (int) $id_state; } else { $state = new State(); $state->active = 1; $state->name = $address->state; $state->id_country = isset($country->id) ? (int) $country->id : 0; $state->id_zone = 0; // Default zone for state to create $state->iso_code = strtoupper(substr($address->state, 0, 2)); // Default iso for state to create $state->tax_behavior = 0; if (($fieldError = $state->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $state->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $state->add()) { $address->id_state = (int) $state->id; } else { $this->_errors[] = $state->name . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } } if (isset($address->customer_email) and !empty($address->customer_email)) { if (Validate::isEmail($address->customer_email)) { $customer = Customer::customerExists($address->customer_email, true); if ($customer) { $address->id_customer = (int) $customer; } else { $this->_errors[] = mysql_error() . ' ' . $address->customer_email . ' ' . Tools::displayError('does not exist in database') . ' ' . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); } } else { $this->_errors[] = '"' . $address->customer_email . '" :' . Tools::displayError('Is not a valid Email'); } } if (isset($address->manufacturer) and is_numeric($address->manufacturer) and Manufacturer::manufacturerExists((int) $address->manufacturer)) { $address->id_manufacturer = (int) $address->manufacturer; } elseif (isset($address->manufacturer) and is_string($address->manufacturer) and !empty($address->manufacturer)) { $manufacturer = new Manufacturer(); $manufacturer->name = $address->manufacturer; if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) { $address->id_manufacturer = (int) $manufacturer->id; } else { $this->_errors[] = mysql_error() . ' ' . $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } if (isset($address->supplier) and is_numeric($address->supplier) and Supplier::supplierExists((int) $address->supplier)) { $address->id_supplier = (int) $address->supplier; } elseif (isset($address->supplier) and is_string($address->supplier) and !empty($address->supplier)) { $supplier = new Supplier(); $supplier->name = $address->supplier; if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) { $address->id_supplier = (int) $supplier->id; } else { $this->_errors[] = mysql_error() . ' ' . $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } $res = false; if (($fieldError = $address->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $address->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { if ($address->id and $address->addressExists($address->id)) { $res = $address->update(); } if (!$res) { $res = $address->add(); } } if (!$res) { $this->_errors[] = $info['alias'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } $this->closeCsvFile($handle); }
} $line = rtrim($line); if (empty($line)) { continue; } if ($line[0] != '\t') { $id = strtolower(substr($line, 0, 4)); $name = addslashes(trim(substr($line, 4))); if ($registeredid->getFromDBByQuery("WHERE `itemtype` = 'Manufacturer' AND `name` = '$id' AND `device_type` = '$type'")) { $manufacturer->getFromDB($registeredid->fields['items_id']); } else { if (!$manufacturer->getFromDBByQuery("WHERE `name` = '$name'")) { $input = array('name' => $name); $manufacturer->add($input); } $input = array('itemtype' => $manufacturer->getType(), 'items_id' => $manufacturer->getID(), 'device_type' => $type, 'name' => $id); $registeredid->add($input); } continue; } // if (($line[0] == "\t") && ($line[1] != '\t')) { // $line = trim($line); // $id = strtolower(substr($line, 0, 4)); // $name = addslashes(trim(substr($line, 4))); // continue; // }
/** Generate bigdump : generate global dropdowns **/ function generateGlobalDropdowns() { global $MAX, $DB; $items = array("CD", "CD-RW", "DVD-R", "DVD+R", "DVD-RW", "DVD+RW", "ramette papier", "disk'ette", "ZIP"); $dp = new ConsumableItemType(); for ($i=0 ; $i<$MAX['consumable_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d' consommable $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("phone d'power"); $dp = new PhonePowerSupply(); for ($i=0 ; $i<$MAX['phone_power'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "power ' $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Grand", "Moyen", "Mic'ro", "1U", "5U"); $dp = new DeviceCaseType(); for ($i=0 ; $i<$MAX['case_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "power ' $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Laser", "Jet d'Encre", "Encre Solide"); $dp = new CartridgeItemType(); for ($i=0 ; $i<$MAX['cartridge_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d' cartouche $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Technicien", "Commercial", "Technico-Commercial", "President", "Secretaire", "Directeur d'agence"); $dp = new ContactType(); for ($i=0 ; $i<$MAX['contact_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d' contact $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Maintenance", "Support", "Location", "Adhesion"); $dp = new ContractType(); for ($i=0 ; $i<$MAX['contract_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d' crontact $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Fournisseur", "Transporteur", "SSII", "Revendeur d'", "Assembleur", "SSLL", "Financeur", "Assureur"); $dp = new SupplierType(); for ($i=0 ; $i<$MAX['enttype'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d'entreprise $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("H.07.02", "I.07.56", "P51", "P52", "1.60", "4.06", "43-4071299", "1.0.14", "3.0.1", "rev 1.0", "rev 1.1", "rev 1.2", "rev 1.2.1", "rev 2.0", "rev 3.0"); $dp = new NetworkEquipmentFirmware(); for ($i=0 ; $i<$MAX['firmware'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "firmware $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Fire'wire"); $dp = new InterfaceType(); for ($i=0 ; $i<$MAX['interface'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d' disque dur $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("100 Base TX", "100 Base T4", "10 base T", "1000 Base SX", "1000 Base LX", "1000 Base T", "ATM", "802.3 10 Base 2", "IEEE 803.3 10 Base 5"); $dp = new NetworkInterface(); for ($i=0 ; $i<$MAX['iface'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type carte reseau $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Non", "Oui - generique", "Oui - specifique d'entite"); $dp = new AutoUpdateSystem(); for ($i=0 ; $i<$MAX['auto_update'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de mise a jour '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Assemble", "Latitude C600", "Latitude C700", "VAIO FX601", "VAIO FX905P", "VAIO TR5MP", "L5000C", "A600K", "PowerBook G4"); $dp = new ComputerModel(); for ($i=0 ; $i<$MAX['model'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "Modele $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment' $val"))); } $items = array("4200 DTN", "4200 DN", "4200 N", "8400 ADP", "7300 ADP", "5550 DN", "PIXMA iP8500", "Stylus Color 3000", "DeskJet 5950"); $dp = new PrinterModel(); for ($i=0 ; $i<$MAX['model_printers'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "modele imprimante $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("LS902UTG", "MA203DT", "P97F+SB", "G220F", "10-30-75", "PLE438S-B0S", "PLE481S-W", "L1740BQ", "L1920P", "SDM-X73H"); $dp = new MonitorModel(); for ($i=0 ; $i<$MAX['model_monitors'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "modele moniteur $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("HP 4108GL", "HP 2524", "HP 5308", "7600", "Catalyst 4500", "Catalyst 2950", "Catalyst 3750", "Catalyst 6500"); $dp = new NetworkEquipmentModel(); for ($i=0 ; $i<$MAX['model_networking'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "modele materiel reseau $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("DCS-2100+", "DCS-2100G", "KD-P35B", "Optical 5000", "Cordless", "ASR 600", "ASR 375", "CS21", "MX5020", "VS4121", "T3030", "T6060"); $dp = new PeripheralModel(); for ($i=0 ; $i<$MAX['model_peripherals'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "modele peripherique $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Alcatel Temporis 22", "Aastra 5370ip", "Alcatel-Lucent 400 DECT Handset", "BlackBerry Curve 9300"); $dp = new PhoneModel(); for ($i=0 ; $i<$MAX['model_phones'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "modele phone $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment' $val"))); } $items = array("SIC", "LMS", "LMP", "LEA", "SP2MI", "STIC", "MATH", "ENS-MECA", "POUBELLE", "WIFI"); $dp = new Network(); for ($i=0 ; $i<$MAX['network'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "reseau $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Windows XP Pro SP2", "Linux (Debian)", "Mac OS X", "Linux (Mandriva 2006)", "Linux (Redhat)", "Windows 98", "Windows 2000", "Windows XP Pro SP1", "LINUX (Suse)", "Linux (Mandriva 10.2)"); $dp = new OperatingSystem(); for ($i=0 ; $i<$MAX['os'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "os $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("XP Pro", "XP Home", "10.0", "10.1", "10.2", "2006", "Sarge"); $dp = new operatingSystemVersion(); for ($i=0 ; $i<$MAX['os_version'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "osversion $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Service Pack 1", "Service Pack 2", "Service Pack 3", "Service Pack 4"); $dp = new OperatingSystemServicePack(); for ($i=0 ; $i<$MAX['os_sp'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "ossp $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("DDR2"); $dp = new DeviceMemoryType(); for ($i=0 ; $i<$MAX['ram_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de ram $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment' $val"))); } $items = array('Bureautique', 'Calcul', "logiciel d'antivirus", 'Multimédia'); $dp = new SoftwareCategory(); for ($i=0 ; $i<max(1,pow($MAX['softwarecategory'],1/2)) ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "category $i"; } $newID = $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['softwarecategory'],1/2)) ; $j++) { $newID2 = $dp->add(toolbox::addslashes_deep(array('name' => "s-category '$j", 'comment' => "comment d' $val s-category $j", 'softwarecategories_id' => $newID))); } } $MAX['rubdocs'] = getMaxItem('glpi_softwarecategories'); $dp = new SoftwareLicenseType(); for ($i=0 ; $i<$MAX['licensetype'] ; $i++) { $val = "type ' $i"; $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("SIC", "LMS", "LMP", "LEA", "SP2MI", "STIC", "MATH", "ENS-MECA", "POUBELLE", "WIFI"); $dp = new Vlan(); for ($i=0 ; $i<$MAX['vlan'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "VLAN $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val", 'tag' => $i))); } $items = array("Portable", "Desktop", "Tour"); $dp = new ComputerType(); for ($i=0 ; $i<$MAX['type_computers'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type ordinateur $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Laser A4", "Jet d'Encre", "Laser A3", "Encre Solide A4", "Encre Solide A3"); $dp = new PrinterType(); for ($i=0 ; $i<$MAX['type_printers'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type d'imprimante $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("TFT 17", "TFT 19", "TFT 21", "CRT 17", "CRT 19", "CRT 21", "CRT 15"); $dp = new MonitorType(); for ($i=0 ; $i<$MAX['type_monitors'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type ecran $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Switch", "Routeur", "Hub", "Borne Wifi", "borne d'accueil"); $dp = new NetworkEquipmentType(); for ($i=0 ; $i<$MAX['type_networking'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de materiel reseau '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Clavier", "Souris", "Webcam", "Enceintes", "Scanner", "Clef USB", "d'autres"); $dp = new PeripheralType(); for ($i=0 ; $i<$MAX['type_peripherals'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de peripheriques '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Analogique", "IP", ); $dp = new PhoneType(); for ($i=0 ; $i<$MAX['type_phones'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de phone $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("DELL", "HP", "IIYAMA", "CANON", "EPSON", "LEXMARK", "ASUS", "MSI"); $dp = new Manufacturer(); for ($i=0 ; $i<$MAX['manufacturer'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "manufacturer $i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment '$val"))); } $items = array("Ingénieur", "Stagiaire", "Secrétaire", "ouvrier d'atelier"); $dp = new UserCategory(); for ($i=0 ; $i<$MAX['user_type'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "user type d'$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Président", "Agent Comptable", "Directeur d'agence"); $dp = new UserTitle(); for ($i=0 ; $i<$MAX['user_title'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "user type '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); } $items = array("Documentation", "Facture", "Bon Livraison", "Bon commande", "Capture d'Ecran", "Dossier Technique"); $dp = new DocumentCategory(); for ($i=0 ; $i<max(1,pow($MAX['rubdocs'],1/2)) ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "category $i"; } $newID = $dp->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['rubdocs'],1/2)) ; $j++) { $newID2 = $dp->add(toolbox::addslashes_deep( array('name' => "s-category '$j", 'comment' => "comment d' $val s-category $j", 'documentcategories_id' => $newID))); } } $MAX['rubdocs'] = getMaxItem('glpi_documentcategories'); $dp = new ItilCategory(); // GLobal ticket categories : also specific ones by entity for ($i=0 ; $i<max(1,pow($MAX['tracking_category'],1/3)) ; $i++) { $newID = $dp->add(toolbox::addslashes_deep( array('name' => "category '$i", 'comment' => "comment ' category $i", 'is_recursive' => 1, 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1))); for ($j=0 ; $j<mt_rand(0,pow($MAX['tracking_category'],1/2)) ; $j++) { $newID2 = $dp->add(toolbox::addslashes_deep( array('name' => "s-category '$j", 'comment' => "comment 'category $i s-category $j", 'is_recursive' => 1, 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1, 'itilcategories_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['tracking_category'],1/2)) ; $k++) { $newID3 = $dp->add(toolbox::addslashes_deep( array('name' => "ss-category' $k", 'comment' => "comment ' category $i s-category $j ss-category $k", 'is_recursive' => 1, 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1, 'itilcategories_id' => $newID2))); } } } $query = "OPTIMIZE TABLE `glpi_itilcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_itilcategories"); $MAX['tracking_category'] = getMaxItem('glpi_itilcategories'); // DEVICE $items = array("Textorm 6A19", "ARIA", "SLK3000B-EU", "Sonata II", "TA-212", "TA-551", "TA-581", "TAC-T01", "CS-512", "Li PC-60891", "STT-TJ02S"); $dp = new DeviceCase(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "case $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment '$val", 'devicecasetypes_id' => mt_rand(0,$MAX["case_type"]), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer'])))); } $items = array("Escalade 8006-2LP", "Escalade 8506-4LP", "2810SA", "1210SA", "DuoConnect", "DU-420", "DUB-A2", "FastTrak SX4100B", "DC-395U", "TFU-H33PI"); $dp = new DeviceControl(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "control $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment ' $val", 'interfacetypes_id' => mt_rand(0,$MAX["interface"]), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer'])))); } $items = array("DUW1616", "DRW-1608P", "DW1625", "GSA-4160B", "GSA-4165B", "GSA-4167RBB", "SHW-16H5S", "SOHW-1673SX", "DVR-110D", "PX-716AL", "PX-755A"); $dp = new DeviceDrive(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "drive $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment '$val", 'is_writer' => mt_rand(0,1), 'speed' => mt_rand(0,60), 'interfacetypes_id' => mt_rand(0,$MAX["interface"]), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer'])))); } $items = array("A9250/TD", "AX550/TD", "Extreme N5900", "V9520-X/TD", "All-In-Wonder X800 GT", "GV-NX66256D", "GV-RX80256DE", "Excalibur 9600XT", "X1300 IceQ", "WinFast PX6200 TD", "Millenium 750","NX6600GT"); $dp = new DeviceGraphicCard(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "gfxcard $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment ' $val", 'interfacetypes_id' => mt_rand(0,$MAX["interface"]), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'memory_default' => 256*mt_rand(0,8)))); } $items = array("Deskstar 7K500", "Deskstar T7K250", "Atlas 15K II", "DiamondMax Plus", "SpinPoint P - SP2514N", "Barracuda 7200.9", "WD2500JS", "WD1600JB", "WD1200JD"); $dp = new DeviceHardDrive(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "hdd $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment' $val", 'interfacetypes_id' => mt_rand(0,$MAX["interface"]), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'capacity_default' => mt_rand(0,300), 'rpm' => mt_rand(0,15000), 'cache' => 51200*mt_rand(0,10)))); } $items = array("DFE-530TX", "DFE-538TX", "PWLA8492MF", "PWLA8492MT", "USBVPN1", "GA311", "FA511", "TEG-PCBUSR", "3C996-SX", "3C996B-T", "3C905C-TX-M"); $dp = new DeviceNetworkCard(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "iface $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment' $val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'bandwidth' => mt_rand(0,1000)))); } $items = array("AW8-MAX", "NV8", "AK86-L", "P4V88", "A8N-SLI", "A8N-VM", "K8V-MX", "K8N4-E", "P5LD2", "GA-K8NE", "GA-8I945P Pro", "D945PBLL", "SE7525GP2", "865PE Neo3-F", "K8N Neo4-F", "Thunder i7520 (S5360G2NR)", "Thunder K8SR - S2881UG2NR", "Tiger K8QS Pro - S4882UG2NR", "Tomcat i875PF (S5105G2NR)"); $dp = new DeviceMotherBoard(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "moboard $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment' $val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'chipset' => 'chipset '.mt_rand(0,1000)))); } $items = array("Instant TV Cardbus", "WinTV Express", "WinTV-NOVA-S-Plus", "WinTV-NOVA-T", "WinTV-PVR-150"); $dp = new DevicePci(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "pci $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment '$val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer'])))); } $items = array("DB-Killer PW335", "DB-Killer PW385", "NeoHE 380", "NeoHE 450", "Phantom 500-PEC", "TruePower 2.0 550", "Master RS-380", "EG375AX-VE-G-SFMA", "EG495AX"); $dp = new DevicePowerSupply(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "power $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment '$val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'power' => mt_rand(0,500).'W', 'is_atx' => mt_rand(0,1)))); } $items = array("Athlon 64 FX-57", "Athlon 64 FX-55", "Sempron 2400+", "Sempron 2600+", "Celeron D 325", "Celeron D 330J", "Pentium 4 530J", "Pentium 4 631", "Pentium D 830", "Pentium D 920"); $dp = new DeviceProcessor(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "processor $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment' $val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'frequence' => mt_rand(1000,3000), 'frequency_default' => 1000+200*mt_rand(0,10), 'nbcores_default' => mt_rand(1,8), 'nbthreads_default' => mt_rand(1,4), ))); } $items = array("CM2X256A-5400C4", "CMX1024-3200C2", "CMXP512-3200XL", "TWIN2X1024-4300C3PRO", "KTD-DM8400/1G", "KTH8348/1G", "KTD4400/256", "D6464D30A", "KTA-G5400/512", "KVR667D2N5/1G", "KVR133X64C3/256"); $dp = new DeviceMemory(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "ram $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment' $val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'frequence' => 100*mt_rand(0,10), 'size_default' => 1024*mt_rand(0,6), 'devicememorytypes_id' => mt_rand(1,$MAX['ram_type'])))); } $items = array("DDTS-100", "Audigy 2 ZS Platinum", "Audigy SE", "DJ Console Mk2", "Gamesurround Muse Pocket USB", "Phase 22", "X-Fi Platinum", "Live! 24-bit", "X-Fi Elite Pro"); $dp = new DeviceSoundCard(); for ($i=0 ; $i<$MAX['device'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "sndcard $i"; } $dp->add(toolbox::addslashes_deep( array('designation' => $val, 'is_recursive' => 1, 'comment' => "comment '$val", 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'type' => 'type '.mt_rand(0,100)))); } } // Fin generation global dropdowns
public function addressImport() { $this->receiveTab(); $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT'); $handle = $this->openCsvFile(); AdminImportController::setLocale(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) { if (Tools::getValue('convert')) { $line = $this->utf8EncodeArray($line); } $info = AdminImportController::getMaskedRow($line); AdminImportController::setDefaultValues($info); $address = new Address(); AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $address); if (isset($address->country) && is_numeric($address->country)) { if (Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), (int) $address->country)) { $address->id_country = (int) $address->country; } } elseif (isset($address->country) && is_string($address->country) && !empty($address->country)) { if ($id_country = Country::getIdByName(null, $address->country)) { $address->id_country = (int) $id_country; } else { $country = new Country(); $country->active = 1; $country->name = AdminImportController::createMultiLangField($address->country); $country->id_zone = 0; // Default zone for country to create $country->iso_code = Tools::strtoupper(Tools::substr($address->country, 0, 2)); // Default iso for country to create $country->contains_states = 0; // Default value for country to create $lang_field_error = $country->validateFieldsLang(UNFRIENDLY_ERROR, true); if (($field_error = $country->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $country->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $country->add()) { $address->id_country = (int) $country->id; } else { $this->errors[] = sprintf(Tools::displayError('%s cannot be saved'), $country->name[$default_language_id]); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } if (isset($address->state) && is_numeric($address->state)) { if (State::getNameById((int) $address->state)) { $address->id_state = (int) $address->state; } } elseif (isset($address->state) && is_string($address->state) && !empty($address->state)) { if ($id_state = State::getIdByName($address->state)) { $address->id_state = (int) $id_state; } else { $state = new State(); $state->active = 1; $state->name = $address->state; $state->id_country = isset($country->id) ? (int) $country->id : 0; $state->id_zone = 0; // Default zone for state to create $state->iso_code = Tools::strtoupper(Tools::substr($address->state, 0, 2)); // Default iso for state to create $state->tax_behavior = 0; if (($field_error = $state->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $state->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $state->add()) { $address->id_state = (int) $state->id; } else { $this->errors[] = sprintf(Tools::displayError('%s cannot be saved'), $state->name); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } if (isset($address->customer_email) && !empty($address->customer_email)) { if (Validate::isEmail($address->customer_email)) { // a customer could exists in different shop $customer_list = Customer::getCustomersByEmail($address->customer_email); if (count($customer_list) == 0) { $this->errors[] = sprintf(Tools::displayError('%1$s does not exist in database %2$s (ID: %3$s), and therefore cannot be saved.'), Db::getInstance()->getMsgError(), $address->customer_email, isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); } } else { $this->errors[] = sprintf(Tools::displayError('"%s" is not a valid email address.'), $address->customer_email); continue; } } elseif (isset($address->id_customer) && !empty($address->id_customer)) { if (Customer::customerIdExistsStatic((int) $address->id_customer)) { $customer = new Customer((int) $address->id_customer); // a customer could exists in different shop $customer_list = Customer::getCustomersByEmail($customer->email); if (count($customer_list) == 0) { $this->errors[] = sprintf(Tools::displayError('%1$s does not exist in database %2$s (ID: %3$s), and therefore cannot be saved.'), Db::getInstance()->getMsgError(), $customer->email, (int) $address->id_customer); } } else { $this->errors[] = sprintf(Tools::displayError('The customer ID #%d does not exist in the database, and therefore cannot be saved.'), $address->id_customer); } } else { $customer_list = array(); $address->id_customer = 0; } if (isset($address->manufacturer) && is_numeric($address->manufacturer) && Manufacturer::manufacturerExists((int) $address->manufacturer)) { $address->id_manufacturer = (int) $address->manufacturer; } elseif (isset($address->manufacturer) && is_string($address->manufacturer) && !empty($address->manufacturer)) { $manufacturer = new Manufacturer(); $manufacturer->name = $address->manufacturer; if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) { $address->id_manufacturer = (int) $manufacturer->id; } else { $this->errors[] = Db::getInstance()->getMsgError() . ' ' . sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } if (isset($address->supplier) && is_numeric($address->supplier) && Supplier::supplierExists((int) $address->supplier)) { $address->id_supplier = (int) $address->supplier; } elseif (isset($address->supplier) && is_string($address->supplier) && !empty($address->supplier)) { $supplier = new Supplier(); $supplier->name = $address->supplier; if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) { $address->id_supplier = (int) $supplier->id; } else { $this->errors[] = Db::getInstance()->getMsgError() . ' ' . sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } $res = false; if (($field_error = $address->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $address->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { if (isset($customer_list) && count($customer_list) > 0) { $filter_list = array(); foreach ($customer_list as $customer) { if (in_array($customer['id_customer'], $filter_list)) { continue; } $filter_list[] = $customer['id_customer']; unset($address->id); $address->id_customer = $customer['id_customer']; $res = $address->add(); if (!$res) { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $info['alias'], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); } } } else { $address->force_id = (bool) Tools::getValue('forceIDs'); if ($address->id && $address->addressExists($address->id)) { $res = $address->update(); } if (!$res) { $res = $address->add(); } } } if (!$res) { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $info['alias'], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } $this->closeCsvFile($handle); }
public function productImport() { $this->receiveTab(); $handle = $this->openCsvFile(); $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT'); $id_lang = Language::getIdByIso(Tools::getValue('iso_lang')); if (!Validate::isUnsignedId($id_lang)) { $id_lang = $default_language_id; } AdminImportController::setLocale(); $shop_ids = Shop::getCompleteListOfShopsID(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) { if (Tools::getValue('convert')) { $line = $this->utf8EncodeArray($line); } $info = AdminImportController::getMaskedRow($line); if (self::ignoreRow($info)) { continue; } if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) { $product = new Product((int) $info['id']); } elseif (Tools::getValue('match_ref') && array_key_exists('reference', $info)) { $datas = Db::getInstance()->getRow(' SELECT p.`id_product` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.`reference` = "' . pSQL($info['reference']) . '" '); if (isset($datas['id_product']) && $datas['id_product']) { $product = new Product((int) $datas['id_product']); } else { $product = new Product(); } } else { if (array_key_exists('id', $info) && is_string($info['id'])) { $prod = self::findProductByName($default_language_id, $info['id'], $info['name']); if ($prod['id_product']) { $info['id'] = (int) $prod['id_product']; } } if (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) { $product = new Product((int) $info['id']); $product->loadStockData(); $category_data = Product::getProductCategories((int) $product->id); if (is_array($category_data)) { foreach ($category_data as $tmp) { if (!isset($product->category) || !$product->category || is_array($product->category)) { $product->category[] = $tmp; } } } } else { $product = new Product(); } } AdminImportController::setEntityDefaultValues($product); AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product); if (!Shop::isFeatureActive()) { $product->shop = 1; } elseif (!isset($product->shop) || empty($product->shop)) { $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID()); } if (!Shop::isFeatureActive()) { $product->id_shop_default = 1; } else { $product->id_shop_default = (int) Context::getContext()->shop->id; } // link product to shops $product->id_shop_list = array(); foreach (explode($this->multiple_value_separator, $product->shop) as $shop) { if (!empty($shop) && !is_numeric($shop)) { $product->id_shop_list[] = Shop::getIdByName($shop); } elseif (!empty($shop)) { $product->id_shop_list[] = $shop; } } if ((int) $product->id_tax_rules_group != 0) { if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) { $address = $this->context->shop->getAddress(); $tax_manager = TaxManagerFactory::getManager($address, $product->id_tax_rules_group); $product_tax_calculator = $tax_manager->getTaxCalculator(); $product->tax_rate = $product_tax_calculator->getTotalRate(); } else { $this->addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID. You first need to create a group with this ID.')); } } if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int) $product->manufacturer)) { $product->id_manufacturer = (int) $product->manufacturer; } elseif (isset($product->manufacturer) && is_string($product->manufacturer) && !empty($product->manufacturer)) { if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) { $product->id_manufacturer = (int) $manufacturer; } else { $manufacturer = new Manufacturer(); $manufacturer->name = $product->manufacturer; if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) { $product->id_manufacturer = (int) $manufacturer->id; } else { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } if (isset($product->supplier) && is_numeric($product->supplier) && Supplier::supplierExists((int) $product->supplier)) { $product->id_supplier = (int) $product->supplier; } elseif (isset($product->supplier) && is_string($product->supplier) && !empty($product->supplier)) { if ($supplier = Supplier::getIdByName($product->supplier)) { $product->id_supplier = (int) $supplier; } else { $supplier = new Supplier(); $supplier->name = $product->supplier; $supplier->active = true; if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) { $product->id_supplier = (int) $supplier->id; $supplier->associateTo($product->id_shop_list); } else { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } if (isset($product->price_tex) && !isset($product->price_tin)) { $product->price = $product->price_tex; } elseif (isset($product->price_tin) && !isset($product->price_tex)) { $product->price = $product->price_tin; // If a tax is already included in price, withdraw it from price if ($product->tax_rate) { $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', ''); } } elseif (isset($product->price_tin) && isset($product->price_tex)) { $product->price = $product->price_tex; } if (!Configuration::get('PS_USE_ECOTAX')) { $product->ecotax = 0; } $properties = $product->productProperties(); if ((double) $properties['pp_unit_price_ratio'] > 0) { $product->unit_price = (double) $product->price / (double) $properties['pp_unit_price_ratio']; } if (isset($product->category) && is_array($product->category) && count($product->category)) { $product->id_category = array(); // Reset default values array foreach ($product->category as $value) { if (is_numeric($value)) { if (Category::categoryExists((int) $value)) { $product->id_category[] = (int) $value; } else { $category_to_create = new Category(); $category_to_create->id = (int) $value; $category_to_create->name = AdminImportController::createMultiLangField($value); $category_to_create->active = 1; $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]); $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite); if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) { $product->id_category[] = (int) $category_to_create->id; } else { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } } } elseif (is_string($value) && !empty($value)) { $category = Category::searchByPath($default_language_id, trim($value), $this, 'productImportCreateCat'); if ($category['id_category']) { $product->id_category[] = (int) $category['id_category']; } else { $this->errors[] = sprintf(Tools::displayError('%1$s cannot be saved'), trim($value)); } } } $product->id_category = array_values(array_unique($product->id_category)); } if (!isset($product->id_category_default) || !$product->id_category_default) { $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : (int) Configuration::get('PS_HOME_CATEGORY'); } $link_rewrite = is_array($product->link_rewrite) && isset($product->link_rewrite[$id_lang]) ? trim($product->link_rewrite[$id_lang]) : ''; $valid_link = Validate::isLinkRewrite($link_rewrite); if (isset($product->link_rewrite[$id_lang]) && empty($product->link_rewrite[$id_lang]) || !$valid_link) { $link_rewrite = Tools::link_rewrite($product->name[$id_lang]); if ($link_rewrite == '') { $link_rewrite = 'friendly-url-autogeneration-failed'; } } if (!$valid_link) { $this->warnings[] = sprintf(Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite); } if (!(Tools::getValue('match_ref') || Tools::getValue('forceIDs')) || !(is_array($product->link_rewrite) && count($product->link_rewrite) && !empty($product->link_rewrite[$id_lang]))) { $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite); } // replace the value of separator by coma if ($this->multiple_value_separator != ',') { if (is_array($product->meta_keywords)) { foreach ($product->meta_keywords as &$meta_keyword) { if (!empty($meta_keyword)) { $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword); } } } } // Convert comma into dot for all floating values foreach (Product::$definition['fields'] as $key => $array) { if ($array['type'] == Product::TYPE_FLOAT) { $product->{$key} = str_replace(',', '.', $product->{$key}); } } // Indexation is already 0 if it's a new product, but not if it's an update $product->indexed = 0; $res = false; $field_error = $product->validateFields(UNFRIENDLY_ERROR, true); $lang_field_error = $product->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($field_error === true && $lang_field_error === true) { // check quantity if ($product->quantity == null) { $product->quantity = 0; } // If match ref is specified && ref product && ref product already in base, trying to update if (Tools::getValue('match_ref') && $product->reference && $product->existsRefInDatabase($product->reference)) { $datas = Db::getInstance()->getRow(' SELECT product_shop.`date_add`, p.`id_product` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.`reference` = "' . pSQL($product->reference) . '" '); $product->id = (int) $datas['id_product']; $product->date_add = pSQL($datas['date_add']); $res = $product->update(); } elseif ($product->id && Product::existsInDatabase((int) $product->id, 'product')) { $datas = Db::getInstance()->getRow(' SELECT product_shop.`date_add` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.`id_product` = ' . (int) $product->id); $product->date_add = pSQL($datas['date_add']); $res = $product->update(); } // If no id_product or update failed $product->force_id = (bool) Tools::getValue('forceIDs'); if (!$res) { if (isset($product->date_add) && $product->date_add != '') { $res = $product->add(false); } else { $res = $product->add(); } } if ($product->getType() == Product::PTYPE_VIRTUAL) { StockAvailable::setProductOutOfStock((int) $product->id, 1); } else { StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock); } } $shops = array(); $product_shop = explode($this->multiple_value_separator, $product->shop); foreach ($product_shop as $shop) { if (empty($shop)) { continue; } $shop = trim($shop); if (!empty($shop) && !is_numeric($shop)) { $shop = Shop::getIdByName($shop); } if (in_array($shop, $shop_ids)) { $shops[] = $shop; } else { $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Shop is not valid')); } } if (empty($shops)) { $shops = Shop::getContextListShopID(); } // If both failed, mysql error if (!$res) { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID'); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); } else { // Product supplier if (isset($product->id) && $product->id && isset($product->id_supplier) && property_exists($product, 'supplier_reference')) { $id_product_supplier = (int) ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier); if ($id_product_supplier) { $product_supplier = new ProductSupplier($id_product_supplier); } else { $product_supplier = new ProductSupplier(); } $product_supplier->id_product = (int) $product->id; $product_supplier->id_product_attribute = 0; $product_supplier->id_supplier = (int) $product->id_supplier; $product_supplier->product_supplier_price_te = $product->wholesale_price; $product_supplier->product_supplier_reference = $product->supplier_reference; $product_supplier->save(); } // SpecificPrice (only the basic reduction feature is supported by the import) if (!Shop::isFeatureActive()) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } // Get shops for each attributes $info['shop'] = explode($this->multiple_value_separator, $info['shop']); $id_shop_list = array(); foreach ($info['shop'] as $shop) { if (!empty($shop) && !is_numeric($shop)) { $id_shop_list[] = (int) Shop::getIdByName($shop); } elseif (!empty($shop)) { $id_shop_list[] = $shop; } } if (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) { foreach ($id_shop_list as $id_shop) { $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, 0, 1, 0, 0, 0, 0); if (is_array($specific_price) && isset($specific_price['id_specific_price'])) { $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']); } else { $specific_price = new SpecificPrice(); } $specific_price->id_product = (int) $product->id; $specific_price->id_specific_price_rule = 0; $specific_price->id_shop = $id_shop; $specific_price->id_currency = 0; $specific_price->id_country = 0; $specific_price->id_group = 0; $specific_price->price = -1; $specific_price->id_customer = 0; $specific_price->from_quantity = 1; $specific_price->reduction = isset($info['reduction_price']) && $info['reduction_price'] ? $info['reduction_price'] : $info['reduction_percent'] / 100; $specific_price->reduction_type = isset($info['reduction_price']) && $info['reduction_price'] ? 'amount' : 'percentage'; $specific_price->from = isset($info['reduction_from']) && Validate::isDate($info['reduction_from']) ? $info['reduction_from'] : '0000-00-00 00:00:00'; $specific_price->to = isset($info['reduction_to']) && Validate::isDate($info['reduction_to']) ? $info['reduction_to'] : '0000-00-00 00:00:00'; if (!$specific_price->save()) { $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid')); } } } if (isset($product->tags) && !empty($product->tags)) { if (isset($product->id) && $product->id) { $tags = Tag::getProductTags($product->id); if (is_array($tags) && count($tags)) { if (!empty($product->tags)) { $product->tags = explode($this->multiple_value_separator, $product->tags); } if (is_array($product->tags) && count($product->tags)) { foreach ($product->tags as $key => $tag) { if (!empty($tag)) { $product->tags[$key] = trim($tag); } } $tags[$id_lang] = $product->tags; $product->tags = $tags; } } } // Delete tags for this id product, for no duplicating error Tag::deleteTagsForProduct($product->id); if (!is_array($product->tags) && !empty($product->tags)) { $product->tags = AdminImportController::createMultiLangField($product->tags); foreach ($product->tags as $key => $tags) { $is_tag_added = Tag::addTags($key, $product->id, $tags, $this->multiple_value_separator); if (!$is_tag_added) { $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Tags list is invalid')); break; } } } else { foreach ($product->tags as $key => $tags) { $str = ''; foreach ($tags as $one_tag) { $str .= $one_tag . $this->multiple_value_separator; } $str = rtrim($str, $this->multiple_value_separator); $is_tag_added = Tag::addTags($key, $product->id, $str, $this->multiple_value_separator); if (!$is_tag_added) { $this->addProductWarning(Tools::safeOutput($info['name']), (int) $product->id, 'Invalid tag(s) (' . $str . ')'); break; } } } } //delete existing images if "delete_existing_images" is set to 1 if (isset($product->delete_existing_images)) { if ((bool) $product->delete_existing_images) { $product->deleteImages(); } } if (isset($product->image) && is_array($product->image) && count($product->image)) { $product_has_images = (bool) Image::getImages($this->context->language->id, (int) $product->id); foreach ($product->image as $key => $url) { $url = trim($url); $error = false; if (!empty($url)) { $url = str_replace(' ', '%20', $url); $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$key && !$product_has_images ? true : false; // file_exists doesn't work with HTTP protocol if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) { // associate image to selected shops $image->associateTo($shops); if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) { $image->delete(); $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url); } } else { $error = true; } } else { $error = true; } if ($error) { $this->warnings[] = sprintf(Tools::displayError('Product #%1$d: the picture (%2$s) cannot be saved.'), $image->id_product, $url); } } } if (isset($product->id_category) && is_array($product->id_category)) { $product->updateCategories(array_map('intval', $product->id_category)); } $product->checkDefaultAttributes(); if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } // Features import $features = get_object_vars($product); if (isset($features['features']) && !empty($features['features'])) { foreach (explode($this->multiple_value_separator, $features['features']) as $single_feature) { if (empty($single_feature)) { continue; } $tab_feature = explode(':', $single_feature); $feature_name = isset($tab_feature[0]) ? trim($tab_feature[0]) : ''; $feature_value = isset($tab_feature[1]) ? trim($tab_feature[1]) : ''; $position = isset($tab_feature[2]) ? (int) $tab_feature[2] - 1 : false; $custom = isset($tab_feature[3]) ? (int) $tab_feature[3] : false; if (!empty($feature_name) && !empty($feature_value)) { $id_feature = (int) Feature::addFeatureImport($feature_name, $position); $id_product = null; if (Tools::getValue('forceIDs') || Tools::getValue('match_ref')) { $id_product = (int) $product->id; } $id_feature_value = (int) FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom); Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value); } } } // clean feature positions to avoid conflict Feature::cleanPositions(); // set advanced stock managment if (isset($product->advanced_stock_management)) { if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product %1$s '), $product->name[$default_language_id]); } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product %1$s '), $product->name[$default_language_id]); } else { $product->setAdvancedStockManagement($product->advanced_stock_management); } // automaticly disable depends on stock, if a_s_m set to disabled if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) { StockAvailable::setProductDependsOnStock($product->id, 0); } } // Check if warehouse exists if (isset($product->warehouse) && $product->warehouse) { if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse not set on product %1$s '), $product->name[$default_language_id]); } else { if (Warehouse::exists($product->warehouse)) { // Get already associated warehouses $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id); // Delete any entry in warehouse for this product foreach ($associated_warehouses_collection as $awc) { $awc->delete(); } $warehouse_location_entity = new WarehouseProductLocation(); $warehouse_location_entity->id_product = $product->id; $warehouse_location_entity->id_product_attribute = 0; $warehouse_location_entity->id_warehouse = $product->warehouse; if (WarehouseProductLocation::getProductLocation($product->id, 0, $product->warehouse) !== false) { $warehouse_location_entity->update(); } else { $warehouse_location_entity->save(); } StockAvailable::synchronize($product->id); } else { $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language_id]); } } } // stock available if (isset($product->depends_on_stock)) { if ($product->depends_on_stock != 0 && $product->depends_on_stock != 1) { $this->warnings[] = sprintf(Tools::displayError('Incorrect value for "depends on stock" for product %1$s '), $product->name[$default_language_id]); } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->depends_on_stock == 1) { $this->warnings[] = sprintf(Tools::displayError('Advanced stock management not enabled, cannot set "depends on stock" for product %1$s '), $product->name[$default_language_id]); } else { StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock); } // This code allows us to set qty and disable depends on stock if (isset($product->quantity) && $product->quantity) { // if depends on stock and quantity, add quantity to stock if ($product->depends_on_stock == 1) { $stock_manager = StockManagerFactory::getManager(); $price = str_replace(',', '.', $product->wholesale_price); if ($price == 0) { $price = 1.0E-6; } $price = round((double) $price, 6); $warehouse = new Warehouse($product->warehouse); if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, $product->quantity, 1, $price, true)) { StockAvailable::synchronize((int) $product->id); } } else { if (Shop::isFeatureActive()) { foreach ($shops as $shop) { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id); } } } } else { if (Shop::isFeatureActive()) { foreach ($shops as $shop) { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id); } } } } $this->closeCsvFile($handle); }
/** * @brief Import Parts (create Parts, and if neccessary, Categories, Footprints and so on) * * @note This function uses database transactions. If an error occurs, all changes will be rolled back. * * @param Database &$database reference to the database object * @param User &$current_user reference to the user which is logged in * @param Log &$log reference to the Log-object * @param array $data The import data array from "extract_import_data_from_request()" * @param boolean $only_check_data If true, this function will only check if all values in "$data" are valid. * In this case, no parts will be imported! * * @retval array All new Part objects (only if "$only_check_data == false") * * @throws Exception if there was an error (maybe the passed data is not valid) */ function import_parts(&$database, &$current_user, &$log, $data, $only_check_data = false) { $parts = array(); try { $transaction_id = $database->begin_transaction(); // start transaction // Get the category, footprint, storelocation, ... which are named "Import", or create them. // We need this elements as parent for new elements, which will be created while import parts. $import_categories = Category::search($database, $current_user, $log, 'Import', true); if (count($import_categories) > 0) { $import_category = $import_categories[0]; $import_category_created = false; } else { $import_category = Category::add($database, $current_user, $log, 'Import', NULL); $import_category_created = true; // we can delete it later if we didn't need it } $import_storelocations = Storelocation::search($database, $current_user, $log, 'Import', true); if (count($import_storelocations) > 0) { $import_storelocation = $import_storelocations[0]; $import_storelocation_created = false; } else { $import_storelocation = Storelocation::add($database, $current_user, $log, 'Import', NULL); $import_storelocation_created = true; // we can delete it later if we didn't need it } $import_footprints = Footprint::search($database, $current_user, $log, 'Import', true); if (count($import_footprints) > 0) { $import_footprint = $import_footprints[0]; $import_footprint_created = false; } else { $import_footprint = Footprint::add($database, $current_user, $log, 'Import', NULL); $import_footprint_created = true; // we can delete it later if we didn't need it } $import_suppliers = Supplier::search($database, $current_user, $log, 'Import', true); if (count($import_suppliers) > 0) { $import_supplier = $import_suppliers[0]; $import_supplier_created = false; } else { $import_supplier = Supplier::add($database, $current_user, $log, 'Import', NULL); $import_supplier_created = true; // we can delete it later if we didn't need it } $import_manufacturers = Manufacturer::search($database, $current_user, $log, 'Import', true); if (count($import_manufacturers) > 0) { $import_manufacturer = $import_manufacturers[0]; $import_manufacturer_created = false; } else { $import_manufacturer = Manufacturer::add($database, $current_user, $log, 'Import', NULL); $import_manufacturer_created = true; // we can delete it later if we didn't need it } $import_category_used = false; $import_storelocation_used = false; $import_footprint_used = false; $import_supplier_used = false; $import_manufacturer_used = false; // start import $row_index = 0; foreach ($data as $row) { $name = $row['part_name']; $description = $row['part_description']; $instock = $row['part_instock']; $mininstock = $row['part_mininstock']; $comment = $row['part_comment']; $category_name = $row['part_category_name']; $footprint_name = $row['part_footprint_name']; $storelocation_name = $row['part_storelocation_name']; $manufacturer_name = $row['part_manufacturer_name']; $supplier_name = $row['part_supplier_name']; $supplierpartnr = $row['part_supplierpartnr']; $price = $row['part_price']; // search elements / create them if they don't exist already if (strlen($category_name) > 0) { $categories = Category::search($database, $current_user, $log, $category_name, true); if (count($categories) > 0) { $category = $categories[0]; } else { $category = Category::add($database, $current_user, $log, $category_name, $import_category->get_id()); $import_category_used = true; } } else { throw new Exception('Jedes Bauteil muss eine Kategorie haben!'); } if (strlen($storelocation_name) > 0) { $storelocations = Storelocation::search($database, $current_user, $log, $storelocation_name, true); if (count($storelocations) > 0) { $storelocation = $storelocations[0]; } else { $storelocation = Storelocation::add($database, $current_user, $log, $storelocation_name, $import_storelocation->get_id()); $import_storelocation_used = true; } } if (strlen($manufacturer_name) > 0) { $manufacturers = Manufacturer::search($database, $current_user, $log, $manufacturer_name, true); if (count($manufacturers) > 0) { $manufacturer = $manufacturers[0]; } else { $manufacturer = Manufacturer::add($database, $current_user, $log, $manufacturer_name, $import_manufacturer->get_id()); $import_manufacturer_used = true; } } if (strlen($footprint_name) > 0) { $footprints = Footprint::search($database, $current_user, $log, $footprint_name, true); if (count($footprints) > 0) { $footprint = $footprints[0]; } else { $footprint = Footprint::add($database, $current_user, $log, $footprint_name, $import_footprint->get_id()); $import_footprint_used = true; } } if (strlen($supplier_name) > 0) { $suppliers = Supplier::search($database, $current_user, $log, $supplier_name, true); if (count($suppliers) > 0) { $supplier = $suppliers[0]; } else { $supplier = Supplier::add($database, $current_user, $log, $supplier_name, $import_supplier->get_id()); $import_supplier_used = true; } } else { if (strlen($supplierpartnr) > 0 || $price > 0) { throw new Exception('Ist eine Bestellnummer oder ein Preis angegeben, so muss auch ein Lieferant angegeben werden!'); } } $new_part = Part::add($database, $current_user, $log, $name, $category->get_id(), $description, $instock, $mininstock, isset($storelocation) ? $storelocation->get_id() : NULL, isset($manufacturer) ? $manufacturer->get_id() : NULL, isset($footprint) ? $footprint->get_id() : NULL, $comment); if (isset($supplier)) { $new_orderdetails = Orderdetails::add($database, $current_user, $log, $new_part->get_id(), $supplier->get_id(), $supplierpartnr); if ($price > 0) { $new_pricedetails = Pricedetails::add($database, $current_user, $log, $new_orderdetails->get_id(), $price); } } if (!$only_check_data) { $parts[] = $new_part; } $row_index++; } // delete all elements which were created in this function, but were not used if ($import_category_created && !$import_category_used) { $import_category->delete(); } if ($import_storelocation_created && !$import_storelocation_used) { $import_storelocation->delete(); } if ($import_footprint_created && !$import_footprint_used) { $import_footprint->delete(); } if ($import_supplier_created && !$import_supplier_used) { $import_supplier->delete(); } if ($import_manufacturer_created && !$import_manufacturer_used) { $import_manufacturer->delete(); } if ($only_check_data) { $database->rollback(); } else { $database->commit($transaction_id); } // commit transaction } catch (Exception $e) { $database->rollback(); // rollback transaction throw new Exception((isset($row_index) ? 'Nr. ' . ($row_index + 1) . ': ' : '') . $e->getMessage()); } return $parts; }
$selected_manufacturer = NULL; } } catch (Exception $e) { $messages[] = array('text' => nl2br($e->getMessage()), 'strong' => true, 'color' => 'red'); $fatal_error = true; } /******************************************************************************** * * Execute actions * *********************************************************************************/ if (!$fatal_error) { switch ($action) { case 'add': try { $new_manufacturer = Manufacturer::add($database, $current_user, $log, $new_name, $new_parent_id, $new_address, $new_phone_number, $new_fax_number, $new_email_address, $new_website, $new_auto_product_url); if (!$add_more) { $selected_manufacturer = $new_manufacturer; $selected_id = $selected_manufacturer->get_id(); } } catch (Exception $e) { $messages[] = array('text' => 'Der neue Hersteller konnte nicht angelegt werden!', 'strong' => true, 'color' => 'red'); $messages[] = array('text' => 'Fehlermeldung: ' . nl2br($e->getMessage()), 'color' => 'red'); } break; case 'delete': try { if (!is_object($selected_manufacturer)) { throw new Exception('Es ist kein Hersteller markiert oder es trat ein Fehler auf!'); } $parts = $selected_manufacturer->get_parts();
protected function importManufacturers() { $this->truncateTables(array('manufacturer', 'manufacturer_lang', 'manufacturer_shop')); $handle = $this->openCsvFile('manufacturers.csv'); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, ';'); $current_line++) { $res = false; $fields = $this->filterFields('Manufacturer', $this->manufacturers_fields, $line); if (!isset($fields['id'])) { $manufacturer = new Manufacturer($line[0]); $manufacturer->id = $line[0]; } else { $manufacturer = new Manufacturer($fields['id']); } foreach ($fields as $key => $field) { if ($key == 'description' || $key == 'short_description' || $key == 'meta_title' || $key == 'meta_keywords' || $key == 'meta_description') { $manufacturer->{$key} = $this->multilFild($field); } else { $manufacturer->{$key} = $field; } } $manufacturer->force_id = true; if (!$res) { $res = $manufacturer->add(); } } $this->closeCsvFile($handle); return true; }