Пример #1
0
 /**
  * Add or update a product
  *
  * @global string $currentIndex Current URL in order to keep current Tab
  */
 public function submitAddProduct($token = NULL)
 {
     global $cookie, $currentIndex, $link;
     $className = 'Product';
     $rules = call_user_func(array($this->className, 'getValidationRules'), $this->className);
     $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
     $languages = Language::getLanguages(false);
     /* Check required fields */
     foreach ($rules['required'] as $field) {
         if (($value = Tools::getValue($field)) == false and $value != '0') {
             if (Tools::getValue('id_' . $this->table) and $field == 'passwd') {
                 continue;
             }
             $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $field, $className) . '</b> ' . $this->l('is required');
         }
     }
     /* Check multilingual required fields */
     foreach ($rules['requiredLang'] as $fieldLang) {
         if (!Tools::getValue($fieldLang . '_' . $defaultLanguage->id)) {
             $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $fieldLang, $className) . '</b> ' . $this->l('is required at least in') . ' ' . $defaultLanguage->name;
         }
     }
     /* Check fields sizes */
     foreach ($rules['size'] as $field => $maxLength) {
         if ($value = Tools::getValue($field) and Tools::strlen($value) > $maxLength) {
             $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $field, $className) . '</b> ' . $this->l('is too long') . ' (' . $maxLength . ' ' . $this->l('chars max') . ')';
         }
     }
     if (isset($_POST['description_short'])) {
         $saveShort = $_POST['description_short'];
         $_POST['description_short'] = strip_tags($_POST['description_short']);
     }
     /* Check description short size without html */
     $limit = (int) Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT');
     if ($limit <= 0) {
         $limit = 400;
     }
     foreach ($languages as $language) {
         if ($value = Tools::getValue('description_short_' . $language['id_lang'])) {
             if (Tools::strlen(strip_tags($value)) > $limit) {
                 $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), 'description_short') . ' (' . $language['name'] . ')</b> ' . $this->l('is too long') . ' : ' . $limit . ' ' . $this->l('chars max') . ' (' . $this->l('count now') . ' ' . Tools::strlen(strip_tags($value)) . ')';
             }
         }
     }
     /* Check multilingual fields sizes */
     foreach ($rules['sizeLang'] as $fieldLang => $maxLength) {
         foreach ($languages as $language) {
             if ($value = Tools::getValue($fieldLang . '_' . $language['id_lang']) and Tools::strlen($value) > $maxLength) {
                 $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $fieldLang, $className) . ' (' . $language['name'] . ')</b> ' . $this->l('is too long') . ' (' . $maxLength . ' ' . $this->l('chars max') . ')';
             }
         }
     }
     if (isset($_POST['description_short'])) {
         $_POST['description_short'] = $saveShort;
     }
     /* Check fields validity */
     foreach ($rules['validate'] as $field => $function) {
         if ($value = Tools::getValue($field)) {
             if (!Validate::$function($value)) {
                 $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $field, $className) . '</b> ' . $this->l('is invalid');
             }
         }
     }
     /* Check multilingual fields validity */
     foreach ($rules['validateLang'] as $fieldLang => $function) {
         foreach ($languages as $language) {
             if ($value = Tools::getValue($fieldLang . '_' . $language['id_lang'])) {
                 if (!Validate::$function($value)) {
                     $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $fieldLang, $className) . ' (' . $language['name'] . ')</b> ' . $this->l('is invalid');
                 }
             }
         }
     }
     /* Categories */
     $productCats = '';
     if (!Tools::isSubmit('categoryBox') or !sizeof(Tools::getValue('categoryBox'))) {
         $this->_errors[] = $this->l('product must be in at least one Category');
     }
     if (!is_array(Tools::getValue('categoryBox')) or !in_array(Tools::getValue('id_category_default'), Tools::getValue('categoryBox'))) {
         $this->_errors[] = $this->l('product must be in the default category');
     }
     /* Tags */
     foreach ($languages as $language) {
         if ($value = Tools::getValue('tags_' . $language['id_lang'])) {
             if (!Validate::isTagsList($value)) {
                 $this->_errors[] = $this->l('Tags list') . ' (' . $language['name'] . ') ' . $this->l('is invalid');
             }
         }
     }
     if (!sizeof($this->_errors)) {
         $id = (int) Tools::getValue('id_' . $this->table);
         $tagError = true;
         /* Update an existing product */
         if (isset($id) and !empty($id)) {
             $object = new $this->className($id);
             if (Validate::isLoadedObject($object)) {
                 $this->_removeTaxFromEcotax();
                 $this->copyFromPost($object, $this->table);
                 if ($object->update()) {
                     if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('mvt_quantity') > 0 and $id_reason > 0) {
                         $reason = new StockMvtReason((int) $id_reason);
                         $qty = Tools::getValue('mvt_quantity') * $reason->sign;
                         if (!$object->addStockMvt($qty, (int) $id_reason, NULL, NULL, (int) $cookie->id_employee)) {
                             $this->_errors[] = Tools::displayError('An error occurred while updating qty.');
                         }
                     }
                     $this->updateAccessories($object);
                     $this->updateDownloadProduct($object);
                     if (!$this->updatePackItems($object)) {
                         $this->_errors[] = Tools::displayError('An error occurred while adding products to the pack.');
                     } elseif (!$object->updateCategories($_POST['categoryBox'], true)) {
                         $this->_errors[] = Tools::displayError('An error occurred while linking object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('To categories');
                     } elseif (!$this->updateTags($languages, $object)) {
                         $this->_errors[] = Tools::displayError('An error occurred while adding tags.');
                     } elseif ($id_image = $this->addProductImage($object, Tools::getValue('resizer'))) {
                         $currentIndex .= '&image_updated=' . (int) Tools::getValue('id_image');
                         Hook::updateProduct($object);
                         Search::indexation(false, $object->id);
                         if (Tools::getValue('resizer') == 'man' && isset($id_image) and is_int($id_image) and $id_image) {
                             Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&edit=' . strval(Tools::getValue('productCreated')) . '&id_image=' . $id_image . '&imageresize&toconf=4&submitAddAndStay=' . ((Tools::isSubmit('submitAdd' . $this->table . 'AndStay') or Tools::getValue('productCreated') == 'on') ? 'on' : 'off') . '&token=' . ($token ? $token : $this->token));
                         }
                         // Save and preview
                         if (Tools::isSubmit('submitAddProductAndPreview')) {
                             $preview_url = $link->getProductLink($this->getFieldValue($object, 'id'), $this->getFieldValue($object, 'link_rewrite', (int) $cookie->id_lang), Category::getLinkRewrite($this->getFieldValue($object, 'id_category_default'), (int) $cookie->id_lang));
                             if (!$object->active) {
                                 $admin_dir = dirname($_SERVER['PHP_SELF']);
                                 $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
                                 $token = Tools::encrypt('PreviewProduct' . $object->id);
                                 if (strpos($preview_url, '?') === false) {
                                     $preview_url .= '?';
                                 } else {
                                     $preview_url .= '&';
                                 }
                                 $preview_url .= 'adtoken=' . $token . '&ad=' . $admin_dir;
                             }
                             Tools::redirectAdmin($preview_url);
                         } elseif (Tools::isSubmit('submitAdd' . $this->table . 'AndStay') or $id_image and $id_image !== true) {
                             // Save and stay on same form
                             // Save and stay on same form
                             if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                                 Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&conf=4&tabs=' . (int) Tools::getValue('tabs') . '&token=' . ($token ? $token : $this->token));
                             }
                         }
                         // Default behavior (save and back)
                         Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=4&token=' . ($token ? $token : $this->token) . '&onredirigeici');
                     }
                 } else {
                     $this->_errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')';
                 }
             } else {
                 $this->_errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> (' . Tools::displayError('Cannot load object') . ')';
             }
         } else {
             $object = new $this->className();
             $this->_removeTaxFromEcotax();
             $this->copyFromPost($object, $this->table);
             if ($object->add()) {
                 $this->updateAccessories($object);
                 if (!$this->updatePackItems($object)) {
                     $this->_errors[] = Tools::displayError('An error occurred while adding products to the pack.');
                 }
                 $this->updateDownloadProduct($object);
                 if (!sizeof($this->_errors)) {
                     if (!$object->updateCategories($_POST['categoryBox'])) {
                         $this->_errors[] = Tools::displayError('An error occurred while linking object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('To categories');
                     } elseif (!$this->updateTags($languages, $object)) {
                         $this->_errors[] = Tools::displayError('An error occurred while adding tags.');
                     } elseif ($id_image = $this->addProductImage($object)) {
                         Hook::addProduct($object);
                         Search::indexation(false, $object->id);
                         // Save and preview
                         if (Tools::isSubmit('submitAddProductAndPreview')) {
                             $preview_url = $link->getProductLink($this->getFieldValue($object, 'id'), $this->getFieldValue($object, 'link_rewrite', (int) $cookie->id_lang), Category::getLinkRewrite($this->getFieldValue($object, 'id_category_default'), (int) $cookie->id_lang));
                             if (!$object->active) {
                                 $admin_dir = dirname($_SERVER['PHP_SELF']);
                                 $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
                                 $token = Tools::encrypt('PreviewProduct' . $object->id);
                                 $preview_url .= '&adtoken=' . $token . '&ad=' . $admin_dir;
                             }
                             Tools::redirectAdmin($preview_url);
                         }
                         if (Tools::getValue('resizer') == 'man' && isset($id_image) and is_int($id_image) and $id_image) {
                             Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&id_image=' . $id_image . '&imageresize&toconf=3&submitAddAndStay=' . (Tools::isSubmit('submitAdd' . $this->table . 'AndStay') ? 'on' : 'off') . '&token=' . ($token ? $token : $this->token));
                         }
                         // Save and stay on same form
                         if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                             Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&conf=3&tabs=' . (int) Tools::getValue('tabs') . '&token=' . ($token ? $token : $this->token));
                         }
                         // Default behavior (save and back)
                         Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=3&token=' . ($token ? $token : $this->token));
                     }
                 } else {
                     $object->delete();
                 }
             } else {
                 $this->_errors[] = Tools::displayError('An error occurred while creating object.') . ' <b>' . $this->table . '</b>';
             }
         }
     }
 }
Пример #2
0
 public function setProducts($array)
 {
     Db::getInstance()->Execute('DELETE FROM ' . _DB_PREFIX_ . 'product_tag WHERE id_tag = ' . (int) $this->id);
     if (is_array($array)) {
         $array = array_map('intval', $array);
         $result1 = Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'product SET indexed = 0 WHERE id_product IN (' . implode(',', array_map('intval', $array)) . ')');
         $ids = array();
         foreach ($array as $id_product) {
             $ids[] = '(' . (int) $id_product . ',' . (int) $this->id . ')';
         }
         return $result1 && Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'product_tag (id_product, id_tag) VALUES ' . implode(',', $ids)) && Search::indexation(false);
     }
     return $result1;
 }
Пример #3
0
 /**
  * Object creation
  */
 public function processAdd()
 {
     if (!Tools::getValue('categoryBox') || !in_array(Tools::getValue('id_category'), Tools::getValue('categoryBox'))) {
         $this->errors[] = $this->l('You need to select at least the root category.');
     }
     if (Tools::isSubmit('id_category_default')) {
         $_POST['id_category'] = (int) Tools::getValue('id_category_default');
     }
     /* Checking fields validity */
     $this->validateRules();
     if (!count($this->errors)) {
         $object = new $this->className();
         $this->copyFromPost($object, $this->table);
         $this->beforeAdd($object);
         if (!$object->add()) {
             $this->errors[] = Tools::displayError('An error occurred while creating an object.') . ' <b>' . $this->table . ' (' . Db::getInstance()->getMsgError() . ')</b>';
         } else {
             if (($_POST[$this->identifier] = $object->id) && $this->postImage($object->id) && !count($this->errors) && $this->_redirect) {
                 $parent_id = (int) Tools::getValue('id_parent', 1);
                 $this->afterAdd($object);
                 $this->updateAssoShop($object->id);
                 // Save and stay on same form
                 if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                     $this->redirect_after = self::$currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=3&update' . $this->table . '&token=' . $this->token;
                 }
                 // Save and back to parent
                 if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
                     $this->redirect_after = self::$currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=3&token=' . $this->token;
                 }
                 // Default behavior (save and back)
                 if (empty($this->redirect_after)) {
                     $this->redirect_after = self::$currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=3&token=' . $this->token;
                 }
             }
         }
     }
     $this->errors = array_unique($this->errors);
     if (count($this->errors) > 0) {
         $this->display = 'add';
         return;
     }
     // specific import for stock
     if (isset($import_data['stock_available']) && isset($import_data['product']) && Tools::isSubmit('useImportData')) {
         $id_src_shop = (int) Tools::getValue('importFromShop');
         if ($object->getGroup()->share_stock == false) {
             StockAvailable::copyStockAvailableFromShopToShop($id_src_shop, $object->id);
         }
     }
     $categories = Tools::getValue('categoryBox');
     array_unshift($categories, Configuration::get('PS_ROOT_CATEGORY'));
     Category::updateFromShop($categories, $object->id);
     Search::indexation(true);
     return $object;
 }
Пример #4
0
 /**
  * PROCESS : installFixtures
  * Install fixtures (E.g. demo products)
  */
 public function installFixtures($entity = null, array $data = array())
 {
     $fixtures_path = _PS_INSTALL_FIXTURES_PATH_ . 'fashion/';
     $fixtures_name = 'fashion';
     $zip_file = _PS_ROOT_DIR_ . '/download/fixtures.zip';
     $temp_dir = _PS_ROOT_DIR_ . '/download/fixtures/';
     // Load class (use fixture class if one exists, or use InstallXmlLoader)
     if (file_exists($fixtures_path . '/install.php')) {
         require_once $fixtures_path . '/install.php';
         $class = 'InstallFixtures' . Tools::toCamelCase($fixtures_name);
         if (!class_exists($class, false)) {
             $this->setError($this->translator->trans('Fixtures class "%class%" not found', array('%class%' => $class), 'Install'));
             return false;
         }
         $xml_loader = new $class();
         if (!$xml_loader instanceof InstallXmlLoader) {
             $this->setError($this->translator->trans('"%class%" must be an instance of "InstallXmlLoader"', array('%class%' => $class), 'Install'));
             return false;
         }
     } else {
         $xml_loader = new InstallXmlLoader();
     }
     // Install XML data (data/xml/ folder)
     $xml_loader->setFixturesPath($fixtures_path);
     if (isset($this->xml_loader_ids) && $this->xml_loader_ids) {
         $xml_loader->setIds($this->xml_loader_ids);
     }
     $languages = array();
     foreach (Language::getLanguages(false) as $lang) {
         $languages[$lang['id_lang']] = $lang['iso_code'];
     }
     $xml_loader->setLanguages($languages);
     if ($entity) {
         $xml_loader->populateEntity($entity);
     } else {
         $xml_loader->populateFromXmlFiles();
         Tools::deleteDirectory($temp_dir, true);
         @unlink($zip_file);
     }
     if ($errors = $xml_loader->getErrors()) {
         $this->setError($errors);
         return false;
     }
     // IDS from xmlLoader are stored in order to use them for fixtures
     $this->xml_loader_ids = $xml_loader->getIds();
     unset($xml_loader);
     // Index products in search tables
     Search::indexation(true);
     return true;
 }
Пример #5
0
 /**
  * PROCESS : installFixtures
  * Install fixtures (E.g. demo products)
  */
 public function installFixtures($entity = null, array $data = array())
 {
     $fixtures_path = _PS_INSTALL_FIXTURES_PATH_ . 'apple/';
     $fixtures_name = 'apple';
     $zip_file = _PS_ROOT_DIR_ . '/download/fixtures.zip';
     $temp_dir = _PS_ROOT_DIR_ . '/download/fixtures/';
     // try to download fixtures if no low memory mode
     if ($entity === null) {
         if (Tools::copy('http://api.prestashop.com/fixtures/' . $data['shop_country'] . '/' . $data['shop_activity'] . '/fixtures.zip', $zip_file)) {
             Tools::deleteDirectory($temp_dir, true);
             if (Tools::ZipTest($zip_file)) {
                 if (Tools::ZipExtract($zip_file, $temp_dir)) {
                     $files = scandir($temp_dir);
                     if (count($files)) {
                         foreach ($files as $file) {
                             if (!preg_match('/^\\./', $file) && is_dir($temp_dir . $file . '/')) {
                                 $fixtures_path = $temp_dir . $file . '/';
                                 $fixtures_name = $file;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     // Load class (use fixture class if one exists, or use InstallXmlLoader)
     if (file_exists($fixtures_path . '/install.php')) {
         require_once $fixtures_path . '/install.php';
         $class = 'InstallFixtures' . Tools::toCamelCase($fixtures_name);
         if (!class_exists($class, false)) {
             $this->setError($this->language->l('Fixtures class "%s" not found', $class));
             return false;
         }
         $xml_loader = new $class();
         if (!$xml_loader instanceof InstallXmlLoader) {
             $this->setError($this->language->l('"%s" must be an instane of "InstallXmlLoader"', $class));
             return false;
         }
     } else {
         $xml_loader = new InstallXmlLoader();
     }
     // Install XML data (data/xml/ folder)
     $xml_loader->setFixturesPath($fixtures_path);
     if (isset($this->xml_loader_ids) && $this->xml_loader_ids) {
         $xml_loader->setIds($this->xml_loader_ids);
     }
     $languages = array();
     foreach (Language::getLanguages(false) as $lang) {
         $languages[$lang['id_lang']] = $lang['iso_code'];
     }
     $xml_loader->setLanguages($languages);
     if ($entity) {
         $xml_loader->populateEntity($entity);
     } else {
         $xml_loader->populateFromXmlFiles();
         Tools::deleteDirectory($temp_dir, true);
         @unlink($zip_file);
     }
     if ($errors = $xml_loader->getErrors()) {
         $this->setError($errors);
         return false;
     }
     // IDS from xmlLoader are stored in order to use them for fixtures
     $this->xml_loader_ids = $xml_loader->getIds();
     unset($xml_loader);
     // Index products in search tables
     Search::indexation(true);
     return true;
 }
Пример #6
0
 public function processUpdate()
 {
     $existing_product = $this->object;
     $this->checkProduct();
     if (!empty($this->errors)) {
         $this->display = 'edit';
         return false;
     }
     $id = (int) Tools::getValue('id_' . $this->table);
     /* Update an existing product */
     if (isset($id) && !empty($id)) {
         $object = new $this->className((int) $id);
         $this->object = $object;
         if (Validate::isLoadedObject($object)) {
             $this->_removeTaxFromEcotax();
             $product_type_before = $object->getType();
             $this->copyFromPost($object, $this->table);
             $object->indexed = 0;
             if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP) {
                 $object->setFieldsToUpdate((array) Tools::getValue('multishop_check'));
             }
             // Duplicate combinations if not associated to shop
             if ($this->context->shop->getContext() == Shop::CONTEXT_SHOP && !$object->isAssociatedToShop()) {
                 $is_associated_to_shop = false;
                 $combinations = Product::getProductAttributesIds($object->id);
                 if ($combinations) {
                     foreach ($combinations as $id_combination) {
                         $combination = new Combination((int) $id_combination['id_product_attribute']);
                         $default_combination = new Combination((int) $id_combination['id_product_attribute'], null, (int) $this->object->id_shop_default);
                         $def = ObjectModel::getDefinition($default_combination);
                         foreach ($def['fields'] as $field_name => $row) {
                             $combination->{$field_name} = ObjectModel::formatValue($default_combination->{$field_name}, $def['fields'][$field_name]['type']);
                         }
                         $combination->save();
                     }
                 }
             } else {
                 $is_associated_to_shop = true;
             }
             if ($object->update()) {
                 // If the product doesn't exist in the current shop but exists in another shop
                 if (Shop::getContext() == Shop::CONTEXT_SHOP && !$existing_product->isAssociatedToShop($this->context->shop->id)) {
                     $out_of_stock = StockAvailable::outOfStock($existing_product->id, $existing_product->id_shop_default);
                     $depends_on_stock = StockAvailable::dependsOnStock($existing_product->id, $existing_product->id_shop_default);
                     StockAvailable::setProductOutOfStock((int) $this->object->id, $out_of_stock, $this->context->shop->id);
                     StockAvailable::setProductDependsOnStock((int) $this->object->id, $depends_on_stock, $this->context->shop->id);
                 }
                 PrestaShopLogger::addLog(sprintf($this->l('%s edition', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $this->object->id, true, (int) $this->context->employee->id);
                 if (in_array($this->context->shop->getContext(), array(Shop::CONTEXT_SHOP, Shop::CONTEXT_ALL))) {
                     if ($this->isTabSubmitted('Shipping')) {
                         $this->addCarriers();
                     }
                     if ($this->isTabSubmitted('Associations')) {
                         $this->updateAccessories($object);
                     }
                     if ($this->isTabSubmitted('Suppliers')) {
                         $this->processSuppliers();
                     }
                     if ($this->isTabSubmitted('Features')) {
                         $this->processFeatures();
                     }
                     if ($this->isTabSubmitted('Combinations')) {
                         $this->processProductAttribute();
                     }
                     if ($this->isTabSubmitted('Prices')) {
                         $this->processPriceAddition();
                         $this->processSpecificPricePriorities();
                     }
                     if ($this->isTabSubmitted('Customization')) {
                         $this->processCustomizationConfiguration();
                     }
                     if ($this->isTabSubmitted('Attachments')) {
                         $this->processAttachments();
                     }
                     $this->updatePackItems($object);
                     // Disallow avanced stock management if the product become a pack
                     if ($product_type_before == Product::PTYPE_SIMPLE && $object->getType() == Product::PTYPE_PACK) {
                         StockAvailable::setProductDependsOnStock((int) $object->id, false);
                     }
                     $this->updateDownloadProduct($object, 1);
                     $this->updateTags(Language::getLanguages(false), $object);
                     if ($this->isProductFieldUpdated('category_box') && !$object->updateCategories(Tools::getValue('categoryBox'))) {
                         $this->errors[] = Tools::displayError('An error occurred while linking the object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('To categories');
                     }
                 }
                 if ($this->isTabSubmitted('Warehouses')) {
                     $this->processWarehouses();
                 }
                 if (empty($this->errors)) {
                     if (in_array($object->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) {
                         Search::indexation(false, $object->id);
                     }
                     // Save and preview
                     if (Tools::isSubmit('submitAddProductAndPreview')) {
                         $this->redirect_after = $this->getPreviewUrl($object);
                     } else {
                         // Save and stay on same form
                         if ($this->display == 'edit') {
                             $this->confirmations[] = $this->l('Update successful');
                             $this->redirect_after = self::$currentIndex . '&id_product=' . (int) $this->object->id . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&updateproduct&conf=4&key_tab=' . Tools::safeOutput(Tools::getValue('key_tab')) . '&token=' . $this->token;
                         } else {
                             // Default behavior (save and back)
                             $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=4&token=' . $this->token;
                         }
                     }
                 } else {
                     $this->display = 'edit';
                 }
             } else {
                 if (!$is_associated_to_shop && $combinations) {
                     foreach ($combinations as $id_combination) {
                         $combination = new Combination((int) $id_combination['id_product_attribute']);
                         $combination->delete();
                     }
                 }
                 $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')';
             }
         } else {
             $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . '</b> (' . Tools::displayError('The object cannot be loaded. ') . ')';
         }
         return $object;
     }
 }
 public function postProcess()
 {
     // die('<pre>' . print_r($_POST, true));
     $this->object->is_virtual = 1;
     $_POST["id_seller"] = AgileSellerManager::getLinkedSellerID($this->context->customer->id);
     // echo '<pre>', print_r($_POST) , '</pre>';
     $this->object->indexed = 0;
     if (Tools::isSubmit("submitProduct")) {
         $this->processSaveProduct();
         if ($_FILES['qqfile']['size'] != 0) {
             $this->ProcessAddImage();
         }
         if (empty($this->errors)) {
             self::$smarty->assign("cfmmsg_flag", 1);
         }
     } else {
         if (Tools::isSubmit("submitAddImage")) {
             $this->ProcessAddImage();
             if (empty($this->errors)) {
                 self::$smarty->assign("cfmmsg_flag", 1);
             }
         } else {
             if (Tools::isSubmit("submitFeatures")) {
                 $this->processFeatures();
                 if (empty($this->errors)) {
                     self::$smarty->assign("cfmmsg_flag", 1);
                 }
             } else {
                 if (Tools::isSubmit("submitAssociations")) {
                     $this->updateAccessories();
                     $this->object->updateCategories(Tools::getValue("categoryBox"), true);
                     ${${"GLOBALS"}["qiymoeuqk"]} = $this->addNewCategory($this->object->id, intval(Tools::getValue("id_category_default")));
                     ${"GLOBALS"}["xgllsk"] = "newid";
                     $this->object->id_category_default = ${${"GLOBALS"}["qiymoeuqk"]} > 0 ? ${${"GLOBALS"}["xgllsk"]} : intval(Tools::getValue("id_category_default"));
                     if (intval($this->object->id_category_default) <= 0) {
                         $this->errors[] = Tools::displayError("Default category is required");
                         return;
                     }
                     $this->object->save();
                     if (empty($this->errors)) {
                         self::$smarty->assign("cfmmsg_flag", 1);
                     }
                 } else {
                     if (Tools::isSubmit("submitSpecificPrices")) {
                         $this->object->wholesale_price = floatval(Tools::getValue("wholesale_price"));
                         $this->object->price = floatval(Tools::getValue("price"));
                         if (floatval(Tools::getValue("unit_price")) != 0) {
                             $this->object->unit_price = (double) Tools::getValue("unit_price");
                             $this->object->unit_price_ratio = $this->object->price / floatval(Tools::getValue("unit_price"));
                         }
                         $this->object->unity = Tools::getValue("unity");
                         $this->object->on_sale = Tools::getValue("on_sale");
                         $this->object->id_tax_rules_group = Tools::getValue("id_tax_rules_group");
                         $this->object->save();
                         $this->processPriceAddition();
                         $this->processSpecificPricePriorities();
                         if (empty($this->errors)) {
                             self::$smarty->assign("cfmmsg_flag", 1);
                         }
                     } else {
                         if (Tools::isSubmit("submitQuantities")) {
                             $this->copyFromPost($this->object, $this->table);
                             $this->object->save();
                             if (empty($this->errors)) {
                                 self::$smarty->assign("cfmmsg_flag", 1);
                             }
                         } else {
                             if (Tools::isSubmit("submitCombinations")) {
                                 $this->processCombinations();
                                 if (empty($this->errors)) {
                                     self::$smarty->assign("cfmmsg_flag", 1);
                                 }
                             } else {
                                 if (Tools::isSubmit("submitVirtualProduct")) {
                                     $this->object->is_virtual = Tools::getValue("is_virtual_good") == "true" ? 1 : 0;
                                     $this->object->save($this->object);
                                     if ($this->object->is_virtual and intval(Tools::getValue("is_virtual_file"))) {
                                         $this->updateDownloadProduct($this->object);
                                     }
                                     if (empty($this->errors)) {
                                         self::$smarty->assign("cfmmsg_flag", 1);
                                     }
                                 } else {
                                     if (Tools::isSubmit("submitShipping")) {
                                         $this->processShipping();
                                         if (empty($this->errors)) {
                                             self::$smarty->assign("cfmmsg_flag", 1);
                                         }
                                     } else {
                                         if (Tools::isSubmit("submitAddAttachments")) {
                                             $this->processAddAttachments();
                                             if (empty($this->errors)) {
                                                 self::$smarty->assign("cfmmsg_flag", 1);
                                             }
                                         } else {
                                             if (Tools::isSubmit("submitAttachments")) {
                                                 $this->processAttachments();
                                                 $this->object->cache_has_attachments = (bool) Db::getInstance()->getValue("SELECT id_attachment FROM " . _DB_PREFIX_ . "product_attachment WHERE id_product=" . (int) $this->object->id);
                                                 if (empty($this->errors)) {
                                                     self::$smarty->assign("cfmmsg_flag", 1);
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     Hook::exec("actionProductUpdate", array("product" => $this->object));
     if (empty($this->errors)) {
         if (Validate::isLoadedObject($this->object) && $this->object->update()) {
             if (in_array($this->object->visibility, array("both", "search")) && Configuration::get("PS_SEARCH_INDEXATION")) {
                 Search::indexation(false, $this->object->id);
             }
         }
     }
 }
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_ADMIN_DIR_')) {
    define('_PS_ADMIN_DIR_', getcwd());
}
include _PS_ADMIN_DIR_ . '/../config/config.inc.php';
Context::getContext()->shop->setContext(Shop::CONTEXT_ALL);
if (substr(_COOKIE_KEY_, 34, 8) != Tools::getValue('token')) {
    die;
}
ini_set('max_execution_time', 7200);
Search::indexation(Tools::getValue('full'));
if (Tools::getValue('redirect')) {
    Tools::redirectAdmin($_SERVER['HTTP_REFERER'] . '&conf=4');
}
Пример #9
0
 public function updateWs($nullValues = false)
 {
     $success = parent::update($nullValues);
     if ($success) {
         Search::indexation(false, $this->id);
     }
     return $success;
 }
Пример #10
0
    public function productImport()
    {
        $this->receiveTab();
        $handle = $this->openCsvFile();
        $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT');
        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);
            if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) {
                $product = new Product((int) $info['id']);
            } else {
                if (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                    $product = new Product((int) $info['id']);
                } else {
                    $product = new Product();
                }
            }
            if (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                $product->loadStockData();
                $category_data = Product::getProductCategories((int) $product->id);
                foreach ($category_data as $tmp) {
                    $product->category[] = $tmp;
                }
            }
            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 (!is_numeric($shop)) {
                    $product->id_shop_list[] = Shop::getIdByName($shop);
                } else {
                    $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 a group with this ID.'));
                }
            }
            if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int) $product->manufacturer)) {
                $product->id_manufacturer = (int) $product->manufacturer;
            } else {
                if (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) ? $manufacturer->id : 'null');
                            $this->errors[] = ($field_error !== true ? $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;
            } else {
                if (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) ? $supplier->id : 'null');
                            $this->errors[] = ($field_error !== true ? $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;
            } else {
                if (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, '.', '');
                    }
                } else {
                    if (isset($product->price_tin) && isset($product->price_tex)) {
                        $product->price = $product->price_tex;
                    }
                }
            }
            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) ? $category_to_create->id : 'null');
                                $this->errors[] = ($field_error !== true ? $field_error : '') . ($lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                            }
                        }
                    } else {
                        if (is_string($value) && !empty($value)) {
                            $category = Category::searchByName($default_language_id, trim($value), true);
                            if ($category['id_category']) {
                                $product->id_category[] = (int) $category['id_category'];
                            } else {
                                $category_to_create = new Category();
                                if (!Shop::isFeatureActive()) {
                                    $category_to_create->id_shop_default = 1;
                                } else {
                                    $category_to_create->id_shop_default = (int) Context::getContext()->shop->id;
                                }
                                $category_to_create->name = AdminImportController::createMultiLangField(trim($value));
                                $category_to_create->active = 1;
                                $category_to_create->id_parent = (int) 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) ? $category_to_create->id : 'null');
                                    $this->errors[] = ($field_error !== true ? $field_error : '') . ($lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                                }
                            }
                        }
                    }
                }
            }
            $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : '';
            $link_rewrite = is_array($product->link_rewrite) && count($product->link_rewrite) ? trim($product->link_rewrite[$default_language_id]) : '';
            $valid_link = Validate::isLinkRewrite($link_rewrite);
            if (isset($product->link_rewrite[$default_language_id]) && empty($product->link_rewrite[$default_language_id]) || !$valid_link) {
                $link_rewrite = Tools::link_rewrite($product->name[$default_language_id]);
                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.'), $link_rewrite, isset($info['id']) ? $info['id'] : 'null', $link_rewrite);
            }
            $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite);
            // replace the value of separator by coma
            if ($this->multiple_value_separator != ',') {
                foreach ($product->meta_keywords as &$meta_keyword) {
                    if (!empty($meta_keyword)) {
                        $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword);
                    }
                }
            }
            $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') == 1 && $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` = "' . $product->reference . '"
					');
                    $product->id = (int) $datas['id_product'];
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                } else {
                    if ($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
                if (!$res) {
                    if (isset($product->date_add) && $product->date_add != '') {
                        $res = $product->add(false);
                    } else {
                        $res = $product->add();
                    }
                }
            }
            $shops = array();
            $product_shop = explode($this->multiple_value_separator, $product->shop);
            foreach ($product_shop as $shop) {
                $shop = trim($shop);
                if (!is_numeric($shop)) {
                    $shop = ShopGroup::getIdByName($shop);
                }
                $shops[] = $shop;
            }
            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'), $info['name'], isset($info['id']) ? $info['id'] : 'null');
                $this->errors[] = ($field_error !== true ? $field_error : '') . ($lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
            } else {
                // Product supplier
                if (isset($product->id_supplier) && isset($product->supplier_reference)) {
                    $id_product_supplier = ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier);
                    if ($id_product_supplier) {
                        $product_supplier = new ProductSupplier((int) $id_product_supplier);
                    } else {
                        $product_supplier = new ProductSupplier();
                    }
                    $product_supplier->id_product = $product->id;
                    $product_supplier->id_product_attribute = 0;
                    $product_supplier->id_supplier = $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 (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) {
                    $specific_price = new SpecificPrice();
                    $specific_price->id_product = (int) $product->id;
                    // @todo multishop specific price import
                    $specific_price->id_shop = $this->context->shop->id;
                    $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->add()) {
                        $this->addProductWarning($info['name'], $product->id, $this->l('Discount is invalid'));
                    }
                }
                if (isset($product->tags) && !empty($product->tags)) {
                    // Delete tags for this id product, for no duplicating error
                    Tag::deleteTagsForProduct($product->id);
                    if (!is_array($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($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($info['name'], $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();
                    } else {
                        if (isset($product->image) && is_array($product->image) && count($product->image)) {
                            $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 (@fopen($url, 'r') == false) {
                                $error = true;
                            } else {
                                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)) {
                                        $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 n°%1$d: the picture cannot be saved: %2$s'), $image->id_product, $url);
                        }
                    }
                }
                if (isset($product->id_category)) {
                    $product->updateCategories(array_map('intval', $product->id_category));
                }
                // 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) {
                        $tab_feature = explode(':', $single_feature);
                        $feature_name = trim($tab_feature[0]);
                        $feature_value = trim($tab_feature[1]);
                        $position = isset($tab_feature[2]) ? $tab_feature[2] : false;
                        $id_feature = Feature::addFeatureImport($feature_name, $position);
                        $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $feature_value);
                        Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                    }
                }
                // clean feature positions to avoid conflict
                Feature::cleanPositions();
            }
            // stock available
            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, $this->context->shop->id);
            }
        }
        if (Configuration::get('PS_SEARCH_INDEXATION')) {
            Search::indexation(true);
        }
        $this->closeCsvFile($handle);
    }
 public static function execImport($pdt)
 {
     if ($pdt->id_product > 0) {
         $product = new Product($pdt->id_product);
     } else {
         $product = new Product();
     }
     if (version_compare(_PS_VERSION_, '1.5', '>=')) {
         foreach (Product::$definition['fields'] as $field => $value) {
             if (isset($pdt->{$field})) {
                 if (is_object($pdt->{$field})) {
                     $fields = array();
                     foreach ($pdt->{$field} as $key => $value) {
                         $fields[$key] = $value;
                     }
                     $product->{$field} = $fields;
                 } else {
                     $product->{$field} = $pdt->{$field};
                 }
             }
         }
     } else {
         $product->id_manufacturer = $pdt->id_manufacturer;
         $product->id_supplier = $pdt->id_supplier;
         if ($pdt->reference) {
             $product->reference = $pdt->reference;
         }
         $product->supplier_reference = $pdt->supplier_reference;
         $product->weight = $pdt->weight;
         $product->id_category_default = $pdt->id_category_default;
         if ($pdt->id_tax_rules_group) {
             $product->id_tax_rules_group = $pdt->id_tax_rules_group;
         }
         if ($pdt->price) {
             $product->price = $pdt->price;
         }
         if ($pdt->wholesale_price) {
             $product->wholesale_price = $pdt->wholesale_price;
         }
         if ($pdt->active) {
             $product->active = $pdt->active;
         }
         if ($pdt->date_add) {
             $product->date_add = $pdt->date_add;
         }
         $product->date_upd = $pdt->date_upd;
         if ($pdt->link_rewrite) {
             foreach ($pdt->link_rewrite as $key => $value) {
                 $product->link_rewrite[$key] = $value;
             }
         }
         if ($pdt->name) {
             foreach ($pdt->name as $key => $value) {
                 $product->name[$key] = $value;
             }
         }
         if ($pdt->description) {
             foreach ($pdt->description as $key => $value) {
                 $product->description[$key] = $value;
             }
         }
         if ($pdt->description_short) {
             foreach ($pdt->description_short as $key => $value) {
                 $product->description_short[$key] = $value;
             }
         }
         if ($pdt->ean13) {
             $product->ean13 = $pdt->ean13;
         }
     }
     if ($pdt->upd_index == 1) {
         $product->indexed = 1;
     }
     if (version_compare(_PS_VERSION_, '1.5', '>=')) {
         $product->id_shop_list[] = $pdt->shop;
     }
     $product->id_category[] = $pdt->categories;
     $product->id_category[] = $pdt->sscategories;
     if ($pdt->id_product) {
         $category_data = Product::getProductCategories((int) $product->id);
         foreach ($category_data as $tmp) {
             $product->id_category[] = $tmp;
         }
     }
     $product->id_category = array_unique($product->id_category);
     $product->save();
     if ($pdt->upd_img == 1 || !$pdt->id_product) {
         self::execImages($pdt, $product);
         self::cleanUploadedImages($pdt, $product);
     }
     if (version_compare(_PS_VERSION_, '1.5', '>=')) {
         if (!$pdt->id_product) {
             self::insertSupplierRef($product->id, 0, $pdt->id_supplier, $pdt->supplier_reference);
         }
     }
     if ($pdt->upd_index == 1) {
         Search::indexation(false, $pdt->id_product);
     }
     $product->updateCategories(array_map('intval', $product->id_category));
     return $product->id;
 }
 protected function importProducts()
 {
     $this->truncateTables(array('product', 'product_lang', 'product_shop', 'product_sale', 'product_supplier', 'product_tag', 'feature_product', 'category_product', 'product_carrier', 'compare_product', 'product_attachment', 'product_country_tax', 'product_download', 'product_group_reduction_cache', 'scene_products', 'warehouse_product_location', 'customization', 'customization_field', 'customization_field_lang', 'supply_order_detail', 'attribute_impact', 'pack'));
     $handle = $this->openCsvFile('products.csv');
     $languages = Language::getLanguages(false);
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, ';'); $current_line++) {
         $res = false;
         $product = new Product((int) $line[0]);
         $product->id = (int) $line[0];
         $product->active = $line[1];
         foreach ($languages as $lang) {
             $product->name[$lang['id_lang']] = $line['2'];
         }
         $categories = explode(',', $line[3]);
         $product->id_category_default = $categories[0] ? $categories[0] : Configuration::get('PS_HOME_CATEGORY');
         if (isset($categories) && $categories && count($categories)) {
             $product->addToCategories($categories);
         }
         if (isset($line[4])) {
             $product->price_tex = $line[4];
         }
         if (isset($line[5])) {
             $product->price_tin = $line[5];
         }
         $product->id_tax_rules_group = trim($line[6]) ? $line[6] : 0;
         $product->wholesale_price = trim($line[7]) ? $line[7] : 0;
         $product->on_sale = trim($line[8]) ? $line[8] : 0;
         if (trim($line[13])) {
             $product->reference = $line[13];
         }
         if (trim($line[14])) {
             $product->supplier_reference = trim($line[14]);
         }
         if (trim($line[15])) {
             $product->id_supplier = (int) $line[15];
         }
         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();
         }
         if (trim($line[16])) {
             $product->id_manufacturer = $line[16];
         }
         if (!Tools::isEmpty(trim($line[17]))) {
             $product->ean13 = $line[17];
         }
         if (trim($line[18])) {
             $product->upc = $line[18];
         }
         if (trim($line[19])) {
             $product->ecotax = $line[19];
         }
         $product->width = $line[20];
         $product->height = $line[21];
         $product->depth = $line[22];
         $product->weight = $line[23];
         if ($line[24]) {
             StockAvailable::setQuantity((int) $product->id, 0, (int) $line[24], (int) $this->context->shop->id);
         }
         $product->minimal_quantity = $line[25];
         $product->visibility = $line[26];
         $product->additional_shipping_cost = $line[27];
         if (trim($line[28])) {
             $product->unity = $line[28];
         }
         if (trim($line[29])) {
             $product->unit_price = $line[29];
         }
         foreach ($languages as $lang) {
             $product->description_short[$lang['id_lang']] = $line[30];
             $product->description[$lang['id_lang']] = $line[31];
         }
         if ($line[32]) {
             foreach ($languages as $lang) {
                 Tag::addTags($lang['id_lang'], $product->id, $line[32]);
             }
         }
         foreach ($languages as $lang) {
             $product->meta_title[$lang['id_lang']] = $line[33];
             $product->meta_keywords[$lang['id_lang']] = $line[34];
             $product->meta_description[$lang['id_lang']] = $line[35];
             $product->link_rewrite[$lang['id_lang']] = $line[36];
             $product->available_now[$lang['id_lang']] = $line[37];
             $product->available_later[$lang['id_lang']] = $line[38];
         }
         $product->available_for_order = $line[39];
         $product->available_date = $line[40];
         $product->date_add = $line[41];
         $product->show_price = $line[42];
         // Features import
         $features = explode(',', $line[45]);
         if ($features) {
             foreach ($features as $feature) {
                 $value = explode(':', $feature);
                 if ($value[0] && $value[1]) {
                     Product::addFeatureProductImport((int) $product->id, (int) $value[0], (int) $value[1]);
                     SpecificPriceRule::applyAllRules(array((int) $product->id));
                 }
             }
         }
         $product->online_only = trim($line[46]) ? $line[46] : 0;
         $product->condition = $line[47];
         $product->customizable = trim($line[48]) ? $line[48] : 0;
         $product->uploadable_files = trim($line[49]) ? $line[49] : 0;
         $product->text_fields = trim($line[50]) ? $line[50] : 0;
         if ($product->getType() == Product::PTYPE_VIRTUAL) {
             StockAvailable::setProductOutOfStock((int) $product->id, 1);
         } else {
             StockAvailable::setProductOutOfStock((int) $product->id, (int) $line[51]);
         }
         $product->id_shop_default = $line[52];
         // add product accessories
         if ($line[56]) {
             $accessories = explode(',', $line[56]);
             foreach ($accessories as $accessory) {
                 $a[]['id'] = $accessory;
             }
             $product->setWsAccessories($a);
         }
         // add product carriers
         if ($line[57]) {
             $carriers = explode(',', $line[57]);
             $product->setCarriers($carriers);
         }
         // add costomisation fields
         if (!Tools::isEmpty($line[58]) && class_exists('CustomizationField')) {
             $customisation_fields_ids = explode(',', $line[58]);
             foreach ($customisation_fields_ids as $customisation_field) {
                 $result = false;
                 $customisation_data = explode(':', $customisation_field);
                 $cf = new CustomizationField();
                 $cf->id_product = $product->id;
                 $cf->type = $customisation_data[1];
                 $cf->required = $customisation_data[2];
                 foreach ($languages as $lang) {
                     $cf->name[$lang['id_lang']] = $customisation_data[3] ? $customisation_data[3] : ' ';
                 }
                 $cf->force_id = 1;
                 if (!$result) {
                     $result = $cf->add();
                 }
             }
         }
         // add attachments
         if ($line[59]) {
             $attachments = explode(',', $line[59]);
             if (isset($attachments) && count($attachments)) {
                 Attachment::attachToProduct($product->id, $attachments);
             }
         }
         if ($line[60]) {
             $product->date_upd = $line[60];
         }
         $product->price = $line[61];
         $product->force_id = 1;
         if (!$res) {
             $res = $product->add();
         }
     }
     $this->closeCsvFile($handle);
     Search::indexation(true);
     return true;
 }
Пример #13
0
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2014 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_ADMIN_DIR_')) {
    define('_PS_ADMIN_DIR_', getcwd());
}
include _PS_ADMIN_DIR_ . '/../config/config.inc.php';
Context::getContext()->shop->setContext(Shop::CONTEXT_ALL);
if (substr(_COOKIE_KEY_, 34, 8) != Tools::getValue('token')) {
    die;
}
ini_set('max_execution_time', 7200);
$id_product = 16623;
Search::indexation(false, $id_product);
if (Tools::getValue('redirect')) {
    Tools::redirectAdmin($_SERVER['HTTP_REFERER'] . '&conf=4');
}
Пример #14
0
 public function updateWs($null_values = false)
 {
     $success = parent::update($null_values);
     if ($success && Configuration::get('PS_SEARCH_INDEXATION')) {
         Search::indexation(false, $this->id);
     }
     return $success;
 }
Пример #15
0
 public function processDuplicate()
 {
     if (!Module::isInstalled('agilemultipleseller')) {
         parent::processDuplicate();
     } else {
         if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
             $id_product_old = $product->id;
             if (empty($product->price) && Shop::getContext() == Shop::CONTEXT_GROUP) {
                 $shops = ShopGroup::getShopsFromGroup(Shop::getContextShopGroupID());
                 foreach ($shops as $shop) {
                     if ($product->isAssociatedToShop($shop['id_shop'])) {
                         $product_price = new Product($id_product_old, false, null, $shop['id_shop']);
                         $product->price = $product_price->price;
                     }
                 }
             }
             unset($product->id);
             unset($product->id_product);
             $product->indexed = 0;
             $product->active = 0;
             if ($product->add() && Category::duplicateProductCategories($id_product_old, $product->id) && ($combination_images = Product::duplicateAttributes($id_product_old, $product->id)) !== false && GroupReduction::duplicateReduction($id_product_old, $product->id) && Product::duplicateAccessories($id_product_old, $product->id) && Product::duplicateFeatures($id_product_old, $product->id) && Product::duplicateSpecificPrices($id_product_old, $product->id) && Pack::duplicate($id_product_old, $product->id) && Product::duplicateCustomizationFields($id_product_old, $product->id) && Product::duplicateTags($id_product_old, $product->id) && Product::duplicateDownload($id_product_old, $product->id)) {
                 if ($product->hasAttributes()) {
                     Product::updateDefaultAttribute($product->id);
                 }
                 AgileSellerManager::assignObjectOwner('product', $product->id, AgileSellerManager::getObjectOwnerID('product', $id_product_old));
                 if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combination_images)) {
                     $this->errors[] = Tools::displayError('An error occurred while copying images.');
                 } else {
                     Hook::exec('actionProductAdd', array('product' => $product));
                     if (in_array($product->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) {
                         Search::indexation(false, $product->id);
                     }
                     $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=19&token=' . $this->token;
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while creating an object.');
             }
         }
     }
 }
Пример #16
0
 /**
  * PROCESS : installFixtures
  * Install fixtures (E.g. demo products)
  */
 public function installFixtures($entity = null)
 {
     // Load class (use fixture class if one exists, or use InstallXmlLoader)
     if (file_exists(_PS_INSTALL_FIXTURES_PATH_ . 'apple/install.php')) {
         require_once _PS_INSTALL_FIXTURES_PATH_ . 'apple/install.php';
         $class = 'InstallFixtures' . Tools::toCamelCase('apple');
         if (!class_exists($class, false)) {
             $this->setError($this->language->l('Fixtures class "%s" not found', $class));
             return false;
         }
         $xml_loader = new $class();
         if (!$xml_loader instanceof InstallXmlLoader) {
             $this->setError($this->language->l('"%s" must be an instane of "InstallXmlLoader"', $class));
             return false;
         }
     } else {
         $xml_loader = new InstallXmlLoader();
     }
     // Install XML data (data/xml/ folder)
     $xml_loader->setFixturesPath();
     if (isset($this->xml_loader_ids) && $this->xml_loader_ids) {
         $xml_loader->setIds($this->xml_loader_ids);
     }
     $languages = array();
     foreach (Language::getLanguages(false) as $lang) {
         $languages[$lang['id_lang']] = $lang['iso_code'];
     }
     $xml_loader->setLanguages($languages);
     if ($entity) {
         $xml_loader->populateEntity($entity);
     } else {
         $xml_loader->populateFromXmlFiles();
     }
     if ($errors = $xml_loader->getErrors()) {
         $this->setError($errors);
         return false;
     }
     // IDS from xmlLoader are stored in order to use them for fixtures
     $this->xml_loader_ids = $xml_loader->getIds();
     unset($xml_loader);
     // Index products in search tables
     Search::indexation(true);
     return true;
 }
Пример #17
0
 public function processUpdate()
 {
     $this->checkProduct();
     if (!empty($this->errors)) {
         $this->display = 'edit';
         return false;
     }
     $id = (int) Tools::getValue('id_' . $this->table);
     /* Update an existing product */
     if (isset($id) && !empty($id)) {
         $object = new $this->className((int) $id);
         $this->object = $object;
         if (Validate::isLoadedObject($object)) {
             $this->_removeTaxFromEcotax();
             $this->copyFromPost($object, $this->table);
             $object->indexed = 0;
             if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP) {
                 $object->setFieldsToUpdate((array) Tools::getValue('multishop_check'));
             }
             if ($object->update()) {
                 if (in_array($this->context->shop->getContext(), array(Shop::CONTEXT_SHOP, Shop::CONTEXT_ALL))) {
                     if ($this->isTabSubmitted('Shipping')) {
                         $this->addCarriers();
                     }
                     if ($this->isTabSubmitted('Associations')) {
                         $this->updateAccessories($object);
                     }
                     if ($this->isTabSubmitted('Suppliers')) {
                         $this->processSuppliers();
                     }
                     if ($this->isTabSubmitted('Features')) {
                         $this->processFeatures();
                     }
                     if ($this->isTabSubmitted('Combinations')) {
                         $this->processProductAttribute();
                     }
                     if ($this->isTabSubmitted('Prices')) {
                         $this->processPriceAddition();
                         $this->processSpecificPricePriorities();
                         $this->object->id_tax_rules_group = (int) Tools::getValue('id_tax_rules_group');
                     }
                     if ($this->isTabSubmitted('Customization')) {
                         $this->processCustomizationConfiguration();
                     }
                     if ($this->isTabSubmitted('Attachments')) {
                         $this->processAttachments();
                     }
                     $this->updatePackItems($object);
                     $this->updateDownloadProduct($object, 1);
                     $this->updateTags(Language::getLanguages(false), $object);
                     if ($this->isProductFieldUpdated('category_box') && !$object->updateCategories(Tools::getValue('categoryBox'))) {
                         $this->errors[] = Tools::displayError('An error occurred while linking object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('To categories');
                     }
                 }
                 if ($this->isTabSubmitted('Warehouses')) {
                     $this->processWarehouses();
                 }
                 if (empty($this->errors)) {
                     Hook::exec('actionProductUpdate', array('product' => $object));
                     if (in_array($object->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) {
                         Search::indexation(false, $object->id);
                     }
                     // Save and preview
                     if (Tools::isSubmit('submitAddProductAndPreview')) {
                         $preview_url = $this->context->link->getProductLink($this->getFieldValue($object, 'id'), $this->getFieldValue($object, 'link_rewrite', $this->context->language->id), Category::getLinkRewrite($this->getFieldValue($object, 'id_category_default'), $this->context->language->id), null, null, Context::getContext()->shop->id, 0, (bool) Configuration::get('PS_REWRITING_SETTINGS'));
                         if (!$object->active) {
                             $admin_dir = dirname($_SERVER['PHP_SELF']);
                             $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
                             if (strpos($preview_url, '?') === false) {
                                 $preview_url .= '?';
                             } else {
                                 $preview_url .= '&';
                             }
                             $preview_url .= 'adtoken=' . $this->token . '&ad=' . $admin_dir . '&id_employee=' . (int) $this->context->employee->id;
                         }
                         $this->redirect_after = $preview_url;
                     } else {
                         // Save and stay on same form
                         if ($this->display == 'edit') {
                             $this->confirmations[] = $this->l('Update successful');
                             $this->redirect_after = self::$currentIndex . '&id_product=' . (int) $this->object->id . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&updateproduct&conf=4&key_tab=' . Tools::safeOutput(Tools::getValue('key_tab')) . '&token=' . $this->token;
                         } else {
                             // Default behavior (save and back)
                             $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=4&token=' . $this->token;
                         }
                     }
                 } else {
                     $this->display = 'edit';
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')';
             }
         } else {
             $this->errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> (' . Tools::displayError('Cannot load object') . ')';
         }
         return $object;
     }
 }
Пример #18
0
                $product->price = $product_price->price;
            }
        }
    }
    if (Validate::isLoadedObject($product)) {
        $id_product_old = $product->id;
        for ($i = 1; $i <= $quantity; $i++) {
            echo $i;
            unset($product->id);
            unset($product->id_product);
            $product->indexed = 0;
            $product->active = 0;
            if ($product->add() && Category::duplicateProductCategories($id_product_old, $product->id) && ($combination_images = Product::duplicateAttributes($id_product_old, $product->id)) !== false && GroupReduction::duplicateReduction($id_product_old, $product->id) && Product::duplicateAccessories($id_product_old, $product->id) && Product::duplicateFeatures($id_product_old, $product->id) && Product::duplicateSpecificPrices($id_product_old, $product->id) && Pack::duplicate($id_product_old, $product->id) && Product::duplicateCustomizationFields($id_product_old, $product->id) && Product::duplicateTags($id_product_old, $product->id) && Product::duplicateDownload($id_product_old, $product->id)) {
                if ($product->hasAttributes()) {
                    Product::updateDefaultAttribute($product->id);
                }
                if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combination_images)) {
                    echo 'An error occurred while copying images.';
                } else {
                    Hook::exec('actionProductAdd', array('product' => $product));
                    if (in_array($product->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) {
                        Search::indexation(false, $product->id);
                    }
                    echo ' Duplication, ProductAddHook and re-index done. ';
                }
            } else {
                echo 'An error occurred while duplicating some object properties.';
            }
        }
    }
}
Пример #19
0
    public function postProcess()
    {
        global $currentIndex;
        /* PrestaShop demo mode */
        if (_PS_MODE_DEMO_) {
            $this->_errors[] = Tools::displayError('This functionnality has been disabled.');
            return;
        }
        /* PrestaShop demo mode*/
        if (Tools::isSubmit('submitFileUpload')) {
            if (isset($_FILES['file']) and !empty($_FILES['file']['error'])) {
                switch ($_FILES['file']['error']) {
                    case UPLOAD_ERR_INI_SIZE:
                        $this->_errors[] = Tools::displayError('The uploaded file exceeds the upload_max_filesize directive in php.ini. If your server configuration allows it, you may add a directive in your .htaccess, for example:') . '<br/><a href="?tab=AdminGenerator&amp;token=' . Tools::getAdminTokenLite('AdminGenerator') . '" >' . '<code>php_value upload_max_filesize 20M</code> ' . Tools::displayError('(clic to open Generator tab)') . '</a>';
                        break;
                    case UPLOAD_ERR_FORM_SIZE:
                        $this->_errors[] = Tools::displayError('The uploaded file exceeds the post_max_size directive in php.ini. If your server configuration allows it, you may add a directive in your .htaccess, for example:') . '<br/><a href="?tab=AdminGenerator&amp;token=' . Tools::getAdminTokenLite('AdminGenerator') . '" >' . '<code>php_value post_max_size 20M</code> ' . Tools::displayError('(clic to open Generator tab)') . '</a>';
                        break;
                        break;
                    case UPLOAD_ERR_PARTIAL:
                        $this->_errors[] = Tools::displayError('The uploaded file was only partially uploaded.');
                        break;
                        break;
                    case UPLOAD_ERR_NO_FILE:
                        $this->_errors[] = Tools::displayError('No file was uploaded');
                        break;
                        break;
                }
            } elseif (!file_exists($_FILES['file']['tmp_name']) or !@move_uploaded_file($_FILES['file']['tmp_name'], dirname(__FILE__) . '/../import/' . $_FILES['file']['name'] . '.' . date('Ymdhis'))) {
                $this->_errors[] = $this->l('an error occurred while uploading and copying file');
            } else {
                Tools::redirectAdmin($currentIndex . '&token=' . Tools::getValue('token') . '&conf=18');
            }
        } elseif (Tools::isSubmit('submitImportFile')) {
            $this->displayCSV();
        } elseif (Tools::getValue('import')) {
            if (Tools::getValue('truncate')) {
                $this->truncateTables((int) Tools::getValue('entity'));
            }
            $start_time = microtime(true);
            switch ((int) Tools::getValue('entity')) {
                case $this->entities[$this->l('Categories')]:
                    $lines_imported = $this->categoryImport();
                    break;
                case $this->entities[$this->l('Products')]:
                    $lines_imported = $this->productImport();
                    if ($lines_imported) {
                        Search::indexation();
                    }
                    break;
                case $this->entities[$this->l('Customers')]:
                    $lines_imported = $this->customerImport();
                    break;
                case $this->entities[$this->l('Addresses')]:
                    $lines_imported = $this->addressImport();
                    break;
                case $this->entities[$this->l('Combinations')]:
                    $lines_imported = $this->attributeImport();
                    break;
                case $this->entities[$this->l('Manufacturers')]:
                    $lines_imported = $this->manufacturerImport();
                    break;
                case $this->entities[$this->l('Suppliers')]:
                    $lines_imported = $this->supplierImport();
                    break;
                default:
                    $this->_errors[] = $this->l('no entity selected');
            }
            $end_time = microtime(true);
        }
        parent::postProcess();
        if (Tools::getValue('import') && !count($this->_errors)) {
            echo '
			<div class="conf confirm">
				<img src="../img/admin/ok.gif" alt="" />
				' . $this->l('Import successfully performed in') . ' ' . sprintf('%.02f', $end_time - $start_time) . ' ' . $this->l('seconds') . ' - ' . (int) $lines_imported . ' ' . $this->l('line(s) imported') . '
			</div>';
        }
    }
Пример #20
0
function run_indexer()
{
    $iCartType = getCartType();
    // MAGENTO
    if ($iCartType == 3) {
        require_once 'app/Mage.php';
        umask(0);
        Mage::app("default");
        $_processesCollection = Mage::getResourceModel('index/process_collection');
        foreach ($_processesCollection as $process) {
            $processes[] = $process;
        }
        foreach ($processes as $process) {
            try {
                $process->reindexEverything();
                echo $process->getIndexer()->getName() . " index was rebuilt successfully\n";
                echo "<br>";
            } catch (Mage_Core_Exception $e) {
                echo $e->getMessage() . "\n";
                echo "<br>";
            } catch (Exception $e) {
                echo $process->getIndexer()->getName() . " index process unknown error:\n";
                echo $e . "\n";
                echo "<br>";
            }
        }
        // PRESTASHOP
    } elseif ($iCartType == 5) {
        include dirname(__FILE__) . '/config/config.inc.php';
        ini_set('max_execution_time', 7200);
        Search::indexation(1);
        exit;
    }
}
Пример #21
0
 /**
  * Object creation
  */
 public function processAdd()
 {
     if (!Tools::getValue('categoryBox') || !in_array(Tools::getValue('id_category'), Tools::getValue('categoryBox'))) {
         $this->errors[] = $this->l('You need to select at least the root category.');
     }
     if (Tools::isSubmit('id_category_default')) {
         $_POST['id_category'] = (int) Tools::getValue('id_category_default');
     }
     /* Checking fields validity */
     $this->validateRules();
     if (!count($this->errors)) {
         /** @var Shop $object */
         $object = new $this->className();
         $this->copyFromPost($object, $this->table);
         $this->beforeAdd($object);
         if (!$object->add()) {
             $this->errors[] = Tools::displayError('An error occurred while creating an object.') . ' <b>' . $this->table . ' (' . Db::getInstance()->getMsgError() . ')</b>';
         } elseif (($_POST[$this->identifier] = $object->id) && $this->postImage($object->id) && !count($this->errors) && $this->_redirect) {
             $parent_id = (int) Tools::getValue('id_parent', 1);
             $this->afterAdd($object);
             $this->updateAssoShop($object->id);
             // Save and stay on same form
             if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                 $this->redirect_after = self::$currentIndex . '&shop_id=' . (int) $object->id . '&conf=3&update' . $this->table . '&token=' . $this->token;
             }
             // Save and back to parent
             if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
                 $this->redirect_after = self::$currentIndex . '&shop_id=' . (int) $parent_id . '&conf=3&token=' . $this->token;
             }
             // Default behavior (save and back)
             if (empty($this->redirect_after)) {
                 $this->redirect_after = self::$currentIndex . ($parent_id ? '&shop_id=' . $object->id : '') . '&conf=3&token=' . $this->token;
             }
         }
     }
     $this->errors = array_unique($this->errors);
     if (count($this->errors) > 0) {
         $this->display = 'add';
         return;
     }
     $object->associateSuperAdmins();
     $categories = Tools::getValue('categoryBox');
     array_unshift($categories, Configuration::get('PS_ROOT_CATEGORY'));
     Category::updateFromShop($categories, $object->id);
     if (Tools::getValue('useImportData') && ($import_data = Tools::getValue('importData')) && is_array($import_data) && isset($import_data['product'])) {
         ini_set('max_execution_time', 7200);
         // like searchcron.php
         Search::indexation(true);
     }
     return $object;
 }
Пример #22
0
 public function setProducts($array)
 {
     $result = Db::getInstance()->execute('DELETE FROM ' . _DB_PREFIX_ . 'product_tag WHERE id_tag = ' . (int) $this->id);
     if (is_array($array)) {
         $array = array_map('intval', $array);
         $result &= ObjectModel::updateMultishopTable('Product', array('indexed' => 0), 'a.id_product IN (' . implode(',', $array) . ')');
         $ids = array();
         foreach ($array as $id_product) {
             $ids[] = '(' . (int) $id_product . ',' . (int) $this->id . ')';
         }
         if ($result) {
             $result &= Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'product_tag (id_product, id_tag) VALUES ' . implode(',', $ids));
             if (Configuration::get('PS_SEARCH_INDEXATION')) {
                 $result &= Search::indexation(false);
             }
         }
     }
     return $result;
 }
Пример #23
0
 public function updateWs($null_values = false)
 {
     $success = parent::update($null_values);
     if ($success && Configuration::get('PS_SEARCH_INDEXATION')) {
         Search::indexation(false, $this->id);
     }
     Hook::exec('updateProduct', array('id_product' => (int) $this->id));
     return $success;
 }
 /**
  * Add or update a product
  *
  * @global string $currentIndex Current URL in order to keep current Tab
  */
 public function submitAddproduct($token = NULL)
 {
     global $currentIndex;
     $className = 'Product';
     $rules = call_user_func(array($this->className, 'getValidationRules'), $this->className);
     $defaultLanguage = new Language(intval(Configuration::get('PS_LANG_DEFAULT')));
     $languages = Language::getLanguages();
     /* Check required fields */
     foreach ($rules['required'] as $field) {
         if (($value = Tools::getValue($field)) == false and $value != '0') {
             if (Tools::getValue('id_' . $this->table) and $field == 'passwd') {
                 continue;
             }
             $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $field, $className) . '</b> ' . $this->l('is required');
         }
     }
     /* Check multilingual required fields */
     foreach ($rules['requiredLang'] as $fieldLang) {
         if (!Tools::getValue($fieldLang . '_' . $defaultLanguage->id)) {
             $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $fieldLang, $className) . '</b> ' . $this->l('is required at least in') . ' ' . $defaultLanguage->name;
         }
     }
     /* Check fields sizes */
     foreach ($rules['size'] as $field => $maxLength) {
         if ($value = Tools::getValue($field) and Tools::strlen($value) > $maxLength) {
             $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $field, $className) . '</b> ' . $this->l('is too long') . ' (' . $maxLength . ' ' . $this->l('chars max') . ')';
         }
     }
     if (isset($_POST['description_short'])) {
         $saveShort = $_POST['description_short'];
         $_POST['description_short'] = strip_tags($_POST['description_short']);
     }
     /* Check description short size without html */
     foreach ($languages as $language) {
         if ($value = Tools::getValue('description_short_' . $language['id_lang'])) {
             if (Tools::strlen(strip_tags($value)) > 400) {
                 $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), 'description_short') . ' (' . $language['name'] . ')</b> ' . $this->l('is too long') . ' : 400 ' . $this->l('chars max') . ' (' . $this->l('count now') . ' ' . Tools::strlen(strip_tags($value)) . ')';
             }
         }
     }
     /* Check multilingual fields sizes */
     foreach ($rules['sizeLang'] as $fieldLang => $maxLength) {
         foreach ($languages as $language) {
             if ($value = Tools::getValue($fieldLang . '_' . $language['id_lang']) and Tools::strlen($value) > $maxLength) {
                 $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $fieldLang, $className) . ' (' . $language['name'] . ')</b> ' . $this->l('is too long') . ' (' . $maxLength . ' ' . $this->l('chars max') . ')';
             }
         }
     }
     if (isset($_POST['description_short'])) {
         $_POST['description_short'] = $saveShort;
     }
     /* Check fields validity */
     foreach ($rules['validate'] as $field => $function) {
         if ($value = Tools::getValue($field)) {
             if (!Validate::$function($value)) {
                 $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $field, $className) . '</b> ' . $this->l('is invalid');
             }
         }
     }
     /* Check multilingual fields validity */
     foreach ($rules['validateLang'] as $fieldLang => $function) {
         foreach ($languages as $language) {
             if ($value = Tools::getValue($fieldLang . '_' . $language['id_lang'])) {
                 if (!Validate::$function($value)) {
                     $this->_errors[] = $this->l('the field') . ' <b>' . call_user_func(array($className, 'displayFieldName'), $fieldLang, $className) . ' (' . $language['name'] . ')</b> ' . $this->l('is invalid');
                 }
             }
         }
     }
     $productCats = '';
     if (!isset($_POST['categoryBox']) or !sizeof($_POST['categoryBox'])) {
         $this->_errors[] = $this->l('product must be in at least one Category');
     }
     foreach ($languages as $language) {
         if ($value = Tools::getValue('tags_' . $language['id_lang'])) {
             if (!Validate::isTagsList($value)) {
                 $this->_errors[] = $this->l('Tags list') . ' (' . $language['name'] . ') ' . $this->l('is invalid');
             }
         }
     }
     if (!sizeof($this->_errors)) {
         $id = intval(Tools::getValue('id_' . $this->table));
         $tagError = true;
         /* Update an existing product */
         if (isset($id) and !empty($id)) {
             $object = new $this->className($id);
             if (Validate::isLoadedObject($object)) {
                 $this->copyFromPost($object, $this->table);
                 if ($object->update()) {
                     $this->updateAccessories($object);
                     $this->updateDownloadProduct($object);
                     if (!$this->updatePackItems($object)) {
                         $this->_errors[] = Tools::displayError('an error occurred while adding products to the pack');
                     } elseif (!$object->updateCategories($_POST['categoryBox'], true)) {
                         $this->_errors[] = Tools::displayError('an error occurred while linking object') . ' <b>' . $this->table . '</b> ' . Tools::displayError('to categories');
                     } elseif (!$this->updateTags($languages, $object)) {
                         $this->_errors[] = Tools::displayError('an error occurred while adding tags');
                     } elseif ($id_image = $this->addProductImage($object, Tools::getValue('resizer'))) {
                         Hook::updateProduct($object);
                         Search::indexation(false);
                         if (Tools::getValue('resizer') == 'man' && isset($id_image) and is_int($id_image) and $id_image) {
                             Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&edit=' . strval(Tools::getValue('productCreated')) . '&id_image=' . $id_image . '&imageresize&toconf=4&submitAddAndStay=' . ((Tools::isSubmit('submitAdd' . $this->table . 'AndStay') or Tools::getValue('productCreated') == 'on') ? 'on' : 'off') . '&token=' . ($token ? $token : $this->token));
                         }
                         // Save and stay on same form
                         if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay') or $id_image and $id_image !== true) {
                             Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&addproduct&conf=4&tabs=' . intval(Tools::getValue('tabs')) . '&token=' . ($token ? $token : $this->token));
                         }
                         // Default behavior (save and back)
                         Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=4&token=' . ($token ? $token : $this->token));
                     }
                 } else {
                     $this->_errors[] = Tools::displayError('an error occurred while updating object') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')';
                 }
             } else {
                 $this->_errors[] = Tools::displayError('an error occurred while updating object') . ' <b>' . $this->table . '</b> (' . Tools::displayError('cannot load object') . ')';
             }
         } else {
             $object = new $this->className();
             $this->copyFromPost($object, $this->table);
             if ($object->add()) {
                 $this->updateAccessories($object);
                 if (!$this->updatePackItems($object)) {
                     $this->_errors[] = Tools::displayError('an error occurred while adding products to the pack');
                 }
                 $this->updateDownloadProduct($object);
                 if (!sizeof($this->_errors)) {
                     if (!$object->updateCategories($_POST['categoryBox'])) {
                         $this->_errors[] = Tools::displayError('an error occurred while linking object') . ' <b>' . $this->table . '</b> ' . Tools::displayError('to categories');
                     } else {
                         if (!$this->updateTags($languages, $object)) {
                             $this->_errors[] = Tools::displayError('an error occurred while adding tags');
                         } elseif ($id_image = $this->addProductImage($object)) {
                             Hook::addProduct($object);
                             Search::indexation(false);
                             if (Tools::getValue('resizer') == 'man' && isset($id_image) and is_int($id_image) and $id_image) {
                                 Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&id_image=' . $id_image . '&imageresize&toconf=3&submitAddAndStay=' . (Tools::isSubmit('submitAdd' . $this->table . 'AndStay') ? 'on' : 'off') . '&token=' . ($token ? $token : $this->token));
                             }
                             // Save and stay on same form
                             if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                                 Tools::redirectAdmin($currentIndex . '&id_product=' . $object->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&addproduct&conf=3&tabs=' . intval(Tools::getValue('tabs')) . '&token=' . ($token ? $token : $this->token));
                             }
                             // Default behavior (save and back)
                             Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=3&token=' . ($token ? $token : $this->token));
                         }
                     }
                 } else {
                     $object->delete();
                 }
             } else {
                 $this->_errors[] = Tools::displayError('an error occurred while creating object') . ' <b>' . $this->table . '</b>';
             }
         }
     }
 }
 public function createDummyDataForProject()
 {
     //delete privious products of prestashop
     $all_products = Product::getSimpleProducts(Configuration::get('PS_LANG_DEFAULT'));
     foreach ($all_products as $key_pro => $value_pro) {
         $obj_product = new Product($value_pro['id_product']);
         $obj_product->delete();
     }
     // first add a hotel.................
     $def_cont_id = Country::getDefaultCountryId();
     $obj_hotel_info = new HotelBranchInformation();
     $obj_hotel_info->active = 1;
     $obj_hotel_info->hotel_name = "The Hotel Prime";
     $obj_hotel_info->phone = 01234567;
     $obj_hotel_info->email = "*****@*****.**";
     $obj_hotel_info->check_in = '12:00';
     $obj_hotel_info->check_out = '12:00';
     $obj_hotel_info->short_description = $this->l('Nice place to stay');
     $obj_hotel_info->description = $this->l('Nice place to stay');
     $obj_hotel_info->rating = 3;
     $obj_hotel_info->city = 'Nainital';
     $states = State::getStatesByIdCountry($def_cont_id);
     $state_id = $states[0]['id_state'];
     $obj_hotel_info->state_id = $state_id;
     $obj_hotel_info->country_id = $def_cont_id;
     $obj_hotel_info->zipcode = 263001;
     $obj_hotel_info->policies = $this->l('1. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 2. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 3. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 4. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred.');
     $obj_hotel_info->address = 'Near post office, Mallital, Nainital';
     $obj_hotel_info->save();
     $htl_id = $obj_hotel_info->id;
     $grp_ids = array();
     $obj_grp = new Group();
     $data_grp_ids = $obj_grp->getGroups(1, $id_shop = false);
     foreach ($data_grp_ids as $key => $value) {
         $grp_ids[] = $value['id_group'];
     }
     $country_name = (new Country())->getNameById(Configuration::get('PS_LANG_DEFAULT'), $def_cont_id);
     $cat_country = $this->addCategory($country_name, false, $grp_ids);
     if ($cat_country) {
         $states = State::getStatesByIdCountry($def_cont_id);
         $state_name = $states[0]['name'];
         $cat_state = $this->addCategory($state_name, $cat_country, $grp_ids);
     }
     if ($cat_state) {
         $cat_city = $this->addCategory('DefCity', $cat_state, $grp_ids);
     }
     if ($cat_city) {
         $cat_hotel = $this->addCategory('The Hotel Prime', $cat_city, $grp_ids, 1, $htl_id);
     }
     if ($cat_hotel) {
         $obj_hotel_info = new HotelBranchInformation($htl_id);
         $obj_hotel_info->id_category = $cat_hotel;
         $obj_hotel_info->save();
     }
     $branch_ftr_ids = array(1, 2, 4, 7, 8, 9, 11, 12, 14, 16, 17, 18, 21);
     foreach ($branch_ftr_ids as $key_ftr => $value_ftr) {
         $htl_ftr_obj = new HotelBranchFeatures();
         $htl_ftr_obj->id_hotel = $htl_id;
         $htl_ftr_obj->feature_id = $value_ftr;
         $htl_ftr_obj->save();
     }
     $prod_arr = array('Delux Rooms', 'Executive Rooms', 'luxury Rooms');
     $img_num = 1;
     foreach ($prod_arr as $key_prod => $value_prod) {
         // Add Product
         $product = new Product();
         $product->name = array();
         $product->description = array();
         $product->description_short = array();
         $product->link_rewrite = array();
         foreach (Language::getLanguages(true) as $lang) {
             $product->name[$lang['id_lang']] = $value_prod;
             $product->description[$lang['id_lang']] = $this->l('Fashion axe kogi yuccie, ramps shabby chic direct trade before they sold out distillery bicycle rights. Slow-carb +1 quinoa VHS. +1 brunch trust fund, meggings chartreuse sustainable everyday carry tumblr hoodie tacos tilde ramps post-ironic fixie.');
             $product->description_short[$lang['id_lang']] = $this->l('Fashion axe kogi yuccie, ramps shabby chic direct trade before they sold out distillery bicycle rights. Slow-carb +1 quinoa VHS. +1 brunch trust fund, meggings chartreuse sustainable everyday carry tumblr hoodie tacos tilde ramps post-ironic fixie.');
             $product->link_rewrite[$lang['id_lang']] = Tools::link_rewrite('Super Delux Rooms');
         }
         $product->id_shop_default = Context::getContext()->shop->id;
         $product->id_category_default = 2;
         $product->price = 1000;
         $product->active = 1;
         $product->quantity = 99999999;
         $product->is_virtual = 1;
         $product->indexed = 1;
         $product->save();
         $product_id = $product->id;
         Search::indexation(Tools::link_rewrite($value_prod), $product_id);
         $product->addToCategories(2);
         StockAvailable::updateQuantity($product_id, null, 99999999);
         //image upload for products
         $count = 0;
         $have_cover = false;
         $old_path = _PS_MODULE_DIR_ . $this->name . '/views/img/prod_imgs/' . $img_num . '.png';
         $image_obj = new Image();
         $image_obj->id_product = $product_id;
         $image_obj->position = Image::getHighestPosition($product_id) + 1;
         if ($count == 0) {
             if (!$have_cover) {
                 $image_obj->cover = 1;
             }
         } else {
             $image_obj->cover = 0;
         }
         $image_obj->add();
         $new_path = $image_obj->getPathForCreation();
         $imagesTypes = ImageType::getImagesTypes('products');
         foreach ($imagesTypes as $image_type) {
             ImageManager::resize($old_path, $new_path . '-' . $image_type['name'] . '.jpg', $image_type['width'], $image_type['height']);
         }
         ImageManager::resize($old_path, $new_path . '.jpg');
         for ($k = 1; $k <= 5; $k++) {
             $htl_room_info_obj = new HotelRoomInformation();
             $htl_room_info_obj->id_product = $product_id;
             $htl_room_info_obj->id_hotel = $htl_id;
             $htl_room_info_obj->room_num = 'A' . $i . '-10' . $k;
             $htl_room_info_obj->id_status = 1;
             $htl_room_info_obj->floor = 'first';
             $htl_room_info_obj->save();
         }
         $htl_rm_type = new HotelRoomType();
         $htl_rm_type->id_product = $product_id;
         $htl_rm_type->id_hotel = $htl_id;
         $htl_rm_type->adult = 2;
         $htl_rm_type->children = 2;
         $htl_rm_type->save();
         $img_num++;
         // Add features to the product
         $ftr_arr = array(0 => 8, 1 => 9, 2 => 10, 3 => 11);
         $ftr_val_arr = array(0 => 34, 1 => 35, 2 => 36, 3 => 37);
         foreach ($ftr_arr as $key_htl_ftr => $val_htl_ftr) {
             $product->addFeaturesToDB($val_htl_ftr, $ftr_val_arr[$key_htl_ftr]);
         }
     }
     return true;
 }