';die();
}
if (Tools::isSubmit('clean_positionproduct')) {
// Position mise à 0
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'category_product`
SET `position` = 0
WHERE `id_category` = '.(int)$this->_category->id
);
$pos = 0;
foreach ($category_products as $key => $cat_product) {
if(Validate::isLoadedObject($product = new Product((int)$cat_product['id_product']))){
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'category_product`
SET `position` = '. (int)($pos) .'
WHERE `id_product` = '.(int)$cat_product['id_product'].'
AND `id_category`='.(int)$this->_category->id
);
$pos++;
} else {
Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'category_product`
WHERE `id_category` = '.(int)$this->_category->id.'
AND `id_product` = '.(int)$cat_product['id_product'].'
');
continue;
}
}
}
}
Tools::redirectAdmin($currentIndex.(Tools::getValue('id_category') ? '&id_category='.Tools::getValue('id_category') : '').'&token='.($token ? $token : $this->token));
}
if (Tools::isSubmit('reorderproduct') || Tools::isSubmit('reordersubproduct')) {
global $cookie, $currentIndex;
// Position mise à 0
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'category_product`
SET `position` = 0
WHERE `id_category` = '.(int)$this->_category->id
);
if (Tools::isSubmit('reorderproduct')) {
// Récupération de tous les produits de la catégorie ordonée
// selon la position de la sous-catégorie puis de la position dans la sous catégorie et sinon par id_product
$first_products = Db::getInstance()->ExecuteS('
SELECT cp.*
FROM `'._DB_PREFIX_.'category_product` cp
LEFT JOIN `'._DB_PREFIX_.'category` c ON (c.id_parent = cp.id_category)
LEFT JOIN `'._DB_PREFIX_.'category_product` cp2 ON (cp2.id_category = c.id_category AND cp2.id_product=cp.id_product)
RIGHT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product=cp.id_product)
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.id_product=p.id_product AND pl.`id_lang` = 1)
WHERE cp.id_category ='.(int)$this->_category->id.'
AND cp2.id_product IS NOT NULL
ORDER BY c.position, pl.`name`
');
$second_products = Db::getInstance()->ExecuteS('
SELECT cp.*
FROM `'._DB_PREFIX_.'category_product` cp
RIGHT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product=cp.id_product)
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.id_product=p.id_product AND pl.`id_lang` = 1)
WHERE cp.id_category ='.(int)$this->_category->id.'
AND cp.id_product NOT IN
(
SELECT cp2.id_product
FROM `'._DB_PREFIX_.'category_product` cp2
WHERE cp2.id_category IN
(
SELECT id_category
FROM `'._DB_PREFIX_.'category`
WHERE id_parent ='.(int)$this->_category->id.'
)
)
ORDER BY pl.`name`
');
$products = array_merge($first_products,$second_products);
} else {
$products = Db::getInstance()->ExecuteS('
SELECT cp.*
FROM `'._DB_PREFIX_.'category_product` cp
RIGHT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product=cp.id_product)
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.id_product=p.id_product AND pl.`id_lang` = 1)
WHERE cp.id_category ='.(int)$this->_category->id.'
ORDER BY pl.`name`
');
}
// Update des postions
foreach ($products as $key => $product) {
if ($key == 0){
continue;
}
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'category_product`
SET `position` = '. (int)($key) .'
WHERE `id_product` = '.(int)($product['id_product']).'
AND `id_category`='.(int)$this->_category->id
);
}
Tools::redirectAdmin($currentIndex.(Tools::getValue('id_category') ? '&id_category='.Tools::getValue('id_category') : '').'&token='.($token ? $token : $this->token));
}
Module::hookExec('admin_product_postprocess', array());
if(Tools::isSubmit('cloneProduct')){
$products = Tools::getValue('productBox');
$id_category_clonage = Tools::getValue('id_category_clonage');
foreach ($products as $key => $product) {
if (Validate::isLoadedObject($product = new Product((int)$product ) ))
{
$id_product_old = $product->id;
unset($product->id);
unset($product->id_product);
$product->indexed = 0;
$product->active = 0;
$product->id_category_default = (int)$id_category_clonage;
if ($product->add()
AND ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false
AND GroupReduction::duplicateReduction($id_product_old, $product->id)
AND Product::duplicateAccessories($id_product_old, $product->id)
AND Product::duplicateFeatures($id_product_old, $product->id)
AND Product::duplicateSpecificPrices($id_product_old, $product->id)
AND Pack::duplicate($id_product_old, $product->id)
AND Product::duplicateCustomizationFields($id_product_old, $product->id)
AND Product::duplicateTags($id_product_old, $product->id)
AND Product::duplicateDownload($id_product_old, $product->id))
{
$max_position = Db::getInstance()->getValue("SELECT MAX(cp.`position`) AS max FROM `"._DB_PREFIX_."category_product` cp WHERE cp.`id_category`=" . (int)$id_category_clonage );
$add_category = Db::getInstance()->Execute("INSERT INTO `"._DB_PREFIX_."category_product` (`id_product`, `id_category`, `position`)
VALUES (
'". $product->id ."',
'". (int)$id_category_clonage ."',
'". (int)($max_position + 1 ) ."'
)");
if(!$add_category){
$this->_errors[] = Tools::displayError('An error occurred during category association.');
}
if ($product->hasAttributes())
Product::updateDefaultAttribute($product->id);
if (!Tools::getValue('noimage') AND !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages))
$this->_errors[] = Tools::displayError('An error occurred while copying images.');
else
{
Hook::addProduct($product);
Search::indexation(false, $product->id);
}
}
else
$this->_errors[] = Tools::displayError('An error occurred while creating object.');
}
}
echo "
Clonage réussi
";
}
global $cookie, $currentIndex;
// ANTADIS - coup de coeur
if(Tools::getValue('id_product') && $this->tabAccess['edit'] === '1'){
$product = new Product(Tools::getValue('id_product'));
if(isset($_GET['online_onlyproduct']) || isset($_GET['online_onlyproduct1']) ){
$product->toggleCoupCoeur();
Tools::redirectAdmin($currentIndex.'&id_product='.(int)(Tools::getValue($this->identifier)).'&id_category='.(int)(Tools::getValue('id_category')).'&token='.($token ? $token : $this->token));
}
}
// Add a new product
if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview'))
{
if ((Tools::getValue('id_product') && $this->tabAccess['edit'] === '1') || ($this->tabAccess['add'] === '1' && !Tools::isSubmit('id_product')))
$this->submitAddproduct($token);
else
$this->_errors[] = Tools::displayError('You do not have permission to add here.');
}
/* Delete a product in the download folder */
if (Tools::getValue('deleteVirtualProduct'))
{
if ($this->tabAccess['delete'] === '1')
$this->deleteVirtualProduct();
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
/* Update attachments */
elseif (Tools::isSubmit('submitAddAttachments'))
{
if ($this->tabAccess['add'] === '1')
{
$languages = Language::getLanguages(false);
$is_attachment_name_valid = false;
foreach ($languages as $language)
{
$attachment_name_lang = Tools::getValue('attachment_name_'.(int)($language['id_lang']));
if (strlen($attachment_name_lang ) > 0)
$is_attachment_name_valid = true;
if (!Validate::isGenericName(Tools::getValue('attachment_name_'.(int)($language['id_lang']))))
$this->_errors[] = Tools::displayError('Invalid Name');
elseif (Tools::strlen(Tools::getValue('attachment_name_'.(int)($language['id_lang']))) > 32)
$this->_errors[] = Tools::displayError('Name is too long');
if (!Validate::isCleanHtml(Tools::getValue('attachment_description_'.(int)($language['id_lang']))))
$this->_errors[] = Tools::displayError('Invalid description');
}
if (!$is_attachment_name_valid)
$this->_errors[] = Tools::displayError('Attachment Name Required');
if (empty($this->_errors))
{
if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name']))
{
if ($_FILES['attachment_file']['size'] > (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024))
$this->_errors[] = $this->l('File too large, maximum size allowed:').' '.(Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024).' '.$this->l('kb').'. '.$this->l('File size you\'re trying to upload is:').number_format(($_FILES['attachment_file']['size']/1024), 2, '.', '').$this->l('kb');
else
{
do $uniqid = sha1(microtime()); while (file_exists(_PS_DOWNLOAD_DIR_.$uniqid));
if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_.$uniqid))
$this->_errors[] = $this->l('File copy failed');
@unlink($_FILES['attachment_file']['tmp_name']);
}
}
elseif ((int)$_FILES['attachment_file']['error'] === 1)
{
$max_upload = (int)ini_get('upload_max_filesize');
$max_post = (int)ini_get('post_max_size');
$upload_mb = min($max_upload, $max_post);
$this->_errors[] = $this->l('the File').' '.$_FILES['attachment_file']['name'].' '.$this->l('exceeds the size allowed by the server, this limit is set to').' '.$upload_mb.$this->l('Mb').'';
}
if (empty($this->_errors) && isset($uniqid))
{
$attachment = new Attachment();
foreach ($languages AS $language)
{
if (isset($_POST['attachment_name_'.(int)($language['id_lang'])]))
$attachment->name[(int)($language['id_lang'])] = pSQL($_POST['attachment_name_'.(int)($language['id_lang'])]);
if (isset($_POST['attachment_description_'.(int)($language['id_lang'])]))
$attachment->description[(int)($language['id_lang'])] = pSQL($_POST['attachment_description_'.(int)($language['id_lang'])]);
}
$attachment->file = $uniqid;
$attachment->mime = $_FILES['attachment_file']['type'];
$attachment->file_name = pSQL($_FILES['attachment_file']['name']);
if (empty($attachment->mime) OR Tools::strlen($attachment->mime) > 128)
$this->_errors[] = Tools::displayError('Invalid file extension');
if (!Validate::isGenericName($attachment->file_name))
$this->_errors[] = Tools::displayError('Invalid file name');
if (Tools::strlen($attachment->file_name) > 128)
$this->_errors[] = Tools::displayError('File name too long');
if (!sizeof($this->_errors))
{
$attachment->add();
Tools::redirectAdmin($currentIndex.'&id_product='.(int)(Tools::getValue($this->identifier)).'&id_category='.(int)(Tools::getValue('id_category')).'&addproduct&conf=4&tabs=6&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Invalid file');
}
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to add here.');
}
elseif (Tools::isSubmit('submitAttachments'))
{
if ($this->tabAccess['edit'] === '1')
if ($id = (int)(Tools::getValue($this->identifier)))
if (Attachment::attachToProduct($id, $_POST['attachments']))
Tools::redirectAdmin($currentIndex.'&id_product='.(int)$id.(isset($_POST['id_category']) ? '&id_category='.(int)$_POST['id_category'] : '').'&conf=4&add'.$this->table.'&tabs=6&token='.($token ? $token : $this->token));
}
/* Product duplication */
elseif (isset($_GET['duplicate'.$this->table]))
{
if ($this->tabAccess['add'] === '1')
{
if (Validate::isLoadedObject($product = new Product((int)(Tools::getValue('id_product')))))
{
$id_product_old = $product->id;
unset($product->id);
unset($product->id_product);
$product->indexed = 0;
$product->active = 0;
if ($product->add()
AND Category::duplicateProductCategories($id_product_old, $product->id)
AND ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false
AND GroupReduction::duplicateReduction($id_product_old, $product->id)
AND Product::duplicateAccessories($id_product_old, $product->id)
AND Product::duplicateFeatures($id_product_old, $product->id)
AND Product::duplicateSpecificPrices($id_product_old, $product->id)
AND Pack::duplicate($id_product_old, $product->id)
AND Product::duplicateCustomizationFields($id_product_old, $product->id)
AND Product::duplicateTags($id_product_old, $product->id)
AND Product::duplicateDownload($id_product_old, $product->id))
{
if ($product->hasAttributes())
Product::updateDefaultAttribute($product->id);
if (!Tools::getValue('noimage') AND !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages))
$this->_errors[] = Tools::displayError('An error occurred while copying images.');
else
{
Hook::addProduct($product);
Search::indexation(false, $product->id);
Tools::redirectAdmin($currentIndex.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&conf=19&token='.($token ? $token : $this->token));
}
}
else
$this->_errors[] = Tools::displayError('An error occurred while creating object.');
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to add here.');
}
/* Change object statuts (active, inactive) */
elseif (isset($_GET['status']) AND Tools::getValue($this->identifier))
{
if ($this->tabAccess['edit'] === '1')
{
if (Validate::isLoadedObject($object = $this->loadObject()))
{
if ($object->toggleStatus())
Tools::redirectAdmin($currentIndex.'&conf=5'.((($id_category = (!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1')) AND Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
else
$this->_errors[] = Tools::displayError('An error occurred while updating status.');
}
else
$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' '.$this->table.' '.Tools::displayError('(cannot load object)');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
}
/* Delete object */
elseif (isset($_GET['delete'.$this->table]))
{
if ($this->tabAccess['delete'] === '1')
{
if (Validate::isLoadedObject($object = $this->loadObject()) AND isset($this->fieldImageSettings))
{
// check if request at least one object with noZeroObject
if (isset($object->noZeroObject) AND sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1)
$this->_errors[] = Tools::displayError('You need at least one object.').' '.$this->table.' '.Tools::displayError('You cannot delete all of the items.');
else
{
$id_category = Tools::getValue('id_category');
$category_url = empty($id_category) ? '' : '&id_category='.$id_category;
if ($this->deleted)
{
$object->deleteImages();
$object->deleted = 1;
if ($object->update())
Tools::redirectAdmin($currentIndex.'&conf=1&token='.($token ? $token : $this->token).$category_url);
}
elseif ($object->delete())
Tools::redirectAdmin($currentIndex.'&conf=1&token='.($token ? $token : $this->token).$category_url);
$this->_errors[] = Tools::displayError('An error occurred during deletion.');
}
}
else
$this->_errors[] = Tools::displayError('An error occurred while deleting object.').' '.$this->table.' '.Tools::displayError('(cannot load object)');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
/* Delete multiple objects */
elseif (Tools::getValue('submitDel'.$this->table))
{
if ($this->tabAccess['delete'] === '1')
{
if (isset($_POST[$this->table.'Box']))
{
$object = new $this->className();
if (isset($object->noZeroObject) AND
// Check if all object will be deleted
(sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 OR sizeof($_POST[$this->table.'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject)))))
$this->_errors[] = Tools::displayError('You need at least one object.').' '.$this->table.' '.Tools::displayError('You cannot delete all of the items.');
else
{
$result = true;
if ($this->deleted)
{
foreach(Tools::getValue($this->table.'Box') as $id)
{
$toDelete = new $this->className($id);
$toDelete->deleted = 1;
$result = $result AND $toDelete->update();
}
}
else
$result = $object->deleteSelection(Tools::getValue($this->table.'Box'));
if ($result)
{
$id_category = Tools::getValue('id_category');
$category_url = empty($id_category) ? '' : '&id_category='.$id_category;
Tools::redirectAdmin($currentIndex.'&conf=2&token='.$token.$category_url);
}
$this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
}
}
else
$this->_errors[] = Tools::displayError('You must select at least one element to delete.');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
/* Product images management */
elseif (($id_image = (int)(Tools::getValue('id_image'))) AND Validate::isUnsignedId($id_image) AND Validate::isLoadedObject($image = new Image($id_image)))
{
/* PrestaShop demo mode */
if (_PS_MODE_DEMO_)
{
$this->_errors[] = Tools::displayError('This functionnality has been disabled.');
return;
}
/* PrestaShop demo mode*/
if ($this->tabAccess['edit'] === '1')
{
/* Delete product image */
if (isset($_GET['deleteImage']))
{
$image->delete();
if (!Image::getCover($image->id_product))
{
$first_img = Db::getInstance()->getRow('
SELECT `id_image` FROM `'._DB_PREFIX_.'image`
WHERE `id_product` = '.(int)($image->id_product));
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'image`
SET `cover` = 1
WHERE `id_image` = '.(int)($first_img['id_image']));
}
@unlink(_PS_TMP_IMG_DIR_.'/product_'.$image->id_product.'.jpg');
@unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$image->id_product.'.jpg');
Tools::redirectAdmin($currentIndex.'&id_product='.$image->id_product.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=1'.'&token='.($token ? $token : $this->token));
}
/* Update product image/legend */
elseif (isset($_GET['editImage']))
{
if ($image->cover)
$_POST['cover'] = 1;
$languages = Language::getLanguages(false);
foreach ($languages as $language)
if (isset($image->legend[$language['id_lang']]))
$_POST['legend_'.$language['id_lang']] = $image->legend[$language['id_lang']];
$_POST['id_image'] = $image->id;
$this->displayForm();
}
/* Choose product cover image */
elseif (isset($_GET['coverImage']))
{
Image::deleteCover($image->id_product);
$image->cover = 1;
if (!$image->update())
$this->_errors[] = Tools::displayError('Cannot change the product cover');
else
{
$productId = (int)(Tools::getValue('id_product'));
@unlink(_PS_TMP_IMG_DIR_.'/product_'.$productId.'.jpg');
@unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$productId.'.jpg');
Tools::redirectAdmin($currentIndex.'&id_product='.$image->id_product.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&addproduct&tabs=1'.'&token='.($token ? $token : $this->token));
}
}
/* Choose product image position */
elseif (isset($_GET['imgPosition']) AND isset($_GET['imgDirection']))
{
$image->positionImage((int)(Tools::getValue('imgPosition')), (int)(Tools::getValue('imgDirection')));
Tools::redirectAdmin($currentIndex.'&id_product='.$image->id_product.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=1&token='.($token ? $token : $this->token));
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
}
/* Product attributes management */
elseif (Tools::isSubmit('submitProductAttribute'))
{
if (Validate::isLoadedObject($product = new Product((int)(Tools::getValue('id_product')))))
{
if (!isset($_POST['attribute_price']) OR $_POST['attribute_price'] == NULL)
$this->_errors[] = Tools::displayError('Attribute price required.');
if (!isset($_POST['attribute_combinaison_list']) OR !sizeof($_POST['attribute_combinaison_list']))
$this->_errors[] = Tools::displayError('You must add at least one attribute.');
if (!sizeof($this->_errors))
{
if (!isset($_POST['attribute_wholesale_price'])) $_POST['attribute_wholesale_price'] = 0;
if (!isset($_POST['attribute_price_impact'])) $_POST['attribute_price_impact'] = 0;
if (!isset($_POST['attribute_weight_impact'])) $_POST['attribute_weight_impact'] = 0;
if (!isset($_POST['attribute_ecotax'])) $_POST['attribute_ecotax'] = 0;
if (Tools::getValue('attribute_default'))
$product->deleteDefaultAttributes();
// Change existing one
if ($id_product_attribute = (int)(Tools::getValue('id_product_attribute')))
{
if ($this->tabAccess['edit'] === '1')
{
if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute))
$this->_errors[] = Tools::displayError('This attribute already exists.');
else
{
$product->updateProductAttribute($id_product_attribute,
Tools::getValue('attribute_wholesale_price'),
Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'),
Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'),
Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'),
Tools::getValue('attribute_ecotax'),
false,
Tools::getValue('id_image_attr'),
Tools::getValue('attribute_reference'),
Tools::getValue('attribute_supplier_reference'),
Tools::getValue('attribute_ean13'),
Tools::getValue('attribute_default'),
Tools::getValue('attribute_location'),
Tools::getValue('attribute_upc'),
Tools::getValue('attribute_minimal_quantity'));
if ($id_reason = (int)Tools::getValue('id_mvt_reason') AND (int)Tools::getValue('attribute_mvt_quantity') > 0 AND $id_reason > 0)
{
$reason = new StockMvtReason((int)$id_reason);
$qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign;
if (!$product->addStockMvt($qty, $id_reason, (int)$id_product_attribute, NULL, $cookie->id_employee))
$this->_errors[] = Tools::displayError('An error occurred while updating qty.');
}
Hook::updateProductAttribute((int)$id_product_attribute);
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to add here.');
}
// Add new
else
{
if ($this->tabAccess['add'] === '1')
{
if ($product->productAttributeExists($_POST['attribute_combinaison_list']))
$this->_errors[] = Tools::displayError('This combination already exists.');
else
{
$id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'),
Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'),
Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'),
Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'),
Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity'));
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to').''.Tools::displayError('Edit here.');
}
if (!sizeof($this->_errors))
{
$product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list'));
$product->checkDefaultAttributes();
}
if (!sizeof($this->_errors))
{
if (!$product->cache_default_attribute)
Product::updateDefaultAttribute($product->id);
Tools::redirectAdmin($currentIndex.'&id_product='.$product->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=3&token='.($token ? $token : $this->token));
}
}
}
}
elseif (Tools::isSubmit('deleteProductAttribute'))
{
if ($this->tabAccess['delete'] === '1')
{
if (($id_product = (int)(Tools::getValue('id_product'))) AND Validate::isUnsignedId($id_product) AND Validate::isLoadedObject($product = new Product($id_product)))
{
$product->deleteAttributeCombinaison((int)(Tools::getValue('id_product_attribute')));
$product->checkDefaultAttributes();
$product->updateQuantityProductWithAttributeQuantity();
if (!$product->hasAttributes())
{
$product->cache_default_attribute = 0;
$product->update();
}else
Product::updateDefaultAttribute($id_product);
Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&tabs=3&id_product='.$product->id.'&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Cannot delete attribute');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
elseif (Tools::isSubmit('deleteAllProductAttributes'))
{
if ($this->tabAccess['delete'] === '1')
{
if (($id_product = (int)(Tools::getValue('id_product'))) AND Validate::isUnsignedId($id_product) AND Validate::isLoadedObject($product = new Product($id_product)))
{
$product->deleteProductAttributes();
$product->updateQuantityProductWithAttributeQuantity();
if ($product->cache_default_attribute)
{
$product->cache_default_attribute = 0;
$product->update();
}
Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&tabs=3&id_product='.$product->id.'&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Cannot delete attributes');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
elseif (Tools::isSubmit('defaultProductAttribute'))
{
if (Validate::isLoadedObject($product = new Product((int)(Tools::getValue('id_product')))))
{
$product->deleteDefaultAttributes();
$product->setDefaultAttribute((int)(Tools::getValue('id_product_attribute')));
Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&tabs=3&id_product='.$product->id.'&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Cannot make default attribute');
}
/* Product features management */
elseif (Tools::isSubmit('submitProductFeature'))
{
if ($this->tabAccess['edit'] === '1')
{
if (Validate::isLoadedObject($product = new Product((int)(Tools::getValue('id_product')))))
{
// delete all objects
$product->deleteFeatures();
// add new objects
$languages = Language::getLanguages(false);
foreach ($_POST AS $key => $val)
{
if (preg_match('/^feature_([0-9]+)_value/i', $key, $match))
{
if ($val)
$product->addFeaturesToDB($match[1], $val);
else
{
if ($default_value = $this->checkFeatures($languages, $match[1]))
{
$id_value = $product->addFeaturesToDB($match[1], 0, 1, (int)$language['id_lang']);
foreach ($languages AS $language)
{
if ($cust = Tools::getValue('custom_'.$match[1].'_'.(int)$language['id_lang']))
$product->addFeaturesCustomToDB($id_value, (int)$language['id_lang'], $cust);
else
$product->addFeaturesCustomToDB($id_value, (int)$language['id_lang'], $default_value);
}
}
}
}
}
if (!sizeof($this->_errors))
Tools::redirectAdmin($currentIndex.'&id_product='.(int)$product->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=4&conf=4&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Product must be created before adding features.');
}
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
}
/* Product specific prices management */
elseif (Tools::isSubmit('submitPricesModification'))
{
$_POST['tabs'] = 5;
if ($this->tabAccess['edit'] === '1')
{
$id_specific_prices = Tools::getValue('spm_id_specific_price');
$id_shops = Tools::getValue('spm_id_shop');
$id_currencies = Tools::getValue('spm_id_currency');
$id_countries = Tools::getValue('spm_id_country');
$id_groups = Tools::getValue('spm_id_group');
$prices = Tools::getValue('spm_price');
$from_quantities = Tools::getValue('spm_from_quantity');
$reductions = Tools::getValue('spm_reduction');
$reduction_types = Tools::getValue('spm_reduction_type');
$froms = Tools::getValue('spm_from');
$tos = Tools::getValue('spm_to');
foreach ($id_specific_prices as $key => $id_specific_price)
if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key]))
{
$specificPrice = new SpecificPrice((int)($id_specific_price));
$specificPrice->id_shop = (int)($id_shops[$key]);
$specificPrice->id_currency = (int)($id_currencies[$key]);
$specificPrice->id_country = (int)($id_countries[$key]);
$specificPrice->id_group = (int)($id_groups[$key]);
$specificPrice->price = (float)($prices[$key]);
$specificPrice->from_quantity = (int)($from_quantities[$key]);
$specificPrice->reduction = (float)($reduction_types[$key] == 'percentage' ? ($reductions[$key] / 100) : $reductions[$key]);
$specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key];
$specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key];
$specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key];
if (!$specificPrice->update())
$this->_errors = Tools::displayError('An error occurred while updating the specific price.');
}
if (!sizeof($this->_errors))
Tools::redirectAdmin($currentIndex.'&id_product='.(int)(Tools::getValue('id_product')).'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&update'.$this->table.'&tabs=2&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('You do not have permission to add here.');
}
elseif (Tools::isSubmit('submitPriceAddition'))
{
if ($this->tabAccess['add'] === '1')
{
$id_product = (int)(Tools::getValue('id_product'));
$id_shop = Tools::getValue('sp_id_shop');
$id_currency = Tools::getValue('sp_id_currency');
$id_country = Tools::getValue('sp_id_country');
$id_group = Tools::getValue('sp_id_group');
$price = Tools::getValue('sp_price');
$from_quantity = Tools::getValue('sp_from_quantity');
$reduction = (float)(Tools::getValue('sp_reduction'));
$reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type');
$from = Tools::getValue('sp_from');
$to = Tools::getValue('sp_to');
if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to))
{
$specificPrice = new SpecificPrice();
$specificPrice->id_product = $id_product;
$specificPrice->id_shop = (int)($id_shop);
$specificPrice->id_currency = (int)($id_currency);
$specificPrice->id_country = (int)($id_country);
$specificPrice->id_group = (int)($id_group);
$specificPrice->price = (float)($price);
$specificPrice->from_quantity = (int)($from_quantity);
$specificPrice->reduction = (float)($reduction_type == 'percentage' ? $reduction / 100 : $reduction);
$specificPrice->reduction_type = $reduction_type;
$specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from;
$specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to;
if (!$specificPrice->add())
$this->_errors = Tools::displayError('An error occurred while updating the specific price.');
else
Tools::redirectAdmin($currentIndex.(Tools::getValue('id_category') ? '&id_category='.Tools::getValue('id_category') : '').'&id_product='.$id_product.'&add'.$this->table.'&tabs=2&conf=3&token='.($token ? $token : $this->token));
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to add here.');
}
elseif (Tools::isSubmit('deleteSpecificPrice'))
{
if ($this->tabAccess['delete'] === '1')
{
if (!($obj = $this->loadObject()))
return;
if (!$id_specific_price = Tools::getValue('id_specific_price') OR !Validate::isUnsignedId($id_specific_price))
$this->_errors[] = Tools::displayError('Invalid specific price ID');
else
{
$specificPrice = new SpecificPrice((int)($id_specific_price));
if (!$specificPrice->delete())
$this->_errors[] = Tools::displayError('An error occurred while deleting the specific price');
else
Tools::redirectAdmin($currentIndex.(Tools::getValue('id_category') ? '&id_category='.Tools::getValue('id_category') : '').'&id_product='.$obj->id.'&add'.$this->table.'&tabs=2&conf=1&token='.($token ? $token : $this->token));
}
}
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
elseif (Tools::isSubmit('submitSpecificPricePriorities'))
{
if (!($obj = $this->loadObject()))
return;
if (!$priorities = Tools::getValue('specificPricePriority'))
$this->_errors[] = Tools::displayError('Please specify priorities');
elseif (Tools::isSubmit('specificPricePriorityToAll'))
{
if (!SpecificPrice::setPriorities($priorities))
$this->_errors[] = Tools::displayError('An error occurred while updating priorities.');
else
Tools::redirectAdmin($currentIndex.'&id_product='.$obj->id.'&add'.$this->table.'&tabs=2&conf=4&token='.($token ? $token : $this->token));
}
elseif (!SpecificPrice::setSpecificPriority((int)($obj->id), $priorities))
$this->_errors[] = Tools::displayError('An error occurred while setting priorities.');
else
Tools::redirectAdmin($currentIndex.(Tools::getValue('id_category') ? '&id_category='.Tools::getValue('id_category') : '').'&id_product='.$obj->id.'&add'.$this->table.'&tabs=2&conf=4&token='.($token ? $token : $this->token));
}
/* Customization management */
elseif (Tools::isSubmit('submitCustomizationConfiguration'))
{
if ($this->tabAccess['edit'] === '1')
{
if (Validate::isLoadedObject($product = new Product((int)(Tools::getValue('id_product')))))
{
if (!$product->createLabels((int)($_POST['uploadable_files']) - (int)($product->uploadable_files), (int)($_POST['text_fields']) - (int)($product->text_fields)))
$this->_errors[] = Tools::displayError('An error occurred while creating customization fields.');
if (!sizeof($this->_errors) AND !$product->updateLabels())
$this->_errors[] = Tools::displayError('An error occurred while updating customization.');
$product->uploadable_files = (int)($_POST['uploadable_files']);
$product->text_fields = (int)($_POST['text_fields']);
$product->customizable = ((int)($_POST['uploadable_files']) > 0 OR (int)($_POST['text_fields']) > 0) ? 1 : 0;
if (!sizeof($this->_errors) AND !$product->update())
$this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.');
if (!sizeof($this->_errors))
Tools::redirectAdmin($currentIndex.'&id_product='.$product->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=5&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
}
elseif (Tools::isSubmit('submitProductCustomization'))
{
if ($this->tabAccess['edit'] === '1')
{
if (Validate::isLoadedObject($product = new Product((int)(Tools::getValue('id_product')))))
{
foreach ($_POST AS $field => $value)
if (strncmp($field, 'label_', 6) == 0 AND !Validate::isLabel($value))
$this->_errors[] = Tools::displayError('Label fields are invalid');
if (!sizeof($this->_errors) AND !$product->updateLabels())
$this->_errors[] = Tools::displayError('An error occurred while updating customization.');
if (!sizeof($this->_errors))
Tools::redirectAdmin($currentIndex.'&id_product='.$product->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&add'.$this->table.'&tabs=5&token='.($token ? $token : $this->token));
}
else
$this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.');
}
else
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
}
elseif (isset($_GET['position']))
{
if ($this->tabAccess['edit'] !== '1')
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
elseif (!Validate::isLoadedObject($object = $this->loadObject()))
$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' '.$this->table.' '.Tools::displayError('(cannot load object)');
if (!$object->updatePosition((int)(Tools::getValue('way')), (int)(Tools::getValue('position'))))
$this->_errors[] = Tools::displayError('Failed to update the position.');
else
Tools::redirectAdmin($currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.(($id_category = (!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1')) ? ('&id_category='.$id_category) : '').'&token='.Tools::getAdminTokenLite('AdminCatalog'));
}
else
parent::postProcess(true);
}
protected function _validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)
{
if (!Validate::isUnsignedId($id_shop) OR !Validate::isUnsignedId($id_currency) OR !Validate::isUnsignedId($id_country) OR !Validate::isUnsignedId($id_group))
$this->_errors[] = Tools::displayError('Wrong ID\'s');
elseif ((empty($price) AND empty($reduction)) OR (!empty($price) AND !Validate::isPrice($price)) OR (!empty($reduction) AND !Validate::isPrice($reduction)))
$this->_errors[] = Tools::displayError('Invalid price/reduction amount');
elseif (!Validate::isUnsignedInt($from_quantity))
$this->_errors[] = Tools::displayError('Invalid quantity');
elseif ($reduction AND !Validate::isReductionType($reduction_type))
$this->_errors[] = Tools::displayError('Please select a reduction type (amount or percentage)');
elseif ($from AND $to AND (!Validate::isDateFormat($from) OR !Validate::isDateFormat($to)))
$this->_errors[] = Tools::displayError('Wrong from/to date');
else
return true;
return false;
}
// Checking customs feature
private function checkFeatures($languages, $feature_id)
{
$rules = call_user_func(array('FeatureValue', 'getValidationRules'), 'FeatureValue');
$feature = Feature::getFeature(Configuration::get('PS_LANG_DEFAULT'), $feature_id);
$val = 0;
foreach ($languages AS $language)
if ($val = Tools::getValue('custom_'.$feature_id.'_'.$language['id_lang']))
{
$currentLanguage = new Language($language['id_lang']);
if (Tools::strlen($val) > $rules['sizeLang']['value'])
$this->_errors[] = Tools::displayError('name for feature').' '.$feature['name'].' '.Tools::displayError('is too long in').' '.$currentLanguage->name;
elseif (!call_user_func(array('Validate', $rules['validateLang']['value']), $val))
$this->_errors[] = Tools::displayError('Valid name required for feature.').' '.$feature['name'].' '.Tools::displayError('in').' '.$currentLanguage->name;
if (sizeof($this->_errors))
return (0);
// Getting default language
if ($language['id_lang'] == Configuration::get('PS_LANG_DEFAULT'))
return ($val);
}
return (0);
}
/**
* Add or update a product image
*
* @param object $product Product object to add image
*/
public function addProductImage($product, $method = 'auto')
{
/* Updating an existing product image */
if ($id_image = ((int)(Tools::getValue('id_image')))) {
$image = new Image($id_image);
if (!Validate::isLoadedObject($image))
$this->_errors[] = Tools::displayError('An error occurred while loading object image.');
else
{
if (($cover = Tools::getValue('cover')) == 1)
Image::deleteCover($product->id);
$image->cover = $cover;
$this->validateRules('Image');
$this->copyFromPost($image, 'image');
if (sizeof($this->_errors) OR !$image->update())
$this->_errors[] = Tools::displayError('An error occurred while updating image.');
elseif (isset($_FILES['image_product']['tmp_name']) AND $_FILES['image_product']['tmp_name'] != NULL)
$this->copySingleImage($product->id, $image->id, $_FILES['image_product'], $method);
}
if (isset($image) AND Validate::isLoadedObject($image) AND !file_exists(_PS_PROD_IMG_DIR_.$image->getExistingImgPath().'.'.$image->image_format))
$image->delete();
if (sizeof($this->_errors))
return false;
@unlink(_PS_TMP_IMG_DIR_.'/product_'.$product->id.'.jpg');
@unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$product->id.'.jpg');
return ((isset($id_image) AND is_int($id_image) AND $id_image) ? $id_image : true);
}
/* Adding new product images */
elseif (isset($_FILES['image_product']['name']) && is_array($_FILES['image_product']['name'])) {
// ensure there is actually any file to process
$has_any_file = false;
foreach ($_FILES['image_product']['name'] as $value) {
$has_any_file = $has_any_file || !empty($value);
}
if (!$has_any_file) {
return true;
}
$success = true;
// reorganise the array into an indexed array
$images_product = [];
for ($i=sizeof($_FILES['image_product']['name']); $i>0; $i--) {
$images_product[] = [
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => '',
'size' => ''
];
}
foreach ($_FILES['image_product'] as $key => $array_values) {
$i=0;
foreach ($array_values as $value) {
$images_product[$i][$key] = $value;
$i++;
}
}
if (!Validate::isLoadedObject($product)) {
$this->_errors[] = Tools::displayError('Cannot add image because product add failed.');
}
else {
$is_first_uploaded_image_cover = Tools::getValue('cover') == 1;
$cover_already_associated = false;
foreach ($images_product as $image_uploaded) {
if ($error = checkImageUploadError($image_uploaded)) {
$this->_errors[] = $error;
}
if (!sizeof($this->_errors) AND isset($image_uploaded['tmp_name']) AND $image_uploaded['tmp_name'] != NULL)
{
if (substr($image_uploaded['name'], -4) == '.zip') {
return $this->uploadImageZip($product);
}
else {
$image = new Image();
$image->id_product = (int)($product->id);
$_POST['id_product'] = $image->id_product;
$image->position = Image::getHighestPosition($product->id) + 1;
$this->validateRules('Image', 'image');
$this->copyFromPost($image, 'image');
$image->cover = false;
if (!$cover_already_associated) {
if ($is_first_uploaded_image_cover) {
Image::deleteCover($product->id);
$image->cover = true;
}
else {
// the image is cover by default if no images exist.
$image->cover = (0==sizeof($product->getImages(Configuration::get('PS_LANG_DEFAULT'))));
}
$cover_already_associated = true;
}
if (!sizeof($this->_errors))
{
if (!$image->add())
$this->_errors[] = Tools::displayError('Error while creating additional image');
else
$this->copySingleImage($product->id, $image->id, $image_uploaded, $method);
$id_image = $image->id;
}
}
}
if (isset($image) AND Validate::isLoadedObject($image) AND !file_exists(_PS_PROD_IMG_DIR_.$image->getExistingImgPath().'.'.$image->image_format)) {
$image->delete();
}
@unlink(_PS_TMP_IMG_DIR_.'/product_'.$product->id.'.jpg');
@unlink(_PS_TMP_IMG_DIR_.'/product_mini_'.$product->id.'.jpg');
$success = $success && ((isset($id_image) AND is_int($id_image) AND $id_image) ? $id_image : true);
}
if (sizeof($this->_errors))
return false;
return $success;
}
}
}
public function uploadImageZip($product)
{
// Move the ZIP file to the img/tmp directory
if (!$zipfile = tempnam(_PS_TMP_IMG_DIR_, 'PS') OR !move_uploaded_file($_FILES['image_product']['tmp_name'], $zipfile))
{
$this->_errors[] = Tools::displayError('An error occurred during the ZIP file upload.');
return false;
}
// Unzip the file to a subdirectory
$subdir = _PS_TMP_IMG_DIR_.uniqid().'/';
try
{
if (!Tools::ZipExtract($zipfile, $subdir))
throw new Exception(Tools::displayError('An error occurred while unzipping your file.'));
$types = array('.gif' => 'image/gif', '.jpeg' => 'image/jpeg', '.jpg' => 'image/jpg', '.png' => 'image/png');
$_POST['id_product'] = (int)$product->id;
$imagesTypes = ImageType::getImagesTypes('products');
$highestPosition = Image::getHighestPosition($product->id);
foreach (scandir($subdir) as $file)
{
if ($file[0] == '.')
continue;
// Create image object
$image = new Image();
$image->id_product = (int)$product->id;
$image->position = ++$highestPosition;
$image->cover = ($highestPosition == 1 ? true : false);
// Call automated copy function
$this->validateRules('Image', 'image');
$this->copyFromPost($image, 'image');
if (sizeof($this->_errors))
throw new Exception('');
if (!$image->add())
throw new Exception(Tools::displayError('Error while creating additional image'));
if (filesize($subdir.$file) > $this->maxImageSize)
{
$image->delete();
throw new Exception(Tools::displayError('Image is too large').' ('.(filesize($subdir.$file) / 1000).Tools::displayError('kB').'). '.Tools::displayError('Maximum allowed:').' '.($this->maxImageSize / 1000).Tools::displayError('kB'));
}
$ext = (substr($file, -4) == 'jpeg') ? '.jpeg' : substr($file, -4);
$type = (isset($types[$ext]) ? $types[$ext] : '');
if (!isPicture(array('tmp_name' => $subdir.$file, 'type' => $type)))
{
$image->delete();
throw new Exception(Tools::displayError('Image format not recognized, allowed formats are: .gif, .jpg, .png'));
}
if (!$new_path = $image->getPathForCreation())
throw new Exception(Tools::displayError('An error occurred during new folder creation'));
if (!imageResize($subdir.$file, $new_path.'.'.$image->image_format))
{
$image->delete();
throw new Exception(Tools::displayError('An error occurred while resizing image.'));
}
foreach ($imagesTypes AS $k => $imageType)
if (!imageResize($image->getPathForCreation().'.jpg', $image->getPathForCreation().'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']))
{
$image->delete();
throw new Exception(Tools::displayError('An error occurred while copying image.').' '.stripslashes($imageType['name']));
}
Module::hookExec('watermark', array('id_image' => $image->id, 'id_product' => $image->id_product));
}
}
catch (Exception $e)
{
if ($error = $e->getMessage());
$this->_errors[] = $error;
Tools::deleteDirectory($subdir);
return false;
}
Tools::deleteDirectory($subdir);
return true;
}
/**
* Copy a product image
*
* @param integer $id_product Product Id for product image filename
* @param integer $id_image Image Id for product image filename
* @param array $image_uploaded (equivalent to $_FILES[''])
*/
private function copySingleImage($id_product, $id_image, array $image_uploaded, $method = 'auto')
{
if (!isset($image_uploaded['tmp_name'])) {
return false;
}
if ($error = checkImage($image_uploaded, $this->maxImageSize))
$this->_errors[] = $error;
else
{
$image = new Image($id_image);
if (!$new_path = $image->getPathForCreation())
$this->_errors[] = Tools::displayError('An error occurred during new folder creation');
if (!$tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS') OR !move_uploaded_file($image_uploaded['tmp_name'], $tmpName))
$this->_errors[] = Tools::displayError('An error occurred during the image upload');
elseif (!imageResize($tmpName, $new_path.'.'.$image->image_format))
$this->_errors[] = Tools::displayError('An error occurred while copying image.');
elseif ($method == 'auto')
{
$imagesTypes = ImageType::getImagesTypes('products');
foreach ($imagesTypes AS $k => $imageType)
if (!imageResize($tmpName, $new_path.'-'.stripslashes($imageType['name']).'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format))
$this->_errors[] = Tools::displayError('An error occurred while copying image:').' '.stripslashes($imageType['name']);
}
@unlink($tmpName);
Module::hookExec('watermark', array('id_image' => $id_image, 'id_product' => $id_product));
}
}
/**
* Copy a product image
*
* @param integer $id_product Product Id for product image filename
* @param integer $id_image Image Id for product image filename
*/
public function copyImage($id_product, $id_image, $method = 'auto')
{
return $this->copySingleImage($id_product, $id_image, $_FILES['image_product'], $method);
}
/**
* Add or update a product
*
* @global string $currentIndex Current URL in order to keep current Tab
*/
public function submitAddProduct($token = NULL)
{
global $cookie, $currentIndex, $link;
$className = 'Product';
$rules = call_user_func(array($this->className, 'getValidationRules'), $this->className);
$defaultLanguage = new Language((int)(Configuration::get('PS_LANG_DEFAULT')));
$languages = Language::getLanguages(false);
/* Check required fields */
foreach ($rules['required'] AS $field)
if (($value = Tools::getValue($field)) == false AND $value != '0')
{
if (Tools::getValue('id_'.$this->table) AND $field == 'passwd')
continue;
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), $field, $className).' '.$this->l('is required');
}
/* Check multilingual required fields */
foreach ($rules['requiredLang'] AS $fieldLang)
if (!Tools::getValue($fieldLang.'_'.$defaultLanguage->id))
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), $fieldLang, $className).' '.$this->l('is required at least in').' '.$defaultLanguage->name;
/* Check fields sizes */
foreach ($rules['size'] AS $field => $maxLength)
if ($value = Tools::getValue($field) AND Tools::strlen($value) > $maxLength)
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), $field, $className).' '.$this->l('is too long').' ('.$maxLength.' '.$this->l('chars max').')';
if (isset($_POST['description_short']))
{
$saveShort = $_POST['description_short'];
$_POST['description_short'] = strip_tags($_POST['description_short']);
}
/* Check description short size without html */
$limit = (int)Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT');
if ($limit <= 0) $limit = 400;
foreach ($languages AS $language)
if ($value = Tools::getValue('description_short_'.$language['id_lang']))
if (Tools::strlen(strip_tags($value)) > $limit)
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), 'description_short').' ('.$language['name'].') '.$this->l('is too long').' : '.$limit.' '.$this->l('chars max').' ('.$this->l('count now').' '.Tools::strlen(strip_tags($value)).')';
/* Check multilingual fields sizes */
foreach ($rules['sizeLang'] AS $fieldLang => $maxLength)
foreach ($languages AS $language)
if ($value = Tools::getValue($fieldLang.'_'.$language['id_lang']) AND Tools::strlen($value) > $maxLength)
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), $fieldLang, $className).' ('.$language['name'].') '.$this->l('is too long').' ('.$maxLength.' '.$this->l('chars max').')';
if (isset($_POST['description_short']))
$_POST['description_short'] = $saveShort;
/* Check fields validity */
foreach ($rules['validate'] AS $field => $function)
if ($value = Tools::getValue($field))
if (!Validate::$function($value))
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), $field, $className).' '.$this->l('is invalid');
/* Check multilingual fields validity */
foreach ($rules['validateLang'] AS $fieldLang => $function)
foreach ($languages AS $language)
if ($value = Tools::getValue($fieldLang.'_'.$language['id_lang']))
if (!Validate::$function($value))
$this->_errors[] = $this->l('the field').' '.call_user_func(array($className, 'displayFieldName'), $fieldLang, $className).' ('.$language['name'].') '.$this->l('is invalid');
/* Categories */
$productCats = '';
if (!Tools::isSubmit('categoryBox') OR !sizeof(Tools::getValue('categoryBox')))
$this->_errors[] = $this->l('product must be in at least one Category');
if (!is_array(Tools::getValue('categoryBox')) OR !in_array(Tools::getValue('id_category_default'), Tools::getValue('categoryBox')))
$this->_errors[] = $this->l('product must be in the default category');
/* Tags */
foreach ($languages AS $language)
if ($value = Tools::getValue('tags_'.$language['id_lang']))
if (!Validate::isTagsList($value))
$this->_errors[] = $this->l('Tags list').' ('.$language['name'].') '.$this->l('is invalid');
if (!sizeof($this->_errors))
{
$id = (int)(Tools::getValue('id_'.$this->table));
$tagError = true;
/* Update an existing product */
if (isset($id) AND !empty($id))
{
$object = new $this->className($id);
// ANTADIS : Customs Inputs update
Db::getInstance()->ExecuteS('
INSERT INTO `'._DB_PREFIX_.'product_customs`
VALUES (
'.(int) $object->id.',
"'.pSQL(Tools::getValue('nc8')).'",
"'.pSQL(Tools::getValue('id_country')).'"
)
ON DUPLICATE KEY UPDATE `nc8` = "'.pSQL(Tools::getValue('nc8')).'",
`id_country` = "'.pSQL(Tools::getValue('id_country')).'"
');
if (Validate::isLoadedObject($object))
{
$this->_removeTaxFromEcotax();
$this->copyFromPost($object, $this->table);
if ($object->update())
{
if ($id_reason = (int)Tools::getValue('id_mvt_reason') AND (int)Tools::getValue('mvt_quantity') > 0 AND $id_reason > 0)
{
$reason = new StockMvtReason((int)$id_reason);
$qty = Tools::getValue('mvt_quantity') * $reason->sign;
if (!$object->addStockMvt($qty, (int)$id_reason, NULL, NULL, (int)$cookie->id_employee))
$this->_errors[] = Tools::displayError('An error occurred while updating qty.');
}
$this->updateAccessories($object);
$this->updateDownloadProduct($object);
if (!$this->updatePackItems($object))
$this->_errors[] = Tools::displayError('An error occurred while adding products to the pack.');
elseif (!$object->updateCategories($_POST['categoryBox'], true))
$this->_errors[] = Tools::displayError('An error occurred while linking object.').' '.$this->table.' '.Tools::displayError('To categories');
elseif (!$this->updateTags($languages, $object))
$this->_errors[] = Tools::displayError('An error occurred while adding tags.');
elseif ($id_image = $this->addProductImage($object, Tools::getValue('resizer')))
{
$currentIndex .= '&image_updated='.(int)Tools::getValue('id_image');
Hook::updateProduct($object);
Search::indexation(false, $object->id);
if (Tools::getValue('resizer') == 'man' && isset($id_image) AND is_int($id_image) AND $id_image)
Tools::redirectAdmin($currentIndex.'&id_product='.$object->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&edit='.strval(Tools::getValue('productCreated')).'&id_image='.$id_image.'&imageresize&toconf=4&submitAddAndStay='.((Tools::isSubmit('submitAdd'.$this->table.'AndStay') OR Tools::getValue('productCreated') == 'on') ? 'on' : 'off').'&token='.(($token ? $token : $this->token)));
// Save and preview
if (Tools::isSubmit('submitAddProductAndPreview'))
{
$preview_url = ($link->getProductLink($this->getFieldValue($object, 'id'), $this->getFieldValue($object, 'link_rewrite', (int)($cookie->id_lang)), Category::getLinkRewrite($this->getFieldValue($object, 'id_category_default'), (int)($cookie->id_lang))));
if (!$object->active)
{
$admin_dir = dirname($_SERVER['PHP_SELF']);
$admin_dir = substr($admin_dir, strrpos($admin_dir,'/') + 1);
$token = Tools::encrypt('PreviewProduct'.$object->id);
if (strpos($preview_url, '?') === false)
$preview_url .= '?';
else
$preview_url .= '&';
$preview_url .= 'adtoken='.$token.'&ad='.$admin_dir;
}
Tools::redirectAdmin($preview_url);
}
// Save and stay on same form
elseif (Tools::isSubmit('submitAdd'.$this->table.'AndStay')
OR ($id_image AND $id_image !== true))
{
// Save and stay on same form
if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
{
Tools::redirectAdmin($currentIndex.'&id_product='.$object->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&addproduct&conf=4&tabs='.(int)(Tools::getValue('tabs')).'&token='.($token ? $token : $this->token));
}
}
// Default behavior (save and back)
Tools::redirectAdmin($currentIndex.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&conf=4&token='.($token ? $token : $this->token).'&onredirigeici');
}
}
else
$this->_errors[] = Tools::displayError('An error occurred while updating object.').' '.$this->table.' ('.Db::getInstance()->getMsgError().')';
}
else
$this->_errors[] = Tools::displayError('An error occurred while updating object.').' '.$this->table.' ('.Tools::displayError('Cannot load object').')';
}
/* Add a new product */
else
{
$object = new $this->className();
$this->_removeTaxFromEcotax();
$this->copyFromPost($object, $this->table);
if ($object->add())
{
$this->updateAccessories($object);
if (!$this->updatePackItems($object))
$this->_errors[] = Tools::displayError('An error occurred while adding products to the pack.');
$this->updateDownloadProduct($object);
if (!sizeof($this->_errors))
{
if (!$object->updateCategories($_POST['categoryBox']))
$this->_errors[] = Tools::displayError('An error occurred while linking object.').' '.$this->table.' '.Tools::displayError('To categories');
elseif (!$this->updateTags($languages, $object))
$this->_errors[] = Tools::displayError('An error occurred while adding tags.');
elseif ($id_image = $this->addProductImage($object))
{
Hook::addProduct($object);
Search::indexation(false, $object->id);
// Save and preview
if (Tools::isSubmit('submitAddProductAndPreview'))
{
$preview_url = ($link->getProductLink($this->getFieldValue($object, 'id'), $this->getFieldValue($object, 'link_rewrite', (int)($cookie->id_lang)), Category::getLinkRewrite($this->getFieldValue($object, 'id_category_default'), (int)($cookie->id_lang))));
if (!$object->active)
{
$admin_dir = dirname($_SERVER['PHP_SELF']);
$admin_dir = substr($admin_dir, strrpos($admin_dir,'/') + 1);
$token = Tools::encrypt('PreviewProduct'.$object->id);
$preview_url .= '&adtoken='.$token.'&ad='.$admin_dir;
}
Tools::redirectAdmin($preview_url);
}
if (Tools::getValue('resizer') == 'man' && isset($id_image) AND is_int($id_image) AND $id_image)
Tools::redirectAdmin($currentIndex.'&id_product='.$object->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&id_image='.$id_image.'&imageresize&toconf=3&submitAddAndStay='.(Tools::isSubmit('submitAdd'.$this->table.'AndStay') ? 'on' : 'off').'&token='.(($token ? $token : $this->token)));
// Save and stay on same form
if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
Tools::redirectAdmin($currentIndex.'&id_product='.$object->id.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&addproduct&conf=3&tabs='.(int)(Tools::getValue('tabs')).'&token='.($token ? $token : $this->token));
// Default behavior (save and back)
Tools::redirectAdmin($currentIndex.'&id_category='.(!empty($_REQUEST['id_category'])?$_REQUEST['id_category']:'1').'&conf=3&token='.($token ? $token : $this->token));
}
}
else
$object->delete();
}
else
$this->_errors[] = Tools::displayError('An error occurred while creating object.').' '.$this->table.'';
}
}
}
private function _removeTaxFromEcotax()
{
$ecotaxTaxRate = Tax::getProductEcotaxRate();
if ($ecotax = Tools::getValue('ecotax'))
$_POST['ecotax'] = Tools::ps_round(Tools::getValue('ecotax') / (1 + $ecotaxTaxRate / 100), 6);
}
private function _applyTaxToEcotax($product)
{
$ecotaxTaxRate = Tax::getProductEcotaxRate();
if ($product->ecotax)
$product->ecotax = Tools::ps_round($product->ecotax * (1 + $ecotaxTaxRate / 100), 2);
}
/**
* Update product download
*
* @param object $product Product
*/
public function updateDownloadProduct($product)
{
/* add or update a virtual product */
if (Tools::getValue('is_virtual_good') == 'true')
{
if (!Tools::getValue('virtual_product_name'))
{
$this->_errors[] = $this->l('the field').' '.$this->l('display filename').' '.$this->l('is required');
return false;
}
if (Tools::getValue('virtual_product_nb_days') === false)
{
$this->_errors[] = $this->l('the field').' '.$this->l('number of days').' '.$this->l('is required');
return false;
}
if (Tools::getValue('virtual_product_expiration_date') AND !Validate::isDate(Tools::getValue('virtual_product_expiration_date')))
{
$this->_errors[] = $this->l('the field').' '.$this->l('expiration date').' '.$this->l('is not valid');
return false;
}
// The oos behavior MUST be "Deny orders" for virtual products
if (Tools::getValue('out_of_stock') != 0)
{
$this->_errors[] = $this->l('The "when out of stock" behavior selection must be "deny order" for virtual products');
return false;
}
$download = new ProductDownload(Tools::getValue('virtual_product_id'));
$download->id_product = $product->id;
$download->display_filename = Tools::getValue('virtual_product_name');
$download->physically_filename = Tools::getValue('virtual_product_filename') ? Tools::getValue('virtual_product_filename') : ProductDownload::getNewFilename();
$download->date_deposit = date('Y-m-d H:i:s');
$download->date_expiration = Tools::getValue('virtual_product_expiration_date') ? Tools::getValue('virtual_product_expiration_date').' 23:59:59' : '';
$download->nb_days_accessible = Tools::getValue('virtual_product_nb_days');
$download->nb_downloadable = Tools::getValue('virtual_product_nb_downloable');
$download->active = 1;
if ($download->save())
return true;
}
else
{
/* unactive download product if checkbox not checked */
if ($id_product_download = ProductDownload::getIdFromIdProduct($product->id))
{
$productDownload = new ProductDownload($id_product_download);
$productDownload->date_expiration = date('Y-m-d H:i:s', time()-1);
$productDownload->active = 0;
return $productDownload->save();
}
}
return false;
}
/**
* Update product accessories
*
* @param object $product Product
*/
public function updateAccessories($product)
{
$product->deleteAccessories();
if ($accessories = Tools::getValue('inputAccessories'))
{
$accessories_id = array_unique(explode('-', $accessories));
if (sizeof($accessories_id))
{
array_pop($accessories_id);
$product->changeAccessories($accessories_id);
}
}
}
/**
* Update product tags
*
* @param array Languages
* @param object $product Product
* @return boolean Update result
*/
public function updateTags($languages, $product)
{
$tagError = true;
/* Reset all tags for THIS product */
if (!Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'product_tag`
WHERE `id_product` = '.(int)($product->id)))
return false;
/* Assign tags to this product */
foreach ($languages AS $language)
if ($value = Tools::getValue('tags_'.$language['id_lang']))
$tagError &= Tag::addTags($language['id_lang'], (int)($product->id), $value);
return $tagError;
}
public function display($token = NULL)
{
global $currentIndex, $cookie;
// adding Antadis
$_quantities = 0;
$this->getList((int)($cookie->id_lang), NULL, NULL,0,1000);
foreach ($this->_list AS $product) {
$result_quantities = Db::getInstance()->executeS('
SELECT od.`product_quantity`,od.`product_quantity_reinjected`
FROM '._DB_PREFIX_.'order_detail od
WHERE od.`product_id` = ' . (int)$product['id_product']
);
$quantity = 0;
foreach ($result_quantities as $od) {
$quantity += ($od['product_quantity'] - $od['product_quantity_reinjected']);
}
if ($quantity>0 && isset($product['quantity'])) {
$_quantities += ($quantity + $product['quantity']);
} elseif (isset($product['quantity'])) {
$_quantities += $product['quantity'];
}
}
if (($id_category = (int)Tools::getValue('id_category')))
$currentIndex .= '&id_category='.$id_category;
$this->getList((int)($cookie->id_lang), !$cookie->__get($this->table.'Orderby') ? 'position' : NULL, !$cookie->__get($this->table.'Orderway') ? 'ASC' : NULL);
$id_category = (Tools::getValue('id_category',1));
if (!$id_category)
$id_category = 1;
echo '
';
}
/**
* displayList show ordered list of current category
*
* @param mixed $token
* @return void
*/
public function displayList($token = NULL)
{
global $currentIndex;
/* Display list header (filtering, pagination and column names) */
$this->displayListHeader($token);
if (!sizeof($this->_list))
echo '
'.$this->l('No items found').'
';
/* Show the content of the table */
$this->displayListContent($token);
/* Close list table and submit button */
$this->displayListFooter($token);
}
public function displayListFooter($token = NULL)
{
echo '';
global $cookie;
if ($this->delete)
echo '';
echo '';
$languages = Language::getLanguages(FALSE);
echo '
'.$this->l('Sometimes one customer could fit in multiple rules, priorities allows you to define which rule to apply.').'
>
>
';
}
protected function _displaySpecificPriceAdditionForm($defaultCurrency, $shops, $currencies, $countries, $groups)
{
if (!($product = $this->loadObject()))
return;
$default_country = new Country((int)Configuration::get('PS_COUNTRY_DEFAULT'));
echo '
'.$this->l('Add a new specific price').'
';
/*
* Form for add a virtual product like software, mp3, etc...
*/
$productDownload = new ProductDownload();
if ($id_product_download = $productDownload->getIdFromIdProduct($this->getFieldValue($obj, 'id')))
$productDownload = new ProductDownload($id_product_download);
?>
';
?>
id OR Tools::getValue('is_virtual_good')=='true') AND $productDownload->active) echo 'checked="checked"' ?> />
id OR !$productDownload->active) echo 'style="display:none;"' ?> >
l('Your download repository is not writable.'); ?>
id) echo '' ?>
checkFile()): ?>
id): ?>
l('This product is missing') ?>:
physically_filename ?>
';
echo ' '.$this->l('Product link will look like this:').' '.(Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').$_SERVER['SERVER_NAME'].'/id_product-.html
';
echo '
'.$this->l('Short description:').'
('.$this->l('appears in the product lists and on the top of the product page').')
';
foreach ($this->_languages as $language)
echo '
';
echo '
'.$this->l('Description:').'
('.$this->l('appears in the body of the product page').')
';
foreach ($this->_languages as $language)
echo '
';
echo '
'.$this->l('More description:').'
';
foreach ($this->_languages as $language)
echo '
';
echo '
'.$this->l('Videos :').'
';
foreach ($this->_languages as $language)
echo '
';
echo '
'.$this->l('Livraison :').'
';
foreach ($this->_languages as $language)
echo '
';
echo '
'.$this->l('Comments :').'
';
foreach ($this->_languages as $language)
echo '
';
echo '
';
echo '
'.$this->l('Tags:').'
';
if ($obj->id)
$obj->tags = Tag::getProductTags((int)$obj->id);
foreach ($this->_languages as $language)
{
echo '
'.(Tools::getValue('id_image')?$this->l('Edit this product image'):$this->l('Add a new image to this product')).'
'.$this->l('File:').'
'.$this->l('Format:').' JPG, GIF, PNG. '.$this->l('Filesize:').' '.($this->maxImageSize / 1000).''.$this->l('Kb max.').'
'.$this->l('You can also upload a ZIP file containing several images. Thumbnails will be resized automatically.').'
'.$this->l('Caption:').'
';
foreach ($this->_languages as $language)
{
if (!Tools::getValue('legend_'.$language['id_lang']))
$legend = $this->getFieldValue($obj, 'name', $language['id_lang']);
else
$legend = Tools::getValue('legend_'.$language['id_lang']);
echo '
*'.$this->l('Forbidden characters:').' <>;=#{} '.$this->l('Forbidden characters will be automatically erased.').'
';
}
echo '
'.$this->l('Short description of the image').'
'.$this->l('Cover:').'
'.$this->l('If you want to select this image as a product cover').'
'; /* DEPRECATED FEATURE
'.$this->l('Thumbnails resize method:').'
'.$this->l('Method you want to use to generate resized thumbnails').'
*/
echo '
';
echo '';
$images = Image::getImages((int)($cookie->id_lang), $obj->id);
$imagesTotal = Image::getImagesTotal($obj->id);
if (isset($obj->id) AND sizeof($images))
{
echo '';
echo '
';
}
else
echo ''.$this->l('You must save this product before adding features').'.';
}
public function haveThisAccessory($accessoryId, $accessories)
{
foreach ($accessories AS $accessory)
if ((int)($accessory['id_product']) == (int)($accessoryId))
return true;
return false;
}
private function displayPack(Product $obj)
{
global $currentIndex, $cookie;
$boolPack = (($obj->id AND Pack::isPack($obj->id)) OR Tools::getValue('ppack')) ? true : false;
$packItems = $boolPack ? Pack::getItems($obj->id, $cookie->id_lang) : array();
echo '
';
foreach ($packItems as $packItem)
echo $packItem->pack_quantity.' x '.$packItem->name.' ';
echo '
'.$this->l('Begin typing the first letters of the product name, then select the product from the drop-down list:').'
'.$this->l('You cannot add downloadable products to a pack.').'
';
// param multipleSeparator:'||' ajouté à cause de bug dans lib autocomplete
echo '';
}
private function addPackItem()
{
return '
function addPackItem()
{
if ($(\'#curPackItemId\').val() == \'\' || $(\'#curPackItemName\').val() == \'\')
{
alert(\''.$this->l('Thanks to select at least one product.').'\');
return false;
}
else if ($(\'#curPackItemId\').val() == \'\' || $(\'#curPackItemQty\').val() == \'\')
{
alert(\''.$this->l('Thanks to set a quantity to add a product.').'\');
return false;
}
var lineDisplay = $(\'#curPackItemQty\').val()+ \'x \' +$(\'#curPackItemName\').val();
var divContent = $(\'#divPackItems\').html();
divContent += lineDisplay;
divContent += \' \';
// QTYxID-QTYxID
var line = $(\'#curPackItemQty\').val()+ \'x\' +$(\'#curPackItemId\').val();
$(\'#inputPackItems\').val($(\'#inputPackItems\').val() + line + \'-\');
$(\'#divPackItems\').html(divContent);
$(\'#namePackItems\').val($(\'#namePackItems\').val() + lineDisplay + \'¤\');
$(\'#curPackItemId\').val(\'\');
$(\'#curPackItemName\').val(\'\');
$(\'#curPackItemName\').setOptions({
extraParams: {excludeIds : getSelectedIds()}
});
}
';
}
private function delPackItem()
{
return '
function delPackItem(id)
{
var reg = new RegExp(\'-\', \'g\');
var regx = new RegExp(\'x\', \'g\');
var div = getE(\'divPackItems\');
var input = getE(\'inputPackItems\');
var name = getE(\'namePackItems\');
var select = getE(\'curPackItemId\');
var select_quantity = getE(\'curPackItemQty\');
var inputCut = input.value.split(reg);
var nameCut = name.value.split(new RegExp(\'¤\', \'g\'));
input.value = \'\';
name.value = \'\';
div.innerHTML = \'\';
for (var i = 0; i < inputCut.length; ++i)
if (inputCut[i])
{
var inputQty = inputCut[i].split(regx);
if (inputQty[1] != id)
{
input.value += inputCut[i] + \'-\';
name.value += nameCut[i] + \'¤\';
div.innerHTML += nameCut[i] + \' \';
}
}
$(\'#curPackItemName\').setOptions({
extraParams: {excludeIds : getSelectedIds()}
});
}';
}
private function _positionJS()
{
return '';
}
public function updatePackItems($product)
{
Pack::deleteItems($product->id);
// lines format: QTY x ID-QTY x ID
if (Tools::getValue('ppack') AND $items = Tools::getValue('inputPackItems') AND sizeof($lines = array_unique(explode('-', $items))))
{
foreach($lines as $line)
{
// line format QTY x ID
list($qty, $item_id) = explode('x', $line);
if ($qty > 0 && isset($item_id))
{
if (!Pack::addItem((int)($product->id), (int)($item_id), (int)($qty)))
return false;
}
}
}
return true;
}
public function getL($key)
{
$trad = array(
'Default category:' => $this->l('Default category:'),
'Catalog:' => $this->l('Catalog:'),
'Consider changing the default category.' => $this->l('Consider changing the default category.'),
'ID' => $this->l('ID'),
'Name' => $this->l('Name'),
'Mark all checkbox(es) of categories in which product is to appear' => $this->l('Mark all checkbox(es) of categories in which product is to appear')
);
return $trad[$key];
}
public function getFieldValue($obj, $data, $id_lang) {
global $cookie;
// if ($id_lang == 0) {
// $id_lang = (int)($cookie->id_lang);
// }
$customs_data = Db::getInstance()->getRow('
SELECT `nc8`, `id_country`
FROM `'._DB_PREFIX_.'product_customs`
WHERE id_product = '.(int)$obj->id
);
switch ($data) {
case 'nc8':
return (!empty($customs_data['nc8']) ? $customs_data['nc8'] : '');
break;
case 'id_country':
return (!empty($customs_data['id_country']) ? $customs_data['id_country'] : '');
break;
default:
return parent::getFieldValue($obj, $data, $id_lang);
break;
}
}
}