first commit

This commit is contained in:
2025-01-06 20:47:25 +01:00
commit 3bdbd78c2f
25591 changed files with 3586440 additions and 0 deletions

View File

@@ -0,0 +1,630 @@
<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
if (!defined('_PS_VERSION_'))
exit;
class Ets_pr_obj extends ObjectModel
{
/** @var Ets_promotion */
public $module;
public function __construct($id = null, $id_lang = null, $id_shop = null, $translator = null)
{
parent::__construct($id, $id_lang, $id_shop, $translator);
$this->module = new Ets_promotion();
}
public function renderForm()
{
Ets_promotion::registerPlugins();
$this->fields = $this->getListFields();
$helper = new HelperForm();
$helper->module = new ets_promotion();
$configs = $this->fields['configs'];
$fields_form = array();
$fields_form['form'] = $this->fields['form'];
if($configs)
{
foreach($configs as $key => $config)
{
if(isset($config['type']) && in_array($config['type'],array('sort_order')))
continue;
$confFields = array(
'name' => $key,
'type' => $config['type'],
'class'=>isset($config['class'])?$config['class']:'',
'label' => $config['label'],
'desc' => isset($config['desc']) ? $config['desc'] : false,
'required' => isset($config['required']) && $config['required'] ? true : false,
'readonly' => isset($config['readonly']) ? $config['readonly'] : false,
'autoload_rte' => isset($config['autoload_rte']) && $config['autoload_rte'] ? true : false,
'options' => isset($config['options']) && $config['options'] ? $config['options'] : array(),
'suffix' => isset($config['suffix']) && $config['suffix'] ? $config['suffix'] : false,
'values' => isset($config['values']) ? $config['values'] : false,
'lang' => isset($config['lang']) ? $config['lang'] : false,
'showRequired' => isset($config['showRequired']) && $config['showRequired'],
'hide_delete' => isset($config['hide_delete']) ? $config['hide_delete'] : false,
'placeholder' => isset($config['placeholder']) ? $config['placeholder'] : false,
'display_img' => $this->id && isset($config['type']) && $config['type']=='file' && $this->$key!='' && @file_exists(_PS_ETS_PR_IMG_DIR_.$this->$key) ? _PS_ETS_PR_IMG_.$this->$key : false,
'img_del_link' => $this->id && isset($config['type']) && $config['type']=='file' && $this->$key!='' && @file_exists(_PS_ETS_PR_IMG_DIR_.$this->$key) ? $this->context->link->getAdminBaseLink('AdminModules').'&configure=ets_promotion&deleteimage='.$key.'&itemId='.(isset($this->id)?$this->id:'0').'&Ets_pr_object=PRMN_'.Tools::ucfirst($fields_form['form']['name']) : false,
'min' => isset($config['min']) ? $config['min'] : false,
'max' => isset($config['max']) ? $config['max'] : false,
'data_suffix' => isset($config['data_suffix']) ? $config['data_suffix'] :'',
'data_suffixs' => isset($config['data_suffixs']) ? $config['data_suffixs'] :'',
'multiple' => isset($config['multiple']) ? $config['multiple']: false,
'tab' => isset($config['tab']) ? $config['tab']:false,
'html_content' => isset($config['html_content']) ? $config['html_content']:'',
'form_group_class' => isset($config['form_group_class']) ? $config['form_group_class']:'',
'no_display' => isset($config['no_display']) ? $config['no_display']:false,
);
if(isset($config['col']) && $config['col'])
$confFields['col'] = $config['col'];
if(isset($config['tree']) && $config['tree'])
{
$confFields['tree'] = $config['tree'];
if(isset($config['tree']['use_checkbox']) && $config['tree']['use_checkbox'])
$confFields['tree']['selected_categories'] = $this->$key ? explode(',',$this->$key):array();
else
$confFields['tree']['selected_categories'] = array($this->$key);
}
if(!$confFields['suffix'])
unset($confFields['suffix']);
$fields_form['form']['input'][] = $confFields;
}
}
$fields_form['form']['input'][] = array(
'type' => 'hidden',
'name' => $fields_form['form']['key'],
);
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'save_'.$this->fields['form']['name'];
$helper->currentIndex = '';
$language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$fields = array();
$languages = Language::getLanguages(false);
$helper->override_folder = '/';
if($configs)
{
foreach($configs as $key => $config)
{
if($config['type']=='checkbox' || (isset($config['multiple']) && $config['multiple']))
{
if(Tools::isSubmit($key))
$fields[$key] = Tools::getValue($key);
else
$fields[$key] = $this->id ? ($this->$key ? explode(',',$this->$key):array()) : (isset($config['default']) && $config['default'] ? $config['default'] : array());
}
elseif(isset($config['lang']) && $config['lang'])
{
foreach($languages as $l)
{
$temp = $this->$key;
if(Tools::isSubmit($key.'_'.$l['id_lang']))
$fields[$key][$l['id_lang']] = Tools::getValue($key.'_'.$l['id_lang']);
else
$fields[$key][$l['id_lang']] = $this->id ? $temp[$l['id_lang']] : (isset($config['default']) && $config['default'] ? $config['default'] : null);
}
}
elseif(isset($config['type']) && $config['type']=='file_lang')
{
foreach($languages as $l)
{
$temp = $this->$key;
$fields[$key][$l['id_lang']] = $this->id ? $temp[$l['id_lang']] : (isset($config['default']) && $config['default'] ? $config['default'] : null);
}
}
elseif(!isset($config['tree']))
{
if(Tools::isSubmit($key))
$fields[$key] = Tools::getValue($key);
else
{
$fields[$key] = $this->id ? $this->$key : (isset($config['default']) && $config['default'] ? $config['default'] : null);
// if(isset($config['validate']) && ($config['validate']=='isUnsignedFloat' || $config['validate']=='isUnsignedInt') && $fields[$key]==0)
// $fields[$key] ='';
if(isset($config['validate']) && $config['validate']=='isDate' && $fields[$key]=='0000-00-00 00:00:00')
$fields[$key] ='';
}
}
}
}
$fields[$fields_form['form']['key']] = $this->id;
$helper->tpl_vars = array(
'base_url' => Context::getContext()->shop->getBaseURL(),
'language' => array(
'id_lang' => $language->id,
'iso_code' => $language->iso_code
),
'fields_value' => $fields,
'languages' => Context::getContext()->controller->getLanguages(),
'id_language' => Context::getContext()->language->id,
'key_name' => 'id_'.$fields_form['form']['name'],
'item_id' => $this->id,
'list_item' => true,
'image_baseurl' => _PS_ETS_PR_IMG_,
'configTabs'=> isset($this->fields['tabs']) ? $this->fields['tabs']:false,
'display_advanced_setting' => (int)Tools::getValue('display_advanced_setting'),
'name_controller' => isset($this->fields['name_controller']) ? $this->fields['name_controller']:'',
);
return str_replace(array('id="ets_pr_rule_form"','id="fieldset_0"'),'',$helper->generateForm(array($fields_form)));
}
public function saveData()
{
$this->fields = $this->getListFields();
$errors = array();
$success = array();
$languages = Language::getLanguages(false);
$id_lang_default = (int)Configuration::get('PS_LANG_DEFAULT');
$parent=isset($this->fields['form']['parent'])? $this->fields['form']['parent']:'1';
$configs = $this->fields['configs'];
$files = array();
$old_files = array();
if(method_exists($this,'validateCustomField'))
$this->validateCustomField($errors);
if($configs)
{
foreach($configs as $key => $config)
{
$value_key = Tools::getValue($key);
if($config['type']=='sort_order' || $config['type']=='html')
continue;
if(isset($config['lang']) && $config['lang'])
{
$key_value_lang_default = trim(Tools::getValue($key.'_'.$id_lang_default));
if(isset($config['required']) && $config['required'] && $config['type']!='switch' && $key_value_lang_default == '')
{
$errors[] = sprintf($this->l('%s is required','ets_pr_obj'),$config['label']);
}
elseif($key_value_lang_default!='' && isset($config['validate']) && ($config['validate']=='isColor' || $config['validate']=='isLink'))
{
$validate = $config['validate'];
if(!Ets_promotion::$validate(trim($key_value_lang_default)))
$errors[] = sprintf($this->l('%s is not valid','ets_pr_obj'),$config['label']);
unset($validate);
}
elseif($key_value_lang_default!='' && !is_array($key_value_lang_default) && isset($config['validate']) && method_exists('Validate',$config['validate']))
{
$validate = $config['validate'];
if(!Validate::$validate(trim($key_value_lang_default)))
$errors[] = sprintf($this->l('%s is not valid','ets_pr_obj'),$config['label']);
unset($validate);
}
elseif(!Validate::isCleanHtml($key_value_lang_default))
$errors[] = sprintf($this->l('%s is not valid','ets_pr_obj'),$config['label']);
else
{
foreach($languages as $language)
{
if($language['id_lang']!=$id_lang_default)
{
$value_lang = trim(Tools::getValue($key.'_'.$language['id_lang']));
if($value_lang!='' && isset($config['validate']) && ($config['validate']=='isColor' || $config['validate']=='isLink'))
{
$validate = $config['validate'];
if(!Ets_promotion::$validate(trim($value_lang)))
$errors[] = sprintf($this->l('%s is not valid in %s','ets_pr_obj'),$config['label'],$language['iso_code']);
unset($validate);
}
elseif($value_lang!='' && !is_array($value_lang) && isset($config['validate']) && method_exists('Validate',$config['validate']))
{
$validate = $config['validate'];
if(!Validate::$validate(trim($value_lang)))
$errors[] = sprintf($this->l('%s is not valid in %s','ets_pr_obj'),$config['label'],$language['iso_code']);
unset($validate);
}
elseif(!Validate::isCleanHtml($value_lang))
$errors[] = sprintf($this->l('%s is not valid in %s','ets_pr_obj'),$config['label'],$language['iso_code']);
}
}
}
}
elseif($config['type']=='file_lang')
{
$files[$key] = array();
foreach($languages as $l)
{
$name = $key.'_'.$l['id_lang'];
if(isset($_FILES[$name]['tmp_name']) && isset($_FILES[$name]['name']) && $_FILES[$name]['name'])
{
$_FILES[$name]['name'] = str_replace(array(' ','(',')','!','@','#','+'),'_',$_FILES[$name]['name']);
$type = Tools::strtolower(Tools::substr(strrchr($_FILES[$name]['name'], '.'), 1));
$imageName = @file_exists(_PS_ETS_PR_IMG_DIR_.Tools::strtolower($_FILES[$name]['name'])) ? Tools::passwdGen().'-'.Tools::strtolower($_FILES[$name]['name']) : Tools::strtolower($_FILES[$name]['name']);
$fileName = _PS_ETS_PR_IMG_DIR_.$imageName;
$max_file_size = Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE')*1024*1024;
if(!Validate::isFileName($_FILES[$name]['name']))
$errors[] = sprintf($this->l('%s is not valid','ets_pr_obj'),$config['label']);
elseif($_FILES[$name]['size'] > $max_file_size)
$errors[] = sprintf($this->l('%s file is too large','ets_pr_obj'),$config['label']);
elseif(file_exists($fileName))
{
$errors[] =sprintf($this->l('%s file already existed','ets_pr_obj'),$config['label']);
}
else
{
$imagesize = @getimagesize($_FILES[$name]['tmp_name']);
if (!$errors && isset($_FILES[$name]) &&
!empty($_FILES[$name]['tmp_name']) &&
!empty($imagesize) &&
in_array($type, array('jpg', 'gif', 'jpeg', 'png'))
)
{
$temp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error = ImageManager::validateUpload($_FILES[$name]))
$errors[] = $error;
elseif (!$temp_name || !move_uploaded_file($_FILES[$name]['tmp_name'], $temp_name))
$errors[] = sprintf($this->l('%s cannot upload in %s','ets_pr_obj'),$config['label'],$l['iso_code']);
elseif (!ImageManager::resize($temp_name, $fileName, null, null, $type))
$errors[] = printf($this->l('%s An error occurred during the image upload process in %s','ets_pr_obj'),$config['label'],$l['iso_code']);
if (isset($temp_name))
@unlink($temp_name);
if(!$errors)
{
$files[$key][$l['id_lang']] = $imageName;
}
}
else
$errors[] = sprintf($this->l('%s file in %s is not in the correct format, accepted formats: jpg, gif, jpeg, png.','ets_pr_obj'),$config['label'],$l['iso_code']);
}
}
}
}
else
{
if(isset($config['required']) && $config['required'] && isset($config['type']) && $config['type']=='file')
{
if($this->$key=='' && !isset($_FILES[$key]['size']))
$errors[] = sprintf($this->l('%s is required','ets_pr_obj'),$config['label']);
elseif(isset($_FILES[$key]['size']))
{
$fileSize = round((int)$_FILES[$key]['size'] / (1024 * 1024));
if($fileSize > 100)
$errors[] = sprintf($this->l('%s file is too large','ets_pr_obj'),$config['label']);
}
}
else
{
if(isset($config['required']) && $config['required'] && $config['type']!='switch' && !is_array($value_key) && trim($value_key) == '')
{
$errors[] = sprintf($this->l('%s is required','ets_pr_obj'),$config['label']);
}
elseif($value_key!='' && isset($config['validate']) && ($config['validate']=='isColor' || $config['validate']=='isLink'))
{
$validate = $config['validate'];
if(!Ets_promotion::$validate(trim($value_key)))
$errors[] = sprintf($this->l('%s is not valid','ets_pr_obj'),$config['label']);
unset($validate);
}
elseif($value_key!='' && !is_array($value_key) && isset($config['validate']) && method_exists('Validate',$config['validate']))
{
$validate = $config['validate'];
if(!Validate::$validate(trim($value_key)))
$errors[] = sprintf($this->l('%s is not valid','ets_pr_obj'),$config['label']);
unset($validate);
}
elseif($value_key!='' && !is_array($value_key) && !Validate::isCleanHtml(trim($value_key)))
{
$errors[] = sprintf($this->l('%s is required','ets_pr_obj'),$config['label']);
}
}
}
}
}
if(!$errors)
{
if($configs)
{
foreach($configs as $key => $config)
{
if( $config['type']=='html')
continue;
$value_key = Tools::getValue($key);
if(isset($config['type']) && $config['type']=='sort_order')
{
if(!$this->id)
{
if(!isset($config['order_group'][$parent]) || isset($config['order_group'][$parent]) && !$config['order_group'][$parent])
$this->$key = $this->maxVal($key)+1;
else
{
$orderGroup = $config['order_group'][$parent];
$this->$key = $this->maxVal($key,$orderGroup,(int)$this->$orderGroup)+1;
}
}
}
elseif(isset($config['lang']) && $config['lang'])
{
$valules = array();
$key_value_lang_default = trim(Tools::getValue($key.'_'.$id_lang_default));
foreach($languages as $lang)
{
$key_value_lang = trim(Tools::getValue($key.'_'.$lang['id_lang']));
if($config['type']=='switch')
$valules[$lang['id_lang']] = (int)$key_value_lang ? 1 : 0;
elseif(Validate::isCleanHtml($key_value_lang))
$valules[$lang['id_lang']] = $key_value_lang ? : (Validate::isCleanHtml($key_value_lang_default) ? $key_value_lang_default:'');
}
$this->$key = $valules;
}
elseif($config['type']=='file_lang')
{
if(isset($files[$key]))
{
$valules = array();
$old_values = $this->$key;
$old_files[$key] = array();
foreach($languages as $lang)
{
if(isset($files[$key][$lang['id_lang']]) && $files[$key][$lang['id_lang']])
{
$valules[$lang['id_lang']] = $files[$key][$lang['id_lang']];
if($old_values[$lang['id_lang']])
$old_files[$key][$lang['id_lang']] = $old_values[$lang['id_lang']];
}
elseif(!$old_values[$lang['id_lang']] && isset($files[$key][$id_lang_default]) && $files[$key][$id_lang_default])
$valules[$lang['id_lang']] = $files[$key][$id_lang_default];
else
$valules[$lang['id_lang']] = $old_values[$lang['id_lang']];
}
$this->$key = $valules;
}
}
elseif($config['type']=='switch')
{
$this->$key = (int)$value_key ? 1 : 0;
}
elseif($config['type']=='categories' && is_array($value_key) && isset($config['tree']['use_checkbox']) && $config['tree']['use_checkbox'] || $config['type']=='checkbox')
{
if($value_key)
{
if(in_array('all',$value_key))
$this->$key = 'all';
else
$this->$key = implode(',',$value_key);
}
else
$this->$key='';
}
elseif(Validate::isCleanHtml($value_key))
$this->$key = trim($value_key);
}
}
}
if (!count($errors))
{
$this->module->_clearSmartyCacheWhenUpdatePrRule();
$this->module->_clearSmartyCache('*', $this->module->_getCacheId(['condition'], false));
$this->id_shop = Context::getContext()->shop->id;
if($this->id && $this->update() || !$this->id && $this->add(true,true))
{
$success[] = $this->l('Saved successfully','ets_pr_obj');
if($old_files)
{
foreach($old_files as $key_file => $file)
{
if($file)
{
if(is_array($file))
{
foreach($file as $f)
{
if(!in_array($f,$this->$key_file))
@unlink(_PS_ETS_PR_IMG_DIR_.$f);
}
}
else
@unlink(_PS_ETS_PR_IMG_DIR_.$file);
}
}
}
}
else
{
if($files)
{
foreach($files as $key_file => $file)
{
if($file)
{
if(is_array($file))
{
foreach($file as $f)
{
@unlink(_PS_ETS_PR_IMG_DIR_.$f);
}
}
else
@unlink(_PS_ETS_PR_IMG_DIR_.$file);
}
}
}
$errors[] = $this->l('Saving failed','ets_pr_obj');
}
}
return array('errors' => $errors, 'success' => $success);
}
public function update($null_value=false)
{
$ok = parent::update($null_value);
return $ok;
}
public function maxVal($key,$group = false, $groupval=0)
{
return ($max = Db::getInstance()->getValue("SELECT max(".pSQL($key).") FROM "._DB_PREFIX_."ets_pr_".pSQL($this->fields['form']['name']).($group && ($groupval > 0) ? " WHERE ".pSQL($group)."=".(int)$groupval : ''))) ? (int)$max : 0;
}
public function getGroups()
{
$sql ='SELECT g.id_group,gl.name FROM `'._DB_PREFIX_.'group` g
INNER JOIN `'._DB_PREFIX_.'group_shop` gs ON (gs.id_group = g.id_group AND gs.id_shop="'.(int)Context::getContext()->shop->id.'")
LEFT JOIN `'._DB_PREFIX_.'group_lang` gl ON (g.id_group = gl.id_group AND gl.id_lang="'.(int)Context::getContext()->language->id.'")
';
return Db::getInstance()->executeS($sql);
}
public function getCarriers($filter ='')
{
$sql ='SELECT c.id_reference,c.name FROM `'._DB_PREFIX_.'carrier` c
INNER JOIN `'._DB_PREFIX_.'carrier_shop` cs ON (cs.id_carrier = c.id_carrier AND cs.id_shop="'.(int)Context::getContext()->shop->id.'")
LEFT JOIN `'._DB_PREFIX_.'carrier_lang` cl ON (c.id_carrier = cl.id_carrier AND cl.id_lang="'.(int)Context::getContext()->language->id.'")
WHERE c.deleted=0 AND c.active=1 '.(string)$filter. ' ORDER BY c.id_reference';
$carriers = Db::getInstance()->executeS($sql);
if($carriers)
{
foreach($carriers as &$carrier)
{
if(!$carrier['name'])
$carrier['name'] = Context::getContext()->shop->name;
}
}
return $carriers;
}
public function getGenders()
{
$sql ='SELECT g.id_gender,gl.name FROM `'._DB_PREFIX_.'gender` g
LEFT JOIN `'._DB_PREFIX_.'gender_lang` gl ON (g.id_gender = gl.id_gender AND gl.id_lang="'.(int)Context::getContext()->language->id.'")
';
return Db::getInstance()->executeS($sql);
}
public function getListZones()
{
$sql = 'SELECT z.id_zone,z.name FROM `'._DB_PREFIX_.'zone` z
INNER JOIN `'._DB_PREFIX_.'zone_shop` zs ON (z.id_zone = zs.id_zone AND zs.id_shop="'.(int)Context::getContext()->shop->id.'")
WHERE z.active=1';
return Db::getInstance()->executeS($sql);
}
public function getListCountries()
{
$sql = 'SELECT c.id_country, cl.name FROM `'._DB_PREFIX_.'country` c
INNER JOIN `'._DB_PREFIX_.'country_shop` cs ON (c.id_country = cs.id_country AND cs.id_shop="'.(int)Context::getContext()->shop->id.'")
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (c.id_country= cl.id_country AND cl.id_lang="'.(int)Context::getContext()->language->id.'")
WHERE c.active=1';
return Db::getInstance()->executeS($sql);
}
public function getListStates($id_country)
{
if($id_country)
{
$sql = 'SELECT id_state,name FROM `'._DB_PREFIX_.'state` WHERE id_country='.(int)$id_country;
return Db::getInstance()->executeS($sql);
}
return array();
}
public function getOrderStates()
{
$sql ='SELECT os.id_order_state,osl.name FROM `'._DB_PREFIX_.'order_state` os
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.id_order_state = osl.id_order_state AND osl.id_lang="'.(int)Context::getContext()->language->id.'")
';
return Db::getInstance()->executeS($sql);
}
public function getOrderStatesPaid()
{
$sql ='SELECT id_order_state FROM `'._DB_PREFIX_.'order_state` WHERE paid=1';
$states = Db::getInstance()->executeS($sql);
$result = array();
if($states)
{
foreach($states as $state)
{
$result[] = $state['id_order_state'];
}
}
return $result;
}
public function getAttributes($filter ='')
{
$sql = 'SELECT a.id_attribute, CONCAT(agl.name,": ",al.name) as name FROM `'._DB_PREFIX_.'attribute` a
INNER JOIN `'._DB_PREFIX_.'attribute_shop` ats ON (a.id_attribute = ats.id_attribute AND ats.id_shop="'.(int)Context::getContext()->shop->id.'")
INNER JOIN `'._DB_PREFIX_.'attribute_group` ag ON (a.id_attribute_group = ag.id_attribute_group)
LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.id_attribute= al.id_attribute AND al.id_lang="'.(int)Context::getContext()->language->id.'")
LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.id_attribute_group = agl.id_attribute_group AND agl.id_lang="'.(int)Context::getContext()->language->id.'")
WHERE 1'.(string)$filter;
return Db::getInstance()->executeS($sql);
}
public function getFeatures($filter='')
{
$sql = 'SELECT f.id_feature, fl.name FROM `'._DB_PREFIX_.'feature` f
INNER JOIN `'._DB_PREFIX_.'feature_shop` fs ON (f.id_feature = fs.id_feature AND fs.id_shop="'.(int)Context::getContext()->shop->id.'")
LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON (f.id_feature= fl.id_feature AND fl.id_lang="'.(int)Context::getContext()->language->id.'")
WHERE 1 '.(string)$filter;
return Db::getInstance()->executeS($sql);
}
public function getSuppliers()
{
$sql = 'SELECT s.id_supplier, s.name FROM `'._DB_PREFIX_.'supplier` s
INNER JOIN `'._DB_PREFIX_.'supplier_shop` ss ON (s.id_supplier = ss.id_supplier AND ss.id_shop="'.(int)Context::getContext()->shop->id.'")';
return Db::getInstance()->executeS($sql);
}
public function getManufacturers($filter='')
{
$sql = 'SELECT m.id_manufacturer, m.name FROM `'._DB_PREFIX_.'manufacturer` m
INNER JOIN `'._DB_PREFIX_.'manufacturer_shop` ms ON (m.id_manufacturer = ms.id_manufacturer AND ms.id_shop="'.(int)Context::getContext()->shop->id.'")
WHERE 1 '.(string)$filter;
return Db::getInstance()->executeS($sql);
}
public function getPaymentModules($filter='')
{
$hook_payment = version_compare(_PS_VERSION_, '1.7', '>=') ? 'paymentOptions' : 'payment';
$sql = 'SELECT m.id_module,m.name
FROM `' . _DB_PREFIX_ . 'module` m
INNER JOIN `' . _DB_PREFIX_ . 'hook_module` hm ON (m.id_module = hm.id_module)
INNER JOIN `' . _DB_PREFIX_ . 'hook` h ON (hm.id_hook= h.id_hook)
WHERE m.active=1 AND h.name = "' . pSQL($hook_payment) . '" AND hm.id_shop = ' . (int)Context::getContext()->shop->id .(string)$filter.' GROUP BY m.id_module';
$modules = Db::getInstance()->executeS($sql);
$custom_modules = array();
if($modules)
{
foreach($modules as $key=> &$module)
{
$moduleOjb = Module::getInstanceByName($module['name']);
if($module['name']=='ets_payment_with_fee')
{
$sql = 'SELECT * FROM `'._DB_PREFIX_.'ets_paymentmethod` p
LEFT JOIN `'._DB_PREFIX_.'ets_paymentmethod_lang` pl ON (p.id_ets_paymentmethod =pl.id_ets_paymentmethod AND pl.id_lang="'.(int)Context::getContext()->language->id.'")';
$custom_payments = Db::getInstance()->executeS($sql);
if($custom_payments)
{
foreach($custom_payments as $payment)
{
$custom_modules[] = array(
'id_module' => $moduleOjb->id.'-'.$payment['id_ets_paymentmethod'],
'name' => $payment['method_name'],
);
}
}
unset($modules[$key]);
}
else{
if($moduleOjb->id)
$module['name'] = $moduleOjb->displayName;
}
}
}
return array_merge($modules,$custom_modules);
}
}

View File

@@ -0,0 +1,377 @@
<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
class Ets_pr_overrideUtil
{
/**
* @var array[]
*/
static public $conflict = [
[
'class' => 'Cart',
'file' => 'classes/Cart.php',
'method' => 'getOrderTotal',
'conflicts' => ['ets_promotion', 'ets_payment_with_fee'],
'priority' => [
0 => 'ets_promotion',
1 => 'ets_payment_with_fee',
]
],
[
'class' => 'CartController',
'file' => 'controllers/front/CartController.php',
'method' => 'displayAjaxRefresh',
'conflicts' => ['ets_promotion','ets_extraoptions'],
'priority' => [
0 => 'ets_promotion',
1 => 'ets_extraoptions',
]
],
[
'class' => 'AdminCartRulesController',
'file' => 'controllers/admin/AdminCartRulesController.php',
'method' => 'postProcess',
'conflicts' => ['ets_promotion','etsdiscountcombinations'],
'priority' => [
0 => 'ets_promotion',
1 => 'etsdiscountcombinations',
]
],
];
/**
* Run AFTER enable
* @param Module $currentModule
* @throws Exception
*/
public static function onModuleEnabled(Module $currentModule)
{
$curModuleName = $currentModule->name;
foreach (self::$conflict as $item) {
if(in_array($curModuleName, $item['conflicts'])){
$matchedByPriority = null;
foreach ($item['priority'] as $i => $name) {
if(self::isEnabled($name) || $name==$curModuleName){
$matchedByPriority = $name;
break;
}
}
if($matchedByPriority !== null){
if($matchedByPriority !== $curModuleName){
self::removeOverrideMethod($currentModule, $item['class'], $item['method']);
$instance = Module::getInstanceByName($matchedByPriority);
$instance && self::addOverrideMethod($instance, $item['class'], $item['method']);
}
}
}
}
}
/**
* Run BEFORE enable module
* @param \Module $currentModule
* @throws \ReflectionException
*/
public static function resolveConflict(Module $currentModule)
{
$curModuleName = $currentModule->name;
foreach (self::$conflict as $item) {
if(in_array($curModuleName, $item['conflicts'])){
foreach ($item['conflicts'] as $name) {
$instance = Module::getInstanceByName($name);
self::isEnabled($name) && $instance && self::removeOverrideMethod($instance, $item['class'], $item['method']);
}
}
}
}
/**
* Run after disable module
* @param \Module $moddule
* @throws \ReflectionException
*/
public static function restoreReplacedMethod(\Module $moddule)
{
$curModuleName = $moddule->name;
foreach (self::$conflict as $item) {
if(in_array($curModuleName, $item['conflicts']) && ($currentPriority = array_search($curModuleName, $item['priority'], true)) !== false){
foreach ($item['priority'] as $i => $name) {
if(self::isEnabled($name) && $name!=$curModuleName){
if ($i > $currentPriority) {
$instance = Module::getInstanceByName($name);
$instance && self::addOverrideMethod($instance, $item['class'], $item['method']);
}
break;
}
}
}
}
}
/**
* @param Module $module
* @param $classname
* @param $method_name
*/
public static function addOverrideMethod($module,$classname,$method_name)
{
PrestaShopAutoload::getInstance()->generateIndex();
$orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');
if (!$path) {
$path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php';
}
$path_override = $module->getLocalPath() . 'override' . DIRECTORY_SEPARATOR . $path;
if (!file_exists($path_override)) {
return false;
} else {
file_put_contents($path_override, preg_replace('#(\r\n|\r)#ism', "\n", file_get_contents($path_override)));
}
$pattern_escape_com = '#(^\s*?\/\/.*?\n|\/\*(?!\n\s+\* module:.*?\* date:.*?\* version:.*?\*\/).*?\*\/)#ism';
// Check if there is already an override file, if not, we just need to copy the file
if ($file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {
// Check if override file is writable
$override_path = _PS_ROOT_DIR_ . '/' . $file;
if ((!file_exists($override_path) && !is_writable(dirname($override_path))) || (file_exists($override_path) && !is_writable($override_path))) {
throw new Exception(Context::getContext()->getTranslator()->trans('file (%s) not writable', [$override_path], 'Admin.Notifications.Error'));
}
// Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration
do {
$uniq = uniqid();
} while (class_exists($classname . 'OverrideOriginal_remove', false));
// Make a reflection of the override class and the module override class
$override_file = file($override_path);
$override_file = array_diff($override_file, ["\n"]);
eval(
preg_replace(
['#^\s*<\?(?:php)?#', '#class\s+' . $classname . '\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?#i'],
[' ', 'class ' . $classname . 'OverrideOriginal' . $uniq . ' extends \stdClass'],
implode('', $override_file)
)
);
$override_class = new ReflectionClass($classname . 'OverrideOriginal' . $uniq);
$module_file = file($path_override);
$module_file = array_diff($module_file, ["\n"]);
eval(
preg_replace(
['#^\s*<\?(?:php)?#', '#class\s+' . $classname . '(\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?)?#i'],
[' ', 'class ' . $classname . 'Override' . $uniq . ' extends \stdClass'],
implode('', $module_file)
)
);
$module_class = new ReflectionClass($classname . 'Override' . $uniq);
$matchedMethod = null;
// Check if none of the methods already exists in the override class
foreach ($module_class->getMethods() as $method) {
if($method->getName() != $method_name)
continue;
if ($override_class->hasMethod($method->getName()) ) {
return true;
}
$module_file = preg_replace('/((:?public|private|protected)\s+(static\s+)?function\s+(?:\b' . $method->getName() . '\b))/ism', "/*\n * module: " . $module->name . "\n * date: " . date('Y-m-d H:i:s') . "\n * version: " . $module->version . "\n */\n $1", $module_file);
$matchedMethod = $method;
}
// Insert the methods from module override in override
$copy_from = array_slice($module_file, $matchedMethod->getStartLine() - 1, $matchedMethod->getEndLine() - $matchedMethod->getStartLine() + 1);
array_splice($override_file, $override_class->getEndLine() - 1, 0, $copy_from);
$code = implode('', $override_file);
file_put_contents($override_path, preg_replace($pattern_escape_com, '', $code));
} else {
$override_src = $path_override;
$override_dest = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR . $path;
$dir_name = dirname($override_dest);
if (!$orig_path && !is_dir($dir_name)) {
@mkdir($dir_name, FileSystem::DEFAULT_MODE_FOLDER);
}
if (!is_writable($dir_name)) {
throw new Exception(Context::getContext()->getTranslator()->trans('directory (%s) not writable', [$dir_name], 'Admin.Notifications.Error'));
}
$module_file = file($override_src);
$module_file = array_diff($module_file, ["\n"]);
if ($orig_path) {
do {
$uniq = uniqid();
} while (class_exists($classname . 'OverrideOriginal_remove', false));
eval(
preg_replace(
['#^\s*<\?(?:php)?#', '#class\s+' . $classname . '(\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?)?#i'],
[' ', 'class ' . $classname . 'Override' . $uniq . ' extends \stdClass'],
implode('', $module_file)
)
);
$module_class = new ReflectionClass($classname . 'Override' . $uniq);
// For each method found in the override, prepend a comment with the module name and version
foreach ($module_class->getMethods() as $method) {
if($method->getName()== $method_name)
{
$module_file = preg_replace('/((:?public|private|protected)\s+(static\s+)?function\s+(?:\b' . $method->getName() . '\b))/ism', "/*\n * module: " . $module->name . "\n * date: " . date('Y-m-d H:i:s') . "\n * version: " . $module->version . "\n */\n $1", $module_file);
if ($module_file === null) {
throw new Exception(Context::getContext()->getTranslator()->trans('Failed to override method %1$s in class %2$s.', [$method->getName(), $classname], 'Admin.Modules.Notification'));
}
}
}
}
file_put_contents($override_dest, preg_replace($pattern_escape_com, '', $module_file));
}
PrestashopAutoload::getInstance()->generateIndex();
}
/**
* @param Module $module
* @param $classname
* @param $method_name
*/
public static function removeOverrideMethod($module,$classname,$method_name)
{
PrestaShopAutoload::getInstance()->generateIndex();
$orig_path = $path = PrestaShopAutoload::getInstance()->getClassPath($classname . 'Core');
if ($orig_path && !$file = PrestaShopAutoload::getInstance()->getClassPath($classname)) {
return true;
} elseif (!$orig_path && Module::getModuleIdByName($classname)) {
$path = 'modules' . DIRECTORY_SEPARATOR . $classname . DIRECTORY_SEPARATOR . $classname . '.php';
}
// Check if override file is writable
if ($orig_path) {
$override_path = _PS_ROOT_DIR_ . '/' . $file;
} else {
$override_path = _PS_OVERRIDE_DIR_ . $path;
}
if (!is_file($override_path)) {
return true;
}
if (!is_writable($override_path)) {
return false;
}
file_put_contents($override_path, preg_replace('#(\r\n|\r)#ism', "\n", file_get_contents($override_path)));
if ($orig_path) {
// Get a uniq id for the class, because you can override a class (or remove the override) twice in the same session and we need to avoid redeclaration
do {
$uniq = uniqid();
} while (class_exists($classname . 'OverrideOriginal_remove', false));
// Make a reflection of the override class and the module override class
$override_file = file($override_path);
eval(
preg_replace(
['#^\s*<\?(?:php)?#', '#class\s+' . $classname . '\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?#i'],
[' ', 'class ' . $classname . 'OverrideOriginal_remove' . $uniq . ' extends \stdClass'],
implode('', $override_file)
)
);
$override_class = new ReflectionClass($classname . 'OverrideOriginal_remove' . $uniq);
$module_file = file($module->getLocalPath() . 'override/' . $path);
eval(
preg_replace(
['#^\s*<\?(?:php)?#', '#class\s+' . $classname . '(\s+extends\s+([a-z0-9_]+)(\s+implements\s+([a-z0-9_]+))?)?#i'],
[' ', 'class ' . $classname . 'Override_remove' . $uniq . ' extends \stdClass'],
implode('', $module_file)
)
);
$module_class = new ReflectionClass($classname . 'Override_remove' . $uniq);
// Remove methods from override file
foreach ($module_class->getMethods() as $method) {
if (!$override_class->hasMethod($method->getName()) || $method->getName()!=$method_name) {
continue;
}
$method = $override_class->getMethod($method->getName());
$length = $method->getEndLine() - $method->getStartLine() + 1;
$module_method = $module_class->getMethod($method->getName());
$override_file_orig = $override_file;
$orig_content = preg_replace('/\s/', '', implode('', array_splice($override_file, $method->getStartLine() - 1, $length, array_pad([], $length, '#--remove--#'))));
$module_content = preg_replace('/\s/', '', implode('', array_splice($module_file, $module_method->getStartLine() - 1, $length, array_pad([], $length, '#--remove--#'))));
$replace = true;
if (preg_match('/\* module: (' . $module->name . ')/ism', $override_file[$method->getStartLine() - 5])) {
$override_file[$method->getStartLine() - 6] = $override_file[$method->getStartLine() - 5] = $override_file[$method->getStartLine() - 4] = $override_file[$method->getStartLine() - 3] = $override_file[$method->getStartLine() - 2] = '#--remove--#';
$replace = false;
}
if (md5($module_content) != md5($orig_content) && $replace) {
$override_file = $override_file_orig;
}
}
$count = count($override_file);
for ($i = 0; $i < $count; ++$i) {
if (preg_match('/(^\s*\/\/.*)/i', $override_file[$i])) {
$override_file[$i] = '#--remove--#';
} elseif (preg_match('/(^\s*\/\*)/i', $override_file[$i])) {
if (!preg_match('/(^\s*\* module:)/i', $override_file[$i + 1])
&& !preg_match('/(^\s*\* date:)/i', $override_file[$i + 2])
&& !preg_match('/(^\s*\* version:)/i', $override_file[$i + 3])
&& !preg_match('/(^\s*\*\/)/i', $override_file[$i + 4])) {
for (; $override_file[$i] && !preg_match('/(.*?\*\/)/i', $override_file[$i]); ++$i) {
$override_file[$i] = '#--remove--#';
}
$override_file[$i] = '#--remove--#';
}
}
}
// Rewrite nice code
$code = '';
foreach ($override_file as $line) {
if ($line == '#--remove--#') {
continue;
}
$code .= $line;
}
$to_delete = preg_match('/<\?(?:php)?\s+(?:abstract|interface)?\s*?class\s+' . $classname . '\s+extends\s+' . $classname . 'Core\s*?[{]\s*?[}]/ism', $code);
}
if (!isset($to_delete) || $to_delete) {
unlink($override_path);
} else {
file_put_contents($override_path, $code);
}
PrestashopAutoload::getInstance()->generateIndex();
return true;
}
public static function isEnabled($module_name)
{
$id_module = Module::getModuleIdByName($module_name);
if (Db::getInstance()->getValue('SELECT `id_module` FROM `' . _DB_PREFIX_ . 'module_shop` WHERE `id_module` = ' . (int) $id_module)) {
return true;
}
return false;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,810 @@
<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
if (!defined('_PS_VERSION_'))
exit;
class Ets_pr_defines
{
public static $instance;
public $name = 'ets_promotion';
public $is17 = false;
public function __construct()
{
$this->context = Context::getContext();
if (is_object($this->context->smarty)) {
$this->smarty = $this->context->smarty;
}
if(version_compare(_PS_VERSION_, '1.7', '>='))
$this->is17 = true;
}
public static function getInstance()
{
if (!(isset(self::$instance)) || !self::$instance) {
self::$instance = new Ets_pr_defines();
}
return self::$instance;
}
public function l($string)
{
return Translate::getModuleTranslation('ets_promotion', $string, pathinfo(__FILE__, PATHINFO_FILENAME));
}
public function installDb(){
if(!is_dir(_PS_ETS_PR_IMG_DIR_))
{
@mkdir(_PS_ETS_PR_IMG_DIR_,0755,true);
@copy(dirname(__FILE__).'/index.php', _PS_ETS_PR_IMG_DIR_. 'index.php');
}
$res = Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_rule` (
`id_ets_pr_rule` INT(11) NOT NULL AUTO_INCREMENT ,
`active` INT(1) ,
`priority` INT(11),
`quantity` INT(11),
`quantity_per_user` INT(11),
`apply_other_rule_presteahop` INT(1) ,
`apply_other_rule` INT(1) ,
`from_date` DATETIME ,
`to_date` DATETIME ,
`id_shop` INT(11) NOT NULL ,
`new_customer` INT(11),
`date_add` DATETIME ,
`date_upd` DATETIME ,
PRIMARY KEY (`id_ets_pr_rule`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
$res &= Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_condition_rule` (
`id_ets_pr_condition_rule` INT(11) NOT NULL AUTO_INCREMENT ,
`id_ets_pr_rule` INT(11) NOT NULL ,
`parent_codition` VARCHAR(222) ,
`condition` VARCHAR(32),
`id_customers` VARCHAR(222),
`only_apply_on_default_group` INT(1),
`id_groups` VARCHAR(222),
`id_genders` VARCHAR(222),
`age_from` INT(11),
`age_to` INT(11),
`on_customer_birthday` INT(11),
`verified_customer` INT(11),
`customer_signed_up_from` datetime,
`customer_signed_up_to` datetime,
`days_since_signed_up_cal` VARCHAR(22),
`days_since_singed_up_day` INT(11),
`newsletter_registration` VARCHAR(50),
`order_criteria` VARCHAR(50),
`first_order_of_customer` INT(1),
`number_of_order_cal` VARCHAR(50),
`number_of_order` INT(11),
`number_of_product_cal` VARCHAR(50),
`number_of_product` INT(11),
`amount_of_money_spent_cal` VARCHAR(50),
`amount_of_money_spent` FLOAT(10,2),
`amount_of_money_spent_tax_incl` INT(1),
`amount_of_money_spent_shipping_incl` INT(1),
`amount_of_money_spent_discount_incl` INT(1),
`order_time_in` VARCHAR(50),
`order_time_in_last_day` INT(11),
`order_time_in_from` datetime,
`order_time_in_to` datetime,
`order_status_in` VARCHAR(300),
`cart_amount_cal` VARCHAR(50),
`cart_amount` FLOAT(10,2),
`cart_amount_tax_incl` INT(1),
`cart_amount_shipping_incl` INT(1),
`cart_amount_discount_incl` INT(1),
`total_product_quantity_cal` VARCHAR(50),
`total_product_quantity` INT(11),
`quantity_of_same_product_cal` VARCHAR(50),
`quantity_of_same_product` INT(11),
`number_of_different_product_cal` VARCHAR(50),
`number_of_different_product` INT(11),
`number_of_product_in_same_category_cal` VARCHAR(50),
`number_of_product_in_same_category` INT(11),
`apply_for_discounted_products` INT(1),
`products_with_different_attribute` INT(1),
`applicable_product_categories` VARCHAR(50),
`include_specific_products` VARCHAR(300),
`exclude_products` VARCHAR(300),
`apply_all_attribute` INT(1),
`select_attributes` VARCHAR(300),
`apply_all_features` INT(1),
`select_features` VARCHAR(300),
`apply_all_supplier` INT(1),
`select_suppliers` VARCHAR(300),
`apply_all_manufacturer` INT(1),
`select_manufacturers` VARCHAR(300),
`apply_for_product_price_cal` VARCHAR(50),
`apply_for_product_price` FLOAT(10,2),
`apply_for_availabled_quantity_stock_cal` VARCHAR(50),
`apply_for_availabled_quantity_stock` INT(11),
`delivery_total_cart_weight_cal` VARCHAR(50),
`delivery_total_cart_weight` FLOAT(10,2),
`delivery_apply_to_carriers` VARCHAR(300),
`delivery_id_zone` INT(11),
`delivery_id_country` INT(11),
`delivery_id_state` INT(11),
`delivery_speed_grade_cal` VARCHAR(50),
`delivery_speed_grade` FLOAT(10,2),
`payments` VARCHAR(500),
`specific_occasion` VARCHAR(50),
`specific_occasion_hour_of_day_from` text,
`specific_occasion_hour_of_day_to` text,
`specific_occasion_day_of_week` text,
`specific_occasion_day_of_week_from` text,
`specific_occasion_day_of_week_to` text,
`specific_occasion_month_of_year` text,
`specific_occasion_month_of_year_from` text,
`specific_occasion_month_of_year_to` text,
`specific_occasion_date_from` text,
`specific_occasion_date_to` text,
`include_sub_categories` INT(1),
`applicable_categories` text,
INDEX(id_ets_pr_rule), PRIMARY KEY (`id_ets_pr_condition_rule`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
$res &= Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_rule_lang` (
`id_ets_pr_rule` INT(11) NOT NULL ,
`id_lang` INT(11) NOT NULL,
`name` VARCHAR(1000),
`description` TEXT,
PRIMARY KEY (`id_ets_pr_rule`,`id_lang`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci') ;
$res &= Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_action_rule` (
`id_ets_pr_action_rule` INT(11) NOT NULL AUTO_INCREMENT ,
`id_ets_pr_rule` INT(11) NOT NULL ,
`type_action` VARCHAR(222),
`apply_free_shipping` INT(11),
`discount_on_shipping_cost` VARCHAR(32),
`amount_discount_on_shipping_cost` FLOAT(10,2),
`percent_discount_on_shipping_cost` FLOAT(10,2),
`maximum_discount_on_shipping_cost` FLOAT(10,2),
`carrier_apply_discount_on_shipping_cost` VARCHAR(200),
`discount_on_total_cart` VARCHAR(32),
`percent_total_cart` FLOAT(10,2),
`amount_total_cart` FLOAT(10,2),
`maximum_discount_value` FLOAT(10,2),
`exclude_tax_before_cal_discount` INT(1),
`exclude_shipping_fee_before_cal_disount` INT(1),
`discount_on_product` VARCHAR(50),
`discount_type` VARCHAR(50),
`amount_discount_product` FLOAT(10,2),
`percent_discount_proudct` FLOAT(10,2),
`maximum_discount_product` FLOAT(10,2),
`apply_for_discounted_product` INT(1),
`applicable_product_categories` VARCHAR(50),
`include_specific_products` VARCHAR(300),
`exclude_products` VARCHAR(300),
`apply_all_attribute` INT(1),
`select_attributes` VARCHAR(300),
`apply_all_features` INT(1),
`select_features` VARCHAR(300),
`apply_all_supplier` INT(1),
`select_suppliers` VARCHAR(300),
`apply_all_manufacturer` INT(1),
`select_manufacturers` VARCHAR(300),
`apply_for_product_price_cal` VARCHAR(50),
`apply_for_product_price` FLOAT(10,2),
`apply_for_availabled_quantity_stock_cal` VARCHAR(50),
`apply_for_availabled_quantity_stock` INT(11),
`purchase_quantity_more_of_same_product` INT(11),
`discount_on_all_quantities` VARCHAR(50),
`percent_discount_on_all_quantities` FLOAT(10,2),
`amount_discount_on_all_quantities` FLOAT(10,2),
`maximum_discount_on_all_quantities` FLOAT(10,2),
`discount_all_quantities_action_on` VARCHAR(100),
`product_with_deffierent_attribute` INT(1),
`gift_or_with_discount_product` VARCHAR(100),
`gift_product` VARCHAR(300),
`quantity_gift_product` INT(11),
`apply_action_on` VARCHAR(20),
`gift_add_selected_product_to_cart` VARCHAR(100),
`new_product_with_discount_price` VARCHAR(50),
`percent_new_product_with_discount_price` FLOAT(10,2),
`amount_new_product_with_discount_price` FLOAT(10,2),
`maximum_new_product_with_discount_price` FLOAT(10,2),
`purchase_more_product_quantity` INT(11),
`discount_purchase_more_product_quantity` VARCHAR(100),
`percent_discount_purchase_more_product_quantity` FLOAT(10,2),
`amount_discount_purchase_more_product_quantity` FLOAT(10,2),
`maximum_discount_purchase_more_product_quantity` FLOAT(10,2),
`start_counting_purchase_more_product_quantity` VARCHAR(100),
`purchase_more_product_amount` FLOAT(10,2),
`discount_purchase_more_product_amount` VARCHAR(100),
`percent_discount_purchase_more_product_amount` FLOAT(10,2),
`amount_discount_purchase_more_product_amount` FLOAT(10,2),
`maximum_discount_purchase_more_product_amount` FLOAT(10,2),
`start_counting_purchase_more_product_amount` VARCHAR(100),
`purchase_discount_on_next_same_product` INT(11),
`discount_on_next_same_product` VARCHAR(100),
`percent_discount_on_next_same_product` FLOAT(10,2),
`amount_discount_on_next_same_product` FLOAT(10,2),
`amount_discount_on_next_same_product_tax_incl` INT(1),
`maximum_discount_on_next_same_product` FLOAT(10,2),
`apply_on_next_same_product` INT(11),
`action_on_next_same_product` VARCHAR(100),
`repeat_the_action_on_next_same_product` VARCHAR(100),
`maximum_time_on_next_same_product` INT(11),
`include_sub_categories` INT(1),
`reduction_currency` INT(11),
`reduction_tax` INT(1),
`reduction_currency_discount_product` INT(11),
`reduction_tax_discount_product` INT(1),
`reduction_currency_discount_all_quantities` INT(11),
`reduction_tax_discount_all_quantities` INT(1),
`reduction_currency_discount_on_shipping_cost` INT(11),
`reduction_tax_discount_on_shipping_cost` INT(1),
`reduction_currency_discount_on_new_product` INT(11),
`reduction_tax_discount_on_new_product` INT(1),
`reduction_currency_discount_on_more_product_quantity` INT(11),
`reduction_tax_discount_on_more_product_quantity` INT(1),
`reduction_currency_discount_on_more_product_amount` INT(11),
`reduction_tax_discount_on_more_product_amount` INT(1),
`reduction_currency_discount_on_next_same_product` INT(11),
`applicable_categories` text,
`code` VARCHAR(222) ,
`highlight` INT(1),
`apply_discount_code` VARCHAR(10),
INDEX(id_ets_pr_rule), PRIMARY KEY (`id_ets_pr_action_rule`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
$res &= Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_promote_rule` (
`id_ets_pr_promote_rule` INT(11) NOT NULL AUTO_INCREMENT ,
`id_ets_pr_rule` INT(11) NOT NULL ,
`way_to_promote` VARCHAR(55),
`position_to_display` VARCHAR(1000),
`text_color` VARCHAR(55),
`background_color` VARCHAR(55),
`button_close_color` VARCHAR(55),
`title_popup_color` VARCHAR(55),
`background_title_popup_color` VARCHAR(55),
`background_content_popup_color` VARCHAR(55),
`border_radius` VARCHAR(55),
`close_button_popup_color` VARCHAR(55),
`applicable_product_categories` VARCHAR(500),
`applicable_categories` VARCHAR(500),
`include_sub_categories` VARCHAR(500),
`include_specific_products` VARCHAR(500),
`exclude_products` VARCHAR(500),
`delay_popup` INT(11),
`notification_text_color` VARCHAR(55),
`notification_background_color` VARCHAR(55),
`notification_border_color` VARCHAR(55),
INDEX(id_ets_pr_rule), PRIMARY KEY (`id_ets_pr_promote_rule`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
$res &= Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_promote_rule_lang` (
`id_ets_pr_promote_rule` INT(11) NOT NULL,
`id_lang` INT(11) NOT NULL ,
`notification` text,
`banner` VARCHAR(200),
`banner_link` VARCHAR(300),
`content_bar` VARCHAR(500),
`title_popup` VARCHAR(500),
`content_popup` VARCHAR(500),
PRIMARY KEY (`id_ets_pr_promote_rule`,`id_lang`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
$res &= Db::getInstance()->execute('CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'ets_pr_cart_rule` (
`id_ets_pr_rule` INT(11) NOT NULL,
`id_cart` INT(11) NOT NULL,
`date_add` datetime,
PRIMARY KEY (`id_ets_pr_rule`,`id_cart`)) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci');
if(!$this->checkCreatedColumn('order_cart_rule','id_ets_pr_rule'))
$res &= Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'order_cart_rule` ADD `id_ets_pr_rule` INT(11)');
self::alterDb();
return $res;
}
public static function alterDb()
{
$sqls = array();
$sqls[] = 'ALTER TABLE `'._DB_PREFIX_.'ets_pr_condition_rule` CHANGE `amount_of_money_spent` `amount_of_money_spent` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `cart_amount` `cart_amount` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `apply_for_product_price` `apply_for_product_price` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `delivery_total_cart_weight` `delivery_total_cart_weight` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `delivery_speed_grade` `delivery_speed_grade` DECIMAL(20,6) NULL DEFAULT NULL';
$sqls[] = 'ALTER TABLE `'._DB_PREFIX_.'ets_pr_condition_rule` CHANGE `include_specific_products` `include_specific_products` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `exclude_products` `exclude_products` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_attributes` `select_attributes` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_features` `select_features` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_suppliers` `select_suppliers` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_manufacturers` `select_manufacturers` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `delivery_apply_to_carriers` `delivery_apply_to_carriers` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL';
$sqls[] = 'ALTER TABLE `'._DB_PREFIX_.'ets_pr_action_rule` CHANGE `amount_discount_on_shipping_cost` `amount_discount_on_shipping_cost` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_discount_on_shipping_cost` `percent_discount_on_shipping_cost` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_on_shipping_cost` `maximum_discount_on_shipping_cost` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_total_cart` `percent_total_cart` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_total_cart` `amount_total_cart` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_value` `maximum_discount_value` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_discount_product` `amount_discount_product` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_discount_proudct` `percent_discount_proudct` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_product` `maximum_discount_product` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `apply_for_product_price` `apply_for_product_price` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_discount_on_all_quantities` `percent_discount_on_all_quantities` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_discount_on_all_quantities` `amount_discount_on_all_quantities` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_on_all_quantities` `maximum_discount_on_all_quantities` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_new_product_with_discount_price` `percent_new_product_with_discount_price` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_new_product_with_discount_price` `amount_new_product_with_discount_price` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_new_product_with_discount_price` `maximum_new_product_with_discount_price` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_discount_purchase_more_product_quantity` `percent_discount_purchase_more_product_quantity` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_discount_purchase_more_product_quantity` `amount_discount_purchase_more_product_quantity` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_purchase_more_product_quantity` `maximum_discount_purchase_more_product_quantity` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `purchase_more_product_amount` `purchase_more_product_amount` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_discount_purchase_more_product_amount` `percent_discount_purchase_more_product_amount` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_discount_purchase_more_product_amount` `amount_discount_purchase_more_product_amount` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_purchase_more_product_amount` `maximum_discount_purchase_more_product_amount` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `percent_discount_on_next_same_product` `percent_discount_on_next_same_product` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `amount_discount_on_next_same_product` `amount_discount_on_next_same_product` DECIMAL(20,6) NULL DEFAULT NULL, CHANGE `maximum_discount_on_next_same_product` `maximum_discount_on_next_same_product` DECIMAL(20,6) NULL DEFAULT NULL';
$sqls[] = 'ALTER TABLE `ps_ets_pr_action_rule` CHANGE `include_specific_products` `include_specific_products` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `exclude_products` `exclude_products` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_attributes` `select_attributes` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_features` `select_features` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_suppliers` `select_suppliers` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `select_manufacturers` `select_manufacturers` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, CHANGE `gift_product` `gift_product` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL';
foreach($sqls as $sql)
Db::getInstance()->execute($sql);
return true;
}
public function checkCreatedColumn($table, $column)
{
$fieldsCustomers = Db::getInstance()->ExecuteS('DESCRIBE ' . _DB_PREFIX_ . pSQL($table));
$check_add = false;
foreach ($fieldsCustomers as $field) {
if ($field['Field'] == $column) {
$check_add = true;
break;
}
}
return $check_add;
}
public function unInstallDb()
{
$tables = array(
'ets_pr_rule',
'ets_pr_rule_lang',
'ets_pr_condition_rule',
'ets_pr_action_rule',
'ets_pr_promote_rule',
'ets_pr_promote_rule_lang',
'ets_pr_cart_rule'
);
if($tables)
{
foreach($tables as $table)
Db::getInstance()->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . pSQL($table).'`');
}
if($this->checkCreatedColumn('order_cart_rule','id_ets_pr_rule'))
Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'order_cart_rule` DROP `id_ets_pr_rule`');
return true;
}
public function searchProduct()
{
if (($query = Tools::getValue('q', false)) && Validate::isCleanHtml($query))
{
$imageType = Ets_pr_defines::getFormattedName('cart');
if ($pos = strpos($query, ' (ref:')) {
$query = Tools::substr($query, 0, $pos);
}
$excludeIds = Tools::getValue('excludeIds', false);
$excludedProductIds = array();
if ($excludeIds && $excludeIds != 'NaN' && Validate::isCleanHtml($excludeIds)) {
$excludeIds = implode(',', array_map('intval', explode(',', $excludeIds)));
if($excludeIds && ($ids = explode(',',$excludeIds)) ) {
foreach($ids as $id) {
if($id)
{
$id = explode('-',$id);
if(isset($id[0]) && isset($id[1]) && !$id[1]) {
$excludedProductIds[] = (int)$id[0];
}
}
}
}
} else {
$excludeIds = false;
}
$excludeVirtuals = (bool)Tools::getValue('excludeVirtuals', false);
$exclude_packs = (bool)Tools::getValue('exclude_packs', false);
if (version_compare(_PS_VERSION_, '1.6.1.0', '<'))
{
$imgLeftJoin = ' LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product`) '.Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover = 1');
}
else
{
$imgLeftJoin = ' LEFT JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (image_shop.`id_product` = p.`id_product` AND image_shop.id_shop=' . (int)$this->context->shop->id . ' AND image_shop.cover = 1) ';
}
$sql = 'SELECT p.`id_product`, pl.`link_rewrite`, p.`reference`, pl.`name`, image_shop.`id_image` id_image, il.`legend`, p.`cache_default_attribute`
FROM `' . _DB_PREFIX_ . 'product` p
' . Shop::addSqlAssociation('product', 'p') . '
LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (pl.id_product = p.id_product AND pl.id_lang = ' . (int)$this->context->language->id . Shop::addSqlRestrictionOnLang('pl') . ')
'. pSQL($imgLeftJoin) .'
LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int)$this->context->language->id . ')
LEFT JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.`id_product` = ps.`id_product`)
WHERE '.($excludedProductIds ? 'p.`id_product` NOT IN('.implode(',',array_map('intval',$excludedProductIds)).') AND ' : '').' (pl.name LIKE \'%' . pSQL($query) . '%\' OR p.reference LIKE \'%' . pSQL($query) . '%\' OR p.id_product = '.(int)$query.') AND ps.`active` = 1 AND ps.`id_shop` = '.(int)$this->context->shop->id .
($excludeVirtuals ? ' AND NOT EXISTS (SELECT 1 FROM `' . _DB_PREFIX_ . 'product_download` pd WHERE (pd.id_product = p.id_product))' : '') .
($exclude_packs ? ' AND (p.cache_is_pack IS NULL OR p.cache_is_pack = 0)' : '') .
' GROUP BY p.id_product';
if (($items = Db::getInstance()->executeS($sql)))
{
$results = array();
foreach ($items as $item)
{
if (Combination::isFeatureActive() && (int)$item['cache_default_attribute'])
{
$sql = 'SELECT pa.`id_product_attribute`, pa.`reference`, ag.`id_attribute_group`, pai.`id_image`, agl.`name` AS group_name, al.`name` AS attribute_name, NULL as `attribute`, a.`id_attribute`
FROM `' . _DB_PREFIX_ . 'product_attribute` pa
' . Shop::addSqlAssociation('product_attribute', 'pa') . '
LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute`
LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute`
LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group`
LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = ' . (int)$this->context->language->id . ')
LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = ' . (int)$this->context->language->id . ')
LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_image` pai ON pai.`id_product_attribute` = pa.`id_product_attribute`
WHERE pa.`id_product` = ' . (int)$item['id_product'] . ($excludeIds ? ' AND NOT FIND_IN_SET(CONCAT(pa.`id_product`,"-", IF(pa.`id_product_attribute` IS NULL,0,pa.`id_product_attribute`)), "' . pSQL($excludeIds) . '")' : '') . '
GROUP BY pa.`id_product_attribute`, ag.`id_attribute_group`
ORDER BY pa.`id_product_attribute`';
if (($combinations = Db::getInstance()->executeS($sql)))
{
foreach ($combinations as $combination) {
$results[$combination['id_product_attribute']]['id_product'] = $item['id_product'];
$results[$combination['id_product_attribute']]['id_product_attribute'] = $combination['id_product_attribute'];
$results[$combination['id_product_attribute']]['name'] = $item['name'];
// get name attribute with combination
!empty($results[$combination['id_product_attribute']]['attribute']) ? $results[$combination['id_product_attribute']]['attribute'] .= ' ' . $combination['group_name'] . '-' . $combination['attribute_name']
: $results[$combination['id_product_attribute']]['attribute'] = $item['attribute'] . ' ' . $combination['group_name'] . '-' . $combination['attribute_name'];
// get reference combination
if (!empty($combination['reference'])) {
$results[$combination['id_product_attribute']]['ref'] = $combination['reference'];
} else {
$results[$combination['id_product_attribute']]['ref'] = !empty($item['reference']) ? $item['reference'] : '';
}
// get image combination
if (empty($results[$combination['id_product_attribute']]['image']))
{
$results[$combination['id_product_attribute']]['image'] = str_replace('http://', Tools::getShopProtocol(), $this->context->link->getImageLink($item['link_rewrite'], (!empty($combination['id_image'])? (int)$combination['id_image'] : (int)$item['id_image']),$imageType));
}
}
}
}
else
{
if(!$item['id_image'])
{
$image = Product::getCover($item['id_product']);
if($image)
$item['id_image'] = $image['id_image'];
}
$results[] = array(
'id_product' => (int)($item['id_product']),
'id_product_attribute' => 0,
'name' => $item['name'],
'attribute' => '',
'ref' => (!empty($item['reference']) ? $item['reference'] : ''),
'image' =>$item['id_image'] ? str_replace('http://', Tools::getShopProtocol(), $this->context->link->getImageLink($item['link_rewrite'], $item['id_image'], $imageType)):str_replace('http://', Tools::getShopProtocol(), $this->context->link->getImageLink($item['link_rewrite'], $this->context->language->iso_code.'-default', $imageType)),
);
}
}
if ($results)
{
foreach ($results as &$item)
echo trim($item['id_product'] . '|' . (int)($item['id_product_attribute']) . '|' . Tools::ucfirst($item['name']). '|' . $item['attribute'] . '|' . $item['ref'] . '|' . $item['image']).'|'.Context::getContext()->link->getProductLink($item['id_product'],null,null,null,null,null,$item['id_product_attribute']). "\n";
}
}
die;
}
die;
}
public function searchCustomer()
{
if (($query = Tools::getValue('q', false)) && Validate::isCleanHtml($query))
{
$excludeIds = Tools::getValue('excludeIds', false);
$excludedCustomerds = array();
if ($excludeIds && $excludeIds != 'NaN' && Validate::isCleanHtml($excludeIds)) {
$excludeIds = implode(',', array_map('intval', explode(',', $excludeIds)));
if($excludeIds && ($ids = explode(',',$excludeIds)) ) {
foreach($ids as $id) {
$excludedCustomerds[] = $id;
}
}
} else {
$excludeIds = false;
}
$sql = 'SELECT * FROM `'._DB_PREFIX_.'customer` WHERE id_shop="'.(int)Context::getContext()->shop->id.'" AND (CONCAT(firstname," ",lastname) LIKE "%'.pSQL($query).'%" OR email like "%'.pSQL($query).'%")'.($excludedCustomerds ? ' AND id_customer NOT IN ('.implode(',',array_map('intval',$excludedCustomerds)).')':'');
$customers = Db::getInstance()->executeS($sql);
if ($customers)
{
foreach ($customers as &$item)
echo $item['id_customer'] . '|' . $item['firstname'].' '.$item['lastname'] . '|' . $item['email']. "\n";
}
}
die;
}
public static function getFormattedName($name)
{
$themeName = Context::getContext()->shop->theme_name;
$nameWithoutThemeName = str_replace(['_' . $themeName, $themeName . '_'], '', $name);
//check if the theme name is already in $name if yes only return $name
if ($themeName !== null && strstr($name, $themeName) && ImageType::getByNameNType($name)) {
return $name;
}
if (ImageType::getByNameNType($nameWithoutThemeName . '_' . $themeName)) {
return $nameWithoutThemeName . '_' . $themeName;
}
if (ImageType::getByNameNType($themeName . '_' . $nameWithoutThemeName)) {
return $themeName . '_' . $nameWithoutThemeName;
}
return $nameWithoutThemeName . '_default';
}
public static function getProductsByIds($products)
{
if (!$products)
return false;
if (!is_array($products))
{
$IDs = explode(',', $products);
$products = array();
foreach ($IDs as $ID) {
if ($ID &&($tmpIDs = explode('-', $ID)) && $tmpIDs[0] ) {
$products[] = array(
'id_product' => $tmpIDs[0],
'id_product_attribute' => isset($tmpIDs[1])? $tmpIDs[1] : 0,
);
}
}
}
if($products)
{
$context = Context::getContext();
$id_group = isset($context->customer->id) && $context->customer->id? Customer::getDefaultGroupId((int)$context->customer->id) : (int)Group::getCurrent()->id;
$group = new Group($id_group);
$useTax = $group->price_display_method? false : true;
$imageType = self::getFormattedName('cart');
foreach($products as &$product)
{
$p = new Product($product['id_product'], true, $context->language->id, $context->shop->id);
$product['link_rewrite'] = $p->link_rewrite;
$product['price_float'] = $p->getPrice($useTax,$product['id_product_attribute'] ? $product['id_product_attribute'] : null);
$product['price'] = Tools::displayPrice($product['price_float']);
$product['name'] = $p->name;
$product['description_short'] = $p->description_short;
$image = ($product['id_product_attribute'] && ($image = self::getCombinationImageById($product['id_product_attribute'],$context->language->id))) ? $image : Product::getCover($product['id_product']);
$product['link'] = $context->link->getProductLink($product,null,null,null,null,null,$product['id_product_attribute'] ? $product['id_product_attribute'] : 0);
$product['id_image'] = isset($image['id_image']) && $image['id_image'] ? $image['id_image'] : $context->language->iso_code.'-default';
$product['image'] = $context->link->getImageLink($p->link_rewrite, isset($image['id_image']) ? $image['id_image'] : $context->language->iso_code.'-default', $imageType);
if($product['id_product_attribute'])
{
$attributes = $p->getAttributeCombinationsById((int)$product['id_product_attribute'],$context->language->id);
if($attributes)
{
$product['attributes']='';
foreach($attributes as $attribute)
{
$product['attributes'] .= $attribute['group_name'].': '.$attribute['attribute_name'].', ';
}
$product['attributes'] = trim($product['attributes'],', ');
}
}
}
unset($context);
}
return $products;
}
public static function getCombinationImageById($id_product_attribute, $id_lang)
{
if(version_compare(_PS_VERSION_,'1.6.1.0', '>=')) {
return Product::getCombinationImageById($id_product_attribute, $id_lang);
}
else
{
if (!Combination::isFeatureActive() || !$id_product_attribute) {
return false;
}
$result = Db::getInstance()->executeS('
SELECT pai.`id_image`, pai.`id_product_attribute`, il.`legend`
FROM `'._DB_PREFIX_.'product_attribute_image` pai
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (il.`id_image` = pai.`id_image`)
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_image` = pai.`id_image`)
WHERE pai.`id_product_attribute` = '.(int)$id_product_attribute.' AND il.`id_lang` = '.(int)$id_lang.' ORDER by i.`position` LIMIT 1'
);
if (!$result) {
return false;
}
return $result[0];
}
}
public function getConfigInputs()
{
return array(
array(
'type' => 'text',
'label' => $this->l('Title of product gift'),
'lang' => true,
'name' => 'ETS_PR_TITLE_OF_PRODUCT_GIFT',
'default' => $this->l('Please choose product gift'),
'default_lang' => 'Please choose product gift',
'validate' => 'isCleanHtml',
'tab' => 'general',
),
array(
'name' => 'ETS_PR_STATUS_ORDER_VALIDATED',
'label' => $this->l('Total order amount calculated if order status is'),
'type'=> 'checkbox',
'values' => array(
'query' => OrderState::getOrderStates($this->context->language->id),
'id' => 'id_order_state',
'name' => 'name',
),
'default' => $this->getOrderStateDefault('approved'),
'tab' => 'general',
),
array(
'type'=> 'switch',
'label' => $this->l('Auto clear discount codes if expired'),
'name' => 'ETS_PR_AUTO_CLEAR_RULE_EXPIRED',
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'default' => 0,
'validate' => 'isUnsignedInt',
'tab' => 'general',
'desc' => $this->l('Make sure cronjob is already configured on the server to clear expired discount codes automatically. [highlighta]Configure Cronjob.[end_highlighta]')
),
array(
'type'=> 'switch',
'label' => $this->l('Auto clear discount codes if used'),
'name' => 'ETS_PR_AUTO_CLEAR_DISCOUNT_USED',
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'default' => 0,
'validate' => 'isUnsignedInt',
'tab' => 'general',
'desc' => $this->l('Make sure cronjob is already configured on the server to clear expired discount codes automatically. [highlighta]Configure Cronjob.[end_highlighta]')
),
array(
'type' => 'html',
'html_content' => $this->renderFromCronJob(),
'tab' => 'cronjob',
'name'=>'',
),
);
}
public function renderFromCronJob()
{
$context = Context::getContext();
if(!Configuration::getGlobalValue('ETS_PR_CRONJOB_TOKEN'))
Configuration::updateGlobalValue('ETS_PR_CRONJOB_TOKEN',Tools::passwdGen(12));
$cronjob_last= '';
$run_cronjob = false;
if(Configuration::get('ETS_PR_AUTO_CLEAR_RULE_EXPIRED') || Configuration::get('ETS_PR_AUTO_CLEAR_DISCOUNT_USED'))
$check_run = false;
else
$check_run = true;
if($cronjob_time = Configuration::getGlobalValue('ETS_PR_TIME_LOG_CRONJOB'))
{
$last_time = strtotime($cronjob_time);
$time = strtotime(date('Y-m-d H:i:s'))-$last_time;
if($time <= 43200 && $time)
$run_cronjob = true;
else
$run_cronjob = false;
if($time > 86400)
{
$cronjob_last = Tools::displayDate($cronjob_time,null,true);
}
elseif($time)
{
$check_run = true;
if($hours =floor($time/3600))
{
$cronjob_last .= $hours.' '.$this->l('hours').' ';
$time = $time%3600;
}
if($minutes = floor($time/60))
{
$cronjob_last .= $minutes.' '.$this->l('minutes').' ';
$time = $time%60;
}
if($time)
$cronjob_last .= $time.' '.$this->l('seconds').' ';
$cronjob_last .= $this->l('ago');
}
}
$ETS_PR_CRONJOB_TOKEN = Tools::getValue('ETS_PR_CRONJOB_TOKEN',Configuration::getGlobalValue('ETS_PR_CRONJOB_TOKEN'));
$this->context->smarty->assign(
array(
'dir_cronjob' => _PS_MODULE_DIR_.'ets_promotion/cronjob.php',
'php_path' => (defined('PHP_BINDIR') && PHP_BINDIR && is_string(PHP_BINDIR) ? PHP_BINDIR.'/' : '').'php ',
'link_conjob' => '',
'ETS_PR_CRONJOB_TOKEN' => $ETS_PR_CRONJOB_TOKEN,
'cronjob_log' => file_exists(_PS_ETS_PROMOTION_LOG_DIR_.'ets_promotion.log') ? Tools::file_get_contents(_PS_ETS_PROMOTION_LOG_DIR_.'ets_promotion.log'):'',
'ETS_PR_SAVE_CRONJOB_LOG' => Configuration::getGlobalValue('ETS_PR_SAVE_CRONJOB_LOG'),
'run_cronjob' => $run_cronjob,
'cronjob_last' => $cronjob_last,
'check_run' => $check_run,
)
);
return $context->smarty->fetch(_PS_MODULE_DIR_.'ets_promotion/views/templates/hook/cron.tpl');
}
public function getOrderStateDefault($type='pending')
{
$orderStates = OrderState::getOrderStates($this->context->language->id);
$defaults= array();
if($type=='pending')
$templates = array('cheque','bankwire','cashondelivery','outofstock','preparation');
elseif($type=='approved')
$templates = array('payment','payment','');
elseif($type=='cancel')
$templates = array('order_canceled','refund','payment_error');
if($orderStates)
{
foreach($orderStates as $orderState)
{
if(in_array($orderState['template'],$templates))
$defaults[] = $orderState['id_order_state'];
}
}
if($defaults)
return implode(',',$defaults);
else
return '';
}
public static function getCategoriesById($id_categories)
{
if($id_categories)
{
$ids = explode(',',$id_categories);
$sql = 'SELECT * FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl on (c.id_category = cl.id_category AND cl.id_lang="'.(int)Context::getContext()->language->id.'")
WHERE c.id_category IN ('.implode(',',array_map('intval',$ids)).')';
return Db::getInstance()->executeS($sql);
}
}
public static function displayText($content=null,$tag=null,$class=null,$id=null,$href=null,$blank=false,$src = null,$alt = null,$name = null,$value = null,$type = null,$data_id_product = null,$rel = null,$attr_datas=null, $title = null) {
$text ='';
if($tag)
{
$text .= '<'.$tag.($class ? ' class="'.$class.'"':'').($id ? ' id="'.$id.'"':'');
if($href)
$text .=' href="'.$href.'"';
if($blank && $tag ='a')
$text .=' target="_blank"';
if($src)
$text .=' src ="'.$src.'"';
if($name)
$text .=' name="'.$name.'"';
if($value)
$text .=' value ="'.$value.'"';
if($type)
$text .= ' type="'.$type.'"';
if($data_id_product)
$text .=' data-id_product="'.(int)$data_id_product.'"';
if($rel) {
$text .=' rel="'.$rel.'"';
}
if($alt)
$text .=' alt="'.$alt.'"';
if($title)
$text .=' title="'.$title.'"';
if($attr_datas)
{
foreach($attr_datas as $data)
{
$text .=' '.$data['name'].'='.'"'.$data['value'].'"';
}
}
if($tag=='img' || $tag=='br' || $tag=='input')
$text .='/>';
else
$text .='>';
if ($tag && $tag != 'img' && $tag != 'input' && $tag != 'br' && !is_null($content))
$text .= $content;
if ($tag && $tag != 'img' && $tag != 'path' && $tag != 'input' && $tag != 'br')
$text .= '<'.'/' . $tag . '>';
}
else if ($content)
{
$text = $content;
}
return $text;
}
public static function checkEnableOtherShop($id_module)
{
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'module_shop` WHERE `id_module` = ' . (int) $id_module . ' AND `id_shop` NOT IN(' . implode(', ', Shop::getContextListShopID()) . ')';
return Db::getInstance()->executeS($sql);
}
public static function activeTab($module_name)
{
return Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'tab` SET enabled=1 where module ="'.pSQL($module_name).'"');
}
}

View File

@@ -0,0 +1,146 @@
<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
if (!defined('_PS_VERSION_'))
exit;
class Ets_pr_paggination_class {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 10;
public $url = '';
public $text = 'Showing {start} to {end} of {total} ({pages} Pages)';
public $text_first = '';
public $text_last = '';
public $text_next = '';
public $text_prev = '';
public $style_links = 'links';
public $style_results = 'results';
public $alias;
public $friendly;
public $name;
public function __construct()
{
$this->alias = false;
$this->friendly = false;
$this->text_first = Module::getInstanceByName('ets_promotion')->displayText('|&lt;','span','');
$this->text_last = Module::getInstanceByName('ets_promotion')->displayText('&gt;|','span','');
$this->text_next = Module::getInstanceByName('ets_promotion')->displayText('&gt;','span','');
$this->text_prev = Module::getInstanceByName('ets_promotion')->displayText('&lt;','span','');
}
public function render() {
$total = $this->total;
if($total<=1)
return false;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$output = '';
if ($page > 1) {
$output .= Module::getInstanceByName('ets_promotion')->displayText($this->text_first,'a','frist','',$this->replacePage(1)).Module::getInstanceByName('ets_promotion')->displayText($this->text_prev,'a','prev','',$this->replacePage($page-1));
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
if ($start > 1) {
$output .= Module::getInstanceByName('ets_promotion')->displayText(' .... ','p','paginration_vv');
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= Module::getInstanceByName('ets_promotion')->displayText($i,'b','');
} else {
$output .= Module::getInstanceByName('ets_promotion')->displayText($i,'a','','',$this->replacePage($i));
}
}
if ($end < $num_pages) {
$output .= Module::getInstanceByName('ets_promotion')->displayText(' .... ','p','paginration_vv');
}
}
if ($page < $num_pages) {
$output .= Module::getInstanceByName('ets_promotion')->displayText($this->text_next,'a','next','',$this->replacePage($page+1)).Module::getInstanceByName('ets_promotion')->displayText($this->text_last,'a','last','', $this->replacePage($num_pages));
}
$find = array(
'{start}',
'{end}',
'{total}',
'{pages}'
);
$replace = array(
($total) ? (($page - 1) * $limit) + 1 : 0,
((($page - 1) * $limit) > ($total - $limit)) ? $total : ((($page - 1) * $limit) + $limit),
$total,
$num_pages
);
return Module::getInstanceByName('ets_promotion')->displayText(str_replace($find, $replace, $this->text),'div',$this->style_results).Module::getInstanceByName('ets_promotion')->displayPaggination($limit,$this->name).($output ? Module::getInstanceByName('ets_promotion')->displayText($output,'div','links') : '');
}
public function replacePage($page)
{
$controller = Tools::getValue('controller');
if(!Validate::isControllerName($controller))
$controller='';
if($limt = (int)Tools::getValue('paginator_'.$this->name.'_select_limit'))
$extra ='&paginator_'.$this->name.'_select_limit='.$limt;
else
$extra ='';
if($page > 1)
return str_replace('_page_', $page, $this->url.$extra);
elseif($this->friendly && $this->alias && $controller != 'AdminModules')
return str_replace('/_page_', '', $this->url).$extra;
else
return str_replace('_page_', $page, $this->url).$extra;
}
}
?>

View File

@@ -0,0 +1,698 @@
<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
if (!defined('_PS_VERSION_'))
exit;
class Ets_pr_promote_rule extends Ets_pr_obj
{
public static $instance;
public $id_ets_pr_rule;
public $way_to_promote;
public $position_to_display;
public $notification;
public $banner;
public $banner_link;
public $content_bar;
public $text_color;
public $background_color;
public $button_close_color;
public $title_popup;
public $content_popup;
public $title_popup_color;
public $background_title_popup_color;
public $background_content_popup_color;
public $border_radius;
public $close_button_popup_color;
public $applicable_product_categories;
public $applicable_categories;
public $include_sub_categories;
public $include_specific_products;
public $exclude_products;
public $delay_popup;
public $notification_text_color;
public $notification_background_color;
public $notification_border_color;
public static $definition = array(
'table' => 'ets_pr_promote_rule',
'primary' => 'id_ets_pr_promote_rule',
'multilang' => true,
'fields' => array(
'id_ets_pr_rule' => array('type' => self::TYPE_INT),
'way_to_promote' => array('type' => self::TYPE_STRING),
'position_to_display' => array('type' => self::TYPE_STRING),
'text_color' => array('type' => self::TYPE_STRING),
'background_color' => array('type' => self::TYPE_STRING),
'button_close_color' => array('type' => self::TYPE_STRING),
'title_popup_color' => array('type' => self::TYPE_STRING),
'background_title_popup_color' => array('type' => self::TYPE_STRING),
'background_content_popup_color' => array('type' => self::TYPE_STRING),
'border_radius' => array('type' => self::TYPE_STRING),
'close_button_popup_color' => array('type' => self::TYPE_STRING),
'applicable_product_categories' => array('type' => self::TYPE_STRING),
'applicable_categories' => array('type' => self::TYPE_STRING),
'include_sub_categories' => array('type' => self::TYPE_STRING),
'include_specific_products' => array('type' => self::TYPE_STRING),
'exclude_products' => array('type' => self::TYPE_STRING),
'delay_popup' => array('type'=> self::TYPE_INT),
'notification_text_color' => array('type' => self::TYPE_STRING),
'notification_background_color' => array('type' => self::TYPE_STRING),
'notification_border_color' => array('type' => self::TYPE_STRING),
'notification' => array('type' => self::TYPE_STRING,'lang'=>true),
'banner' => array('type' => self::TYPE_STRING,'lang'=>true),
'banner_link' => array('type' => self::TYPE_STRING,'lang'=>true),
'content_bar' => array('type' => self::TYPE_STRING,'lang'=>true),
'title_popup' => array('type' => self::TYPE_STRING,'lang'=>true),
'content_popup' => array('type' => self::TYPE_HTML,'lang'=>true),
),
);
public function __construct($id_item = null, $id_lang = null, $id_shop = null)
{
parent::__construct($id_item, $id_lang, $id_shop);
}
public static function getInstance()
{
if (!(isset(self::$instance)) || !self::$instance) {
self::$instance = new Ets_pr_promote_rule();
}
return self::$instance;
}
public function l($string,$file_name='')
{
return Translate::getModuleTranslation('ets_promotion', $string, $file_name ? : pathinfo(__FILE__, PATHINFO_FILENAME));
}
public function getListFields()
{
$configs = array(
'id_ets_pr_rule' => array(
'type' => 'hidden',
'label' => '',
'default' => $this->id_ets_pr_rule,
'validate'=>'isUnsignedId',
),
'way_to_promote' =>array(
'type' => 'select',
'label' => $this->l('How to promote discount:'),
'options' => array(
'query' => array(
array(
'id' => 'display_notification',
'name' => $this->l('Display notification message'),
),
array(
'id' => 'display_banner',
'name' => $this->l('Display discount banner'),
),
array(
'id' => 'display_popup',
'name' => $this->l('Display discount popup'),
),
array(
'id' => 'display_highlight_bar',
'name' => $this->l('Display highlight bar notification'),
)
),
'id' => 'id',
'name' => 'name'
),
'validate'=>'isCleanHtml',
),
'notification' => array(
'type' => 'textarea',
'lang'=> true,
'label' => $this->l('Notification message'),
'form_group_class' => 'way_to_promote display_notification',
'desc' => sprintf($this->l('Countdown will be displayed in the center of the notification %s Available tags: [highlight][rule_name][end_highlight] [highlight][discount_code][end_highlight] [highlight][from_date][end_highlight] [highlight][to_date][end_highlight] [highlight][from_datetime][end_highlight] [highlight][to_datetime][end_highlight] [highlight][value][end_highlight] [highlight][countdown][end_highlight]'),'<br/>'),
'validate'=>'isCleanHtml',
'showRequired' => true,
),
'banner' => array(
'type' => 'file_lang',
'label' => $this->l('Banner'),
'form_group_class' => 'way_to_promote display_banner',
'desc' => sprintf($this->l('Available image type: jpg, png, gif, jpeg. Limit %sMb'),Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE')),
'showRequired' => true,
),
'banner_link' => array(
'type' => 'text',
'label' => $this->l('Banner link'),
'form_group_class' => 'way_to_promote display_banner',
'lang' => true,
'validate'=>'isLink',
),
'content_bar' => array(
'type' => 'text',
'label' => $this->l('Content'),
'lang' => true,
'form_group_class' => 'way_to_promote display_highlight_bar',
'validate'=>'isCleanHtml',
'desc' => sprintf($this->l('Countdown will be displayed in the right of the highlight bar %s Available tags: [highlight][rule_name][end_highlight] [highlight][discount_code][end_highlight] [highlight][from_date][end_highlight] [highlight][to_date][end_highlight] [highlight][from_datetime][end_highlight] [highlight][to_datetime][end_highlight] [highlight][value][end_highlight] [highlight][countdown][end_highlight]'),'<br/>'),
'showRequired' => true,
),
'text_color' => array(
'type' => 'color',
'label' => $this->l('Text color'),
'form_group_class' => 'way_to_promote display_highlight_bar',
'validate' => 'isColor',
'class' => 'color',
'default' => '#31708f',
),
'background_color' => array(
'type' => 'color',
'label' => $this->l('Background color'),
'form_group_class' => 'way_to_promote display_highlight_bar',
'validate' => 'isColor',
'class' => 'color',
'default' => '#d9edf7',
),
'button_close_color' => array(
'type' => 'color',
'label' => $this->l('Close button color'),
'form_group_class' => 'way_to_promote display_highlight_bar',
'validate' => 'isColor',
'class' => 'color',
'default' => '#31708f',
),
'title_popup' => array(
'type' => 'text',
'lang' => true,
'label' => $this->l('Title'),
'form_group_class' => 'way_to_promote display_popup',
'validate'=>'isCleanHtml',
),
'content_popup' => array(
'type' => 'textarea',
'lang' => true,
'label' => $this->l('Content'),
'autoload_rte' => true,
'form_group_class' => 'way_to_promote display_popup',
'validate'=>'isCleanHtml',
'showRequired' => true,
'desc' =>$this->l('Available tags: [highlight][rule_name][end_highlight] [highlight][discount_code][end_highlight] [highlight][from_date][end_highlight] [highlight][to_date][end_highlight] [highlight][from_datetime][end_highlight] [highlight][to_datetime][end_highlight] [highlight][value][end_highlight] [highlight][countdown][end_highlight]'),
),
'title_popup_color' => array(
'type' => 'color',
'label' => $this->l('Title text color'),
'form_group_class' => 'way_to_promote display_popup',
'validate' => 'isColor',
'class' => 'color',
'default' => '#232323',
),
'background_title_popup_color' => array(
'type' => 'color',
'label' => $this->l('Title background color'),
'form_group_class' => 'way_to_promote display_popup',
'validate' => 'isColor',
'class' => 'color',
'default' => '#ffffff',
),
'background_content_popup_color' => array(
'type' => 'color',
'label' => $this->l('Content background color'),
'form_group_class' => 'way_to_promote display_popup',
'validate' => 'isColor',
'class' => 'color',
'default' => '#ffffff',
),
'close_button_popup_color' => array(
'type' => 'color',
'label' => $this->l('Close button color'),
'form_group_class' => 'way_to_promote display_popup',
'validate' => 'isColor',
'class' => 'color',
'default' => '#232323',
),
'border_radius' => array(
'label' => $this->l('Border radius'),
'type' => 'range',
'data_suffix' => 'px',
'data_suffixs' => 'px',
'min' =>0,
'max' => 20,
'form_group_class' => 'way_to_promote display_popup',
'validate' => 'isUnsignedInt',
'default' => 5,
),
'delay_popup' => array(
'label' => $this->l('Delay to display since customer accessed website'),
'type' => 'text',
'suffix' => $this->l('Seconds'),
'default' => 5,
'validate' => 'isUnsignedInt',
'form_group_class' => 'way_to_promote display_popup',
'col'=>3,
),
'position_to_display' => array(
'type' => 'checkbox',
'label' => $this->l('Display position'),
'values' => array(
'query' => $this->getPositions(),
'id' => 'id_option',
'name' => 'name'
),
'form_group_class' => 'way_to_promote display_notification display_banner',
'validate'=>'isCleanHtml',
'showRequired' => true,
),
'applicable_product_categories' => array(
'type' => 'radio',
'label' => $this->l('Select product category page(s) to display'),
'desc' => $this->l('Select the category page(s) you want to display promotion notification and/or promotion banner.'),
'default' => 'all_product',
'values' => array(
array(
'id' => 'applicable_product_categories_all_product',
'value' => 'all_product',
'label' => $this->l('All product categories'),
),
array(
'id' => 'applicable_product_categories_specific_product',
'value' => 'specific_product',
'label' => $this->l('Specific product categories'),
),
),
'form_group_class' => 'display_hook',
'validate' => 'isCleanHtml',
),
'applicable_categories' => array(
'label' => $this->l('Select categories to apply condition'),
'type' => 'categories',
'tree' => array(
'id' => 'loyalty-categories-tree',
'selected_categories' => $this->applicable_categories ? explode(',',$this->applicable_categories):array(),
'disabled_categories' => null,
'use_checkbox' => true,
'root_category' => Category::getRootCategory()->id
),
'form_group_class' => 'display_hook',
),
'include_sub_categories' => array(
'type' => 'switch',
'values' => array(
array(
'label' => $this->l('Yes'),
'id' => 'include_sub_categories_on',
'value' => 1,
),
array(
'label' => $this->l('No'),
'id' => 'include_sub_categories_off',
'value' => 0,
)
),
'label' => $this->l('Include products in subcategories'),
'form_group_class' => 'display_hook',
'validate' => 'isUnsignedInt',
),
'include_specific_products' => array(
'type' => 'search_product',
'label' => $this->l('Include specific products'),
'form_group_class' => 'display_hook',
'validate' => 'isCleanHtml',
'placeholder' => $this->l('Search by product name, reference, id')
),
'exclude_products' => array(
'type' => 'search_product',
'label' => $this->l('Exclude products'),
'form_group_class' => 'display_hook',
'validate' => 'isCleanHtml',
'placeholder' => $this->l('Search by product name, reference, id')
),
'notification_text_color' => array(
'type' => 'color',
'label' => $this->l('Text color'),
'form_group_class' => 'way_to_promote display_notification',
'validate' => 'isColor',
'class' => 'color',
'default' => '#31708f',
),
'notification_background_color' => array(
'type' => 'color',
'label' => $this->l('Background color'),
'form_group_class' => 'way_to_promote display_notification',
'validate' => 'isColor',
'class' => 'color',
'default' => '#d9edf7',
),
'notification_border_color' => array(
'type' => 'color',
'label' => $this->l('Border color'),
'form_group_class' => 'way_to_promote display_notification',
'validate' => 'isColor',
'class' => 'color',
'default' => '#d9edf7',
),
);
return array(
'form' => array(
'legend' => array(
'title' => $this->id ? $this->l('Edit promotion way') : $this->l('Add promotion way') ,
),
'input' => array(),
'submit' => array(
'title' => $this->l('Save'),
),
'buttons'=> array(
array(
'title' => $this->l('Cancel'),
'type' => 'submit',
'class' => 'pull-left',
'name' => 'btncancel',
'icon' => 'process-icon-cancel',
)
),
'name' => 'promote_discount_rule',
'key' => 'id_ets_pr_promote_rule',
),
'configs' =>$configs,
);
}
public function validateCustomField(&$errors)
{
$way_to_promote = Tools::getValue('way_to_promote');
$id_lang_default = (int)Configuration::get('PS_LANG_DEFAULT');
if($way_to_promote=='display_notification')
{
$notification = Tools::getValue('notification_'.$id_lang_default);
if($notification=='')
$errors[] = $this->l('Notification is required');
elseif(!Validate::isCleanHtml($notification))
$errors[] = $this->l('Notification is not valid');
}
elseif($way_to_promote=='display_banner')
{
if(!$this->banner[$id_lang_default] && ( !isset($_FILES['banner_'.$id_lang_default]) || !isset($_FILES['banner_'.$id_lang_default]['name']) || !$_FILES['banner_'.$id_lang_default]['name'] ))
$errors[] = $this->l('Banner is required');
}
elseif($way_to_promote=='display_popup')
{
$content_popup = Tools::getValue('content_popup_'.$id_lang_default);
if($content_popup=='')
$errors[] = $this->l('Popup content is required');
elseif(!Validate::isCleanHtml($content_popup))
$errors[] = $this->l('Popup content is not valid');
}
elseif($way_to_promote=='display_highlight_bar')
{
$content_bar = Tools::getValue('content_bar_'.$id_lang_default);
if($content_bar=='')
$errors[] = $this->l('Content is required');
elseif(!Validate::isCleanHtml($content_bar))
$errors[] = $this->l('Content is not valid');
}
if($way_to_promote=='display_notification' || $way_to_promote=='display_banner')
{
$position_to_display = Tools::getValue('position_to_display');
if(!$position_to_display)
$errors[] = $this->l('Display position is required');
elseif(!Ets_promotion::validateArray($position_to_display))
$errors[] = $this->l('Display position is not valid');
}
}
public function getPositions()
{
$positions = array(
'displayHome' => array(
'id_option' => 'displayHome',
'name' => $this->l('[highlight]Home page[end_highlight]')
),
'displayLeftColumn' => array(
'id_option' => 'displayLeftColumn',
'name' => $this->l('[highlight]Left column:[end_highlight] On the bottom of the left column')
),
'displayLeftColumnBefore' => array(
'id_option' => 'displayBeforeLeftColumn',
'name' => $this->l('[highlight]Left column:[end_highlight] On the top of the left column')
),
'displayRightColumn' => array(
'id_option' => 'displayRightColumn',
'name' => $this->l('[highlight]Right column:[end_highlight] On the bottom of the right column')
),
'displayRightColumnBefore' => array(
'id_option' => 'displayBeforeRightColumn',
'name' => $this->l('[highlight]Right column:[end_highlight] On the top of the right column')
),
'displayCartGridBodyBefore2' => array(
'id_option' => 'displayCartGridBodyBefore2',
'name' => $this->l('[highlight]Checkout page:[end_highlight] On top of the checkout page')
),
'displayCartGridBodyAfter' => array(
'id_option' => 'displayCartGridBodyAfter',
'name' => $this->l('[highlight]Checkout page:[end_highlight] On the bottom of the checkout page')
),
'displayProductListHeaderBefore' => array(
'id_option' => 'displayProductListHeaderBefore',
'name'=> $this->l('[highlight]Category page:[end_highlight] On top of the header of product listing page'),
'class'=> 'display_hook',
),
'displayProductListHeaderAfter' => array(
'id_option' => 'displayProductListHeaderAfter',
'name'=> $this->l('[highlight]Category page:[end_highlight] Under the header of product listing page'),
'class'=> 'display_hook',
),
'displayFooterCategory' => array(
'id_option' => 'displayFooterCategory',
'name'=> $this->l('[highlight]Category page:[end_highlight] On the bottom of product category page'),
'class'=> 'display_hook',
),
'displayNav1' => array(
'id_option' => 'displayNav1',
'name'=> $this->l('[highlight]Header:[end_highlight] On the top navigation bar'),
),
'displayFooterBefore' => array(
'id_option' => 'displayFooterBefore',
'name' => $this->l('[highlight]Footer:[end_highlight] On top of Footer section'),
),
'displayFooterAfter' => array(
'id_option' => 'displayFooterAfter',
'name' => $this->l('[highlight]Footer:[end_highlight] On the bottom of Footer section'),
),
'displayCartGridBodyBefore1' => array(
'id_option' => 'displayCartGridBodyBefore1',
'name' => sprintf($this->l('[highlight]Cart page:[end_highlight] On the top of shopping cart detail on %sShopping cart%s page'),'"','"'),
),
'displayShoppingCartFooter' => array(
'id_option' => 'displayShoppingCartFooter',
'name' => $this->l('[highlight]Cart page:[end_highlight] On the bottom of shopping cart detail'),
),
'displayFooterProduct' => array(
'id_option' => 'displayFooterProduct',
'name' => $this->l('[highlight]Product page:[end_highlight] Under the product description section'),
'class'=> 'display_hook',
),
'displayProductVariantsBefore' => array(
'id_option' => 'displayProductVariantsBefore',
'name' => $this->l('[highlight]Product page:[end_highlight] On top of the product combination block'),
'class'=> 'display_hook',
),
'displayProductVariantsAfter' => array(
'id_option' => 'displayProductVariantsAfter',
'name' => $this->l('[highlight]Product page:[end_highlight] On the bottom of the product combination block'),
'class'=> 'display_hook',
),
'displayReassurance' => array(
'id_option' => 'displayReassurance',
'name' => sprintf($this->l('[highlight]Product page:[end_highlight] Under the %sCustomer reassurance%s block'),'"','"'),
'class'=> 'display_hook',
),
'displayAfterProductThumbs' => array(
'id_option' => 'displayAfterProductThumbs',
'name' => $this->l('[highlight]Product page:[end_highlight] Under the product thumbnail images on product detail page'),
'class'=> 'display_hook',
),
'displayProductAdditionalInfo' => array(
'id_option' => 'displayProductAdditionalInfo',
'name' => sprintf($this->l('[highlight]Product page:[end_highlight] On bottom of %sSocial sharing%s block on product detail page'),'"','"'),
'class'=> 'display_hook',
),
'displayProductCommentsListHeaderBefore' => array(
'id_option' => 'displayProductCommentsListHeaderBefore',
'name' => sprintf($this->l('[highlight]Product page:[end_highlight] On top of %sProduct Comments%s block on product detail page'),'"','"'),
'class'=> 'display_hook',
),
);
$version = (string)_PS_VERSION_;
$version = (string)Tools::substr($version, 0, 7);
$version = str_replace('.', '', $version);
$version = (int)$version;
if($version <= 0)
{
unset($positions['displayProductListHeaderBefore']);
unset($positions['displayProductListHeaderAfter']);
}
if($version<1770)
{
unset($positions['displayFooterCategory']);
}
if($version < 1700)
{
unset($positions['displayNav1']);
unset($positions['displayFooterBefore']);
unset($positions['displayFooterAfter']);
unset($positions['displayCartGridBodyBefore1']);
unset($positions['displayReassurance']);
}
if($version < 1710)
{
unset($positions['displayAfterProductThumbs']);
}
if($version < 1760)
{
unset($positions['displayProductActions']);
unset($positions['displayProductCommentsListHeaderBefore']);
}
return $positions;
}
public function getListPromoteByRule($id_rule)
{
$sql ='SELECT * FROM `'._DB_PREFIX_.'ets_pr_promote_rule` p
LEFT JOIN `'._DB_PREFIX_.'ets_pr_promote_rule_lang` pl ON (p.id_ets_pr_promote_rule = pl.id_ets_pr_promote_rule AND pl.id_lang="'.(int)Context::getContext()->language->id.'" )
WHERE id_ets_pr_rule='.(int)$id_rule;
$promotes = Db::getInstance()->executeS($sql);
if($promotes)
{
foreach($promotes as &$promote)
{
switch($promote['way_to_promote'])
{
case 'display_notification':
$promote['way_to_promote'] = $this->l('Display notification');
$promote['detail'] = $this->l('Notification: ').$promote['notification'];
$promote['position_to_display'] = self::displayPoisition($promote);
break;
case 'display_banner':
$promote['way_to_promote'] = $this->l('Display banner');
$promote['detail'] = self::displayDetailBanner($promote);
$promote['position_to_display'] = self::displayPoisition($promote);
break;
case 'display_popup':
$promote['way_to_promote'] = $this->l('Display popup');
$promote['detail'] = self::displayDetailPopup($promote);
$promote['position_to_display'] = '--';
break;
case 'display_highlight_bar':
$promote['way_to_promote'] = $this->l('Display highlight bar');
$promote['detail'] = $this->l('Content: ').$promote['content_bar'];
$promote['position_to_display'] = '--';
break;
}
}
}
return $promotes;
}
public static function displayDetailBanner($promote)
{
if(is_array($promote))
{
$banner = $promote['banner'];
$banner_link = $promote['banner_link'];
}
else
{
$id_lang = Context::getContext()->language->id;
$banner = $promote->banner[$id_lang];
$banner_link = $promote->banner_link[$id_lang];
}
if($banner)
{
Context::getContext()->smarty->assign(
array(
'banner' => $banner,
'banner_link' => $banner_link,
'link' => Context::getContext()->link,
)
);
return Context::getContext()->smarty->fetch(_PS_MODULE_DIR_.'ets_promotion/views/templates/hook/promote/detail_banner.tpl');
}
}
public static function displayPoisition($promote)
{
if(is_array($promote))
{
$position_to_display = $promote['position_to_display'];
}
else
{
$position_to_display = $promote->position_to_display;
}
if($position_to_display)
{
if($position_to_display)
{
$display_positions = Ets_pr_promote_rule::getInstance()->getPositions();
$positions = array();
foreach($display_positions as $display)
{
$positions[$display['id_option']] = $display['name'];
}
Context::getContext()->smarty->assign(
array(
'display_positions' => explode(',',$position_to_display),
'positions' => $positions,
)
);
return Context::getContext()->smarty->fetch(_PS_MODULE_DIR_.'ets_promotion/views/templates/hook/promote/position.tpl');
}
}
}
public static function displayDetailPopup($promote)
{
if(is_array($promote))
{
$title_popup = $promote['title_popup'];
$content_popup = $promote['content_popup'];
}
else
{
$id_lang = Context::getContext()->language->id;
$title_popup = $promote->title_popup[$id_lang];
$content_popup = $promote->content_popup[$id_lang];
}
if($content_popup)
{
Context::getContext()->smarty->assign(
array(
'title_popup' => $title_popup,
'content_popup' => $content_popup,
)
);
return Context::getContext()->smarty->fetch(_PS_MODULE_DIR_.'ets_promotion/views/templates/hook/promote/detail_popup.tpl');
}
}
public function delete()
{
if(parent::delete())
{
if($this->banner)
{
foreach($this->banner as $banner)
{
if($banner)
@unlink(_PS_ETS_PR_IMG_DIR_.$banner);
}
}
return true;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright ETS Software Technology Co., Ltd
*
* NOTICE OF LICENSE
*
* This file is not open source! Each license that you purchased is only available for 1 website only.
* If you want to use this file on more websites (or projects), you need to purchase additional licenses.
* You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future.
*
* @author ETS Software Technology Co., Ltd
* @copyright ETS Software Technology Co., Ltd
* @license Valid for 1 website (or project) for each purchase of license
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

File diff suppressed because it is too large Load Diff