* @copyright 2003-2015 Business Tech SARL * @version 4.4.0 * @date 21/10/2016 */ if (!defined('_CAN_LOAD_FILES_')) exit; class FBPromote extends Module { /** * @const string BT_FAQ_MAIN_URL : URL of FAQ web site */ const BT_FAQ_MAIN_URL = 'http://faq.businesstech.fr/faq.php?id='; /** * @var string $_html : store html content */ private $_html; /** * @var obj $oCookie : obj cookie itself */ public static $oCookie = array(); /** * @var array $aHooks : array of available hooks */ public static $aHooks = array(); /** * @var array $aSelectedHooks : array of selected hooks */ public static $aSelectedHooks = array(); /** * @var bool $bCompare15 : get compare version for PS 1.5 */ public static $bCompare15 = false; /** * @var bool $bCompare17 : get compare version for PS 1.7 */ public static $bCompare17 = false; /** * @var bool $bAlreadyUse : define if the code is already returned */ public static $bAlreadyUse = false; /** * Magic Method __construct assigns few information about module and instantiate parent class */ public function __construct() { require_once(dirname(__FILE__) . '/conf/admin.conf.php'); require_once('backward_compatibility/backward.php'); $this->name = 'fbpromote'; $this->tab = 'advertising_marketing'; $this->version = '4.4.3'; $this->author = 'Business Tech'; $this->module_key = '7b8c8cba07d49440bf169ee923b7e8b7'; $this->author_address = '0xa42Fc1CAc1DbF5C6FA81Cd792D25b81d40AB687f'; parent::__construct(); $this->displayName = $this->l('Facebook Fan Coupon'); $this->description = $this->l('Promote your Facebook page and store'); // compare PS version self::$bCompare15 = version_compare(_PS_VERSION_, '1.5', '>='); self::$bCompare17 = version_compare(_PS_VERSION_, '1.7', '>='); if (!empty(self::$bCompare15)) { self::$oCookie = Context::getContext()->cookie; $id_shop = Context::getContext()->shop->id; if (!empty($id_shop)) { $this->id_shop = (int)($id_shop); } } else { global $cookie; self::$oCookie = $cookie; } self::$aHooks = array( array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayTop' : 'top'), 'title' => $this->l('Top')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayLeftColumn' : 'leftColumn'), 'title' => $this->l('Left column')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayRightColumn' : 'rightColumn'), 'title' => $this->l('Right column')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayFooter' : 'footer'), 'title' => $this->l('Footer')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayLeftColumnProduct' : 'extraLeft'), 'title' => $this->l('Product left column')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayRightColumnProduct' : 'extraRight'), 'title' => $this->l('Product right column')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayProductButtons' : 'productActions'), 'title' => $this->l('Product action')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayFooterProduct' : 'productfooter'), 'title' => $this->l('Product footer')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayHome' : 'home'), 'title' => $this->l('Homepage')), array('name' => ((version_compare(_PS_VERSION_, '1.5.0', '>'))? 'displayShoppingCartFooter' : 'shoppingCart'), 'title' => $this->l('Cart page')), ); self::$aSelectedHooks = unserialize(Configuration::get('SELECTED_HOOKS')); } /** * install() method install hooks and create sql tables * * @return bool */ public function install() { if (!empty(self::$bCompare15)) { return (parent::install() && $this->registerHook('displayLeftColumn') && $this->registerHook('displayHeader') && $this->registerHook('displayShoppingCartFooter') && $this->registerHook('displayRightColumn') && $this->registerHook('displayFooter') && $this->registerHook('displayLeftColumnProduct') && $this->registerHook('displayRightColumnProduct') && $this->registerHook('displayProductButtons') && $this->registerHook('displayFooterProduct') && $this->registerHook('displayHome') && $this->registerHook('displayTop') && Db::getInstance()->Execute('CREATE TABLE '._DB_PREFIX_.'fb_promote ( id_fb_promote INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , id_guest INT( 11 ) NOT NULL , id_customer INT( 11 ) NOT NULL , id_discount INT( 11 ) NOT NULL , uid_facebook VARCHAR(255) NULL, ip_address VARCHAR(255) NOT NULL, INDEX (id_guest), INDEX (id_customer), INDEX (id_discount) ) ENGINE='._MYSQL_ENGINE_.';') && Db::getInstance()->Execute('CREATE TABLE '._DB_PREFIX_.'fb_promote_categories (id_category int(10) NOT NULL, id_shop int(10) NOT NULL default 1, KEY index_cat (id_category, id_shop)) ENGINE='._MYSQL_ENGINE_.';')); } else { return (parent::install() && $this->registerHook('leftColumn') && $this->registerHook('rightColumn') && $this->registerHook('header') && $this->registerHook('shoppingCart') && $this->registerHook('footer') && $this->registerHook('extraLeft') && $this->registerHook('extraRight') && $this->registerHook('home') && $this->registerHook('productActions') && $this->registerHook('productfooter') && $this->registerHook('top') && Db::getInstance()->Execute('CREATE TABLE '._DB_PREFIX_.'fb_promote ( id_fb_promote INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , id_guest INT( 11 ) NOT NULL , id_customer INT( 11 ) NOT NULL , id_discount INT( 11 ) NOT NULL , uid_facebook VARCHAR(255) NULL, ip_address VARCHAR(255) NOT NULL, INDEX (id_guest), INDEX (id_customer), INDEX (id_discount) ) ENGINE='._MYSQL_ENGINE_.';') && Db::getInstance()->Execute('CREATE TABLE '._DB_PREFIX_.'fb_promote_categories (id_category int(10) NOT NULL, id_shop int(10) NOT NULL default 1, KEY index_cat (id_category, id_shop)) ENGINE='._MYSQL_ENGINE_.';')); } if (!parent::install() OR !Configuration::updateValue('FBPROMOTE_FANPAGE_URL', '') OR !Configuration::updateValue('FBPROMOTE_VOUCHER_DESCRIPTION', '') OR !Configuration::updateValue('FBPROMOTE_VOUCHER_AMOUNT', '') OR !Configuration::updateValue('FBPROMOTE_VOUCHER_PERCENT', '') OR !Configuration::updateValue('FBPROMOTE_VOUCHER_HASMINAMOUNT', '') OR !Configuration::updateValue('FBPROMOTE_VOUCHER_MINAMOUNT', 0) OR !Configuration::updateValue('FBPROMOTE_VOUCHER_VALIDITY', '') OR !Configuration::updateValue('FBPROMOTE_FB_APP_ID', '') OR !Configuration::updateValue('FBPROMOTE_VOUCHER_CUMULATE', 0) OR !Configuration::updateValue('FBPROMOTE_VOUCHER_SELECT', '') OR !Configuration::updateValue('DISPLAY_HOOKS', '') OR !Configuration::updateValue('FBPROMOTE_SHOW_MIN_AMOUNT', 0) ) return false; return true; } /** * uninstall() method uninstall sql tables * * @return bool */ public function uninstall() { Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'fb_promote '); Db::getInstance()->Execute('DROP TABLE '._DB_PREFIX_.'fb_promote_categories '); if (!parent::uninstall() OR !Configuration::deleteByName('FBPROMOTE_FANPAGE_URL') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_DESCRIPTION') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_AMOUNT') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_PERCENT') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_HASMINAMOUNT') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_MINAMOUNT') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_VALIDITY') OR !Configuration::deleteByName('FBPROMOTE_FB_APP_ID') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_CUMULATE') OR !Configuration::deleteByName('FBPROMOTE_VOUCHER_SELECT') OR !Configuration::deleteByName('DISPLAY_HOOKS') OR !Configuration::deleteByName('FBPROMOTE_SHOW_MIN_AMOUNT') ) return false; return true; } /** * _updateModule() method update the module's options * * @return object */ private function _updateModule() { $check = Db::getInstance()->ExecuteS('SHOW TABLES LIKE "'._DB_PREFIX_.'fb_promote_categories"'); if (!$check) { Db::getInstance()->Execute('CREATE TABLE '._DB_PREFIX_.'fb_promote_categories (id_category int(10) NOT NULL, id_shop int(10) NOT NULL default 1, KEY index_cat (id_category, id_shop)) ENGINE='._MYSQL_ENGINE_.';'); } if (version_compare(_PS_VERSION_, '1.5', '>')) { $this->registerHook('displayLeftColumn') && $this->registerHook('displayHeader') && $this->registerHook('displayShoppingCartFooter') && $this->registerHook('displayRightColumn') && $this->registerHook('displayFooter') && $this->registerHook('displayLeftColumnProduct') && $this->registerHook('displayRightColumnProduct') && $this->registerHook('displayProductButtons') && $this->registerHook('displayFooterProduct') && $this->registerHook('displayHome') && $this->registerHook('displayTop'); } else { $this->registerHook('leftColumn') && $this->registerHook('rightColumn') && $this->registerHook('header') && $this->registerHook('shoppingCart') && $this->registerHook('footer') && $this->registerHook('extraLeft') && $this->registerHook('extraRight') && $this->registerHook('home') && $this->registerHook('productActions') && $this->registerHook('productfooter')&& $this->registerHook('top'); } } /** * initCompatibility() method returns current object * * @return object */ public function initCompatibility() { if (strpos(dirname(__FILE__), $this->name) === false) return $this; if (!class_exists('Context')) require_once(realpath(dirname(__FILE__)) . '/libraries/compatibility/Context.php'); return $this; } /** * isReallyInstalled() method returns active module * * @param string $moduleName * @return bool */ public function isReallyInstalled($moduleName = '') { if (!$moduleName) $moduleName = $this->name; $sql = 'SELECT COUNT(id_module) FROM ' . _DB_PREFIX_ .'module WHERE name = "' . pSQL($moduleName) . '" AND active = 1'; return (bool)(int)Db::getInstance()->getValue($sql); } /** * postProcess() method process form post * * @return bool */ private function postProcess() { // facebook url fan page if ($url = Tools::getValue('FBPROMOTE_FANPAGE_URL')) { Configuration::updateValue('FBPROMOTE_FANPAGE_URL', $url); } // description if (Tools::getIsset('FBPROMOTE_VOUCHER_DESCRIPTION')) { $languages = Tools::getValue('FBPROMOTE_VOUCHER_DESCRIPTION'); foreach ($languages as $key => $value) { $languages[(int)$key] = ((empty($value)) ? $url : $value); } Configuration::updateValue('FBPROMOTE_VOUCHER_DESCRIPTION', Tools::getValue('FBPROMOTE_VOUCHER_DESCRIPTION')); } // type if ($type = Tools::getValue('FBPROMOTE_VOUCHER_TYPE')) { Configuration::updateValue('FBPROMOTE_VOUCHER_TYPE', $type); } // amount foreach (Tools::getValue('FBPROMOTE_VOUCHER_AMOUNT') as $id_currency => $voucherAmount) { Configuration::updateValue('FBPROMOTE_VOUCHER_AMOUNT_' . (int)($id_currency), (float)($voucherAmount)); } // percent $fPercentAmount = (float)Tools::getValue('FBPROMOTE_VOUCHER_PERCENT'); if (!empty($fPercentAmount)) { Configuration::updateValue('FBPROMOTE_VOUCHER_PERCENT', (float)Tools::getValue('FBPROMOTE_VOUCHER_PERCENT')); } // hasMinAmount Configuration::updateValue('FBPROMOTE_VOUCHER_HASMINAMOUNT', (int)Tools::getValue('FBPROMOTE_VOUCHER_HASMINAMOUNT')); // minAmount $aMinAmountValues = Tools::getValue('FBPROMOTE_VOUCHER_MINAMOUNT'); if (!empty($aMinAmountValues)) { foreach (Tools::getValue('FBPROMOTE_VOUCHER_MINAMOUNT') as $id_currency => $voucherMinAmount) { Configuration::updateValue('FBPROMOTE_VOUCHER_MINAMOUNT_' . (int)($id_currency), (float)($voucherMinAmount)); } } //show on frontoffice block Configuration::updateValue('FBPROMOTE_SHOW_MIN_AMOUNT', (float)Tools::getValue('FBPROMOTE_SHOW_MIN_AMOUNT')); // validity $fValidity = (float)Tools::getValue('FBPROMOTE_VOUCHER_VALIDITY'); if (!empty($fValidity)) { Configuration::updateValue('FBPROMOTE_VOUCHER_VALIDITY', (float)Tools::getValue('FBPROMOTE_VOUCHER_VALIDITY')); } // facebook app ID $sFacebookId = Tools::getValue('FBPROMOTE_FB_APP_ID'); if (!empty($sFacebookId)) { Configuration::updateValue('FBPROMOTE_FB_APP_ID', Tools::getValue('FBPROMOTE_FB_APP_ID')); } // cumulate with other voucher Configuration::updateValue('FBPROMOTE_VOUCHER_CUMULATE',(int)Tools::getValue('FBPROMOTE_VOUCHER_CUMULATE')); // incentive popup post management Configuration::updateValue('FBPROMOTE_INCENTIVE_POPUP',(int)Tools::getValue('FBPROMOTE_INCENTIVE_POPUP')); // set variable $aSelectedHooks = array(); // selected hooks if (Tools::getIsset('DISPLAY_HOOKS')) { // get hooks form $aFormHooks = Tools::getValue('DISPLAY_HOOKS'); foreach (self::$aHooks as $aHook) { if (in_array($aHook['name'], $aFormHooks)) { $aSelectedHooks[] = $aHook['name']; } } Configuration::updateValue('SELECTED_HOOKS', serialize($aSelectedHooks)); } } /** * getContent() method returns back-office content * * @return string */ public function getContent() { global $cookie; // handle support URL $isoCurrent = Language::getIsoById(intval($cookie->id_lang)); $iSupportToUse = _FBFP_SUPPORT_BT; $ContactUrl = !empty($iSupportToUse) ? _FBFP_SUPPORT_URL . (($isoCurrent == 'fr')? 'fr/contactez-nous' : 'en/contact-us') : _FBFP_SUPPORT_URL . (($isoCurrent == 'fr')? 'fr/ecrire-au-developpeur?id_product=' . _FBFP_SUPPORT_ID : 'en/write-to-developper?id_product=' ._FBFP_SUPPORT_ID); $this->_updateModule(); $aCheck = array(); $aHooks = Tools::getValue('categoryBox'); if (!empty($aHooks)) { Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'fb_promote_categories`'.(!empty(self::$bCompare15) ? ' WHERE `id_shop` = '.(int)($this->id_shop) : '')); foreach ($aHooks as $id_category) { if ((int)($id_category) > 0) { Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'fb_promote_categories` (`id_category`, `id_shop`) values ('.(int)($id_category).', '.(int)(!empty(self::$bCompare15)? $this->id_shop : 0).')'); } } } $cIndex = array(); $categories = Category::getCategories((int)(self::$oCookie->id_lang), false); $indexedCategories = $this->getCategoriesForVoucher(); if ($indexedCategories && is_array($indexedCategories)) { foreach ($indexedCategories AS $row) { $cIndex[] = $row['id_category']; } } // insert for update design tab if (version_compare(_PS_VERSION_, '1.6', '<')) { $this->_html .= ' '; } $this->_html .='
Facebook Fan Coupon

'; if (Tools::isSubmit('submitFbPromote')) { $this->postProcess(); $this->_html .= '

'.$this->l('Settings updated').'

'; } $currencies = Currency::getCurrencies(); $isoCurrent = Language::getIsoById((int)(self::$oCookie->id_lang)); $defaultLanguage = (int)Configuration::get('PS_LANG_DEFAULT'); $languages = Language::getLanguages(false); // check if selected hooks not empty $sSelectHooks = Configuration::get('SELECTED_HOOKS'); if (!empty($sSelectHooks) && is_string($sSelectHooks)) { $aSelectHooks = unserialize($sSelectHooks); } else { $aSelectHooks = array(); } $this->_html .= ' '; $this->_html .='

 '.$this->l('Documentation').'

 '.$this->l('Please read carefully the documentation of the module').' readme_'.$isoCurrent.'.pdf

'.$this->l('About the GDPR').' ' .$this->l('Read FAQ') .'



'.$this->l('Welcome and thank you for purchasing our module. Please read the documentation carefully (visit the Documentation & Help tab)').'

'; $this->_html .='

'.$this->l('Facebook parameters').'

'.'

'.$this->l('Create a voucher when your customers like your page').'

'; foreach ($languages as $language) $this->_html .= '
 
'; $this->_html .= '
'; $this->_html .= $this->displayFlags($languages, $defaultLanguage, 'description', 'description', true); $this->_html .= ' 
'; foreach ($currencies as $currency) $this->_html .= ' '; $this->_html .= '
'.$this->l('Currency').' '.$this->l('Voucher amount').'
'.(Configuration::get('PS_CURRENCY_DEFAULT') == $currency['id_currency'] ? '' : '').htmlentities($currency['name'], ENT_NOQUOTES, 'utf-8').(Configuration::get('PS_CURRENCY_DEFAULT') == $currency['id_currency'] ? '' : '').'
'.$currency['sign'].'
%
 
'; foreach ($currencies as $currency) $this->_html .= ' '; $this->_html .= '
'.$this->l('Currency').' '.$this->l('Minimum checkout').'
'.(Configuration::get('PS_CURRENCY_DEFAULT') == $currency['id_currency'] ? '' : '').htmlentities($currency['name'], ENT_NOQUOTES, 'utf-8').(Configuration::get('PS_CURRENCY_DEFAULT') == $currency['id_currency'] ? '' : '').'
'.$currency['sign'].'
'; $this->_html .='
 '.$this->l('hour(s)').'

'.$this->l('Apply on catgories').'

'; $this->recurseCategoryForInclude($cIndex, $categories, $categories[0][1], 1); $this->_html .= '


'; $this->_html .='

'.$this->l('Hook management').'

'.$this->l('Help / FAQ').'

'.$this->l('ONLINE FAQ : ').' http://faq.businesstech.fr

'.$this->l('CONTACT : ').'' . $ContactUrl . '

'; $this->_html .= $this->display(__FILE__, 'views/templates/admin/module-configure.tpl'); return $this->_html; } /** * hookHeader() method returns HTML content linked to module's header * * @param mixed $params * @return string */ public function hookHeader($params) { if (!empty(self::$bCompare15)) { $smarty = Context::getContext()->smarty; } else { global $smarty; } $smarty->assign( array( 'fb_url' => $this->getUrlFacebookJsLibrary((int)self::$oCookie->id_lang), 'sHookUse' => 'header', 'sJsJqueryPath' => $this->_path.'views/js/jquery-1.11.0.min.js', 'sJsFancyboxPath' => $this->_path.'views/js/jquery.fancybox-1.3.4.min.js', 'bVersion17' => self::$bCompare17, 'sDomainShop' => Configuration::get('PS_SHOP_DOMAIN'), ) ); if (!empty(self::$bCompare15)) { $this->context->controller->addCSS($this->_path . 'views/css/fbpromote.css'); } else { Tools::addCSS($this->_path . 'views/css/fbpromote.css', 'all'); } return $this->display(__FILE__, 'views/templates/hook/header.tpl'); } /** * hookDisplayTop() method returns HTML content linked to module's footer product * * @param mixed $params * @return string */ public function hookDisplayTop($params) { return $this->_checkHook($params, 'top-fbpromote', 'displayTop'); } /** * hookTop() method returns HTML content linked to module's footer product * * @param mixed $params * @return string */ public function hookTop($params) { return $this->_checkHook($params, 'top-fbpromote', 'top'); } /** * hookDisplayLeftColumn() method returns HTML content linked to module's left column * * @param mixed $params * @return string */ public function hookDisplayLeftColumn($params) { return $this->_checkHook($params, 'column-left-fbpromote', 'displayLeftColumn'); } /** * hookLeftColumn() method returns HTML content linked to module's left column * * @param mixed $params * @return string */ public function hookLeftColumn($params) { return $this->_checkHook($params, 'column-left-fbpromote', 'leftColumn'); } /** * hookDisplayLeftColumnProduct() method returns HTML content linked to module's left product column * * @param mixed $params * @return string */ public function hookDisplayLeftColumnProduct($params) { return $this->_checkHook($params, 'product-left-fbpromote', 'displayLeftColumnProduct'); } /** * hookExtraLeft() method returns HTML content linked to module's left product column * * @param mixed $params * @return string */ public function hookExtraLeft($params) { return $this->_checkHook($params, 'product-left-fbpromote', 'extraLeft'); } /** * hookDisplayRightColumnProduct() method returns HTML content linked to module's right product column * * @param mixed $params * @return string */ public function hookDisplayRightColumnProduct($params) { return $this->_checkHook($params, 'product-right-fbpromote', 'displayRightColumnProduct'); } /** * hookExtraRight() method returns HTML content linked to module's right product column * * @param mixed $params * @return string */ public function hookExtraRight($params) { return $this->_checkHook($params, 'product-right-fbpromote', 'extraRight'); } /** * hookDisplayProductButtons() method returns HTML content linked to module's product action * * @param mixed $params * @return string */ public function hookDisplayProductButtons($params) { return $this->_checkHook($params, 'product-action-fbpromote', 'displayProductButtons'); } /** * hookProductActions() method returns HTML content linked to module's product action * * @param mixed $params * @return string */ public function hookProductActions($params) { return $this->_checkHook($params, 'product-action-fbpromote', 'productActions'); } /** * hookDisplayFooterProduct() method returns HTML content linked to module's footer product * * @param mixed $params * @return string */ public function hookDisplayFooterProduct($params) { return $this->_checkHook($params, 'product-footer-fbpromote', 'displayFooterProduct'); } /** * hookProductFooter() method returns HTML content linked to module's footer product * * @param mixed $params * @return string */ public function hookProductFooter($params) { return $this->_checkHook($params, 'product-footer-fbpromote', 'productfooter'); } /** * hookDisplayHome() method returns HTML content linked to module's homepage * * @param mixed $params * @return string */ public function hookDisplayHome($params) { return $this->_checkHook($params, 'home-fbpromote', 'displayHome'); } /** * hookHome() method returns HTML content linked to module's footer product * * @param mixed $params * @return string */ public function hookHome($params) { return $this->_checkHook($params, 'home-fbpromote', 'home'); } /** * hookDisplayFooter() method returns HTML content linked to module's footer * * @param mixed $params * @return string */ public function hookDisplayFooter($params) { return $this->_checkHook($params, 'footer-fbpromote', 'displayFooter'); } /** * hookFooter() method returns HTML content linked to module's footer * * @param mixed $params * @return string */ public function hookFooter($params) { return $this->_checkHook($params, 'footer-fbpromote', 'footer'); } /** * hookDisplayRightColumn() method returns HTML content linked to module's right column * * @param mixed $params * @return string */ public function hookDisplayRightColumn($params) { return $this->_checkHook($params, 'columun-right-fbpromote', 'displayRightColumn'); } /** * hookRightColumn() method returns HTML content linked to module's right column * * @param mixed $params * @return string */ public function hookRightColumn($params) { return $this->_checkHook($params, 'column-right-fbpromote', 'rightColumn'); } /** * hookDisplayShoppingCartFooter() method returns HTML content linked to module's shopping cart * * @param mixed $params * @return string */ public function hookDisplayShoppingCartFooter($params) { return $this->_checkHook($params, 'cart-fbpromote', 'displayShoppingCartFooter'); } /** * hookShoppingCart() method returns HTML content linked to module's shopping cart * * @param mixed $params * @return string */ public function hookShoppingCart($params) { return $this->_checkHook($params, 'cart-fbpromote', 'shoppingCart'); } /** * _checkHook() method returns HTML content if the hook is well assigned in the default hooks to execute * * @param mixed $params * @param string $sHookUse * @param string $sHookName * @return string */ private function _checkHook($params, $sHookUse, $sHookName) { $sContent = ''; if (!empty(self::$aSelectedHooks)) { if (in_array($sHookName, self::$aSelectedHooks)) { $sContent = $this->_execHook($params, $sHookUse); // set the module has already displayed self::$bAlreadyUse = true; } } return $sContent; } /** * _execHook() method returns HTML content for any hooks - same code as generic code * * @param mixed $params * @param string $sHookUse * @return string */ private function _execHook($params, $sHookUse = '') { $currency = new Currency((int)self::$oCookie->id_currency); if (Configuration::get('FBPROMOTE_VOUCHER_TYPE') == "percent") { $discountValue = (float)Configuration::get('FBPROMOTE_VOUCHER_PERCENT') . " %"; } else { $discountValue = Tools::displayPrice((float)Configuration::get('FBPROMOTE_VOUCHER_AMOUNT_'.(int)($currency->id)), $currency); } if (!empty(self::$bCompare15)) { $smarty = Context::getContext()->smarty; } else { global $smarty; } $smarty->assign( array( 'fb_page' => Configuration::get('FBPROMOTE_FANPAGE_URL'), 'fb_appId' => Configuration::get('FBPROMOTE_FB_APP_ID'), 'fb_value' => $discountValue, 'bHasMinAmount' => Configuration::get('FBPROMOTE_VOUCHER_HASMINAMOUNT'), 'bShowMinAmount' => Configuration::get('FBPROMOTE_SHOW_MIN_AMOUNT'), 'sMinAmount' => Tools::displayPrice((float)Configuration::get('FBPROMOTE_VOUCHER_MINAMOUNT_'.(int)($currency->id)), $currency), 'aJSCallback' => array('url' => Configuration::get('FBPROMOTE_FANPAGE_URL'), 'function' => 'bt_generateVoucherCode'), 'bVersion16' => version_compare(_PS_VERSION_, '1.6', '>')? 1 : 0, 'bShowPopUp' => Configuration::get('FBPROMOTE_INCENTIVE_POPUP'), 'sHookUse' => $sHookUse, 'bAlreadyUsed' => self::$bAlreadyUse, 'bVersion17' => self::$bCompare17, ) ); return $this->display(__FILE__, 'views/templates/hook/fbpromoteblock.tpl'); } /** * isFacebookLocaleSupported() method returns FB locale * * @param string $locale * @return bool */ public function isFacebookLocaleSupported($locale) { return in_array($locale, $this->getFacebookLocaleSupported()); } /** * getFacebookLocaleSupported() method returns locales * * @return array */ public function getFacebookLocaleSupported() { $locales = array(); if (($xml=simplexml_load_file(_PS_MODULE_DIR_ . "fbpromote/views/xml/FacebookLocales.xml")) === false) return $locales; $result = $xml->xpath('/locales/locale/codes/code/standard/representation'); foreach ($result as $locale) { list($k, $node) = each($locale); (string)$locales[] = $node; } return $locales; } /** * getUrlFacebookJsLibrary() method returns FB JS library * * @param int $id_lang * @return string */ public function getUrlFacebookJsLibrary($id_lang) { $lang = new Language((int)$id_lang); if (strstr($lang->language_code, '-')) { $res = explode('-', $lang->language_code); $language_iso = Tools::strtolower($res[0]).'_'. Tools::strtoupper($res[1]); } else $language_iso = Tools::strtolower($lang->language_code).'_'. Tools::strtoupper($lang->language_code); if (!$this->isFacebookLocaleSupported($language_iso)) $language_iso = "en_US"; return '//connect.facebook.net/'.$language_iso.'/all.js#xfbml=1'; } /** * quoteQuery() method returns query * * @param string $sql * @param array $values * @return string */ public function quoteQuery($sql, $values = array()) { if (!is_array($values)) throw new Exception("values must be an array"); if (preg_match_all("/(\?)/", $sql, $matches) === false) throw new Exception("bad string"); if (count($values) != count($matches[0])) throw new Exception("some missing elements into sql or values"); foreach ($values as $value) { if (is_int($value)) // convert some strings to int $value = (int)$value; if (is_float($value)) // convert some strings to float $value = (float)$value; if (!is_int($value) && !is_float($value)) $value = "'" . pSQL($value) . "'"; else $value = pSQL($value); $sql = substr_replace($sql, $value, strpos($sql, "?", 0), 1); } return $sql; } /** * isInnoDb() method returns if engine is INNODB * * @return bool */ public function isInnoDb() { if (_MYSQL_ENGINE_ !== 'InnoDB') return false; return true; } /** * beginTransaction() method start transaction * * @return bool */ public function beginTransaction() { if (!$this->isInnoDb()) return true; // default return (bool)Db::getInstance()->Execute('BEGIN'); } /** * rollBack() method rollbacks query * * @return bool */ public function rollBack() { if (!$this->isInnoDb()) return true; // default return (bool)Db::getInstance()->Execute('ROLLBACK'); } /** * commit() method commits query * * @return bool */ public function commit() { if (!$this->isInnoDb()) return true; // default return (bool)Db::getInstance()->Execute('COMMIT'); } /** * createVoucher() method creates voucher * * @param int $id_guest * @param int $id_currency * @return string */ public function createVoucher($id_guest, $id_currency) { if ($this->hasAlreadyVoucher($id_guest)) return false; // TYPE AND VALUE switch (Configuration::get('FBPROMOTE_VOUCHER_TYPE')) { case 'percent': $id_discount_type = 1; $value = Configuration::get('FBPROMOTE_VOUCHER_PERCENT'); break; case 'currency': default: $id_discount_type = 2; $value = Configuration::get('FBPROMOTE_VOUCHER_AMOUNT_'.(int)$id_currency); break; } // VALIDITY $validity = (float)Configuration::get('FBPROMOTE_VOUCHER_VALIDITY'); // return hours if ($validity <= 0) $validity = 30 * 24; // default 30 days $validity = (int)($validity * 3600); // convert to seconds // Code $code = 'FBCOUPON-'. Tools::strtoupper(Tools::passwdGen(8)); $languages = Language::getLanguages(); // id_customer $id_customer = (int)Db::getInstance()->getValue('SELECT id_customer FROM '._DB_PREFIX_.'guest WHERE id_guest='.(int)$id_guest); $restriction_category = unserialize(Tools::getValue('FBPROMOTE_CATEGORY')); if (!empty(self::$bCompare15)) { $voucher = new CartRule(); $voucher->name = Configuration::getInt('FBPROMOTE_VOUCHER_DESCRIPTION'); $aSelectCategory = $this->getCategoriesForVoucher(); if ((int)($id_discount_type) == 1) { // percent $voucher->reduction_percent = $value; } elseif ((int)($id_discount_type) == 2) { // currency $voucher->reduction_amount = $value; $voucher->reduction_tax = 1; } $voucher->code = $code; $voucher->id_customer = (int)$id_customer; $voucher->reduction_currency = (int)$id_currency; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cart_rule_restriction = intval(Configuration::get('FBPROMOTE_VOUCHER_CUMULATE')) == 0 ? 1 : 0 ; if (!empty($aSelectCategory)) { $voucher->product_restriction = 1; } $voucher->partial_use = 0; $voucher->minimum_amount = Configuration::get('FBPROMOTE_VOUCHER_MINAMOUNT_'.(int)$id_currency); $voucher->minimum_amount_currency = (int)($id_currency); $voucher->active = 1; $voucher->highlight = 0; $voucher->date_from = date('Y-m-d H:i:s'); $voucher->date_to = date('Y-m-d H:i:s', time() + $validity); } else { $voucher = new Discount(); $aSelectCategory = unserialize(Configuration::get('FBPROMOTE_CATEGORY')); $voucher->id_discount_type = $id_discount_type; $voucher->description = Configuration::getInt('FBPROMOTE_VOUCHER_DESCRIPTION'); $voucher->value = $value; $voucher->name = $code; $voucher->id_customer = (int)$id_customer; $voucher->id_currency = (int)$id_currency; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = Configuration::get('FBPROMOTE_VOUCHER_CUMULATE'); $voucher->cumulable_reduction = 0; $voucher->minimal = Configuration::get('FBPROMOTE_VOUCHER_MINAMOUNT_'.(int)$id_currency); $voucher->active = 1; $voucher->cart_display = 0; $voucher->date_from = date('Y-m-d H:i:s'); $voucher->date_to = date('Y-m-d H:i:s', time() + $validity); } $this->beginTransaction(); if (!empty(self::$bCompare15)) { if (!$voucher->add()) { $this->rollBack(); throw new Exception("building voucher failed.."); } } else { if (!$voucher->add(true,false,$aSelectCategory)) { $this->rollBack(); throw new Exception("building voucher failed.."); } } $id_discount = $voucher->id; if (!empty($aSelectCategory)) { if (!empty(self::$bCompare15)) { $this->addProductRule($voucher->id, 1, 'categories', $aSelectCategory); } } // insert fb_couponforfriends $ip_address = $_SERVER['REMOTE_ADDR']; if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { $this->rollBack(); throw new Exception("bad ip"); } $sql = 'INSERT INTO '._DB_PREFIX_.'fb_promote (id_guest, id_customer, id_discount, ip_address) VALUES (?, ?, ?, ?)'; $values = array((int)$id_guest, (int)$id_customer, (int)$voucher->id, $ip_address); $sql = $this->quoteQuery($sql, $values); if (!Db::getInstance()->Execute($sql)) { $this->rollBack(); throw new Exception("building voucher failed.."); } $this->commit(); return $id_discount; } /** * hasAlreadyVoucher() method checks if customer already get his voucher code * * @param int $id_guest * @return bool */ public function hasAlreadyVoucher($id_guest) { $sql = 'SELECT id_discount FROM ' . _DB_PREFIX_ . 'fb_promote WHERE id_guest = ?'; $sql = $this->quoteQuery($sql, array($id_guest)); return (int)Db::getInstance()->getValue($sql); } /** * isVoucherValid() method if voucher is valid * * @param int $id_discount * @return bool */ public function isVoucherValid($id_discount) { if (version_compare(_PS_VERSION_, '1.5', '>')) $discount = new CartRule($id_discount); else $discount = new Discount($id_discount); $now = strtotime('now'); if ($now >= strtotime($discount->date_from) AND $now < strtotime($discount->date_to)) return true; return false; } /** * isVoucherAlreadyUsed() method checks if voucher is already used * * @param int $id_discount * @return bool */ public function isVoucherAlreadyUsed($id_discount) { if (version_compare(_PS_VERSION_, '1.5', '>')) { $sql = 'SELECT COUNT(oct.id_order_cart_rule) FROM ' . _DB_PREFIX_ . 'order_cart_rule oct WHERE oct.id_cart_rule = ?'; } else { $sql = 'SELECT COUNT(od.id_order_discount) FROM ' . _DB_PREFIX_ . 'order_discount od WHERE od.id_discount = ?'; } $sql = $this->quoteQuery($sql, array($id_discount)); return (bool)Db::getInstance()->getValue($sql); } /** * deleteVoucher() method deletes voucher * * @param int $id_guest * @return bool */ public function deleteVoucher($id_guest) { $sql = 'SELECT id_discount FROM '._DB_PREFIX_.'fb_promote WHERE id_guest = ?'; $values = array((int)$id_guest); if (!($id_voucher = (int)Db::getInstance()->getValue($this->quoteQuery($sql, $values)))) throw new Exception("unknown id"); $voucher = new Discount((int)$id_voucher); $voucher->delete(); $sql = 'DELETE FROM '._DB_PREFIX_.'fb_promote WHERE id_discount = ?'; $values = array($id_voucher); return (bool)Db::getInstance()->Execute($this->quoteQuery($sql, $values)); } /** * translate() method translate texts * * @param string $key * @return string */ public function translate($key) { $trad = array( 'TITLE_POPUP' => $this->l('Incentive voucher code'), 'VALID' => $this->l('Your voucher code has been created with success'), 'INVALID' => $this->l('A reduction coupon was already associated with your account'), 'AVAILABLE' => $this->l('available until'), 'EXPIRED' => $this->l('your voucher has expired'), 'USED' => $this->l('your voucher has already been used'), 'DISPLAY_AGAIN' => $this->l('You already have generated a voucher code. We are displaying it again below for your convenience. '), 'LABEL_VOUCHER' => $this->l('Your code is : '), 'MINIMUN_AMOUNT' => $this->l('Minimum amount is : '), 'LABEL_DATE' => $this->l('Your avaibility date until : '), 'CLOSE' => $this->l('Close'), ); return $trad[$key]; } /** * formatDate() method formats date * * @param string $date * @return string */ public function formatDate($date) { return $date; } public function recurseCategoryForInclude($indexedCategories, $categories, $current, $id_category = 1, $id_category_default = NULL) { global $done; static $irow; $id_obj = (int)(Tools::getValue($this->identifier)); if (!isset($done[$current['infos']['id_parent']])) $done[$current['infos']['id_parent']] = 0; $done[$current['infos']['id_parent']] += 1; $todo = sizeof($categories[$current['infos']['id_parent']]); // new management for compatibilty for tree if ( $todo == 1 ) { $iMargin = 10; $sIcon = "icon icon-folder"; } elseif($todo == 2) { $iMargin = 20; $sIcon = "icon icon-folder-open"; } elseif($todo == 3) { $iMargin = 30; $sIcon = "icon icon-angle-right"; } elseif($todo == 3) { $iMargin = 30; $sIcon = "icon icon-angle-right"; } elseif($todo == 4) { $iMargin = 40; $sIcon = "icon icon-angle-right"; } elseif($todo == 5) { $iMargin = 50; $sIcon = "icon icon-angle-right"; } elseif($todo == 6) { $iMargin = 60; $sIcon = "icon icon-angle-right"; } elseif($todo == 7) { $iMargin = 70; $sIcon = "icon icon-angle-right"; } $this->_html .= ' '.$id_category.'   '.htmlspecialchars(Tools::stripslashes($current['infos']['name'])).' '; if (isset($categories[$id_category])) foreach ($categories[$id_category] AS $key => $row) if ($key != 'infos') $this->recurseCategoryForInclude($indexedCategories, $categories, $categories[$id_category][$key], $key); } public function getCategoriesForVoucher() { if (version_compare(_PS_VERSION_, '1.5', '>')) return Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'fb_promote_categories` WHERE `id_shop` = '.(int)($this->id_shop)); else return Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'fb_promote_categories`'); } /** * addProductRule() method add a new cart rule * * @param int $iCartRuleId * @param int $iQuantity * @param string $sType * @param array $aIds * @return bool */ public function addProductRule($iCartRuleId, $iQuantity, $sType, array $aIds) { $bInsert = false; // set transaction Db::getInstance()->Execute('BEGIN'); $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule_group (id_cart_rule, quantity) VALUES(' . $iCartRuleId . ', ' . $iQuantity . ')'; // only if group rule is added if (Db::getInstance()->Execute($sQuery)) { $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule (id_product_rule_group, type) VALUES(' . Db::getInstance()->Insert_ID() . ', "' . $sType . '")'; // only if product rule is added if (Db::getInstance()->Execute($sQuery)) { if (!empty($aIds)) { $bInsert = true; $iLastInsertId = Db::getInstance()->Insert_ID(); foreach ($aIds as $iId) { $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule_value (id_product_rule, id_item) VALUES(' . $iLastInsertId . ', ' . $iId['id_category'] . ')'; if (!Db::getInstance()->Execute($sQuery)) { $bInsert = false; } } } } } // commit or rollback transaction $bInsert = ($bInsert)? Db::getInstance()->Execute('COMMIT') : Db::getInstance()->Execute('ROLLBACK'); return $bInsert; } }