/**
  * modifyCategories muokkaa kategorioita poistamalla ja lisäämällä uusia
  */
 public static function modifyCategories()
 {
     $params = $_POST;
     if (!empty($params['categories'])) {
         Category::remove($params['categories']);
     }
     if (!empty($params['newcategory'])) {
         Category::add($params['newcategory']);
     }
 }
Example #2
0
 function init()
 {
     $obj = new Category();
     $func = array_shift($this->param);
     $id = array_shift($this->param);
     if ($func != '') {
         $_SERVER['REQUEST_METHOD'] = 'POST';
         switch ($func) {
             case 'add':
                 $data['parent_id'] = $id;
                 $data['name'] = $_POST['name'];
                 $data['active'] = true;
                 try {
                     $obj->add($data);
                 } catch (Exception $e) {
                 }
                 header('Location: /admin_categories');
                 exit;
                 break;
             case 'save':
                 $data['name'] = $_POST['name'];
                 try {
                     $obj->update($id, $data);
                 } catch (Exception $e) {
                 }
                 header('Location: /admin_categories');
                 exit;
                 break;
             case 'delete':
                 try {
                     $obj->delete($id);
                 } catch (Exception $e) {
                 }
                 header('Location: /admin_categories');
                 exit;
                 break;
             case 'activate':
                 try {
                     $obj->invert($id);
                 } catch (Exception $e) {
                 }
                 header('Location: /admin_categories');
                 exit;
                 break;
         }
     }
 }
Example #3
0
<!--head-->
<script type="text/javascript" src="../js/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="../js/tinymce/tinymce.init.js"></script>
<!--//head-->
<?php 
if (isset($_POST['sveCategory']) && Tools::getRequest('sveCategory') == 'add') {
    $cmscategory = new Category();
    $cmscategory->copyFromPost();
    $cmscategory->add();
    if (is_array($cmscategory->_errors) and count($cmscategory->_errors) > 0) {
        $errors = $cmscategory->_errors;
    } else {
        $_GET['id'] = $cmscategory->id;
        UIAdminAlerts::conf('创建分类成功');
    }
}
if (isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $obj = new Category($id);
}
if (isset($_POST['sveCategory']) && Tools::getRequest('sveCategory') == 'edit') {
    if (Tools::getRequest('id_parent') == $obj->id) {
        $obj->_errors[] = '父分类不能为当前分类!';
    } elseif (Validate::isLoadedObject($obj)) {
        $obj->copyFromPost();
        $obj->update();
    }
    if (is_array($obj->_errors) and count($obj->_errors) > 0) {
        $errors = $obj->_errors;
    } else {
        UIAdminAlerts::conf('更新分类成功');
Example #4
0
 public function productImport()
 {
     global $cookie;
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
     self::setLocale();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $line = $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         if (array_key_exists('id', $info) and (int) $info['id'] and Product::existsInDatabase((int) $info['id'], 'product')) {
             $product = new Product((int) $info['id']);
             $categoryData = Product::getProductCategories((int) $product->id);
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp;
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         if ((int) $product->id_tax_rules_group != 0) {
             if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                 $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0);
             } 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) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists((int) $product->manufacturer)) {
             $product->id_manufacturer = (int) $product->manufacturer;
         } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) {
             if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                 $product->id_manufacturer = (int) $manufacturer;
             } else {
                 $manufacturer = new Manufacturer();
                 $manufacturer->name = $product->manufacturer;
                 if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                     $product->id_manufacturer = (int) $manufacturer->id;
                 } else {
                     $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists((int) $product->supplier)) {
             $product->id_supplier = (int) $product->supplier;
         } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) {
             if ($supplier = Supplier::getIdByName($product->supplier)) {
                 $product->id_supplier = (int) $supplier;
             } else {
                 $supplier = new Supplier();
                 $supplier->name = $product->supplier;
                 if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                     $product->id_supplier = (int) $supplier->id;
                 } else {
                     $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->price_tex) and !isset($product->price_tin)) {
             $product->price = $product->price_tex;
         } elseif (isset($product->price_tin) and !isset($product->price_tex)) {
             $product->price = $product->price_tin;
             // If a tax is already included in price, withdraw it from price
             if ($product->tax_rate) {
                 $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
             }
         } elseif (isset($product->price_tin) and isset($product->price_tex)) {
             $product->price = $product->price_tex;
         }
         if (isset($product->category) and is_array($product->category) and sizeof($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 {
                         $categoryToCreate = new Category();
                         $categoryToCreate->id = (int) $value;
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 } elseif (is_string($value) and !empty($value)) {
                     $category = Category::searchByName($defaultLanguageId, $value, true);
                     if ($category['id_category']) {
                         $product->id_category[] = (int) $category['id_category'];
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
         }
         $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) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($link_rewrite);
         if (isset($product->link_rewrite[$defaultLanguageId]) and empty($product->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
             if ($link_rewrite == '') {
                 $link_rewrite = 'friendly-url-autogeneration-failed';
             }
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrite link for') . ' ' . $link_rewrite . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $link_rewrite;
         }
         $product->link_rewrite = self::createMultiLangField($link_rewrite);
         $res = false;
         $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
         $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
         if ($fieldError === true and $langFieldError === true) {
             // check quantity
             if ($product->quantity == NULL) {
                 $product->quantity = 0;
             }
             // If match ref is specified AND ref product AND ref product already in base, trying to update
             if (Tools::getValue('match_ref') == 1 and $product->reference and Product::existsRefInDatabase($product->reference)) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add`, `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `reference` = "' . $product->reference . '"');
                 $product->id = pSQL($datas['id_product']);
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             } else {
                 if ($product->id and Product::existsInDatabase((int) $product->id, 'product')) {
                     $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `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();
                 }
             }
         }
         // If both failed, mysql error
         if (!$res) {
             $this->_errors[] = $info['name'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         } else {
             // SpecificPrice (only the basic reduction feature is supported by the import)
             if (isset($info['reduction_price']) and $info['reduction_price'] > 0 or isset($info['reduction_percent']) and $info['reduction_percent'] > 0) {
                 $specificPrice = new SpecificPrice();
                 $specificPrice->id_product = (int) $product->id;
                 $specificPrice->id_shop = (int) Shop::getCurrentShop();
                 $specificPrice->id_currency = 0;
                 $specificPrice->id_country = 0;
                 $specificPrice->id_group = 0;
                 $specificPrice->price = 0.0;
                 $specificPrice->from_quantity = 1;
                 $specificPrice->reduction = (isset($info['reduction_price']) and $info['reduction_price']) ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                 $specificPrice->reduction_type = (isset($info['reduction_price']) and $info['reduction_price']) ? 'amount' : 'percentage';
                 $specificPrice->from = (isset($info['reduction_from']) and Validate::isDate($info['reduction_from'])) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                 $specificPrice->to = (isset($info['reduction_to']) and Validate::isDate($info['reduction_to'])) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                 if (!$specificPrice->add()) {
                     $this->_addProductWarning($info['name'], $product->id, $this->l('Discount is invalid'));
                 }
             }
             if (isset($product->tags) and !empty($product->tags)) {
                 // Delete tags for this id product, for no duplicating error
                 Tag::deleteTagsForProduct($product->id);
                 $tag = new Tag();
                 if (!is_array($product->tags)) {
                     $product->tags = self::createMultiLangField($product->tags);
                     foreach ($product->tags as $key => $tags) {
                         $isTagAdded = $tag->addTags($key, $product->id, $tags);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, $this->l('Tags list') . ' ' . $this->l('is invalid'));
                             break;
                         }
                     }
                 } else {
                     foreach ($product->tags as $key => $tags) {
                         $str = '';
                         foreach ($tags as $one_tag) {
                             $str .= $one_tag . ',';
                         }
                         $str = rtrim($str, ',');
                         $isTagAdded = $tag->addTags($key, $product->id, $str);
                         if (!$isTagAdded) {
                             $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();
                 } elseif (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                     $product->deleteImages();
                 }
             }
             if (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                 $productHasImages = (bool) Image::getImages((int) $cookie->id_lang, (int) $product->id);
                 foreach ($product->image as $key => $url) {
                     if (!empty($url)) {
                         $image = new Image();
                         $image->id_product = (int) $product->id;
                         $image->position = Image::getHighestPosition($product->id) + 1;
                         $image->cover = (!$key and !$productHasImages) ? true : false;
                         $image->legend = self::createMultiLangField($product->name[$defaultLanguageId]);
                         if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                             if (!self::copyImg($product->id, $image->id, $url)) {
                                 $this->_warnings[] = Tools::displayError('Error copying image: ') . $url;
                             }
                         } else {
                             $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
             if (isset($product->id_category)) {
                 $product->updateCategories(array_map('intval', $product->id_category));
             }
             $features = get_object_vars($product);
             foreach ($features as $feature => $value) {
                 if (!strncmp($feature, '#F_', 3) and Tools::strlen($product->{$feature})) {
                     $feature_name = str_replace('#F_', '', $feature);
                     $id_feature = Feature::addFeatureImport($feature_name);
                     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $product->{$feature});
                     Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                 }
             }
         }
     }
     $this->closeCsvFile($handle);
 }
 public function productImportCreateCat($default_language_id, $category_name, $id_parent_category = null)
 {
     $category_to_create = new Category();
     $shop_is_feature_active = Shop::isFeatureActive();
     if (!$shop_is_feature_active) {
         $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($category_name));
     $category_to_create->active = 1;
     $category_to_create->id_parent = (int) $id_parent_category ? (int) $id_parent_category : (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()) {
         $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
         if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
             $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
         }
     }
 }
    public function install()
    {
        if (!method_exists('Tools', 'jsonDecode') || !method_exists('Tools', 'jsonEncode')) {
            return false;
        }
        foreach ($this->available_languages as $iso => $lang) {
            Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'CERTIFICATE_' . strtoupper($iso), Tools::htmlentitiesUTF8(Tools::jsonEncode(array('stateEnum' => '', 'typeEnum' => '', 'url' => '', 'tsID' => '', 'user' => '', 'password' => ''))));
        }
        Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'SHOPSW', '');
        Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'ET_CID', '');
        Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'ET_LID', '');
        Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'ENV_API', TSBuyerProtection::ENV_PROD);
        $req = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . TSBuyerProtection::DB_ITEMS . '` (
			`id_item` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
			`id_product` INT NOT NULL,
			`ts_id` VARCHAR( 33 ) NOT NULL,
			`id` INT NOT NULL,
			`currency` VARCHAR( 3 ) NOT NULL ,
			`gross_fee` DECIMAL( 20, 6 ) NOT NULL ,
			`net_fee` DECIMAL( 20, 6 ) NOT NULL ,
			`protected_amount_decimal` INT NOT NULL ,
			`protection_duration_int` INT NOT NULL ,
			`ts_product_id` TEXT NOT NULL ,
			`creation_date` VARCHAR( 25 ) NOT NULL
			);
		';
        Db::getInstance()->Execute($req);
        $req = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . TSBuyerProtection::DB_APPLI . '` (
			`id_application` INT NOT NULL PRIMARY KEY,
			`ts_id` VARCHAR( 33 ) NOT NULL,
			`id_order` INT NOT NULL,
			`statut_number` INT NOT NULL DEFAULT \'0\',
			`creation_date` DATETIME NOT NULL,
			`last_update` DATETIME NOT NULL
			);
		';
        Db::getInstance()->Execute($req);
        //add hidden category
        $category = new Category();
        $languages = Language::getLanguages(true);
        foreach ($this->available_languages as $iso => $lang) {
            $category->name[Language::getIdByIso(strtolower($iso))] = 'Trustedshops';
            $category->link_rewrite[Language::getIdByIso(strtolower($iso))] = 'trustedshops';
        }
        // If the default lang is different than available languages :
        // (Bug occurred otherwise)
        if (!array_key_exists(Language::getIsoById((int) Configuration::get('PS_LANG_DEFAULT')), $this->available_languages)) {
            $category->name[(int) Configuration::get('PS_LANG_DEFAULT')] = 'Trustedshops';
            $category->link_rewrite[(int) Configuration::get('PS_LANG_DEFAULT')] = 'trustedshops';
        }
        $category->id_parent = 0;
        $category->level_depth = 0;
        $category->active = 0;
        $category->add();
        Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'CAT_ID', intval($category->id));
        Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE . 'SECURE_KEY', strtoupper(Tools::passwdGen(16)));
        return true;
    }
Example #7
0
 public function productImport()
 {
     global $cookie;
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         if (array_key_exists('id', $info) and intval($info['id']) and Product::existsInDatabase(intval($info['id']))) {
             $product = new Product(intval($info['id']));
             if ($product->reduction_from == '0000-00-00') {
                 $product->reduction_from = date('Y-m-d');
             }
             if ($product->reduction_to == '0000-00-00') {
                 $product->reduction_to = date('Y-m-d');
             }
             $categoryData = Product::getIndexedCategories(intval($product->id));
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp['id_category'];
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         // Find id_tax corresponding to given values for product taxe
         if (isset($product->tax_rate)) {
             $product->id_tax = intval(Tax::getTaxIdByRate(floatval($product->tax_rate)));
         }
         if (isset($product->tax_rate) and !$product->id_tax) {
             $tax = new Tax();
             $tax->rate = floatval($product->tax_rate);
             $tax->name = self::createMultiLangField(strval($product->tax_rate));
             if (($fieldError = $tax->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $tax->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $tax->add()) {
                 $product->id_tax = intval($tax->id);
             } else {
                 $this->_errors[] = 'TAX ' . $tax->name[$defaultLanguageId] . ' ' . Tools::displayError('cannot be saved');
                 $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
             }
         }
         if (isset($product->manufacturer) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists(intval($product->manufacturer))) {
             $product->id_manufacturer = intval($product->manufacturer);
         } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) {
             if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                 $product->id_manufacturer = intval($manufacturer);
             } else {
                 $manufacturer = new Manufacturer();
                 $manufacturer->name = $product->manufacturer;
                 if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                     $product->id_manufacturer = intval($manufacturer->id);
                 } else {
                     $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists(intval($product->supplier))) {
             $product->id_supplier = intval($product->supplier);
         } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) {
             if ($supplier = Supplier::getIdByName($product->supplier)) {
                 $product->id_supplier = intval($supplier);
             } else {
                 $supplier = new Supplier();
                 $supplier->name = $product->supplier;
                 if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                     $product->id_supplier = intval($supplier->id);
                 } else {
                     $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->price_tex) and !isset($product->price_tin)) {
             $product->price = $product->price_tex;
         } elseif (isset($product->price_tin) and !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 = floatval(number_format($product->price / (1 + $product->tax_rate / 100), 6));
             }
         } elseif (isset($product->price_tin) and isset($product->price_tex)) {
             $product->price = $product->price_tex;
         }
         if (isset($product->category) and is_array($product->category) and sizeof($product->category)) {
             $product->id_category = array();
             // Reset default values array
             foreach ($product->category as $value) {
                 if (is_numeric($value)) {
                     if (Category::categoryExists(intval($value))) {
                         $product->id_category[] = intval($value);
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->id = intval($value);
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = intval($categoryToCreate->id);
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 } elseif (is_string($value) and !empty($value)) {
                     $category = Category::searchByName($defaultLanguageId, $value, true);
                     if ($category['id_category']) {
                         $product->id_category[] = intval($category['id_category']);
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = intval($categoryToCreate->id);
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
         }
         $product->id_category_default = isset($product->id_category[0]) ? intval($product->id_category[0]) : '';
         $link_rewrite = is_array($product->link_rewrite) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($link_rewrite);
         $bak = $product->link_rewrite;
         if (isset($product->link_rewrite[$defaultLanguageId]) and empty($product->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrited link for') . ' ' . $bak . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $link_rewrite;
         }
         $product->link_rewrite = self::createMultiLangField($link_rewrite);
         $res = false;
         $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
         $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
         if ($fieldError === true and $langFieldError === true) {
             // check quantity
             if ($product->quantity == NULL) {
                 $product->quantity = 0;
             }
             // If id product AND id product already in base, trying to update
             if ($product->id and Product::existsInDatabase(intval($product->id))) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . intval($product->id));
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             }
             // If no id_product or update failed
             if (!$res) {
                 $res = $product->add();
             }
         }
         // If both failed, mysql error
         if (!$res) {
             $this->_errors[] = $info['name'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         } else {
             if (isset($product->tags) and !empty($product->tags)) {
                 $tag = new Tag();
                 $array = self::createMultiLangField($product->tags);
                 foreach ($array as $key => $tags) {
                     $a = $tag->addTags($key, $product->id, $tags);
                 }
             }
             if (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                 $productHasImages = (bool) Image::getImages(intval($cookie->id_lang), intval($product->id));
                 foreach ($product->image as $key => $url) {
                     if (!empty($url)) {
                         $image = new Image();
                         $image->id_product = intval($product->id);
                         $image->position = Image::getHighestPosition($product->id) + 1;
                         $image->cover = (!$key and !$productHasImages) ? true : false;
                         $image->legend = self::createMultiLangField($product->name[$defaultLanguageId]);
                         if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                             self::copyImg($product->id, $image->id, $url);
                         } else {
                             $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
             if (isset($product->id_category)) {
                 $product->updateCategories(array_map('intval', $product->id_category));
             }
             $features = get_object_vars($product);
             foreach ($features as $feature => $value) {
                 if (!strncmp($feature, '#F_', 3) and Tools::strlen($product->{$feature})) {
                     $feature_name = str_replace('#F_', '', $feature);
                     $id_feature = Feature::addFeatureImport($feature_name);
                     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $product->{$feature});
                     Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                 }
             }
         }
     }
     $this->closeCsvFile($handle);
 }
Example #8
0
<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
//autoload packages
$db = new Database();
$category = new Category($db->conn);
//dump($vendors);
if ($_POST) {
    //dump($_FILES);
    $category->name = $_POST['name'];
    $category->status = isset($_POST['status']) ? 1 : 0;
    $num = 0;
    //exit;
    $state = false;
    if ($category->add()) {
        $state = true;
        unset($_POST);
    }
}
include 'templates/header.php';
include 'templates/sidemenu.php';
?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            Add vendor Item
            <small>Add New vendor Items to the system</small>
        </h1>
 /**
  * 自动远程保存图片
  *
  */
 public function action_saveimg()
 {
     $source = $this->getQuery('src');
     if (!URL::ping($source)) {
         echo $source;
         die;
     }
     $title = trim($this->getQuery('title'));
     $data = @file_get_contents($source);
     $filename = basename($source);
     $extension = strtolower(strtolower(substr(strrchr($filename, '.'), 1)));
     $saveName = str_replace('.', '', microtime(true));
     // 保存的文件名
     $disk = ORM::factory('img_disk')->where('is_use', '=', 1)->find();
     $save_dir = ORM::factory('user', $this->auth['uid'])->save_dir;
     $savefile = Io::strip(Io::mkdir(DOCROOT . $disk->disk_name . '/' . $save_dir) . '/' . $saveName . ".{$extension}");
     $filesize = @file_put_contents($savefile, $data);
     //保存文件,返回文件的size
     if ($filesize == 0) {
         //保存失败
         @unlink($savefile);
         throw new Exception('文件保存到本地目录时失败');
     }
     list($w, $h, $t, ) = getimagesize($savefile);
     $filetype = image_type_to_mime_type($t);
     if (!preg_match('/^image\\/.+/i', $filetype)) {
         throw new Exception('转存文件并非有效的图片文件');
     }
     $category = ORM::factory('img_category')->where('cate_name', '=', '产品搬家')->where('uid', '=', $this->auth['uid'])->find();
     $cate = new Category();
     if (empty($category->cate_name)) {
         $cate_id = $cate->add(array('cate_name' => '产品搬家', 'uid' => $this->auth['uid']));
     } else {
         $cate_id = $category->cate_id;
     }
     $movehomeSession = Session::instance()->get('movehome_id', false);
     if (!empty($title)) {
         if (empty($movehomeSession)) {
             $cate_id = $cate->add(array('cate_name' => $title, 'uid' => $this->auth['uid'], 'parent_id' => $cate_id));
             Session::instance()->set('movehome_id', $cate_id);
         } else {
             $cate_id = $movehomeSession;
         }
     }
     $img = ORM::factory('img');
     $img->picname = $saveName . ".{$extension}";
     $img->filename = $filename;
     $img->filesize = $filesize;
     $img->userid = $this->auth['uid'];
     $img->cate_id = $cate_id;
     $img->disk_id = $disk->disk_domain;
     $img->disk_name = $disk->disk_name . '/' . $save_dir;
     $img->custom_name = $saveName;
     $img->save();
     $url = "http://" . $disk->disk_domain . '.wal8.com/' . $disk->disk_name . '/' . $save_dir . '/' . $saveName . ".{$extension}";
     // 统计数据
     $num = $img->where('userid', '=', $this->auth['uid'])->where('cate_id', '=', $cate_id)->count_all();
     DB::update('img_categories')->set(array('img_num' => $num))->where('uid', '=', $this->auth['uid'])->where('cate_id', '=', $cate_id)->execute();
     $rows = DB::select(array('sum("filesize")', 'total_size'), array('count("userid")', 'total_num'))->from('imgs')->where('userid', '=', $this->auth['uid'])->execute()->current();
     DB::update('users')->set(array('use_space' => $rows['total_size'], 'count_img' => $rows['total_num']))->where('uid', '=', $this->auth['uid'])->execute();
     $result = array('status' => true, 'source' => $source, 'url' => $url);
     echo $url;
     $this->auto_render = false;
 }
Example #10
0
 public function addCategory()
 {
     // Get category name from PARAMS
     $categoryName = $this->f3->get('PARAMS.name');
     // setup result object
     $result = array('success' => false, 'status' => '', 'message' => '', 'records' => array());
     // Check if category name already exists
     $category = new Category($this->db);
     $existingCategory = $category->filterByName($categoryName);
     if ($existingCategory >= 1) {
         $result[status] = 'error';
         $result[message] = 'Category name already exists';
     } else {
         // try insert
         $this->f3->set('POST.categoryName', $categoryName);
         $category->add();
         // Change status and message
         $result[status] = 'success';
         $result[success] = true;
         $result[message] = 'Successfully added new category';
         // return new set of categories for client
         $categories = $category->all();
         foreach ($categories as $category) {
             $result[records][] = array('id' => $category->categoryId, 'text' => $category->categoryName);
         }
     }
     header('Content-Type: application/json');
     echo json_encode($result, JSON_NUMERIC_CHECK);
     exit;
 }
 public function addCategory($name, $parent_cat = false, $group_ids, $ishotel = false, $hotel_id = false)
 {
     if (!$parent_cat) {
         $parent_cat = Category::getRootCategory()->id;
     }
     if ($ishotel && $hotel_id) {
         $cat_id_hotel = Db::getInstance()->getValue('SELECT `id_category` FROM `' . _DB_PREFIX_ . 'htl_branch_info` WHERE id=' . $hotel_id);
         if ($cat_id_hotel) {
             $obj_cat = new Category($cat_id_hotel);
             $obj_cat->name = array();
             $obj_cat->description = array();
             $obj_cat->link_rewrite = array();
             foreach (Language::getLanguages(true) as $lang) {
                 $obj_cat->name[$lang['id_lang']] = $name;
                 $obj_cat->description[$lang['id_lang']] = $this->l('this category are for hotels only');
                 $obj_cat->link_rewrite[$lang['id_lang']] = $this->l(Tools::link_rewrite($name));
             }
             $obj_cat->id_parent = $parent_cat;
             $obj_cat->groupBox = $group_ids;
             $obj_cat->save();
             $cat_id = $obj_cat->id;
             return $cat_id;
         }
     }
     $check_category_exists = Category::searchByNameAndParentCategoryId($this->context->language->id, $name, $parent_cat);
     if ($check_category_exists) {
         return $check_category_exists['id_category'];
     } else {
         $obj = new Category();
         $obj->name = array();
         $obj->description = array();
         $obj->link_rewrite = array();
         foreach (Language::getLanguages(true) as $lang) {
             $obj->name[$lang['id_lang']] = $name;
             $obj->description[$lang['id_lang']] = $this->l('this category are for hotels only');
             $obj->link_rewrite[$lang['id_lang']] = $this->l(Tools::link_rewrite($name));
         }
         $obj->id_parent = $parent_cat;
         $obj->groupBox = $group_ids;
         $obj->add();
         $cat_id = $obj->id;
         return $cat_id;
     }
 }
Example #12
0
 * Created by PhpStorm.
 * User: Hoan
 * Date: 10/28/2015
 * Time: 12:50 AM
 * Thêm mới danh mục sản phẩm.
 */
//Khởi động session
session_start();
//Kiểm tra nếu chưa đăng nhập thì quay về trang đăng nhập
if (!isset($_SESSION['user'])) {
    header('location:../user/login.php');
}
require '../../config/Config.php';
require '../../models/Category.php';
date_default_timezone_set('Asia/Ho_Chi_Minh');
if ($_POST) {
    $data = array('name' => $_POST['name'], 'status' => isset($_POST['status']) ? 1 : 0, 'created' => date('Y-m-d H:i:s'), 'modified' => date('Y-m-d H:i:s'));
    $categoryModel = new Category();
    //Thêm mới
    if ($categoryModel->add($data)) {
        //Tạo session để lưu cờ thông báo thành công
        $_SESSION['success'] = true;
        //Tải lại trang (Mục đích là để reset form)
        header('location:list.php');
        //Ngừng thực thi
        exit;
    } else {
        echo "That bai";
    }
}
require '../../views/category/v_add.php';
 /**
  * 增加相册
  *
  */
 public function action_addcate()
 {
     $this->checkSpace();
     //空间验证
     if ($this->isPost()) {
         $post = Validate::factory($this->getPost())->filter(TRUE, 'trim')->rule('cate_name', 'not_empty');
         if ($post->check()) {
             $cate = new Category();
             $arr = array('cate_name' => trim($this->getPost('cate_name')), 'uid' => $this->auth['uid'], 'parent_id' => (int) $this->getPost('parent_id'));
             try {
                 $lastId = $cate->add($arr);
                 $this->request->redirect('/category/list?cate_id=' . $lastId);
             } catch (Exception $e) {
                 $this->show_message('操作失败:' . $e->getMessage());
             }
         } else {
             $e = $post->errors('');
             $this->show_message($e);
         }
     }
     $this->auto_render = false;
 }
    public function install()
    {
        global $cookie;
        if (!parent::install() or !Configuration::updateValue('SOCOLISSIMO_ID', NULL) or !Configuration::updateValue('SOCOLISSIMO_KEY', NULL) or !Configuration::updateValue('SOCOLISSIMO_VERSION', '1.9') or !Configuration::updateValue('SOCOLISSIMO_URL', 'https://ws.colissimo.fr/pudo-fo-frame/storeCall.do') or !Configuration::updateValue('SOCOLISSIMO_PREPARATION_TIME', 1) or !Configuration::updateValue('SOCOLISSIMO_EXP_BEL', false) or !Configuration::updateValue('SOCOLISSIMO_OVERCOST', 3.01) or !$this->registerHook('extraCarrier') or !$this->registerHook('AdminOrder') or !$this->registerHook('updateCarrier') or !Configuration::updateValue('SOCOLISSIMO_COST_SELLER', 0) or !$this->registerHook('newOrder') or !Configuration::updateValue('SOCOLISSIMO_SUP_URL', 'http://ws.colissimo.fr/supervision-pudo-frame/supervision.jsp') or !Configuration::updateValue('SOCOLISSIMO_SUP', true)) {
            return false;
        }
        //creat config table in database
        $sql = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'socolissimo_delivery_info` (
				  `id_cart` int(10) NOT NULL,
				  `id_customer` int(10) NOT NULL,
				  `delivery_mode` varchar(3) NOT NULL,
				  `prid` text(10) NOT NULL,
				  `prname` varchar(64) NOT NULL,
				  `prfirstname` varchar(64) NOT NULL,
				  `prcompladress` text NOT NULL,
				  `pradress1` text NOT NULL,
				  `pradress2` text NOT NULL,
				  `pradress3` text NOT NULL,
				  `pradress4` text NOT NULL,
				  `przipcode` text(10) NOT NULL,
				  `prtown` varchar(64) NOT NULL,
                               `cecountry` varchar(10) NOT NULL,
				  `cephonenumber` varchar(10) NOT NULL,
				  `ceemail` varchar(64) NOT NULL,
				  `cecompanyname` varchar(64) NOT NULL,
				  `cedeliveryinformation` text NOT NULL,
				  `cedoorcode1` varchar(10) NOT NULL,
				  `cedoorcode2` varchar(10) NOT NULL,
				  PRIMARY KEY  (`id_cart`,`id_customer`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8;';
        if (!Db::getInstance()->Execute($sql)) {
            return false;
        }
        //add carrier in back office
        if (!$this->createSoColissimoCarrier($this->_config)) {
            return false;
        }
        // add carrier for cost seller
        if (!$this->createSoColissimoCarrierSeller($this->_config)) {
            return false;
        }
        //add hidden category
        $category = new Category();
        $languages = Language::getLanguages(true);
        foreach ($languages as $language) {
            if ($language['iso_code'] == 'fr') {
                $category->name[$language['id_lang']] = 'SoColissimo';
                $category->link_rewrite[$language['id_lang']] = 'socolissimo';
            }
            if ($language['iso_code'] == 'en') {
                $category->name[$language['id_lang']] = 'SoColissimo';
                $category->link_rewrite[$language['id_lang']] = 'socolissimo';
            }
        }
        $category->link_rewrite = 'socolissimo';
        $category->id_parent = 0;
        $category->level_depth = 0;
        $category->active = 0;
        $category->add();
        Configuration::updateValue('SOCOLISSIMO_CAT_ID', intval($category->id));
        //add hidden product
        $product = new Product();
        $languages = Language::getLanguages(true);
        foreach ($languages as $language) {
            if ($language['iso_code'] == 'fr') {
                $product->name[$language['id_lang']] = 'Surcoût RDV';
                $product->link_rewrite[$language['id_lang']] = 'overcost';
            }
            if ($language['iso_code'] == 'en') {
                $product->name[$language['id_lang']] = 'Overcost';
                $product->link_rewrite[$language['id_lang']] = 'overcost';
            }
        }
        $product->quantity = 10;
        $product->price = 0;
        $product->id_category_default = intval($category->id);
        $product->active = true;
        $product->id_tax = 0;
        $product->add();
        Configuration::updateValue('SOCOLISSIMO_PRODUCT_ID', intval($product->id));
        //add hidden product overcots belgium
        $product = new Product();
        $languages = Language::getLanguages(true);
        foreach ($languages as $language) {
            if ($language['iso_code'] == 'fr') {
                $product->name[$language['id_lang']] = 'Surcoût belgique';
                $product->link_rewrite[$language['id_lang']] = 'belgium';
            }
            if ($language['iso_code'] == 'en') {
                $product->name[$language['id_lang']] = 'Overcost Belgium';
                $product->link_rewrite[$language['id_lang']] = 'belgium';
            }
        }
        $product->quantity = 10;
        $product->price = 0;
        $product->id_category_default = intval($category->id);
        $product->active = true;
        $product->id_tax = 0;
        $product->add();
        Configuration::updateValue('SOCOLISSIMO_PRODUCT_ID_BELG', intval($product->id));
        return true;
    }
Example #15
0
 public function loadCategory($str_category)
 {
     $categoryArr = explode($this->limit, $str_category);
     array_pop($categoryArr);
     array_shift($categoryArr);
     $id_parent = 1;
     $category_paths = array();
     foreach ($categoryArr as $name) {
         if (!($result = $this->_catelogExists($name, $id_parent))) {
             $category = new Category();
             $category->copyFromPost();
             $category->name = pSQL($name);
             $category->active = 1;
             $category->id_parent = (int) $id_parent;
             $category->rewrite = pSQL(preg_replace("/[^-0-9a-zA-Z]+/", "", str_replace(' ', '-', trim($name))));
             $category->add();
             $id_parent = $category->id;
             unset($category);
         } else {
             $id_parent = $result;
         }
         $category_paths[] = $id_parent;
     }
     return $category_paths;
 }
Example #16
0
function importer($path, $node, $line)
{
    global $blogid, $migrational, $items, $item;
    switch ($path) {
        case '/blog/setting':
            setProgress($item++ / $items * 100, _t('블로그 설정을 복원하고 있습니다.'));
            $setting = new BlogSetting();
            if (isset($node['title'][0]['.value'])) {
                $setting->title = $node['title'][0]['.value'];
            }
            if (isset($node['description'][0]['.value'])) {
                $setting->description = $node['description'][0]['.value'];
            }
            if (isset($node['banner'][0]['name'][0]['.value'])) {
                $setting->banner = $node['banner'][0]['name'][0]['.value'];
            }
            if (isset($node['useSloganOnPost'][0]['.value'])) {
                $setting->useSloganOnPost = $node['useSloganOnPost'][0]['.value'];
            }
            if (isset($node['postsOnPage'][0]['.value'])) {
                $setting->postsOnPage = $node['postsOnPage'][0]['.value'];
            }
            if (isset($node['postsOnList'][0]['.value'])) {
                $setting->postsOnList = $node['postsOnList'][0]['.value'];
            }
            if (isset($node['postsOnFeed'][0]['.value'])) {
                $setting->postsOnFeed = $node['postsOnFeed'][0]['.value'];
            }
            if (isset($node['publishWholeOnFeed'][0]['.value'])) {
                $setting->publishWholeOnFeed = $node['publishWholeOnFeed'][0]['.value'];
            }
            if (isset($node['acceptGuestComment'][0]['.value'])) {
                $setting->acceptGuestComment = $node['acceptGuestComment'][0]['.value'];
            }
            if (isset($node['acceptcommentOnGuestComment'][0]['.value'])) {
                $setting->acceptcommentOnGuestComment = $node['acceptcommentOnGuestComment'][0]['.value'];
            }
            if (isset($node['language'][0]['.value'])) {
                $setting->language = $node['language'][0]['.value'];
            }
            if (isset($node['timezone'][0]['.value'])) {
                $setting->timezone = $node['timezone'][0]['.value'];
            }
            if (!$setting->save()) {
                user_error(__LINE__ . $setting->error);
            }
            if (!empty($setting->banner) && !empty($node['banner'][0]['content'][0]['.stream'])) {
                Attachment::confirmFolder();
                Utils_Base64Stream::decode($node['banner'][0]['content'][0]['.stream'], Path::combine(ROOT, 'attach', $blogid, $setting->banner));
                Attachment::adjustPermission(Path::combine(ROOT, 'attach', $blogid, $setting->banner));
                fclose($node['banner'][0]['content'][0]['.stream']);
                unset($node['banner'][0]['content'][0]['.stream']);
            }
            return true;
        case '/blog/category':
            setProgress($item++ / $items * 100, _t('분류를 복원하고 있습니다.'));
            $category = new Category();
            $category->name = $node['name'][0]['.value'];
            $category->priority = $node['priority'][0]['.value'];
            if (isset($node['root'][0]['.value'])) {
                $category->id = 0;
            }
            if (!$category->add()) {
                user_error(__LINE__ . $category->error);
            }
            if (isset($node['category'])) {
                for ($i = 0; $i < count($node['category']); $i++) {
                    $childCategory = new Category();
                    $childCategory->parent = $category->id;
                    $cursor =& $node['category'][$i];
                    $childCategory->name = $cursor['name'][0]['.value'];
                    $childCategory->priority = $cursor['priority'][0]['.value'];
                    if (!$childCategory->add()) {
                        user_error(__LINE__ . $childCategory->error);
                    }
                }
            }
            return true;
        case '/blog/post':
            setProgress($item++ / $items * 100, _t('글을 복원하고 있습니다.'));
            $post = new Post();
            $post->id = $node['id'][0]['.value'];
            $post->slogan = @$node['.attributes']['slogan'];
            $post->visibility = $node['visibility'][0]['.value'];
            if (isset($node['starred'][0]['.value'])) {
                $post->starred = $node['starred'][0]['.value'];
            } else {
                $post->starred = 0;
            }
            $post->title = $node['title'][0]['.value'];
            $post->content = $node['content'][0]['.value'];
            $post->contentformatter = isset($node['content'][0]['.attributes']['formatter']) ? $node['content'][0]['.attributes']['formatter'] : 'ttml';
            $post->contenteditor = isset($node['content'][0]['.attributes']['editor']) ? $node['content'][0]['.attributes']['editor'] : 'modern';
            $post->location = $node['location'][0]['.value'];
            $post->password = isset($node['password'][0]['.value']) ? $node['password'][0]['.value'] : null;
            $post->acceptcomment = $node['acceptComment'][0]['.value'];
            $post->accepttrackback = $node['acceptTrackback'][0]['.value'];
            $post->published = $node['published'][0]['.value'];
            if (isset($node['longitude'][0]['.value'])) {
                $post->longitude = $node['longitude'][0]['.value'];
            }
            if (isset($node['latitude'][0]['.value'])) {
                $post->latitude = $node['latitude'][0]['.value'];
            }
            $post->created = @$node['created'][0]['.value'];
            $post->modified = @$node['modified'][0]['.value'];
            if ($post->visibility == 'private' && intval($post->published) > $_SERVER['REQUEST_TIME'] || !empty($node['appointed'][0]['.value']) && $node['appointed'][0]['.value'] == 'true') {
                // for compatibility of appointed entries
                $post->visibility = 'appointed';
            }
            if ($post->slogan == '') {
                $post->slogan = 'Untitled' . $post->id;
            }
            if (!empty($node['category'][0]['.value'])) {
                $post->category = Category::getId($node['category'][0]['.value']);
            }
            if (isset($node['tag'])) {
                $post->tags = array();
                for ($i = 0; $i < count($node['tag']); $i++) {
                    if (!empty($node['tag'][$i]['.value'])) {
                        array_push($post->tags, $node['tag'][$i]['.value']);
                    }
                }
            }
            if (floatval(Setting::getServiceSettingGlobal('newlineStyle')) >= 1.1 && floatval(@$node['.attributes']['format']) < 1.1) {
                $post->content = nl2brWithHTML($post->content);
            }
            if (!$post->add()) {
                user_error(__LINE__ . $post->error);
            }
            if (isset($node['attachment'])) {
                for ($i = 0; $i < count($node['attachment']); $i++) {
                    $attachment = new Attachment();
                    $attachment->parent = $post->id;
                    $cursor =& $node['attachment'][$i];
                    $attachment->name = $cursor['name'][0]['.value'];
                    $attachment->label = $cursor['label'][0]['.value'];
                    $attachment->mime = @$cursor['.attributes']['mime'];
                    $attachment->size = $cursor['.attributes']['size'];
                    $attachment->width = $cursor['.attributes']['width'];
                    $attachment->height = $cursor['.attributes']['height'];
                    $attachment->enclosure = @$cursor['enclosure'][0]['.value'];
                    $attachment->attached = $cursor['attached'][0]['.value'];
                    $attachment->downloads = @$cursor['downloads'][0]['.value'];
                    if (!$attachment->add()) {
                        user_error(__LINE__ . $attachment->error);
                    } else {
                        if ($cursor['name'][0]['.value'] != $attachment->name) {
                            $post2 = new Post();
                            if ($post2->open($post->id, 'id, content')) {
                                $post2->content = str_replace($cursor['name'][0]['.value'], $attachment->name, $post2->content);
                                $post2->loadTags();
                                $post2->update();
                                $post2->close();
                            }
                            unset($post2);
                        }
                    }
                    if (!empty($cursor['content'][0]['.stream'])) {
                        Utils_Base64Stream::decode($cursor['content'][0]['.stream'], Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        Attachment::adjustPermission(Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        fclose($cursor['content'][0]['.stream']);
                        unset($cursor['content'][0]['.stream']);
                    }
                }
            }
            if (isset($node['comment'])) {
                for ($i = 0; $i < count($node['comment']); $i++) {
                    $comment = new Comment();
                    $comment->entry = $post->id;
                    $cursor =& $node['comment'][$i];
                    $comment->name = $cursor['commenter'][0]['name'][0]['.value'];
                    if (!empty($cursor['id'][0]['.value'])) {
                        $comment->id = $cursor['id'][0]['.value'];
                    }
                    if (!empty($cursor['commenter'][0]['.attributes']['id'])) {
                        $comment->commenter = $cursor['commenter'][0]['.attributes']['id'];
                    }
                    if (!empty($cursor['commenter'][0]['homepage'][0]['.value'])) {
                        $comment->homepage = $cursor['commenter'][0]['homepage'][0]['.value'];
                    }
                    if (!empty($cursor['commenter'][0]['ip'][0]['.value'])) {
                        $comment->ip = $cursor['commenter'][0]['ip'][0]['.value'];
                    }
                    if (!empty($cursor['commenter'][0]['openid'][0]['.value'])) {
                        $comment->openid = $cursor['commenter'][0]['openid'][0]['.value'];
                    }
                    $comment->password = $cursor['password'][0]['.value'];
                    $comment->secret = $cursor['secret'][0]['.value'];
                    $comment->written = $cursor['written'][0]['.value'];
                    if (isset($cursor['longitude'][0]['.value'])) {
                        $comment->longitude = $cursor['longitude'][0]['.value'];
                    }
                    if (isset($cursor['latitude'][0]['.value'])) {
                        $comment->latitude = $cursor['latitude'][0]['.value'];
                    }
                    $comment->content = $cursor['content'][0]['.value'];
                    if (!empty($cursor['isFiltered'][0]['.value'])) {
                        $comment->isfiltered = $cursor['isFiltered'][0]['.value'];
                    }
                    if (!$comment->add()) {
                        user_error(__LINE__ . $comment->error);
                    }
                    if (isset($node['comment'][$i]['comment'])) {
                        for ($j = 0; $j < count($node['comment'][$i]['comment']); $j++) {
                            $childComment = new Comment();
                            $childComment->entry = $post->id;
                            $childComment->parent = $comment->id;
                            $cursor =& $node['comment'][$i]['comment'][$j];
                            if (!empty($cursor['id'][0]['.value'])) {
                                $childComment->id = $cursor['id'][0]['.value'];
                            }
                            if (!empty($cursor['commenter'][0]['.attributes']['id'])) {
                                $childComment->commenter = $cursor['commenter'][0]['.attributes']['id'];
                            }
                            $childComment->name = $cursor['commenter'][0]['name'][0]['.value'];
                            if (!empty($cursor['commenter'][0]['homepage'][0]['.value'])) {
                                $childComment->homepage = $cursor['commenter'][0]['homepage'][0]['.value'];
                            }
                            if (!empty($cursor['commenter'][0]['ip'][0]['.value'])) {
                                $childComment->ip = $cursor['commenter'][0]['ip'][0]['.value'];
                            }
                            if (!empty($cursor['commenter'][0]['openid'][0]['.value'])) {
                                $childComment->openid = $cursor['commenter'][0]['openid'][0]['.value'];
                            }
                            $childComment->password = $cursor['password'][0]['.value'];
                            $childComment->secret = $cursor['secret'][0]['.value'];
                            $childComment->written = $cursor['written'][0]['.value'];
                            if (isset($cursor['longitude'][0]['.value'])) {
                                $comment->longitude = $cursor['longitude'][0]['.value'];
                            }
                            if (isset($cursor['latitude'][0]['.value'])) {
                                $comment->latitude = $cursor['latitude'][0]['.value'];
                            }
                            $childComment->content = $cursor['content'][0]['.value'];
                            if (!empty($cursor['isFiltered'][0]['.value'])) {
                                $childComment->isfiltered = $cursor['isFiltered'][0]['.value'];
                            }
                            if (!$childComment->add()) {
                                user_error(__LINE__ . $childComment->error);
                            }
                        }
                    }
                }
            }
            if (isset($node['trackback'])) {
                for ($i = 0; $i < count($node['trackback']); $i++) {
                    $trackback = new Trackback();
                    $trackback->entry = $post->id;
                    $cursor =& $node['trackback'][$i];
                    $trackback->url = $cursor['url'][0]['.value'];
                    $trackback->site = $cursor['site'][0]['.value'];
                    $trackback->title = $cursor['title'][0]['.value'];
                    $trackback->excerpt = @$cursor['excerpt'][0]['.value'];
                    if (!empty($cursor['ip'][0]['.value'])) {
                        $trackback->ip = $cursor['ip'][0]['.value'];
                    }
                    if (!empty($cursor['received'][0]['.value'])) {
                        $trackback->received = $cursor['received'][0]['.value'];
                    }
                    if (!empty($cursor['isFiltered'][0]['.value'])) {
                        $trackback->isFiltered = $cursor['isFiltered'][0]['.value'];
                    }
                    if (!$trackback->add()) {
                        user_error(__LINE__ . $trackback->error);
                    }
                }
            }
            if (isset($node['logs'][0]['trackback'])) {
                for ($i = 0; $i < count($node['logs'][0]['trackback']); $i++) {
                    $log = new TrackbackLog();
                    $log->entry = $post->id;
                    $cursor =& $node['logs'][0]['trackback'][$i];
                    $log->url = $cursor['url'][0]['.value'];
                    if (!empty($cursor['sent'][0]['.value'])) {
                        $log->sent = $cursor['sent'][0]['.value'];
                    }
                    if (!$log->add()) {
                        user_error(__LINE__ . $log->error);
                    }
                }
            }
            return true;
        case '/blog/page':
            setProgress($item++ / $items * 100, _t('페이지를 복원하고 있습니다.'));
            $page = new Page();
            $page->id = $node['id'][0]['.value'];
            $page->slogan = @$node['.attributes']['slogan'];
            $page->visibility = $node['visibility'][0]['.value'];
            if (isset($node['starred'][0]['.value'])) {
                $page->starred = $node['starred'][0]['.value'];
            } else {
                $page->starred = 0;
            }
            $page->title = $node['title'][0]['.value'];
            $page->content = $node['content'][0]['.value'];
            $page->contentformatter = isset($node['content']['.attributes']['formatter']) ? $node['content']['.attributes']['formatter'] : getDefaultFormatter();
            $page->contenteditor = isset($node['content']['.attributes']['editor']) ? $node['content']['.attributes']['editor'] : getDefaultEditor();
            $page->published = $node['published'][0]['.value'];
            $page->created = @$node['created'][0]['.value'];
            $page->modified = @$node['modified'][0]['.value'];
            if (floatval(Setting::getServiceSettingGlobal('newlineStyle')) >= 1.1 && floatval(@$node['.attributes']['format']) < 1.1) {
                $page->content = nl2brWithHTML($page->content);
            }
            if (!$page->add()) {
                user_error(__LINE__ . $page->error);
            }
            if (isset($node['attachment'])) {
                for ($i = 0; $i < count($node['attachment']); $i++) {
                    $attachment = new Attachment();
                    $attachment->parent = $page->id;
                    $cursor =& $node['attachment'][$i];
                    $attachment->name = $cursor['name'][0]['.value'];
                    $attachment->label = $cursor['label'][0]['.value'];
                    $attachment->mime = @$cursor['.attributes']['mime'];
                    $attachment->size = $cursor['.attributes']['size'];
                    $attachment->width = $cursor['.attributes']['width'];
                    $attachment->height = $cursor['.attributes']['height'];
                    $attachment->enclosure = @$cursor['enclosure'][0]['.value'];
                    $attachment->attached = $cursor['attached'][0]['.value'];
                    $attachment->downloads = @$cursor['downloads'][0]['.value'];
                    if (Attachment::doesExist($attachment->name)) {
                        if (!$attachment->add()) {
                            user_error(__LINE__ . $attachment->error);
                        }
                        $page2 = new Page();
                        if ($page2->open($page->id, 'id, content')) {
                            $page2->content = str_replace($cursor['name'][0]['.value'], $attachment->name, $page2->content);
                            $page2->update();
                            $page2->close();
                        }
                        unset($page2);
                    } else {
                        if (!$attachment->add()) {
                            user_error(__LINE__ . $attachment->error);
                        }
                    }
                    if (!empty($cursor['content'][0]['.stream'])) {
                        Utils_Base64Stream::decode($cursor['content'][0]['.stream'], Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        Attachment::adjustPermission(Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        fclose($cursor['content'][0]['.stream']);
                        unset($cursor['content'][0]['.stream']);
                    }
                }
            }
            return true;
        case '/blog/notice':
            setProgress($item++ / $items * 100, _t('공지를 복원하고 있습니다.'));
            $notice = new Notice();
            $notice->id = $node['id'][0]['.value'];
            $notice->slogan = @$node['.attributes']['slogan'];
            $notice->visibility = $node['visibility'][0]['.value'];
            if (isset($node['starred'][0]['.value'])) {
                $notice->starred = $node['starred'][0]['.value'];
            } else {
                $notice->starred = 0;
            }
            $notice->title = $node['title'][0]['.value'];
            $notice->content = $node['content'][0]['.value'];
            $notice->contentformatter = isset($node['content'][0]['.attributes']['formatter']) ? $node['content'][0]['.attributes']['formatter'] : getDefaultFormatter();
            $notice->contenteditor = isset($node['content'][0]['.attributes']['editor']) ? $node['content'][0]['.attributes']['editor'] : getDefaultEditor();
            $notice->published = intval($node['published'][0]['.value']);
            $notice->created = @$node['created'][0]['.value'];
            $notice->modified = @$node['modified'][0]['.value'];
            if (floatval(Setting::getServiceSettingGlobal('newlineStyle')) >= 1.1 && floatval(@$node['.attributes']['format']) < 1.1) {
                $notice->content = nl2brWithHTML($notice->content);
            }
            if (!$notice->add()) {
                user_error(__LINE__ . $notice->error);
            }
            if (isset($node['attachment'])) {
                for ($i = 0; $i < count($node['attachment']); $i++) {
                    $attachment = new Attachment();
                    $attachment->parent = $notice->id;
                    $cursor =& $node['attachment'][$i];
                    $attachment->name = $cursor['name'][0]['.value'];
                    $attachment->label = $cursor['label'][0]['.value'];
                    $attachment->mime = @$cursor['.attributes']['mime'];
                    $attachment->size = $cursor['.attributes']['size'];
                    $attachment->width = $cursor['.attributes']['width'];
                    $attachment->height = $cursor['.attributes']['height'];
                    $attachment->enclosure = @$cursor['enclosure'][0]['.value'];
                    $attachment->attached = $cursor['attached'][0]['.value'];
                    $attachment->downloads = @$cursor['downloads'][0]['.value'];
                    if (Attachment::doesExist($attachment->name)) {
                        if (!$attachment->add()) {
                            user_error(__LINE__ . $attachment->error);
                        }
                        $notice2 = new Notice();
                        if ($notice2->open($notice->id, 'id, content')) {
                            $notice2->content = str_replace($cursor['name'][0]['.value'], $attachment->name, $notice2->content);
                            $notice2->update();
                            $notice2->close();
                        }
                        unset($notice2);
                    } else {
                        if (!$attachment->add()) {
                            user_error(__LINE__ . $attachment->error);
                        }
                    }
                    if (!empty($cursor['content'][0]['.stream'])) {
                        Utils_Base64Stream::decode($cursor['content'][0]['.stream'], Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        Attachment::adjustPermission(Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        fclose($cursor['content'][0]['.stream']);
                        unset($cursor['content'][0]['.stream']);
                    }
                }
            }
            return true;
        case '/blog/keyword':
            setProgress($item++ / $items * 100, _t('키워드를 복원하고 있습니다.'));
            $keyword = new Keyword();
            $keyword->id = $node['id'][0]['.value'];
            $keyword->visibility = $node['visibility'][0]['.value'];
            if (isset($node['starred'][0]['.value'])) {
                $keyword->starred = $node['starred'][0]['.value'];
            } else {
                $keyword->starred = 0;
            }
            $keyword->name = $node['name'][0]['.value'];
            $keyword->description = $node['description'][0]['.value'];
            $keyword->descriptionEditor = isset($node['description'][0]['.attributes']['editor']) ? $node['description'][0]['.attributes']['editor'] : getDefaultEditor();
            $keyword->descriptionFormatter = isset($node['description'][0]['.attributes']['formatter']) ? $node['description'][0]['.attributes']['formatter'] : getDefaultFormatter();
            $keyword->published = intval($node['published'][0]['.value']);
            $keyword->created = @$node['created'][0]['.value'];
            $keyword->modified = @$node['modified'][0]['.value'];
            if (floatval(Setting::getServiceSettingGlobal('newlineStyle')) >= 1.1 && floatval(@$node['.attributes']['format']) < 1.1) {
                $keyword->description = nl2brWithHTML($keyword->description);
            }
            if (!$keyword->add()) {
                user_error(__LINE__ . $keyword->error);
            }
            if (isset($node['attachment'])) {
                for ($i = 0; $i < count($node['attachment']); $i++) {
                    $attachment = new Attachment();
                    $attachment->parent = $keyword->id;
                    $cursor =& $node['attachment'][$i];
                    $attachment->name = $cursor['name'][0]['.value'];
                    $attachment->label = $cursor['label'][0]['.value'];
                    $attachment->mime = @$cursor['.attributes']['mime'];
                    $attachment->size = $cursor['.attributes']['size'];
                    $attachment->width = $cursor['.attributes']['width'];
                    $attachment->height = $cursor['.attributes']['height'];
                    $attachment->enclosure = @$cursor['enclosure'][0]['.value'];
                    $attachment->attached = $cursor['attached'][0]['.value'];
                    $attachment->downloads = @$cursor['downloads'][0]['.value'];
                    if (Attachment::doesExist($attachment->name)) {
                        if (!$attachment->add()) {
                            user_error(__LINE__ . $attachment->error);
                        }
                        $keyword2 = new Keyword();
                        if ($keyword2->open($keyword->id, 'id, content')) {
                            $keyword2->content = str_replace($cursor['name'][0]['.value'], $attachment->name, $keyword2->content);
                            $keyword2->update();
                            $keyword2->close();
                        }
                        unset($keyword2);
                    } else {
                        if (!$attachment->add()) {
                            user_error(__LINE__ . $attachment->error);
                        }
                    }
                    if (!empty($cursor['content'][0]['.stream'])) {
                        Utils_Base64Stream::decode($cursor['content'][0]['.stream'], Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        Attachment::adjustPermission(Path::combine(ROOT, 'attach', $blogid, $attachment->name));
                        fclose($cursor['content'][0]['.stream']);
                        unset($cursor['content'][0]['.stream']);
                    }
                }
            }
            return true;
        case '/blog/linkCategories':
            setProgress($item++ / $items * 100, _t('링크 카테고리를 복원하고 있습니다.'));
            $linkCategory = new LinkCategories();
            $linkCategory->name = $node['name'][0]['.value'];
            $linkCategory->priority = $node['priority'][0]['.value'];
            $linkCategory->visibility = !isset($node['visibility'][0]['.value']) || empty($node['visibility'][0]['.value']) ? 2 : $node['visibility'][0]['.value'];
            $linkCategory->id = LinkCategories::getId($linkCategory->name);
            if ($linkCategory->id) {
                if (!$linkCategory->update()) {
                    user_error(__LINE__ . $linkCategory->error);
                }
            } else {
                if (!$linkCategory->add()) {
                    user_error(__LINE__ . $linkCategory->error);
                }
            }
            return true;
        case '/blog/link':
            setProgress($item++ / $items * 100, _t('링크를 복원하고 있습니다.'));
            $link = new Link();
            $link->category = empty($node['category'][0]['.value']) ? 0 : $node['category'][0]['.value'];
            $link->url = $node['url'][0]['.value'];
            $link->title = $node['title'][0]['.value'];
            if (!empty($node['feed'][0]['.value'])) {
                $link->feed = $node['feed'][0]['.value'];
            }
            if (!empty($node['registered'][0]['.value'])) {
                $link->registered = $node['registered'][0]['.value'];
            }
            if (!empty($node['xfn'][0]['.value'])) {
                $link->xfn = $node['xfn'][0]['.value'];
            }
            $link->id = Link::getId($link->url);
            if ($link->id) {
                if (!$link->update()) {
                    user_error(__LINE__ . $link->error);
                }
            } else {
                if (!$link->add()) {
                    user_error(__LINE__ . $link->error);
                }
            }
            return true;
        case '/blog/logs/referer':
            setProgress($item++ / $items * 100, _t('리퍼러 로그를 복원하고 있습니다.'));
            $log = new RefererLog();
            if (isset($node['path'][0]['.value'])) {
                $log->url = $node['path'][0]['.value'];
            } else {
                $log->url = $node['url'][0]['.value'];
            }
            $log->referred = $node['referred'][0]['.value'];
            if (!$log->add(false)) {
                user_error(__LINE__ . $log->error);
            }
            return true;
        case '/blog/commentsNotified/comment':
            setProgress($item++ / $items * 100, _t('댓글 알리미 내용을 복원하고 있습니다.'));
            $cmtNotified = new CommentNotified();
            $cmtNotified->id = $node['id'][0]['.value'];
            $cursor =& $node['commenter'][0];
            $cmtNotified->name = $cursor['name'][0]['.value'];
            $cmtNotified->homepage = $cursor['homepage'][0]['.value'];
            $cmtNotified->ip = $cursor['ip'][0]['.value'];
            $cmtNotified->entry = $node['entry'][0]['.value'];
            $cmtNotified->password = $node['password'][0]['.value'];
            $cmtNotified->content = $node['content'][0]['.value'];
            $cmtNotified->parent = $node['parent'][0]['.value'];
            $cmtNotified->secret = $node['secret'][0]['.value'];
            $cmtNotified->written = $node['written'][0]['.value'];
            $cmtNotified->modified = $node['modified'][0]['.value'];
            $cmtNotified->url = $node['url'][0]['.value'];
            $cmtNotified->isnew = $node['isNew'][0]['.value'];
            $site = new CommentNotifiedSiteInfo();
            if (!$site->open("url = '{$node['site'][0]['.value']}'")) {
                $site->title = '';
                $site->name = '';
                $site->modified = 31536000;
                $site->url = $node['site'][0]['.value'];
                $site->add();
            }
            $cmtNotified->siteid = $site->id;
            $site->close();
            $cmtNotified->remoteid = $node['remoteId'][0]['.value'];
            $cmtNotified->entrytitle = !isset($node['entryTitle'][0]['.value']) || empty($node['entryTitle'][0]['.value']) ? 'No title' : $node['entryTitle'][0]['.value'];
            $cmtNotified->entryurl = $node['entryUrl'][0]['.value'];
            if (!$cmtNotified->add()) {
                user_error(__LINE__ . $cmtNotified->error);
            }
            return true;
        case '/blog/commentsNotifiedSiteInfo/site':
            setProgress($item++ / $items * 100, _t('댓글 알리미 내용을 복원하고 있습니다.'));
            $cmtNotifiedSite = new CommentNotifiedSiteInfo();
            if ($cmtNotifiedSite->open("url = '{$node['url'][0]['.value']}'")) {
                if (intval($node['modified'][0]['.value']) > intval($cmtNotifiedSite->modified)) {
                    $cmtNotifiedSite->title = $node['title'][0]['.value'];
                    $cmtNotifiedSite->name = $node['name'][0]['.value'];
                    $cmtNotifiedSite->modified = $node['modified'][0]['.value'];
                }
                if (!$cmtNotifiedSite->update()) {
                    user_error(__LINE__ . $cmtNotifiedSite->error);
                }
            } else {
                $cmtNotifiedSite->url = $node['url'][0]['.value'];
                $cmtNotifiedSite->title = $node['title'][0]['.value'];
                $cmtNotifiedSite->name = $node['name'][0]['.value'];
                $cmtNotifiedSite->modified = $node['modified'][0]['.value'];
                if (!$cmtNotifiedSite->add()) {
                    user_error(__LINE__ . $cmtNotifiedSite->error);
                }
            }
            return true;
        case '/blog/statistics/referer':
            setProgress($item++ / $items * 100, _t('리퍼러 통계를 복원하고 있습니다.'));
            $statistics = new RefererStatistics();
            $statistics->host = $node['host'][0]['.value'];
            $statistics->count = $node['count'][0]['.value'];
            if (!$statistics->add()) {
                user_error(__LINE__ . $statistics->error);
            }
            return true;
        case '/blog/statistics/visits':
            setProgress($item++ / $items * 100, _t('블로그 통계 정보를 복원하고 있습니다.'));
            $statistics = new BlogStatistics();
            $statistics->visits = $node['.value'];
            if (!$statistics->add()) {
                user_error(__LINE__ . $statistics->error);
            }
            return true;
        case '/blog/statistics/daily':
            setProgress($item++ / $items * 100, _t('일별 통계 정보를 복원하고 있습니다.'));
            $statistics = new DailyStatistics();
            $statistics->date = $node['date'][0]['.value'];
            $statistics->visits = $node['visits'][0]['.value'];
            if (!$statistics->add()) {
                user_error(__LINE__ . $statistics->error);
            }
            return true;
        case '/blog/skin':
            setProgress($item++ / $items * 100, _t('스킨 설정을 복원하고 있습니다.'));
            $setting = new SkinSetting();
            if (false) {
                $setting->skin = $node['name'][0]['.value'];
                if (!$setting->save()) {
                    user_error(__LINE__ . $setting->error);
                }
                $setting->skin = null;
            }
            $setting->entriesOnRecent = $node['entriesOnRecent'][0]['.value'];
            $setting->commentsOnRecent = $node['commentsOnRecent'][0]['.value'];
            $setting->trackbacksOnRecent = $node['trackbacksOnRecent'][0]['.value'];
            $setting->commentsOnGuestbook = $node['commentsOnGuestbook'][0]['.value'];
            $setting->tagsOnTagbox = $node['tagsOnTagbox'][0]['.value'];
            $setting->alignOnTagbox = $node['alignOnTagbox'][0]['.value'];
            $setting->expandComment = $node['expandComment'][0]['.value'];
            $setting->expandTrackback = $node['expandTrackback'][0]['.value'];
            if (!empty($node['recentNoticeLength'][0]['.value'])) {
                $setting->recentNoticeLength = $node['recentNoticeLength'][0]['.value'];
            }
            $setting->recentEntryLength = $node['recentEntryLength'][0]['.value'];
            $setting->recentTrackbackLength = $node['recentTrackbackLength'][0]['.value'];
            $setting->linkLength = $node['linkLength'][0]['.value'];
            $setting->showListOnCategory = $node['showListOnCategory'][0]['.value'];
            $setting->showListOnArchive = $node['showListOnArchive'][0]['.value'];
            if (isset($node['tree'])) {
                $cursor =& $node['tree'][0];
                $setting->tree = $cursor['name'][0]['.value'];
                $setting->colorOnTree = $cursor['color'][0]['.value'];
                $setting->bgcolorOnTree = $cursor['bgColor'][0]['.value'];
                $setting->activecolorOnTree = $cursor['activeColor'][0]['.value'];
                $setting->activebgcolorOnTree = $cursor['activeBgColor'][0]['.value'];
                $setting->labelLengthOnTree = $cursor['labelLength'][0]['.value'];
                $setting->showValueOnTree = $cursor['showValue'][0]['.value'];
            }
            if (!$setting->save()) {
                user_error(__LINE__ . $setting->error);
            }
            return true;
        case '/blog/plugin':
            //			setProgress($item++ / $items * 100, _t('플러그인 설정을 복원하고 있습니다.'));
            //			$setting = new PluginSetting();
            //			$setting->name = $node['name'][0]['.value'];
            //			$setting->setting = $node['setting'][0]['.value'];
            //			if (!$setting->add())
            //				user_error(__LINE__ . $setting->error);
            return true;
        case '/blog/personalization':
            //			setProgress($item++ / $items * 100, _t('사용자 편의 설정을 복원하고 있습니다.'));
            //			$setting = new UserSetting();
            //			$setting->name = 'rowsPerPage';
            //			$setting->value = $node['rowsPerPage'][0]['.value'];
            //			if (!$setting->add())
            //				user_error(__LINE__ . $setting->error);
            //			$setting->name = 'readerPannelVisibility';
            //			$setting->value = $node['readerPannelVisibility'][0]['.value'];
            //			if (!$setting->add())
            //				user_error(__LINE__ . $setting->error);
            //			$setting->name = 'readerPannelHeight';
            //			$setting->value = $node['readerPannelHeight'][0]['.value'];
            //			if (!$setting->add())
            //				user_error(__LINE__ . $setting->error);
            //			$setting->name = 'lastVisitNotifiedPage';
            //			$setting->value = $node['lastVisitNotifiedPage'][0]['.value'];
            //			if (!$setting->add())
            //				user_error(__LINE__ . $setting->error);
            return true;
        case '/blog/userSetting':
            //			setProgress($item++ / $items * 100, _t('사용자 편의 설정을 복원하고 있습니다'));
            //			$setting = new UserSetting();
            //			$setting->name = $node['name'][0]['.value'];
            //			$setting->value = $node['value'][0]['.value'];
            //			if (!$setting->add())
            //				user_error(__LINE__ . $setting->error);
            return true;
        case '/blog/guestbook/comment':
            setProgress($item++ / $items * 100, _t('방명록을 복원하고 있습니다.'));
            $comment = new GuestComment();
            $comment->name = $node['commenter'][0]['name'][0]['.value'];
            if (!empty($node['id'][0]['.value'])) {
                $comment->id = $node['id'][0]['.value'];
            }
            if (!empty($node['commenter'][0]['.attributes']['id'])) {
                $comment->commenter = $node['commenter'][0]['.attributes']['id'];
            }
            if (!empty($node['commenter'][0]['homepage'][0]['.value'])) {
                $comment->homepage = $node['commenter'][0]['homepage'][0]['.value'];
            }
            if (!empty($node['commenter'][0]['ip'][0]['.value'])) {
                $comment->ip = $node['commenter'][0]['ip'][0]['.value'];
            }
            if (!empty($node['commenter'][0]['openid'][0]['.value'])) {
                $comment->openid = $node['commenter'][0]['openid'][0]['.value'];
            }
            $comment->password = $node['password'][0]['.value'];
            $comment->secret = @$node['secret'][0]['.value'];
            $comment->written = $node['written'][0]['.value'];
            $comment->content = $node['content'][0]['.value'];
            if (!$comment->add()) {
                user_error(__LINE__ . $comment->error);
            }
            if (isset($node['comment'])) {
                for ($j = 0; $j < count($node['comment']); $j++) {
                    $childComment = new GuestComment();
                    $childComment->parent = $comment->id;
                    $cursor =& $node['comment'][$j];
                    $childComment->name = $cursor['commenter'][0]['name'][0]['.value'];
                    if (!empty($cursor['id'][0]['.value'])) {
                        $comment->id = $cursor['id'][0]['.value'];
                    }
                    if (!empty($cursor['commenter'][0]['.attributes']['id'])) {
                        $childComment->commenter = $cursor['commenter'][0]['.attributes']['id'];
                    }
                    if (!empty($cursor['commenter'][0]['homepage'][0]['.value'])) {
                        $childComment->homepage = $cursor['commenter'][0]['homepage'][0]['.value'];
                    }
                    if (!empty($cursor['commenter'][0]['ip'][0]['.value'])) {
                        $childComment->ip = $cursor['commenter'][0]['ip'][0]['.value'];
                    }
                    if (!empty($cursor['commenter'][0]['openid'][0]['.value'])) {
                        $childComment->openid = $cursor['commenter'][0]['openid'][0]['.value'];
                    }
                    $childComment->password = $cursor['password'][0]['.value'];
                    $childComment->secret = @$cursor['secret'][0]['.value'];
                    $childComment->written = $cursor['written'][0]['.value'];
                    $childComment->content = $cursor['content'][0]['.value'];
                    if (!$childComment->add()) {
                        user_error(__LINE__ . $childComment->error);
                    }
                }
            }
            return true;
        case '/blog/filter':
            setProgress($item++ / $items * 100, _t('필터 설정을 복원하고 있습니다.'));
            $filter = new Filter();
            $filter->type = $node['.attributes']['type'];
            $filter->pattern = $node['pattern'][0]['.value'];
            if (!$filter->add()) {
                user_error(__LINE__ . $filter->error);
            }
            return true;
        case '/blog/feed':
            setProgress($item++ / $items * 100, _t('리더 데이터를 복원하고 있습니다.'));
            $feed = new Feed();
            if (!empty($node['group'][0]['.value'])) {
                $feed->group = FeedGroup::getId($node['group'][0]['.value'], true);
            }
            $feed->url = $node['url'][0]['.value'];
            if (!$feed->add()) {
                user_error(__LINE__ . $feed->error);
            }
            return true;
        case '/blog/line':
            setProgress($item++ / $items * 100, _t('라인을 복원하고 있습니다.'));
            $line = Model_Line::getInstance();
            $line->reset();
            if (!empty($node['author'][0]['.value'])) {
                $line->author = $node['author'][0]['.value'];
            }
            if (!empty($node['category'][0]['.value'])) {
                $line->category = $node['category'][0]['.value'];
            }
            if (!empty($node['root'][0]['.value'])) {
                $line->root = $node['root'][0]['.value'];
            }
            if (!empty($node['permalink'][0]['.value'])) {
                $line->permalink = $node['permalink'][0]['.value'];
            }
            if (!empty($node['content'][0]['.value'])) {
                $line->content = $node['content'][0]['.value'];
            }
            if (!empty($node['created'][0]['.value'])) {
                $line->created = intval($node['created'][0]['.value']);
            }
            if ($line->add()) {
                return true;
            } else {
                user_error(__LINE__ . $line->_error);
            }
    }
}
 private function addTrashCategory()
 {
     $obj_category = new Category();
     $obj_category->name = array();
     $obj_category->link_rewrite = array();
     foreach (Language::getLanguages(false) as $language) {
         $obj_category->name[$language['id_lang']] = $this->trash_category_name;
         $obj_category->link_rewrite[$language['id_lang']] = $this->trash_category_name;
     }
     $obj_category->id_parent = Configuration::get('PS_HOME_CATEGORY');
     $obj_category->active = 0;
     if (!$obj_category->add()) {
         $this->_errors[] = $this->l('Error while creating trash category. Please try again or contact the customer service.');
     }
     return true;
 }
 public function create()
 {
     $obj = new Category($this->db);
     echo json_encode($obj->add($this->f3->get("POST.postdata")));
 }
Example #19
0
/**
 * @brief Import Parts (create Parts, and if neccessary, Categories, Footprints and so on)
 *
 * @note    This function uses database transactions. If an error occurs, all changes will be rolled back.
 *
 * @param Database  &$database          reference to the database object
 * @param User      &$current_user      reference to the user which is logged in
 * @param Log       &$log               reference to the Log-object
 * @param array     $data               The import data array from "extract_import_data_from_request()"
 * @param boolean   $only_check_data    If true, this function will only check if all values in "$data" are valid.
 *                                      In this case, no parts will be imported!
 *
 * @retval array    All new Part objects (only if "$only_check_data == false")
 *
 * @throws Exception    if there was an error (maybe the passed data is not valid)
 */
function import_parts(&$database, &$current_user, &$log, $data, $only_check_data = false)
{
    $parts = array();
    try {
        $transaction_id = $database->begin_transaction();
        // start transaction
        // Get the category, footprint, storelocation, ... which are named "Import", or create them.
        // We need this elements as parent for new elements, which will be created while import parts.
        $import_categories = Category::search($database, $current_user, $log, 'Import', true);
        if (count($import_categories) > 0) {
            $import_category = $import_categories[0];
            $import_category_created = false;
        } else {
            $import_category = Category::add($database, $current_user, $log, 'Import', NULL);
            $import_category_created = true;
            // we can delete it later if we didn't need it
        }
        $import_storelocations = Storelocation::search($database, $current_user, $log, 'Import', true);
        if (count($import_storelocations) > 0) {
            $import_storelocation = $import_storelocations[0];
            $import_storelocation_created = false;
        } else {
            $import_storelocation = Storelocation::add($database, $current_user, $log, 'Import', NULL);
            $import_storelocation_created = true;
            // we can delete it later if we didn't need it
        }
        $import_footprints = Footprint::search($database, $current_user, $log, 'Import', true);
        if (count($import_footprints) > 0) {
            $import_footprint = $import_footprints[0];
            $import_footprint_created = false;
        } else {
            $import_footprint = Footprint::add($database, $current_user, $log, 'Import', NULL);
            $import_footprint_created = true;
            // we can delete it later if we didn't need it
        }
        $import_suppliers = Supplier::search($database, $current_user, $log, 'Import', true);
        if (count($import_suppliers) > 0) {
            $import_supplier = $import_suppliers[0];
            $import_supplier_created = false;
        } else {
            $import_supplier = Supplier::add($database, $current_user, $log, 'Import', NULL);
            $import_supplier_created = true;
            // we can delete it later if we didn't need it
        }
        $import_manufacturers = Manufacturer::search($database, $current_user, $log, 'Import', true);
        if (count($import_manufacturers) > 0) {
            $import_manufacturer = $import_manufacturers[0];
            $import_manufacturer_created = false;
        } else {
            $import_manufacturer = Manufacturer::add($database, $current_user, $log, 'Import', NULL);
            $import_manufacturer_created = true;
            // we can delete it later if we didn't need it
        }
        $import_category_used = false;
        $import_storelocation_used = false;
        $import_footprint_used = false;
        $import_supplier_used = false;
        $import_manufacturer_used = false;
        // start import
        $row_index = 0;
        foreach ($data as $row) {
            $name = $row['part_name'];
            $description = $row['part_description'];
            $instock = $row['part_instock'];
            $mininstock = $row['part_mininstock'];
            $comment = $row['part_comment'];
            $category_name = $row['part_category_name'];
            $footprint_name = $row['part_footprint_name'];
            $storelocation_name = $row['part_storelocation_name'];
            $manufacturer_name = $row['part_manufacturer_name'];
            $supplier_name = $row['part_supplier_name'];
            $supplierpartnr = $row['part_supplierpartnr'];
            $price = $row['part_price'];
            // search elements / create them if they don't exist already
            if (strlen($category_name) > 0) {
                $categories = Category::search($database, $current_user, $log, $category_name, true);
                if (count($categories) > 0) {
                    $category = $categories[0];
                } else {
                    $category = Category::add($database, $current_user, $log, $category_name, $import_category->get_id());
                    $import_category_used = true;
                }
            } else {
                throw new Exception('Jedes Bauteil muss eine Kategorie haben!');
            }
            if (strlen($storelocation_name) > 0) {
                $storelocations = Storelocation::search($database, $current_user, $log, $storelocation_name, true);
                if (count($storelocations) > 0) {
                    $storelocation = $storelocations[0];
                } else {
                    $storelocation = Storelocation::add($database, $current_user, $log, $storelocation_name, $import_storelocation->get_id());
                    $import_storelocation_used = true;
                }
            }
            if (strlen($manufacturer_name) > 0) {
                $manufacturers = Manufacturer::search($database, $current_user, $log, $manufacturer_name, true);
                if (count($manufacturers) > 0) {
                    $manufacturer = $manufacturers[0];
                } else {
                    $manufacturer = Manufacturer::add($database, $current_user, $log, $manufacturer_name, $import_manufacturer->get_id());
                    $import_manufacturer_used = true;
                }
            }
            if (strlen($footprint_name) > 0) {
                $footprints = Footprint::search($database, $current_user, $log, $footprint_name, true);
                if (count($footprints) > 0) {
                    $footprint = $footprints[0];
                } else {
                    $footprint = Footprint::add($database, $current_user, $log, $footprint_name, $import_footprint->get_id());
                    $import_footprint_used = true;
                }
            }
            if (strlen($supplier_name) > 0) {
                $suppliers = Supplier::search($database, $current_user, $log, $supplier_name, true);
                if (count($suppliers) > 0) {
                    $supplier = $suppliers[0];
                } else {
                    $supplier = Supplier::add($database, $current_user, $log, $supplier_name, $import_supplier->get_id());
                    $import_supplier_used = true;
                }
            } else {
                if (strlen($supplierpartnr) > 0 || $price > 0) {
                    throw new Exception('Ist eine Bestellnummer oder ein Preis angegeben, so muss auch ein Lieferant angegeben werden!');
                }
            }
            $new_part = Part::add($database, $current_user, $log, $name, $category->get_id(), $description, $instock, $mininstock, isset($storelocation) ? $storelocation->get_id() : NULL, isset($manufacturer) ? $manufacturer->get_id() : NULL, isset($footprint) ? $footprint->get_id() : NULL, $comment);
            if (isset($supplier)) {
                $new_orderdetails = Orderdetails::add($database, $current_user, $log, $new_part->get_id(), $supplier->get_id(), $supplierpartnr);
                if ($price > 0) {
                    $new_pricedetails = Pricedetails::add($database, $current_user, $log, $new_orderdetails->get_id(), $price);
                }
            }
            if (!$only_check_data) {
                $parts[] = $new_part;
            }
            $row_index++;
        }
        // delete all elements which were created in this function, but were not used
        if ($import_category_created && !$import_category_used) {
            $import_category->delete();
        }
        if ($import_storelocation_created && !$import_storelocation_used) {
            $import_storelocation->delete();
        }
        if ($import_footprint_created && !$import_footprint_used) {
            $import_footprint->delete();
        }
        if ($import_supplier_created && !$import_supplier_used) {
            $import_supplier->delete();
        }
        if ($import_manufacturer_created && !$import_manufacturer_used) {
            $import_manufacturer->delete();
        }
        if ($only_check_data) {
            $database->rollback();
        } else {
            $database->commit($transaction_id);
        }
        // commit transaction
    } catch (Exception $e) {
        $database->rollback();
        // rollback transaction
        throw new Exception((isset($row_index) ? 'Nr. ' . ($row_index + 1) . ': ' : '') . $e->getMessage());
    }
    return $parts;
}
Example #20
0
        $selected_category = NULL;
    }
} catch (Exception $e) {
    $messages[] = array('text' => nl2br($e->getMessage()), 'strong' => true, 'color' => 'red');
    $fatal_error = true;
}
/********************************************************************************
 *
 *   Execute actions
 *
 *********************************************************************************/
if (!$fatal_error) {
    switch ($action) {
        case 'add':
            try {
                $new_category = Category::add($database, $current_user, $log, $new_name, $new_parent_id, $new_disable_footprints, $new_disable_manufacturers, $new_disable_autodatasheets);
                $html->set_variable('refresh_navigation_frame', true, 'boolean');
                if (!$add_more) {
                    $selected_category = $new_category;
                    $selected_id = $selected_category->get_id();
                }
            } catch (Exception $e) {
                $messages[] = array('text' => 'Die neue Kategorie konnte nicht angelegt werden!', 'strong' => true, 'color' => 'red');
                $messages[] = array('text' => 'Fehlermeldung: ' . nl2br($e->getMessage()), 'color' => 'red');
            }
            break;
        case 'delete':
            try {
                if (!is_object($selected_category)) {
                    throw new Exception('Es ist keine Kategorie markiert oder es trat ein Fehler auf!');
                }
Example #21
0
 function category_handler()
 {
     $this->check_login();
     $params = $this->input->post();
     if (isset($params['save'])) {
         Category::add($params);
     }
     redirect('admin/categories');
 }
Example #22
0
        $cat->setGenerateCertificates(true);
    } else {
        $cat->setGenerateCertificates(false);
    }
    if (isset($values['is_requirement'])) {
        $cat->setIsRequirement(true);
    } else {
        $cat->setIsRequirement(false);
    }
    if (empty($values['visible'])) {
        $visible = 0;
    } else {
        $visible = 1;
    }
    $cat->set_visible($visible);
    $result = $cat->add();
    header('Location: ' . Security::remove_XSS($_SESSION['gradebook_dest']) . '?addcat=&selectcat=' . $cat->get_parent_id() . '&' . api_get_cidreq());
    exit;
}
if (!$_in_course) {
    $interbreadcrumb[] = array('url' => Security::remove_XSS($_SESSION['gradebook_dest']) . '?selectcat=' . $get_select_cat . '&' . api_get_cidreq(), 'name' => get_lang('Gradebook'));
}
$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('ToolGradebook'));
Display::display_header(get_lang('NewCategory'));
$display_form = true;
/*if (!empty($grading_contents)) {
    $count_items = count($grading_contents['items']);
    $cats  = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init
    $cats_count = count($cats) - 1 ;

    if ($cats_count >= $count_items) {
 /**
  * @param null $course_code
  * @param int $gradebook_model_id
  * @return mixed
  */
 public static function create_default_course_gradebook($course_code = null, $gradebook_model_id = 0)
 {
     if (api_is_allowed_to_edit(true, true)) {
         if (!isset($course_code) || empty($course_code)) {
             $course_code = api_get_course_id();
         }
         $session_id = api_get_session_id();
         $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
         $sql = "SELECT * FROM {$t} WHERE course_code = '" . Database::escape_string($course_code) . "' ";
         if (!empty($session_id)) {
             $sql .= " AND session_id = " . (int) $session_id;
         } else {
             $sql .= " AND (session_id IS NULL OR session_id = 0) ";
         }
         $sql .= " ORDER BY id";
         $res = Database::query($sql);
         if (Database::num_rows($res) < 1) {
             //there is no unique category for this course+session combination,
             $cat = new Category();
             if (!empty($session_id)) {
                 $my_session_id = api_get_session_id();
                 $s_name = api_get_session_name($my_session_id);
                 $cat->set_name($course_code . ' - ' . get_lang('Session') . ' ' . $s_name);
                 $cat->set_session_id($session_id);
             } else {
                 $cat->set_name($course_code);
             }
             $cat->set_course_code($course_code);
             $cat->set_description(null);
             $cat->set_user_id(api_get_user_id());
             $cat->set_parent_id(0);
             $default_weight_setting = api_get_setting('gradebook_default_weight');
             $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
             $cat->set_weight($default_weight);
             $cat->set_grade_model_id($gradebook_model_id);
             $cat->set_certificate_min_score(75);
             $cat->set_visible(0);
             $cat->add();
             $category_id = $cat->get_id();
             unset($cat);
         } else {
             $row = Database::fetch_array($res);
             $category_id = $row['id'];
         }
     }
     return $category_id;
 }
 /**
  * Create a Category in Prestashop.
  * 
  * @param string $name_category
  * @param integer $id_parent_category
  * @param integer $language
  * @return integer 
  *
  */
 private function setCategoriesForProduct($name_category, $id_parent_category, $language)
 {
     $id_category = 2;
     $category = new Category();
     $array_categories = $category::searchByNameAndParentCategoryId($language, trim($name_category), $id_parent_category);
     if (empty($array_categories)) {
         $category_for_product = new Category();
         $category_for_product->active = 0;
         $category_for_product->id_parent = (int) trim($id_parent_category);
         $category_for_product->name = $this->setArrayElementForLinkRewrite(trim($name_category), true, $language);
         $category_for_product->link_rewrite = $this->setArrayElementForLinkRewrite(trim($name_category), false, $language);
         $category_for_product->meta_keywords = trim($name_category);
         $category_for_product->add();
         $id_category = $category_for_product->id;
     } else {
         $id_category = (int) $array_categories["id_category"];
     }
     return $id_category;
 }
Example #25
0
	requireStrictRoute();

	$response = array();
	$response['error'] = 0;
	$response['message'] = '';
	
	$name = $_POST['name'];
	
	$filter = isset($_POST['filter'])?$_POST['filter']:'';

	if(empty($name)) {
			$response['error'] = -1;
			$response['message'] = _t('잘못된 접근입니다.');
	} else {
		if (!isAdmin()) {
			$response['error'] = 1;
			$response['message'] = _t('관리자만이 이 기능을 사용할 수 있습니다.');
		} else {
			requireComponent('Bloglounge.Data.Category');
			if(!Category::add($name, $filter)) {
				$response['error'] = 2;
				$response['message'] = _t('분류추가를 실패하였습니다.');
			} else {
				$response['message'] = $name;
			}
		}
	}

	func::printRespond($response);
?>
    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);
    }
Example #27
0
 private function AddCategory($cat_name, $cats)
 {
     $query = 'SELECT id_category FROM ' . _DB_PREFIX_ . 'category_lang WHERE name = "' . $cat_name . '"';
     $category_check = Db::getInstance()->getValue($query);
     $cat_name_hr = $this->GetCategoryPlural($cat_name);
     $paren_name_index = array_search($cat_name, $cats);
     $right_name_index = $paren_name_index + 1;
     $paren_name_index = $paren_name_index - 1;
     $paren_name = $cats[$paren_name_index];
     $right_cat_name = $cats[$right_name_index];
     if (!$category_check) {
         $object = new Category();
         $object->name = array((int) Configuration::get('PS_LANG_DEFAULT') => $cat_name_hr);
         $object->id_parent = $this->GetParentId($paren_name);
         //$object->nleft = $this->GetCatId($paren_name);
         //$object->nright = 0;
         $object->link_rewrite = array((int) Configuration::get('PS_LANG_DEFAULT') => $this->Urlize($cat_name_hr));
         $object->add();
     } else {
         $object = new Category((int) $category_check, true);
         $object->name = array((int) Configuration::get('PS_LANG_DEFAULT') => $cat_name_hr);
         $object->id_parent = $this->GetParentId($paren_name);
         //$object->nleft = $this->GetCatId($paren_name);
         //$object->nright = 0;
         $object->link_rewrite = array((int) Configuration::get('PS_LANG_DEFAULT') => $this->Urlize($cat_name_hr));
         $object->save();
     }
     $this->AddCategoryTrans($cat_name);
 }
    public function productImport()
    {
        $this->receiveTab();
        $handle = $this->openCsvFile();
        $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT');
        $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
        if (!Validate::isUnsignedId($id_lang)) {
            $id_lang = $default_language_id;
        }
        AdminImportController::setLocale();
        $shop_ids = Shop::getCompleteListOfShopsID();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            if (self::ignoreRow($info)) {
                continue;
            }
            if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) {
                $product = new Product((int) $info['id']);
            } elseif (Tools::getValue('match_ref') && array_key_exists('reference', $info)) {
                $datas = Db::getInstance()->getRow('
						SELECT p.`id_product`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`reference` = "' . pSQL($info['reference']) . '"
					');
                if (isset($datas['id_product']) && $datas['id_product']) {
                    $product = new Product((int) $datas['id_product']);
                } else {
                    $product = new Product();
                }
            } else {
                if (array_key_exists('id', $info) && is_string($info['id'])) {
                    $prod = self::findProductByName($default_language_id, $info['id'], $info['name']);
                    if ($prod['id_product']) {
                        $info['id'] = (int) $prod['id_product'];
                    }
                }
                if (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                    $product = new Product((int) $info['id']);
                    $product->loadStockData();
                    $category_data = Product::getProductCategories((int) $product->id);
                    if (is_array($category_data)) {
                        foreach ($category_data as $tmp) {
                            if (!isset($product->category) || !$product->category || is_array($product->category)) {
                                $product->category[] = $tmp;
                            }
                        }
                    }
                } else {
                    $product = new Product();
                }
            }
            AdminImportController::setEntityDefaultValues($product);
            AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
            if (!Shop::isFeatureActive()) {
                $product->shop = 1;
            } elseif (!isset($product->shop) || empty($product->shop)) {
                $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            if (!Shop::isFeatureActive()) {
                $product->id_shop_default = 1;
            } else {
                $product->id_shop_default = (int) Context::getContext()->shop->id;
            }
            // link product to shops
            $product->id_shop_list = array();
            foreach (explode($this->multiple_value_separator, $product->shop) as $shop) {
                if (!empty($shop) && !is_numeric($shop)) {
                    $product->id_shop_list[] = Shop::getIdByName($shop);
                } elseif (!empty($shop)) {
                    $product->id_shop_list[] = $shop;
                }
            }
            if ((int) $product->id_tax_rules_group != 0) {
                if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                    $address = $this->context->shop->getAddress();
                    $tax_manager = TaxManagerFactory::getManager($address, $product->id_tax_rules_group);
                    $product_tax_calculator = $tax_manager->getTaxCalculator();
                    $product->tax_rate = $product_tax_calculator->getTotalRate();
                } else {
                    $this->addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID. You first need to create a group with this ID.'));
                }
            }
            if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int) $product->manufacturer)) {
                $product->id_manufacturer = (int) $product->manufacturer;
            } elseif (isset($product->manufacturer) && is_string($product->manufacturer) && !empty($product->manufacturer)) {
                if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                    $product->id_manufacturer = (int) $manufacturer;
                } else {
                    $manufacturer = new Manufacturer();
                    $manufacturer->name = $product->manufacturer;
                    if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) {
                        $product->id_manufacturer = (int) $manufacturer->id;
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($product->supplier) && is_numeric($product->supplier) && Supplier::supplierExists((int) $product->supplier)) {
                $product->id_supplier = (int) $product->supplier;
            } elseif (isset($product->supplier) && is_string($product->supplier) && !empty($product->supplier)) {
                if ($supplier = Supplier::getIdByName($product->supplier)) {
                    $product->id_supplier = (int) $supplier;
                } else {
                    $supplier = new Supplier();
                    $supplier->name = $product->supplier;
                    $supplier->active = true;
                    if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) {
                        $product->id_supplier = (int) $supplier->id;
                        $supplier->associateTo($product->id_shop_list);
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($product->price_tex) && !isset($product->price_tin)) {
                $product->price = $product->price_tex;
            } elseif (isset($product->price_tin) && !isset($product->price_tex)) {
                $product->price = $product->price_tin;
                // If a tax is already included in price, withdraw it from price
                if ($product->tax_rate) {
                    $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
                }
            } elseif (isset($product->price_tin) && isset($product->price_tex)) {
                $product->price = $product->price_tex;
            }
            if (!Configuration::get('PS_USE_ECOTAX')) {
                $product->ecotax = 0;
            }
            $properties = $product->productProperties();
            if ((double) $properties['pp_unit_price_ratio'] > 0) {
                $product->unit_price = (double) $product->price / (double) $properties['pp_unit_price_ratio'];
            }
            if (isset($product->category) && is_array($product->category) && count($product->category)) {
                $product->id_category = array();
                // Reset default values array
                foreach ($product->category as $value) {
                    if (is_numeric($value)) {
                        if (Category::categoryExists((int) $value)) {
                            $product->id_category[] = (int) $value;
                        } else {
                            $category_to_create = new Category();
                            $category_to_create->id = (int) $value;
                            $category_to_create->name = AdminImportController::createMultiLangField($value);
                            $category_to_create->active = 1;
                            $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY');
                            // Default parent is home for unknown category to create
                            $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]);
                            $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
                            if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) {
                                $product->id_category[] = (int) $category_to_create->id;
                            } else {
                                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                            }
                        }
                    } elseif (is_string($value) && !empty($value)) {
                        $category = Category::searchByPath($default_language_id, trim($value), $this, 'productImportCreateCat');
                        if ($category['id_category']) {
                            $product->id_category[] = (int) $category['id_category'];
                        } else {
                            $this->errors[] = sprintf(Tools::displayError('%1$s cannot be saved'), trim($value));
                        }
                    }
                }
                $product->id_category = array_values(array_unique($product->id_category));
            }
            if (!isset($product->id_category_default) || !$product->id_category_default) {
                $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : (int) Configuration::get('PS_HOME_CATEGORY');
            }
            $link_rewrite = is_array($product->link_rewrite) && isset($product->link_rewrite[$id_lang]) ? trim($product->link_rewrite[$id_lang]) : '';
            $valid_link = Validate::isLinkRewrite($link_rewrite);
            if (isset($product->link_rewrite[$id_lang]) && empty($product->link_rewrite[$id_lang]) || !$valid_link) {
                $link_rewrite = Tools::link_rewrite($product->name[$id_lang]);
                if ($link_rewrite == '') {
                    $link_rewrite = 'friendly-url-autogeneration-failed';
                }
            }
            if (!$valid_link) {
                $this->warnings[] = sprintf(Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite);
            }
            if (!(Tools::getValue('match_ref') || Tools::getValue('forceIDs')) || !(is_array($product->link_rewrite) && count($product->link_rewrite) && !empty($product->link_rewrite[$id_lang]))) {
                $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite);
            }
            // replace the value of separator by coma
            if ($this->multiple_value_separator != ',') {
                if (is_array($product->meta_keywords)) {
                    foreach ($product->meta_keywords as &$meta_keyword) {
                        if (!empty($meta_keyword)) {
                            $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword);
                        }
                    }
                }
            }
            // Convert comma into dot for all floating values
            foreach (Product::$definition['fields'] as $key => $array) {
                if ($array['type'] == Product::TYPE_FLOAT) {
                    $product->{$key} = str_replace(',', '.', $product->{$key});
                }
            }
            // Indexation is already 0 if it's a new product, but not if it's an update
            $product->indexed = 0;
            $res = false;
            $field_error = $product->validateFields(UNFRIENDLY_ERROR, true);
            $lang_field_error = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
            if ($field_error === true && $lang_field_error === true) {
                // check quantity
                if ($product->quantity == null) {
                    $product->quantity = 0;
                }
                // If match ref is specified && ref product && ref product already in base, trying to update
                if (Tools::getValue('match_ref') && $product->reference && $product->existsRefInDatabase($product->reference)) {
                    $datas = Db::getInstance()->getRow('
						SELECT product_shop.`date_add`, p.`id_product`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`reference` = "' . pSQL($product->reference) . '"
					');
                    $product->id = (int) $datas['id_product'];
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                } elseif ($product->id && Product::existsInDatabase((int) $product->id, 'product')) {
                    $datas = Db::getInstance()->getRow('
						SELECT product_shop.`date_add`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`id_product` = ' . (int) $product->id);
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                }
                // If no id_product or update failed
                $product->force_id = (bool) Tools::getValue('forceIDs');
                if (!$res) {
                    if (isset($product->date_add) && $product->date_add != '') {
                        $res = $product->add(false);
                    } else {
                        $res = $product->add();
                    }
                }
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    StockAvailable::setProductOutOfStock((int) $product->id, 1);
                } else {
                    StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock);
                }
            }
            $shops = array();
            $product_shop = explode($this->multiple_value_separator, $product->shop);
            foreach ($product_shop as $shop) {
                if (empty($shop)) {
                    continue;
                }
                $shop = trim($shop);
                if (!empty($shop) && !is_numeric($shop)) {
                    $shop = Shop::getIdByName($shop);
                }
                if (in_array($shop, $shop_ids)) {
                    $shops[] = $shop;
                } else {
                    $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Shop is not valid'));
                }
            }
            if (empty($shops)) {
                $shops = Shop::getContextListShopID();
            }
            // If both failed, mysql error
            if (!$res) {
                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID');
                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
            } else {
                // Product supplier
                if (isset($product->id) && $product->id && isset($product->id_supplier) && property_exists($product, 'supplier_reference')) {
                    $id_product_supplier = (int) ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier);
                    if ($id_product_supplier) {
                        $product_supplier = new ProductSupplier($id_product_supplier);
                    } else {
                        $product_supplier = new ProductSupplier();
                    }
                    $product_supplier->id_product = (int) $product->id;
                    $product_supplier->id_product_attribute = 0;
                    $product_supplier->id_supplier = (int) $product->id_supplier;
                    $product_supplier->product_supplier_price_te = $product->wholesale_price;
                    $product_supplier->product_supplier_reference = $product->supplier_reference;
                    $product_supplier->save();
                }
                // SpecificPrice (only the basic reduction feature is supported by the import)
                if (!Shop::isFeatureActive()) {
                    $info['shop'] = 1;
                } elseif (!isset($info['shop']) || empty($info['shop'])) {
                    $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
                }
                // Get shops for each attributes
                $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
                $id_shop_list = array();
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $id_shop_list[] = (int) Shop::getIdByName($shop);
                    } elseif (!empty($shop)) {
                        $id_shop_list[] = $shop;
                    }
                }
                if (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) {
                    foreach ($id_shop_list as $id_shop) {
                        $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, 0, 1, 0, 0, 0, 0);
                        if (is_array($specific_price) && isset($specific_price['id_specific_price'])) {
                            $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']);
                        } else {
                            $specific_price = new SpecificPrice();
                        }
                        $specific_price->id_product = (int) $product->id;
                        $specific_price->id_specific_price_rule = 0;
                        $specific_price->id_shop = $id_shop;
                        $specific_price->id_currency = 0;
                        $specific_price->id_country = 0;
                        $specific_price->id_group = 0;
                        $specific_price->price = -1;
                        $specific_price->id_customer = 0;
                        $specific_price->from_quantity = 1;
                        $specific_price->reduction = isset($info['reduction_price']) && $info['reduction_price'] ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                        $specific_price->reduction_type = isset($info['reduction_price']) && $info['reduction_price'] ? 'amount' : 'percentage';
                        $specific_price->from = isset($info['reduction_from']) && Validate::isDate($info['reduction_from']) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                        $specific_price->to = isset($info['reduction_to']) && Validate::isDate($info['reduction_to']) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                        if (!$specific_price->save()) {
                            $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                        }
                    }
                }
                if (isset($product->tags) && !empty($product->tags)) {
                    if (isset($product->id) && $product->id) {
                        $tags = Tag::getProductTags($product->id);
                        if (is_array($tags) && count($tags)) {
                            if (!empty($product->tags)) {
                                $product->tags = explode($this->multiple_value_separator, $product->tags);
                            }
                            if (is_array($product->tags) && count($product->tags)) {
                                foreach ($product->tags as $key => $tag) {
                                    if (!empty($tag)) {
                                        $product->tags[$key] = trim($tag);
                                    }
                                }
                                $tags[$id_lang] = $product->tags;
                                $product->tags = $tags;
                            }
                        }
                    }
                    // Delete tags for this id product, for no duplicating error
                    Tag::deleteTagsForProduct($product->id);
                    if (!is_array($product->tags) && !empty($product->tags)) {
                        $product->tags = AdminImportController::createMultiLangField($product->tags);
                        foreach ($product->tags as $key => $tags) {
                            $is_tag_added = Tag::addTags($key, $product->id, $tags, $this->multiple_value_separator);
                            if (!$is_tag_added) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Tags list is invalid'));
                                break;
                            }
                        }
                    } else {
                        foreach ($product->tags as $key => $tags) {
                            $str = '';
                            foreach ($tags as $one_tag) {
                                $str .= $one_tag . $this->multiple_value_separator;
                            }
                            $str = rtrim($str, $this->multiple_value_separator);
                            $is_tag_added = Tag::addTags($key, $product->id, $str, $this->multiple_value_separator);
                            if (!$is_tag_added) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), (int) $product->id, 'Invalid tag(s) (' . $str . ')');
                                break;
                            }
                        }
                    }
                }
                //delete existing images if "delete_existing_images" is set to 1
                if (isset($product->delete_existing_images)) {
                    if ((bool) $product->delete_existing_images) {
                        $product->deleteImages();
                    }
                }
                if (isset($product->image) && is_array($product->image) && count($product->image)) {
                    $product_has_images = (bool) Image::getImages($this->context->language->id, (int) $product->id);
                    foreach ($product->image as $key => $url) {
                        $url = trim($url);
                        $error = false;
                        if (!empty($url)) {
                            $url = str_replace(' ', '%20', $url);
                            $image = new Image();
                            $image->id_product = (int) $product->id;
                            $image->position = Image::getHighestPosition($product->id) + 1;
                            $image->cover = !$key && !$product_has_images ? true : false;
                            // file_exists doesn't work with HTTP protocol
                            if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) {
                                // associate image to selected shops
                                $image->associateTo($shops);
                                if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) {
                                    $image->delete();
                                    $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                                }
                            } else {
                                $error = true;
                            }
                        } else {
                            $error = true;
                        }
                        if ($error) {
                            $this->warnings[] = sprintf(Tools::displayError('Product #%1$d: the picture (%2$s) cannot be saved.'), $image->id_product, $url);
                        }
                    }
                }
                if (isset($product->id_category) && is_array($product->id_category)) {
                    $product->updateCategories(array_map('intval', $product->id_category));
                }
                $product->checkDefaultAttributes();
                if (!$product->cache_default_attribute) {
                    Product::updateDefaultAttribute($product->id);
                }
                // Features import
                $features = get_object_vars($product);
                if (isset($features['features']) && !empty($features['features'])) {
                    foreach (explode($this->multiple_value_separator, $features['features']) as $single_feature) {
                        if (empty($single_feature)) {
                            continue;
                        }
                        $tab_feature = explode(':', $single_feature);
                        $feature_name = isset($tab_feature[0]) ? trim($tab_feature[0]) : '';
                        $feature_value = isset($tab_feature[1]) ? trim($tab_feature[1]) : '';
                        $position = isset($tab_feature[2]) ? (int) $tab_feature[2] - 1 : false;
                        $custom = isset($tab_feature[3]) ? (int) $tab_feature[3] : false;
                        if (!empty($feature_name) && !empty($feature_value)) {
                            $id_feature = (int) Feature::addFeatureImport($feature_name, $position);
                            $id_product = null;
                            if (Tools::getValue('forceIDs') || Tools::getValue('match_ref')) {
                                $id_product = (int) $product->id;
                            }
                            $id_feature_value = (int) FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
                            Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                        }
                    }
                }
                // clean feature positions to avoid conflict
                Feature::cleanPositions();
                // set advanced stock managment
                if (isset($product->advanced_stock_management)) {
                    if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product %1$s '), $product->name[$default_language_id]);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        $product->setAdvancedStockManagement($product->advanced_stock_management);
                    }
                    // automaticly disable depends on stock, if a_s_m set to disabled
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0);
                    }
                }
                // Check if warehouse exists
                if (isset($product->warehouse) && $product->warehouse) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse not set on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        if (Warehouse::exists($product->warehouse)) {
                            // Get already associated warehouses
                            $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
                            // Delete any entry in warehouse for this product
                            foreach ($associated_warehouses_collection as $awc) {
                                $awc->delete();
                            }
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = 0;
                            $warehouse_location_entity->id_warehouse = $product->warehouse;
                            if (WarehouseProductLocation::getProductLocation($product->id, 0, $product->warehouse) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language_id]);
                        }
                    }
                }
                // stock available
                if (isset($product->depends_on_stock)) {
                    if ($product->depends_on_stock != 0 && $product->depends_on_stock != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->depends_on_stock == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management not enabled, cannot set "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock);
                    }
                    // This code allows us to set qty and disable depends on stock
                    if (isset($product->quantity) && $product->quantity) {
                        // if depends on stock and quantity, add quantity to stock
                        if ($product->depends_on_stock == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $product->wholesale_price);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round((double) $price, 6);
                            $warehouse = new Warehouse($product->warehouse);
                            if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, $product->quantity, 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($shops as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($shops as $shop) {
                            StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
Example #29
0
// ACTIONS
//this is called when there is no data for the course admin
if (isset($_GET['createallcategories'])) {
    GradebookUtils::block_students();
    $coursecat = Category::get_not_created_course_categories(api_get_user_id());
    if (!count($coursecat) == 0) {
        foreach ($coursecat as $row) {
            $cat = new Category();
            $cat->set_name($row[1]);
            $cat->set_course_code($row[0]);
            $cat->set_description(null);
            $cat->set_user_id(api_get_user_id());
            $cat->set_parent_id(0);
            $cat->set_weight(0);
            $cat->set_visible(0);
            $cat->add();
            unset($cat);
        }
    }
    header('Location: ' . $_SESSION['gradebook_dest'] . '?addallcat=&selectcat=0');
    exit;
}
//move a category
$selectcat = isset($_GET['selectcat']) ? Security::remove_XSS($_GET['selectcat']) : '';
if (isset($_GET['movecat'])) {
    $move_cat = Security::remove_XSS($_GET['movecat']);
    GradebookUtils::block_students();
    $cats = Category::load($move_cat);
    if (!isset($_GET['targetcat'])) {
        $move_form = new CatForm(CatForm::TYPE_MOVE, $cats[0], 'move_cat_form', null, api_get_self() . '?movecat=' . $move_cat . '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
        if ($move_form->validate()) {
 protected function importCategories()
 {
     $handle = $this->openCsvFile('categories.csv');
     $this->cleanCategoriesTables();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, ';'); $current_line++) {
         $res = false;
         $fields = $this->filterFields('Category', $this->category_fields, $line);
         if (!isset($fields['id'])) {
             $category = new Category($line[0]);
             $category->id = $line[0];
         } else {
             $category = new Category($fields['id']);
         }
         foreach ($fields as $key => $field) {
             if ($key == 'name' || $key == 'description' || $key == 'meta_title' || $key == 'meta_keywords' || $key == 'meta_description' || $key == 'link_rewrite') {
                 $category->{$key} = $this->multilFild($field);
             } else {
                 if ($key == 'id_parent') {
                     // hack for old wersion where force_id don't working
                     $parent_category = new Category((int) $field);
                     if (!Validate::isLoadedObject($parent_category)) {
                         $category->{$key} = 3;
                     } else {
                         $category->{$key} = $field;
                     }
                 } else {
                     $category->{$key} = $field;
                 }
             }
         }
         $category->force_id = true;
         if (!$res) {
             $res = $category->add();
         }
     }
     $this->closeCsvFile($handle);
     return true;
 }