Example #1
0
 public static function getModulesByDirct($type)
 {
     $_modules = array();
     $result = opendir(_TM_MODULES_DIR . $type);
     while ($dir = readdir($result)) {
         if (Validate::isModuleName($dir) && is_dir(_TM_MODULES_DIR . $type . '/' . $dir)) {
             include _TM_MODULES_DIR . $type . '/' . $dir . '/config.php';
             if (!($mod = Module::existsModule($dir))) {
                 $module = new Module();
                 $module->alias = pSQL($dir);
                 $module->name = pSQL($_modules[$type][$dir]['name']);
                 $module->type = pSQL($type);
                 $module->description = pSQL($_modules[$type][$dir]['description']);
                 $module->active = 0;
                 $module->add();
                 $_modules[$type][$dir]['id'] = $module->id;
             } else {
                 $_modules[$type][$dir]['id'] = $mod['id_module'];
                 $_modules[$type][$dir]['active'] = $mod['active'];
                 $_modules[$type][$dir]['type'] = $mod['type'];
             }
         }
     }
     return $_modules[$type];
 }
Example #2
0
 public function engine($params)
 {
     if (!($render = Configuration::get('PS_STATS_GRID_RENDER'))) {
         return Tools::displayError('No grid engine selected');
     }
     if (!Validate::isModuleName($render)) {
         die(Tools::displayError());
     }
     if (!file_exists(_PS_ROOT_DIR_ . '/modules/' . $render . '/' . $render . '.php')) {
         return Tools::displayError('Grid engine selected is unavailable.');
     }
     $grider = 'grider.php?render=' . $render . '&module=' . Tools::safeOutput(Tools::getValue('module'));
     $context = Context::getContext();
     $grider .= '&id_employee=' . (int) $context->employee->id;
     $grider .= '&id_lang=' . (int) $context->language->id;
     if (!isset($params['width']) || !Validate::IsUnsignedInt($params['width'])) {
         $params['width'] = 600;
     }
     if (!isset($params['height']) || !Validate::IsUnsignedInt($params['height'])) {
         $params['height'] = 920;
     }
     if (!isset($params['start']) || !Validate::IsUnsignedInt($params['start'])) {
         $params['start'] = 0;
     }
     if (!isset($params['limit']) || !Validate::IsUnsignedInt($params['limit'])) {
         $params['limit'] = 40;
     }
     $grider .= '&width=' . $params['width'];
     $grider .= '&height=' . $params['height'];
     if (isset($params['start']) && Validate::IsUnsignedInt($params['start'])) {
         $grider .= '&start=' . $params['start'];
     }
     if (isset($params['limit']) && Validate::IsUnsignedInt($params['limit'])) {
         $grider .= '&limit=' . $params['limit'];
     }
     if (isset($params['type']) && Validate::IsName($params['type'])) {
         $grider .= '&type=' . $params['type'];
     }
     if (isset($params['option']) && Validate::IsGenericName($params['option'])) {
         $grider .= '&option=' . $params['option'];
     }
     if (isset($params['sort']) && Validate::IsName($params['sort'])) {
         $grider .= '&sort=' . $params['sort'];
     }
     if (isset($params['dir']) && Validate::isSortDirection($params['dir'])) {
         $grider .= '&dir=' . $params['dir'];
     }
     require_once _PS_ROOT_DIR_ . '/modules/' . $render . '/' . $render . '.php';
     return call_user_func(array($render, 'hookGridEngine'), $params, $grider);
 }
    public function ajaxProcessSaveTabModulePreferences()
    {
        $values = Tools::getValue('value_pref');
        $module = Tools::getValue('module_pref');
        if (Validate::isModuleName($module)) {
            Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'tab_module_preference` WHERE `id_employee` = ' . (int) $this->id_employee . ' AND `module` = \'' . pSQL($module) . '\'');
            if (is_array($values) && count($values)) {
                foreach ($values as $value) {
                    Db::getInstance()->execute('
						INSERT INTO `' . _DB_PREFIX_ . 'tab_module_preference` (`id_tab_module_preference`, `id_employee`, `id_tab`, `module`) 
						VALUES (NULL, ' . (int) $this->id_employee . ', ' . (int) $value . ', \'' . pSQL($module) . '\');');
                }
            }
        }
        die('OK');
    }
 public function ajaxProcessremoveSideBarModule()
 {
     $result = array();
     $pagemeta = Tools::getValue('pagemeta');
     $hookname = Tools::getValue('hookname');
     $hookexec_name = Tools::getValue('hookexec_name');
     $module_name = Tools::getValue('module_name');
     if ($module_name && Validate::isModuleName($module_name) && $hookexec_name && Validate::isHookName($hookexec_name)) {
         $HookedModulesArr = OvicLayoutControl::getSideBarModulesByPage($pagemeta, $hookname, false);
         $moduleHook = array();
         $moduleHook[] = $module_name;
         $moduleHook[] = $hookexec_name;
         if ($HookedModulesArr && is_array($HookedModulesArr) && sizeof($HookedModulesArr)) {
             $key = array_search($moduleHook, $HookedModulesArr);
             unset($HookedModulesArr[$key]);
         }
         $HookedModulesArr = array_values($HookedModulesArr);
         $result['status'] = OvicLayoutControl::registerSidebarModule($pagemeta, $hookname, Tools::jsonEncode($HookedModulesArr), $this->context->shop->id);
         $result['msg'] = $this->l('Successful deletion');
     }
     Tools::clearCache();
     die(Tools::jsonEncode($result));
 }
 public function ajaxProcessSaveDashConfig()
 {
     $return = array('has_errors' => false, 'errors' => array());
     $module = Tools::getValue('module');
     $hook = Tools::getValue('hook');
     $configs = Tools::getValue('configs');
     $params = array('date_from' => $this->context->employee->stats_date_from, 'date_to' => $this->context->employee->stats_date_to);
     if (Validate::isModuleName($module) && ($module_obj = Module::getInstanceByName($module))) {
         if (Validate::isLoadedObject($module_obj) && method_exists($module_obj, 'validateDashConfig')) {
             $return['errors'] = $module_obj->validateDashConfig($configs);
         }
         if (!count($return['errors'])) {
             if (Validate::isLoadedObject($module_obj) && method_exists($module_obj, 'saveDashConfig')) {
                 $return['has_errors'] = $module_obj->saveDashConfig($configs);
             } elseif (is_array($configs) && count($configs)) {
                 foreach ($configs as $name => $value) {
                     if (Validate::isConfigName($name)) {
                         Configuration::updateValue($name, $value);
                     }
                 }
             }
         } else {
             $return['has_errors'] = true;
         }
     }
     if (Validate::isHookName($hook) && method_exists($module_obj, $hook)) {
         $return['widget_html'] = $module_obj->{$hook}($params);
     }
     die(Tools::jsonEncode($return));
 }
 public function getContent()
 {
     if (Tools::isSubmit('submitModule')) {
         Configuration::updateValue('PS_QUICK_VIEW', (int) Tools::getValue('quick_view'));
         Configuration::updateValue('PS_TC_ACTIVE', (int) Tools::getValue('live_conf'));
         Configuration::updateValue('PS_GRID_PRODUCT', (int) Tools::getValue('grid_list'));
         Configuration::updateValue('PS_SET_DISPLAY_SUBCATEGORIES', (int) Tools::getValue('sub_cat'));
         foreach ($this->getConfigurableModules() as $module) {
             if (!isset($module['is_module']) || !$module['is_module'] || !Validate::isModuleName($module['name']) || !Tools::isSubmit($module['name'])) {
                 continue;
             }
             $module_instance = Module::getInstanceByName($module['name']);
             if ($module_instance === false || !is_object($module_instance)) {
                 continue;
             }
             $is_installed = (int) Validate::isLoadedObject($module_instance);
             if ($is_installed) {
                 if (($active = (int) Tools::getValue($module['name'])) == $module_instance->active) {
                     continue;
                 }
                 if ($active) {
                     $module_instance->enable();
                 } else {
                     $module_instance->disable();
                 }
             } else {
                 if ((int) Tools::getValue($module['name'])) {
                     $module_instance->install();
                 }
             }
         }
     }
     if (Tools::isSubmit('newItem')) {
         $this->addItem();
     } elseif (Tools::isSubmit('updateItem')) {
         $this->updateItem();
     } elseif (Tools::isSubmit('removeItem')) {
         $this->removeItem();
     }
     $html = $this->renderConfigurationForm();
     $html .= $this->renderThemeConfiguratorForm();
     return $html;
 }
Example #7
0
    public function genericImportWS($className, $fields, $save = false)
    {
        $return = '';
        $json = array();
        $errors = array();
        $json['hasError'] = false;
        $json['datas'] = array_values($fields);
        $languages = array();
        $defaultLanguage = '';
        $table = $this->supportedImports[strtolower($className)]['table'];
        $object = new $className();
        $rules = call_user_func(array($className, 'getValidationRules'), $className);
        if (sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang']) || Tools::isSubmit('syncLangWS') || Tools::isSubmit('syncCurrency')) {
            $moduleName = Tools::getValue('moduleName');
            if (Validate::isModuleName($moduleName) && file_exists('../../modules/' . $moduleName . '/' . $moduleName . '.php')) {
                require_once '../../modules/' . $moduleName . '/' . $moduleName . '.php';
                $importModule = new $moduleName();
                $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
                $languages = $importModule->getLangagues();
                if (Tools::isSubmit('syncLangWS')) {
                    $defaultIdLand = $importModule->getDefaultIdLang();
                    $defaultLanguageImport = new Language(Language::getIdByIso($languages[$defaultIdLand]['iso_code']));
                    if ($defaultLanguage->iso_code != $defaultLanguageImport->iso_code) {
                        $errors[] = $this->l('Default language doesn\'t match : ') . '<br>' . Configuration::get('PS_SHOP_NAME') . ' : ' . $defaultLanguage->name . ' ≠
											' . $importModule->displayName . ' : ' . $defaultLanguageImport->name . '<br>' . $this->l('Please change default language in your configuration');
                    }
                }
                if (Tools::isSubmit('syncCurrency')) {
                    $defaultIdCurrency = $importModule->getDefaultIdCurrency();
                    $currencies = $importModule->getCurrencies();
                    if (!empty($currencies[$defaultIdCurrency]['iso_code'])) {
                        $defaultCurrencyImport = new Currency((int) Currency::getIdByIsoCode($currencies[$defaultIdCurrency]['iso_code']));
                    } else {
                        $defaultCurrencyImport = new Currency((int) Currency::getIdByIsoCodeNum($currencies[$defaultIdCurrency]['iso_code_num']));
                    }
                    $defaultCurrency = new Currency((int) Configuration::get('PS_CURRENCY_DEFAULT'));
                    if ($defaultCurrency->iso_code != $defaultCurrencyImport->iso_code) {
                        $errors[] = $this->l('Default currency doesn\'t match : ') . '<br>' . Configuration::get('PS_SHOP_NAME') . ' : ' . $defaultCurrency->name . ' ≠ ' . $importModule->displayName . ' : ' . $defaultCurrencyImport->name . '<br>' . $this->l('Please change default currency in your configuration');
                    }
                }
                if (!empty($errors)) {
                    die('{"hasError" : true, "error" : ' . Tools::jsonEncode($errors) . '}');
                }
            } else {
                die('{"hasError" : true, "error" : ["FATAL ERROR"], "datas" : []}');
            }
        }
        foreach ($fields as $key => $field) {
            $id = $this->supportedImports[strtolower($className)]['identifier'];
            //remove wrong fields (ex : id_toto in Customer)
            foreach ($field as $name => $value) {
                if (!array_key_exists($name, get_object_vars($object)) and $name != $id and $name != 'association' and $name != 'images' and strtolower($className) != 'cart') {
                    unset($field[$name]);
                }
            }
            $return = $this->validateRules($rules, $field, $className, $languages, $defaultLanguage);
            $fields[$key] = $field;
            if (!empty($return)) {
                //skip mode
                if (Tools::getValue('hasErrors') == 1) {
                    unset($fields[$key]);
                }
                $errors[] = $return;
                array_unshift($errors[sizeof($errors) - 1], $field[$id]);
            }
        }
        if (sizeof($errors) > 0) {
            $json['hasError'] = true;
            $json['error'] = $errors;
        }
        if ($save || Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS')) {
            //add language if not exist in prestashop
            if ($className == 'Language') {
                if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS')) {
                    $add = true;
                } else {
                    $add = false;
                }
                $errors = $this->checkAndAddLang($fields, $add);
            } elseif ($className == 'Cart') {
                $this->saveOrders($fields);
            } else {
                $return = $this->saveObject($className, $fields);
                $this->cleanPositions($table);
                //insert association
                if (array_key_exists('association', $this->supportedImports[strtolower($className)])) {
                    $this->insertAssociation(strtolower($className), $fields);
                }
                if (!empty($return)) {
                    $json['hasError'] = true;
                    $json['error'] = $return;
                }
            }
            if ($className == 'Category' and sizeof($fields) != (int) Tools::getValue('nbr_import')) {
                $this->updateCat();
            }
        }
        if (sizeof($errors) > 0 and is_array($errors)) {
            $json['hasError'] = true;
            $json['error'] = $errors;
        }
        die(Tools::jsonEncode($json));
    }
Example #8
0
 /**
  * Create link after language change, for the change language block
  *
  * @param integer $id_lang Language ID
  * @return string link
  */
 public function getLanguageLink($id_lang, Context $context = null)
 {
     if (!$context) {
         $context = Context::getContext();
     }
     $params = $_GET;
     unset($params['isolang'], $params['controller']);
     if (!$this->allow) {
         $params['id_lang'] = $id_lang;
     } else {
         unset($params['id_lang']);
     }
     $controller = Dispatcher::getInstance()->getController();
     if (!empty(Context::getContext()->controller->php_self)) {
         $controller = Context::getContext()->controller->php_self;
     }
     if ($controller == 'product' && isset($params['id_product'])) {
         return $this->getProductLink((int) $params['id_product'], null, null, null, (int) $id_lang);
     } elseif ($controller == 'category' && isset($params['id_category'])) {
         return $this->getCategoryLink((int) $params['id_category'], null, (int) $id_lang);
     } elseif ($controller == 'supplier' && isset($params['id_supplier'])) {
         return $this->getSupplierLink((int) $params['id_supplier'], null, (int) $id_lang);
     } elseif ($controller == 'manufacturer' && isset($params['id_manufacturer'])) {
         return $this->getManufacturerLink((int) $params['id_manufacturer'], null, (int) $id_lang);
     } elseif ($controller == 'cms' && isset($params['id_cms'])) {
         return $this->getCMSLink((int) $params['id_cms'], null, false, (int) $id_lang);
     } elseif ($controller == 'cms' && isset($params['id_cms_category'])) {
         return $this->getCMSCategoryLink((int) $params['id_cms_category'], null, (int) $id_lang);
     } elseif (isset($params['fc']) && $params['fc'] == 'module') {
         $module = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';
         if (!empty($module)) {
             unset($params['fc'], $params['module']);
             return $this->getModuleLink($module, $controller, $params, null, (int) $id_lang);
         }
     }
     return $this->getPageLink($controller, null, $id_lang, $params);
 }
 public function displayStats()
 {
     $tpl = $this->createTemplate('stats.tpl');
     if ((!($module_name = Tools::getValue('module')) || !Validate::isModuleName($module_name)) && ($module_instance = Module::getInstanceByName('statsforecast')) && $module_instance->active) {
         $module_name = 'statsforecast';
     }
     if ($module_name) {
         $_GET['module'] = $module_name;
         if (!isset($module_instance)) {
             $module_instance = Module::getInstanceByName($module_name);
         }
         if ($module_instance && $module_instance->active) {
             $hook = Hook::exec('displayAdminStatsModules', null, $module_instance->id);
         }
     }
     $tpl->assign(array('module_name' => $module_name, 'module_instance' => isset($module_instance) ? $module_instance : null, 'hook' => isset($hook) ? $hook : null));
     return $tpl->fetch();
 }
 /**
  * This method is used to wright translation for mails.
  * This wrights subject translation files
  * (in root/mails/lang_choosen/lang.php or root/_PS_THEMES_DIR_/mails/lang_choosen/lang.php)
  * and mails files.
  */
 protected function submitTranslationsMails()
 {
     $arr_mail_content = array();
     $arr_mail_path = array();
     if (Tools::getValue('core_mail')) {
         $arr_mail_content['core_mail'] = Tools::getValue('core_mail');
         // Get path of directory for find a good path of translation file
         if ($this->theme_selected != self::DEFAULT_THEME_NAME) {
             $arr_mail_path['core_mail'] = $this->translations_informations[$this->type_selected]['override']['dir'];
         } else {
             $arr_mail_path['core_mail'] = $this->translations_informations[$this->type_selected]['dir'];
         }
     }
     if (Tools::getValue('module_mail')) {
         $arr_mail_content['module_mail'] = Tools::getValue('module_mail');
         // Get path of directory for find a good path of translation file
         if ($this->theme_selected != self::DEFAULT_THEME_NAME) {
             $arr_mail_path['module_mail'] = $this->translations_informations['modules']['override']['dir'] . '{module}/mails/' . $this->lang_selected->iso_code . '/';
         } else {
             $arr_mail_path['module_mail'] = $this->translations_informations['modules']['dir'] . '{module}/mails/' . $this->lang_selected->iso_code . '/';
         }
     }
     // Save each mail content
     foreach ($arr_mail_content as $group_name => $all_content) {
         foreach ($all_content as $type_content => $mails) {
             foreach ($mails as $mail_name => $content) {
                 $module_name = false;
                 $module_name_pipe_pos = stripos($mail_name, '|');
                 if ($module_name_pipe_pos) {
                     $module_name = substr($mail_name, 0, $module_name_pipe_pos);
                     if (!Validate::isModuleName($module_name)) {
                         throw new PrestaShopException(sprinf(Tools::displayError('Invalid module name "%s"'), $module_name));
                     }
                     $mail_name = substr($mail_name, $module_name_pipe_pos + 1);
                     if (!Validate::isTplName($mail_name)) {
                         throw new PrestaShopException(sprintf(Tools::displayError('Invalid mail name "%s"'), $mail_name));
                     }
                 }
                 if ($type_content == 'html') {
                     $content = Tools::htmlentitiesUTF8($content);
                     $content = htmlspecialchars_decode($content);
                     // replace correct end of line
                     $content = str_replace("\r\n", PHP_EOL, $content);
                     $title = '';
                     if (Tools::getValue('title_' . $group_name . '_' . $mail_name)) {
                         $title = Tools::getValue('title_' . $group_name . '_' . $mail_name);
                     }
                     $string_mail = $this->getMailPattern();
                     $content = str_replace(array('#title', '#content'), array($title, $content), $string_mail);
                     // Magic Quotes shall... not.. PASS!
                     if (_PS_MAGIC_QUOTES_GPC_) {
                         $content = stripslashes($content);
                     }
                 }
                 if (Validate::isCleanHTML($content)) {
                     $path = $arr_mail_path[$group_name];
                     if ($module_name) {
                         $path = str_replace('{module}', $module_name, $path);
                     }
                     file_put_contents($path . $mail_name . '.' . $type_content, $content);
                 } else {
                     throw new PrestaShopException(Tools::displayError('HTML e-mail templates cannot contain JavaScript code.'));
                 }
             }
         }
     }
     // Update subjects
     $array_subjects = array();
     if (($subjects = Tools::getValue('subject')) && is_array($subjects)) {
         $array_subjects['core_and_modules'] = array('translations' => array(), 'path' => $arr_mail_path['core_mail'] . 'lang.php');
         foreach ($subjects as $subject_translation) {
             $array_subjects['core_and_modules']['translations'] = array_merge($array_subjects['core_and_modules']['translations'], $subject_translation);
         }
     }
     if (!empty($array_subjects)) {
         foreach ($array_subjects as $infos) {
             $this->writeSubjectTranslationFile($infos['translations'], $infos['path']);
         }
     }
     if (Tools::isSubmit('submitTranslationsMailsAndStay')) {
         $this->redirect(true);
     } else {
         $this->redirect();
     }
 }
 public function processSave()
 {
     $id = Tools::getValue('block_identifier');
     if (Validate::isModuleName($id)) {
         return parent::processSave();
     }
     $this->errors[] = Tools::displayError('The field "block_identifier" is invalid. Allowed characters:') . ' a-z, A-Z, 0-9, _';
     $this->display = 'edit';
     return FALSE;
 }
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Configuration::get('PS_CATALOG_MODE')) {
                 $payment_module = Module::getInstanceByName($module_name);
             } else {
                 $payment_module = new BoOrder();
             }
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $bad_delivery = false;
             if (($bad_delivery = (bool) (!Address::isCountryActiveById((int) $cart->id_address_delivery))) || !Address::isCountryActiveById((int) $cart->id_address_invoice)) {
                 if ($bad_delivery) {
                     $this->errors[] = Tools::displayError('This delivery address country is not active.');
                 } else {
                     $this->errors[] = Tools::displayError('This invoice address country is not active.');
                 }
             } else {
                 $employee = new Employee((int) Context::getContext()->cookie->id_employee);
                 $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
                 if ($payment_module->currentOrder) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } else {
         parent::postProcess();
     }
 }
Example #13
0
 /**
  * Return modules directory list
  *
  * @return array Modules Directory List
  */
 public static function getModulesDirOnDisk()
 {
     $module_list = array();
     $modules = scandir(_PS_MODULE_DIR_);
     foreach ($modules as $name) {
         if (is_file(_PS_MODULE_DIR_ . $name)) {
             continue;
         } elseif (is_dir(_PS_MODULE_DIR_ . $name . DIRECTORY_SEPARATOR) && Tools::file_exists_cache(_PS_MODULE_DIR_ . $name . '/' . $name . '.php')) {
             if (!Validate::isModuleName($name)) {
                 throw new PrestaShopException(sprintf('Module %s is not a valid module name', $name));
             }
             $module_list[] = $name;
         }
     }
     return $module_list;
 }
 public function hookdisplayOvicCategorySizeChart($params)
 {
     $module_name = '';
     if (Validate::isModuleName(Tools::getValue('module'))) {
         $module_name = Tools::getValue('module');
     }
     if (!empty($this->context->controller->php_self)) {
         $page_name = $this->context->controller->php_self;
     } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) {
         $page_name = 'module-payment-submit';
     } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {
         $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]);
     } else {
         $page_name = Dispatcher::getInstance()->getController();
         $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name;
     }
     if (strlen($page_name) <= 0) {
         return '';
     }
     if ($page_name == 'category') {
         $id_category = (int) Tools::getValue('id_category');
     } elseif ($page_name == 'product') {
         $id_product = (int) Tools::getValue('id_product');
         $product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);
         $id_category = $product->id_category_default;
     }
     if (!isset($id_category) or is_null($id_category)) {
         return;
     }
     $sizecharts = $this->getSizechart(true, $id_category);
     $check_sizechart = true;
     if (!$sizecharts && count($sizecharts) < 1) {
         $check_sizechart = false;
     }
     if ($page_name == 'category' || $page_name == 'product') {
         $this->smarty->assign('category_sizechart', $sizecharts);
     } else {
         return;
     }
     if (!$check_sizechart) {
         return;
     }
     // Check if not a mobile theme
     if ($this->context->getMobileDevice() != false) {
         return false;
     }
     return $this->display(__FILE__, 'oviccategorysizechart.tpl');
 }
 /**
  * remove a module from a hook
  */
 public function ajaxProcessremoveModuleHook()
 {
     $result = array();
     $hookname = Tools::getValue('hookname');
     $id_option = (int) Tools::getValue('id_option');
     $option = new Options($id_option);
     $hookexec_name = Tools::getValue('hookexec_name');
     $module_name = Tools::getValue('module_name');
     if ($option && Validate::isLoadedObject($option) && $module_name && Validate::isModuleName($module_name) && $hookname && Validate::isHookName($hookname) && $hookexec_name && Validate::isHookName($hookexec_name)) {
         $HookedModulesArr = OvicLayoutControl::getModulesHook($option->theme, $option->alias, $hookname);
         $HookedModulesArr = Tools::jsonDecode($HookedModulesArr['modules'], true);
         $HookedModulesArr = array_values($HookedModulesArr);
         $moduleHook = array();
         $moduleHook[] = $module_name;
         $moduleHook[] = $hookexec_name;
         if ($HookedModulesArr && is_array($HookedModulesArr) && sizeof($HookedModulesArr)) {
             $key = array_search($moduleHook, $HookedModulesArr);
             unset($HookedModulesArr[$key]);
         }
         $HookedModulesArr = array_values($HookedModulesArr);
         $result['status'] = OvicLayoutControl::registerHookModule($option, $hookname, Tools::jsonEncode($HookedModulesArr), $this->context->shop->id);
         $result['msg'] = $this->l('Successful deletion');
         //$this->displayError
     }
     Tools::clearCache();
     die(Tools::jsonEncode($result));
 }
Example #16
0
 public static function execModuleHook($hook_name, $hook_args = array(), $module_name, $use_push = false, $id_shop = null)
 {
     static $disable_non_native_modules = null;
     if ($disable_non_native_modules === null) {
         $disable_non_native_modules = (bool) Configuration::get('PS_DISABLE_NON_NATIVE_MODULE');
     }
     // Check arguments validity
     if (!Validate::isModuleName($module_name) || !Validate::isHookName($hook_name)) {
         throw new PrestaShopException('Invalid module name or hook name');
     }
     // If no modules associated to hook_name or recompatible hook name, we stop the function
     if (!Hook::getHookModuleExecList($hook_name)) {
         return '';
     }
     // Check if hook exists
     if (!($id_hook = Hook::getIdByName($hook_name))) {
         return false;
     }
     // Store list of executed hooks on this page
     Hook::$executed_hooks[$id_hook] = $hook_name;
     //		$live_edit = false;
     $context = Context::getContext();
     if (!isset($hook_args['cookie']) || !$hook_args['cookie']) {
         $hook_args['cookie'] = $context->cookie;
     }
     if (!isset($hook_args['cart']) || !$hook_args['cart']) {
         $hook_args['cart'] = $context->cart;
     }
     $retro_hook_name = Hook::getRetroHookName($hook_name);
     // Look on modules list
     $altern = 0;
     $output = '';
     if ($disable_non_native_modules && !isset(Hook::$native_module)) {
         Hook::$native_module = Module::getNativeModuleList();
     }
     $different_shop = false;
     if ($id_shop !== null && Validate::isUnsignedId($id_shop) && $id_shop != $context->shop->getContextShopID()) {
         //			$old_context_shop_id = $context->shop->getContextShopID();
         $old_context = $context->shop->getContext();
         $old_shop = clone $context->shop;
         $shop = new Shop((int) $id_shop);
         if (Validate::isLoadedObject($shop)) {
             $context->shop = $shop;
             $context->shop->setContext(Shop::CONTEXT_SHOP, $shop->id);
             $different_shop = true;
         }
     }
     // Check errors
     if ((bool) $disable_non_native_modules && Hook::$native_module && count(Hook::$native_module) && !in_array($module_name, self::$native_module)) {
         return;
     }
     if (!($moduleInstance = Module::getInstanceByName($module_name))) {
         return;
     }
     if ($use_push && !$moduleInstance->allow_push) {
         continue;
     }
     // Check which / if method is callable
     $hook_callable = is_callable(array($moduleInstance, 'hook' . $hook_name));
     $hook_retro_callable = is_callable(array($moduleInstance, 'hook' . $retro_hook_name));
     if (($hook_callable || $hook_retro_callable) && Module::preCall($moduleInstance->name)) {
         $hook_args['altern'] = ++$altern;
         if ($use_push && isset($moduleInstance->push_filename) && file_exists($moduleInstance->push_filename)) {
             Tools::waitUntilFileIsModified($moduleInstance->push_filename, $moduleInstance->push_time_limit);
         }
         // Call hook method
         if ($hook_callable) {
             $display = $moduleInstance->{'hook' . $hook_name}($hook_args);
         } elseif ($hook_retro_callable) {
             $display = $moduleInstance->{'hook' . $retro_hook_name}($hook_args);
         }
         $output .= $display;
     }
     if ($different_shop) {
         $context->shop = $old_shop;
         $context->shop->setContext($old_context, $shop->id);
     }
     return $output;
     // Return html string
 }
 public function ajaxProcessGetHookableModuleList()
 {
     if ($this->tabAccess['view'] === '1') {
         /* PrestaShop demo mode */
         if (_PS_MODE_DEMO_) {
             die('{"hasError" : true, "errors" : ["Live Edit : This functionnality has been disabled"]}');
         }
         /* PrestaShop demo mode*/
         $hook_name = Tools::getValue('hook');
         $hookableModulesList = array();
         $modules = Db::getInstance()->executeS('SELECT id_module, name FROM `' . _DB_PREFIX_ . 'module` ');
         foreach ($modules as $module) {
             if (!Validate::isModuleName($module['name'])) {
                 continue;
             }
             if (file_exists(_PS_MODULE_DIR_ . $module['name'] . '/' . $module['name'] . '.php')) {
                 include_once _PS_MODULE_DIR_ . $module['name'] . '/' . $module['name'] . '.php';
                 $mod = new $module['name']();
                 if ($mod->isHookableOn($hook_name)) {
                     $hookableModulesList[] = array('id' => (int) $mod->id, 'name' => $mod->displayName, 'display' => Hook::exec($hook_name, array(), (int) $mod->id));
                 }
             }
         }
         die(Tools::jsonEncode($hookableModulesList));
     }
 }
Example #18
0
 public function engine($params)
 {
     $context = Context::getContext();
     if (!($render = Configuration::get('PS_STATS_RENDER'))) {
         return Tools::displayError('No graph engine selected');
     }
     if (!Validate::isModuleName($render)) {
         die(Tools::displayError());
     }
     if (!file_exists(_PS_ROOT_DIR_ . '/modules/' . $render . '/' . $render . '.php')) {
         return Tools::displayError('Graph engine selected is unavailable.');
     }
     $id_employee = (int) $context->employee->id;
     $id_lang = (int) $context->language->id;
     if (!isset($params['layers'])) {
         $params['layers'] = 1;
     }
     if (!isset($params['type'])) {
         $params['type'] = 'column';
     }
     if (!isset($params['width'])) {
         $params['width'] = 550;
     }
     if (!isset($params['height'])) {
         $params['height'] = 270;
     }
     $url_params = $params;
     $url_params['render'] = $render;
     $url_params['module'] = Tools::getValue('module');
     $url_params['id_employee'] = $id_employee;
     $url_params['id_lang'] = $id_lang;
     $drawer = 'drawer.php?' . http_build_query(array_map('Tools::safeOutput', $url_params), '', '&');
     require_once _PS_ROOT_DIR_ . '/modules/' . $render . '/' . $render . '.php';
     return call_user_func(array($render, 'hookGraphEngine'), $params, $drawer);
 }
Example #19
0
 public function displayModuleOptions($module, $output_type = 'link', $back = null)
 {
     if (!isset($module->enable_device)) {
         $module->enable_device = Context::DEVICE_COMPUTER | Context::DEVICE_TABLET | Context::DEVICE_MOBILE;
     }
     $this->translationsTab['confirm_uninstall_popup'] = isset($module->confirmUninstall) ? $module->confirmUninstall : $this->l('Do you really want to uninstall this module?');
     if (!isset($this->translationsTab['Disable this module'])) {
         $this->translationsTab['Disable this module'] = $this->l('Disable this module');
         $this->translationsTab['Enable this module for all shops'] = $this->l('Enable this module for all shops');
         $this->translationsTab['Disable'] = $this->l('Disable');
         $this->translationsTab['Enable'] = $this->l('Enable');
         $this->translationsTab['Disable on mobiles'] = $this->l('Disable on mobiles');
         $this->translationsTab['Disable on tablets'] = $this->l('Disable on tablets');
         $this->translationsTab['Disable on computers'] = $this->l('Disable on computers');
         $this->translationsTab['Display on mobiles'] = $this->l('Display on mobiles');
         $this->translationsTab['Display on tablets'] = $this->l('Display on tablets');
         $this->translationsTab['Display on computers'] = $this->l('Display on computers');
         $this->translationsTab['Reset'] = $this->l('Reset');
         $this->translationsTab['Configure'] = $this->l('Configure');
         $this->translationsTab['Delete'] = $this->l('Delete');
         $this->translationsTab['Install'] = $this->l('Install');
         $this->translationsTab['Uninstall'] = $this->l('Uninstall');
         $this->translationsTab['Would you like to delete the content related to this module ?'] = $this->l('Would you like to delete the content related to this module ?');
         $this->translationsTab['This action will permanently remove the module from the server. Are you sure you want to do this?'] = $this->l('This action will permanently remove the module from the server. Are you sure you want to do this?');
         $this->translationsTab['Remove from Favorites'] = $this->l('Remove from Favorites');
         $this->translationsTab['Mark as Favorite'] = $this->l('Mark as Favorite');
     }
     $link_admin_modules = $this->context->link->getAdminLink('AdminModules', true);
     $modules_options = array();
     $configure_module = array('href' => $link_admin_modules . '&configure=' . urlencode($module->name) . '&tab_module=' . $module->tab . '&module_name=' . urlencode($module->name), 'onclick' => $module->onclick_option && isset($module->onclick_option_content['configure']) ? $module->onclick_option_content['configure'] : '', 'title' => '', 'text' => $this->translationsTab['Configure'], 'cond' => $module->id && isset($module->is_configurable) && $module->is_configurable, 'icon' => 'wrench');
     $desactive_module = array('href' => $link_admin_modules . '&module_name=' . urlencode($module->name) . '&' . ($module->active ? 'enable=0' : 'enable=1') . '&tab_module=' . $module->tab, 'onclick' => $module->active && $module->onclick_option && isset($module->onclick_option_content['desactive']) ? $module->onclick_option_content['desactive'] : '', 'title' => Shop::isFeatureActive() ? htmlspecialchars($module->active ? $this->translationsTab['Disable this module'] : $this->translationsTab['Enable this module for all shops']) : '', 'text' => $module->active ? $this->translationsTab['Disable'] : $this->translationsTab['Enable'], 'cond' => $module->id, 'icon' => 'off');
     $link_reset_module = $link_admin_modules . '&module_name=' . urlencode($module->name) . '&reset&tab_module=' . $module->tab;
     $is_reset_ready = false;
     if (Validate::isModuleName($module->name)) {
         if (method_exists(Module::getInstanceByName($module->name), 'reset')) {
             $is_reset_ready = true;
         }
     }
     $reset_module = array('href' => $link_reset_module, 'onclick' => $module->onclick_option && isset($module->onclick_option_content['reset']) ? $module->onclick_option_content['reset'] : '', 'title' => '', 'text' => $this->translationsTab['Reset'], 'cond' => $module->id && $module->active, 'icon' => 'undo', 'class' => $is_reset_ready ? 'reset_ready' : '');
     $delete_module = array('href' => $link_admin_modules . '&delete=' . urlencode($module->name) . '&tab_module=' . $module->tab . '&module_name=' . urlencode($module->name), 'onclick' => $module->onclick_option && isset($module->onclick_option_content['delete']) ? $module->onclick_option_content['delete'] : 'return confirm(\'' . $this->translationsTab['This action will permanently remove the module from the server. Are you sure you want to do this?'] . '\');', 'title' => '', 'text' => $this->translationsTab['Delete'], 'cond' => true, 'icon' => 'trash', 'class' => 'text-danger');
     $display_mobile = array('href' => $link_admin_modules . '&module_name=' . urlencode($module->name) . '&' . ($module->enable_device & Context::DEVICE_MOBILE ? 'disable_device' : 'enable_device') . '=' . Context::DEVICE_MOBILE . '&tab_module=' . $module->tab, 'onclick' => '', 'title' => htmlspecialchars($module->enable_device & Context::DEVICE_MOBILE ? $this->translationsTab['Disable on mobiles'] : $this->translationsTab['Display on mobiles']), 'text' => $module->enable_device & Context::DEVICE_MOBILE ? $this->translationsTab['Disable on mobiles'] : $this->translationsTab['Display on mobiles'], 'cond' => $module->id, 'icon' => 'mobile');
     $display_tablet = array('href' => $link_admin_modules . '&module_name=' . urlencode($module->name) . '&' . ($module->enable_device & Context::DEVICE_TABLET ? 'disable_device' : 'enable_device') . '=' . Context::DEVICE_TABLET . '&tab_module=' . $module->tab, 'onclick' => '', 'title' => htmlspecialchars($module->enable_device & Context::DEVICE_TABLET ? $this->translationsTab['Disable on tablets'] : $this->translationsTab['Display on tablets']), 'text' => $module->enable_device & Context::DEVICE_TABLET ? $this->translationsTab['Disable on tablets'] : $this->translationsTab['Display on tablets'], 'cond' => $module->id, 'icon' => 'tablet');
     $display_computer = array('href' => $link_admin_modules . '&module_name=' . urlencode($module->name) . '&' . ($module->enable_device & Context::DEVICE_COMPUTER ? 'disable_device' : 'enable_device') . '=' . Context::DEVICE_COMPUTER . '&tab_module=' . $module->tab, 'onclick' => '', 'title' => htmlspecialchars($module->enable_device & Context::DEVICE_COMPUTER ? $this->translationsTab['Disable on computers'] : $this->translationsTab['Display on computers']), 'text' => $module->enable_device & Context::DEVICE_COMPUTER ? $this->translationsTab['Disable on computers'] : $this->translationsTab['Display on computers'], 'cond' => $module->id, 'icon' => 'desktop');
     $install = array('href' => $link_admin_modules . '&install=' . urlencode($module->name) . '&tab_module=' . $module->tab . '&module_name=' . $module->name . '&anchor=' . ucfirst($module->name) . (!is_null($back) ? '&back=' . urlencode($back) : ''), 'onclick' => '', 'title' => $this->translationsTab['Install'], 'text' => $this->translationsTab['Install'], 'cond' => $module->id, 'icon' => 'plus-sign-alt');
     $uninstall = array('href' => $link_admin_modules . '&uninstall=' . urlencode($module->name) . '&tab_module=' . $module->tab . '&module_name=' . $module->name . '&anchor=' . ucfirst($module->name) . (!is_null($back) ? '&back=' . urlencode($back) : ''), 'onclick' => isset($module->onclick_option_content['uninstall']) ? $module->onclick_option_content['uninstall'] : 'return confirm(\'' . $this->translationsTab['confirm_uninstall_popup'] . '\');', 'title' => $this->translationsTab['Uninstall'], 'text' => $this->translationsTab['Uninstall'], 'cond' => $module->id, 'icon' => 'minus-sign-alt');
     $remove_from_favorite = array('href' => '#', 'class' => 'action_unfavorite toggle_favorite', 'onclick' => '', 'title' => $this->translationsTab['Remove from Favorites'], 'text' => $this->translationsTab['Remove from Favorites'], 'cond' => $module->id, 'icon' => 'star', 'data-value' => '0', 'data-module' => $module->name);
     $mark_as_favorite = array('href' => '#', 'class' => 'action_favorite toggle_favorite', 'onclick' => '', 'title' => $this->translationsTab['Mark as Favorite'], 'text' => $this->translationsTab['Mark as Favorite'], 'cond' => $module->id, 'icon' => 'star', 'data-value' => '1', 'data-module' => $module->name);
     $update = array('href' => $module->options['update_url'], 'onclick' => '', 'title' => 'Update it!', 'text' => 'Update it!', 'icon' => 'refresh', 'cond' => $module->id);
     $divider = array('href' => '#', 'onclick' => '', 'title' => 'divider', 'text' => 'divider', 'cond' => $module->id);
     if (isset($module->version_addons) && $module->version_addons) {
         $modules_options[] = $update;
     }
     if ($module->active) {
         $modules_options[] = $configure_module;
         $modules_options[] = $desactive_module;
         $modules_options[] = $display_mobile;
         $modules_options[] = $display_tablet;
         $modules_options[] = $display_computer;
     } else {
         $modules_options[] = $desactive_module;
         $modules_options[] = $configure_module;
     }
     $modules_options[] = $reset_module;
     if ($output_type == 'select') {
         if (!$module->id) {
             $modules_options[] = $install;
         } else {
             $modules_options[] = $uninstall;
         }
     } elseif ($output_type == 'array') {
         if ($module->id) {
             $modules_options[] = $uninstall;
         }
     }
     if (isset($module->preferences) && isset($module->preferences['favorite']) && $module->preferences['favorite'] == 1) {
         $remove_from_favorite['style'] = '';
         $mark_as_favorite['style'] = 'display:none;';
         $modules_options[] = $remove_from_favorite;
         $modules_options[] = $mark_as_favorite;
     } else {
         $mark_as_favorite['style'] = '';
         $remove_from_favorite['style'] = 'display:none;';
         $modules_options[] = $remove_from_favorite;
         $modules_options[] = $mark_as_favorite;
     }
     if ($module->id == 0) {
         $install['cond'] = 1;
         $install['flag_install'] = 1;
         $modules_options[] = $install;
     }
     $modules_options[] = $divider;
     $modules_options[] = $delete_module;
     $return = '';
     foreach ($modules_options as $option_name => $option) {
         if ($option['cond']) {
             if ($output_type == 'link') {
                 $return .= '<li><a class="' . $option_name . ' action_module';
                 $return .= '" href="' . $option['href'] . (!is_null($back) ? '&back=' . urlencode($back) : '') . '"';
                 $return .= ' onclick="' . $option['onclick'] . '"  title="' . $option['title'] . '"><i class="icon-' . (isset($option['icon']) && $option['icon'] ? $option['icon'] : 'cog') . '"></i>&nbsp;' . $option['text'] . '</a></li>';
             } elseif ($output_type == 'array') {
                 if (!is_array($return)) {
                     $return = array();
                 }
                 $html = '<a class="';
                 $is_install = isset($option['flag_install']) ? true : false;
                 if (isset($option['class'])) {
                     $html .= $option['class'];
                 }
                 if ($is_install) {
                     $html .= ' btn btn-success';
                 }
                 if (!$is_install && count($return) == 0) {
                     $html .= ' btn btn-default';
                 }
                 $html .= '"';
                 if (isset($option['data-value'])) {
                     $html .= ' data-value="' . $option['data-value'] . '"';
                 }
                 if (isset($option['data-module'])) {
                     $html .= ' data-module="' . $option['data-module'] . '"';
                 }
                 if (isset($option['style'])) {
                     $html .= ' style="' . $option['style'] . '"';
                 }
                 $html .= ' href="' . htmlentities($option['href']) . (!is_null($back) ? '&back=' . urlencode($back) : '') . '" onclick="' . $option['onclick'] . '"  title="' . $option['title'] . '"><i class="icon-' . (isset($option['icon']) && $option['icon'] ? $option['icon'] : 'cog') . '"></i> ' . $option['text'] . '</a>';
                 $return[] = $html;
             } elseif ($output_type == 'select') {
                 $return .= '<option id="' . $option_name . '" data-href="' . htmlentities($option['href']) . (!is_null($back) ? '&back=' . urlencode($back) : '') . '" data-onclick="' . $option['onclick'] . '">' . $option['text'] . '</option>';
             }
         }
     }
     if ($output_type == 'select') {
         $return = '<select id="select_' . $module->name . '">' . $return . '</select>';
     }
     return $return;
 }
Example #20
0
 private function generalHook($hookname)
 {
     if (!Validate::isHookName($hookname)) {
         return '';
     }
     $html = '';
     $id_shop = (int) $this->context->shop->id;
     $layoutColumn = (int) Configuration::get('OVIC_LAYOUT_COLUMN', null, null, $id_shop);
     $curent_id_option = Configuration::get('OVIC_CURRENT_OPTION', null, null, $id_shop);
     $current_theme = Theme::getThemeInfo($this->context->shop->id_theme);
     $curent_option = new Options($curent_id_option);
     if (strtolower($curent_option->theme) != strtolower($current_theme['theme_name'])) {
         return '';
     }
     if ($curent_option && Validate::isLoadedObject($curent_option)) {
         if ($hookname == 'displayLeftColumn' || $hookname == 'displayRightColumn') {
             $module_name = '';
             if (Validate::isModuleName(Tools::getValue('module'))) {
                 $module_name = Tools::getValue('module');
             }
             if (!empty($this->context->controller->page_name)) {
                 $page_name = $this->context->controller->page_name;
             } elseif (!empty($this->context->controller->php_self)) {
                 $page_name = $this->context->controller->php_self;
             } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) {
                 $page_name = 'module-payment-submit';
             } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {
                 $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]);
             } else {
                 $page_name = Dispatcher::getInstance()->getController();
                 $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name;
             }
             if (strlen($page_name) <= 0) {
                 return '';
             }
         }
         if ($hookname == 'displayLeftColumn') {
             if ($page_name == 'index' && $layoutColumn > 1) {
                 return '';
             }
             if ($page_name == 'index') {
                 $optionModules = self::getModulesHook($curent_option->theme, $curent_option->alias, $hookname);
                 if (!is_null($optionModules['modules'])) {
                     $optionModules = Tools::jsonDecode($optionModules['modules'], true);
                 } else {
                     $optionModules = array();
                 }
             } else {
                 $optionModules = self::getSideBarModulesByPage($page_name, 'left', false);
             }
             if ($optionModules && is_array($optionModules) && sizeof($optionModules) > 0) {
                 foreach ($optionModules as $optionModule) {
                     $moduleObject = Module::getInstanceByName($optionModule[0]);
                     $html .= $this->ModuleHookExec($moduleObject, $optionModule[1]);
                 }
             }
             return $html;
         }
         if ($hookname == 'displayRightColumn') {
             if ($page_name == 'index' && $layoutColumn !== 0 && $layoutColumn !== 2) {
                 return '';
             }
             if ($page_name == 'index') {
                 $optionModules = self::getModulesHook($curent_option->theme, $curent_option->alias, $hookname);
                 if (!is_null($optionModules['modules'])) {
                     $optionModules = Tools::jsonDecode($optionModules['modules'], true);
                 } else {
                     $optionModules = array();
                 }
             } else {
                 $optionModules = self::getSideBarModulesByPage($page_name, 'right', false);
             }
             if ($optionModules && is_array($optionModules) && sizeof($optionModules) > 0) {
                 foreach ($optionModules as $optionModule) {
                     $moduleObject = Module::getInstanceByName($optionModule[0]);
                     $html .= $this->ModuleHookExec($moduleObject, $optionModule[1]);
                 }
             }
             return $html;
         }
         $optionModules = self::getModulesHook($curent_option->theme, $curent_option->alias, $hookname);
         if (!is_null($optionModules['modules'])) {
             $optionModules = Tools::jsonDecode($optionModules['modules'], true);
         } else {
             $optionModules = array();
         }
         if ($optionModules && is_array($optionModules) && sizeof($optionModules) > 0) {
             foreach ($optionModules as $optionModule) {
                 $moduleObject = Module::getInstanceByName($optionModule[0]);
                 $html .= $this->ModuleHookExec($moduleObject, $optionModule[1]);
             }
         }
     }
     return $html;
 }
Example #21
0
$render = Tools::getValue('render');
$type = Tools::getValue('type');
$option = Tools::getValue('option');
$width = (int) Tools::getValue('width', 600);
$height = (int) Tools::getValue('height', 920);
$start = (int) Tools::getValue('start', 0);
$limit = (int) Tools::getValue('limit', 40);
$sort = Tools::getValue('sort', 0);
// Should be a String. Default value is an Integer because we don't know what can be the name of the column to sort.
$dir = Tools::getValue('dir', 0);
// Should be a String : Either ASC or DESC
$id_employee = (int) Tools::getValue('id_employee');
$id_lang = (int) Tools::getValue('id_lang');
if (!isset($cookie->id_employee) || !$cookie->id_employee || $cookie->id_employee != $id_employee) {
    die(Tools::displayError());
}
if (!Validate::isModuleName($module)) {
    die(Tools::displayError());
}
if (!Tools::file_exists_cache($module_path = dirname(__FILE__) . '/../modules/' . $module . '/' . $module . '.php')) {
    die(Tools::displayError());
}
require_once $module_path;
$grid = new $module();
$grid->setEmployee($id_employee);
$grid->setLang($id_lang);
if ($option) {
    $grid->setOption($option);
}
$grid->create($render, $type, $width, $height, $start, $limit, $sort, $dir);
$grid->render();
Example #22
0
 /**
  * Find the controller and instantiate it
  */
 public function dispatch()
 {
     $controller_class = '';
     // Get current controller
     $this->getController();
     if (!$this->controller) {
         $this->controller = $this->useDefaultController();
     }
     // Dispatch with right front controller
     switch ($this->front_controller) {
         // Dispatch front office controller
         case self::FC_FRONT:
             $controllers = Dispatcher::getControllers(array(_PS_FRONT_CONTROLLER_DIR_, _PS_OVERRIDE_DIR_ . 'controllers/front/'));
             $controllers['index'] = 'IndexController';
             if (isset($controllers['auth'])) {
                 $controllers['authentication'] = $controllers['auth'];
             }
             if (isset($controllers['compare'])) {
                 $controllers['productscomparison'] = $controllers['compare'];
             }
             if (isset($controllers['contact'])) {
                 $controllers['contactform'] = $controllers['contact'];
             }
             if (!isset($controllers[strtolower($this->controller)])) {
                 $this->controller = $this->controller_not_found;
             }
             $controller_class = $controllers[strtolower($this->controller)];
             $params_hook_action_dispatcher = array('controller_type' => self::FC_FRONT, 'controller_class' => $controller_class, 'is_module' => 0);
             break;
             // Dispatch module controller for front office
         // Dispatch module controller for front office
         case self::FC_MODULE:
             $module_name = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';
             $module = Module::getInstanceByName($module_name);
             $controller_class = 'PageNotFoundController';
             if (Validate::isLoadedObject($module) && $module->active) {
                 $controllers = Dispatcher::getControllers(_PS_MODULE_DIR_ . $module_name . '/controllers/front/');
                 if (isset($controllers[strtolower($this->controller)])) {
                     include_once _PS_MODULE_DIR_ . $module_name . '/controllers/front/' . $this->controller . '.php';
                     $controller_class = $module_name . $this->controller . 'ModuleFrontController';
                 }
             }
             $params_hook_action_dispatcher = array('controller_type' => self::FC_FRONT, 'controller_class' => $controller_class, 'is_module' => 1);
             break;
             // Dispatch back office controller + module back office controller
         // Dispatch back office controller + module back office controller
         case self::FC_ADMIN:
             if ($this->use_default_controller && !Tools::getValue('token') && Validate::isLoadedObject(Context::getContext()->employee) && Context::getContext()->employee->isLoggedBack()) {
                 Tools::redirectAdmin('index.php?controller=' . $this->controller . '&token=' . Tools::getAdminTokenLite($this->controller));
             }
             $tab = Tab::getInstanceFromClassName($this->controller, Configuration::get('PS_LANG_DEFAULT'));
             $retrocompatibility_admin_tab = null;
             if ($tab->module) {
                 if (file_exists(_PS_MODULE_DIR_ . $tab->module . '/' . $tab->class_name . '.php')) {
                     $retrocompatibility_admin_tab = _PS_MODULE_DIR_ . $tab->module . '/' . $tab->class_name . '.php';
                 } else {
                     $controllers = Dispatcher::getControllers(_PS_MODULE_DIR_ . $tab->module . '/controllers/admin/');
                     if (!isset($controllers[strtolower($this->controller)])) {
                         $this->controller = $this->controller_not_found;
                         $controller_class = 'AdminNotFoundController';
                     } else {
                         // Controllers in modules can be named AdminXXX.php or AdminXXXController.php
                         include_once _PS_MODULE_DIR_ . $tab->module . '/controllers/admin/' . $controllers[strtolower($this->controller)] . '.php';
                         $controller_class = $controllers[strtolower($this->controller)] . (strpos($controllers[strtolower($this->controller)], 'Controller') ? '' : 'Controller');
                     }
                 }
                 $params_hook_action_dispatcher = array('controller_type' => self::FC_ADMIN, 'controller_class' => $controller_class, 'is_module' => 1);
             } else {
                 $controllers = Dispatcher::getControllers(array(_PS_ADMIN_DIR_ . '/tabs/', _PS_ADMIN_CONTROLLER_DIR_, _PS_OVERRIDE_DIR_ . 'controllers/admin/'));
                 if (!isset($controllers[strtolower($this->controller)])) {
                     // If this is a parent tab, load the first child
                     if (Validate::isLoadedObject($tab) && $tab->id_parent == 0 && ($tabs = Tab::getTabs(Context::getContext()->language->id, $tab->id)) && isset($tabs[0])) {
                         Tools::redirectAdmin(Context::getContext()->link->getAdminLink($tabs[0]['class_name']));
                     }
                     $this->controller = $this->controller_not_found;
                 }
                 $controller_class = $controllers[strtolower($this->controller)];
                 $params_hook_action_dispatcher = array('controller_type' => self::FC_ADMIN, 'controller_class' => $controller_class, 'is_module' => 0);
                 if (file_exists(_PS_ADMIN_DIR_ . '/tabs/' . $controller_class . '.php')) {
                     $retrocompatibility_admin_tab = _PS_ADMIN_DIR_ . '/tabs/' . $controller_class . '.php';
                 }
             }
             // @retrocompatibility with admin/tabs/ old system
             if ($retrocompatibility_admin_tab) {
                 include_once $retrocompatibility_admin_tab;
                 include_once _PS_ADMIN_DIR_ . '/functions.php';
                 runAdminTab($this->controller, !empty($_REQUEST['ajaxMode']));
                 return;
             }
             break;
         default:
             throw new PrestaShopException('Bad front controller chosen');
     }
     // Instantiate controller
     try {
         // Loading controller
         $controller = Controller::getController($controller_class);
         // Execute hook dispatcher
         if (isset($params_hook_action_dispatcher)) {
             Hook::exec('actionDispatcher', $params_hook_action_dispatcher);
         }
         // Running controller
         $controller->run();
     } catch (PrestaShopException $e) {
         $e->displayMessage();
     }
 }
Example #23
0
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
             if (!Validate::isLoadedObject($order_carrier)) {
                 $this->errors[] = Tools::displayError('The order carrier ID is invalid.');
             } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                 $this->errors[] = Tools::displayError('The tracking number is incorrect.');
             } else {
                 // update shipping number
                 // Keep these two following lines for backward compatibility, remove on 1.6 version
                 $order->shipping_number = Tools::getValue('tracking_number');
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                 if ($order_carrier->update()) {
                     // Send mail to customer
                     $customer = new Customer((int) $order->id_customer);
                     $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                     if (!Validate::isLoadedObject($customer)) {
                         throw new PrestaShopException('Can\'t load Customer object');
                     }
                     if (!Validate::isLoadedObject($carrier)) {
                         throw new PrestaShopException('Can\'t load Carrier object');
                     }
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{shipping_number}' => $order->shipping_number, '{order_name}' => $order->getUniqReference());
                     if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                         Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order, 'customer' => $customer, 'carrier' => $carrier), null, false, true, false, $order->id_shop);
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                     } else {
                         $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('The order carrier cannot be updated.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitState') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_state = new OrderState(Tools::getValue('id_order_state'));
             if (!Validate::isLoadedObject($order_state)) {
                 $this->errors[] = Tools::displayError('The new order status is invalid.');
             } else {
                 $current_order_state = $order->getCurrentOrderState();
                 if ($current_order_state->id != $order_state->id) {
                     // Create new OrderHistory
                     $history = new OrderHistory();
                     $history->id_order = $order->id;
                     $history->id_employee = (int) $this->context->employee->id;
                     $use_existings_payment = false;
                     if (!$order->hasInvoice()) {
                         $use_existings_payment = true;
                     }
                     $history->changeIdOrderState((int) $order_state->id, $order, $use_existings_payment);
                     $carrier = new Carrier($order->id_carrier, $order->id_lang);
                     $templateVars = array();
                     if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
                         $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                     }
                     // Save all changes
                     if ($history->addWithemail(true, $templateVars)) {
                         // synchronizes quantities if needed..
                         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                             foreach ($order->getProducts() as $product) {
                                 if (StockAvailable::dependsOnStock($product['product_id'])) {
                                     StockAvailable::synchronize($product['product_id'], (int) $product['id_shop']);
                                 }
                             }
                         }
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                     }
                     $this->errors[] = Tools::displayError('An error occurred while changing order status, or we were unable to send an email to the customer.');
                 } else {
                     $this->errors[] = Tools::displayError('The order has already been assigned this status.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $customer = new Customer(Tools::getValue('id_customer'));
             if (!Validate::isLoadedObject($customer)) {
                 $this->errors[] = Tools::displayError('The customer is invalid.');
             } elseif (!Tools::getValue('message')) {
                 $this->errors[] = Tools::displayError('The message cannot be blank.');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false && (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
                             $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $field);
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->errors[] = sprintf(Tools::displayError('field %1$s is too long (%2$d chars max).'), $field, $maxLength);
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $field);
                         }
                     }
                 }
                 if (!count($this->errors)) {
                     //check if a thread already exist
                     $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                     if (!$id_customer_thread) {
                         $customer_thread = new CustomerThread();
                         $customer_thread->id_contact = 0;
                         $customer_thread->id_customer = (int) $order->id_customer;
                         $customer_thread->id_shop = (int) $this->context->shop->id;
                         $customer_thread->id_order = (int) $order->id;
                         $customer_thread->id_lang = (int) $this->context->language->id;
                         $customer_thread->email = $customer->email;
                         $customer_thread->status = 'open';
                         $customer_thread->token = Tools::passwdGen(12);
                         $customer_thread->add();
                     } else {
                         $customer_thread = new CustomerThread((int) $id_customer_thread);
                     }
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = (int) $this->context->employee->id;
                     $customer_message->message = Tools::getValue('message');
                     $customer_message->private = Tools::getValue('visibility');
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving the message.');
                     } elseif ($customer_message->private) {
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
                     } else {
                         $message = $customer_message->message;
                         if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
                             $message = Tools::nl2br($customer_message->message);
                         }
                         $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => $message);
                         if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
                         }
                     }
                     $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
         if ($this->tabAccess['edit'] == '1') {
             if (is_array($_POST['partialRefundProduct'])) {
                 $amount = 0;
                 $order_detail_list = array();
                 foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
                     $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
                     if (empty($amount_detail)) {
                         $order_detail = new OrderDetail((int) $id_order_detail);
                         $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity'];
                     } else {
                         $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail);
                     }
                     $amount += $order_detail_list[$id_order_detail]['amount'];
                     $order_detail = new OrderDetail((int) $id_order_detail);
                     if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $order_detail_list[$id_order_detail]['quantity'] > 0) {
                         $this->reinjectQuantity($order_detail, $order_detail_list[$id_order_detail]['quantity']);
                     }
                 }
                 $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost'));
                 if ($shipping_cost_amount > 0) {
                     $amount += $shipping_cost_amount;
                 }
                 $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                 if (Validate::isLoadedObject($order_carrier)) {
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     if ($order_carrier->update()) {
                         $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                     }
                 }
                 if ($amount > 0) {
                     if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
                         $this->errors[] = Tools::displayError('You cannot generate a partial credit slip.');
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) {
                         $cart_rule = new CartRule();
                         $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id);
                         $languages = Language::getLanguages(false);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cart_rule->name[$language['id_lang']] = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         }
                         // Define a temporary code
                         $cart_rule->code = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         $cart_rule->quantity = 1;
                         $cart_rule->quantity_per_user = 1;
                         // Specific to the customer
                         $cart_rule->id_customer = $order->id_customer;
                         $now = time();
                         $cart_rule->date_from = date('Y-m-d H:i:s', $now);
                         $cart_rule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cart_rule->partial_use = 1;
                         $cart_rule->active = 1;
                         $cart_rule->reduction_amount = $amount;
                         $cart_rule->reduction_tax = true;
                         $cart_rule->minimum_amount_currency = $order->id_currency;
                         $cart_rule->reduction_currency = $order->id_currency;
                         if (!$cart_rule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cart_rule->name[$language['id_lang']] = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             }
                             $cart_rule->code = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             if (!$cart_rule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $customer = new Customer((int) $order->id_customer);
                                 $params['{lastname}'] = $customer->lastname;
                                 $params['{firstname}'] = $customer->firstname;
                                 $params['{id_order}'] = $order->id;
                                 $params['{order_name}'] = $order->getUniqReference();
                                 $params['{voucher_amount}'] = Tools::displayPrice($cart_rule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cart_rule->code;
                                 $customer = new Customer((int) $order->id_customer);
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('You have to enter an amount if you want to create a partial credit slip.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=30&token=' . $this->token);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The partial refund data is incorrect.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
         if ($this->tabAccess['delete'] === '1') {
             if (!Tools::isSubmit('id_order_detail') && !Tools::isSubmit('id_customization')) {
                 $this->errors[] = Tools::displayError('You must select a product.');
             } elseif (!Tools::isSubmit('cancelQuantity') && !Tools::isSubmit('cancelCustomizationQuantity')) {
                 $this->errors[] = Tools::displayError('You must enter a quantity.');
             } else {
                 $productList = Tools::getValue('id_order_detail');
                 if ($productList) {
                     $productList = array_map('intval', $productList);
                 }
                 $customizationList = Tools::getValue('id_customization');
                 if ($customizationList) {
                     $customizationList = array_map('intval', $customizationList);
                 }
                 $qtyList = Tools::getValue('cancelQuantity');
                 if ($qtyList) {
                     $qtyList = array_map('intval', $qtyList);
                 }
                 $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
                 if ($customizationQtyList) {
                     $customizationQtyList = array_map('intval', $customizationQtyList);
                 }
                 $full_product_list = $productList;
                 $full_quantity_list = $qtyList;
                 if ($customizationList) {
                     foreach ($customizationList as $key => $id_order_detail) {
                         $full_product_list[(int) $id_order_detail] = $id_order_detail;
                         if (isset($customizationQtyList[$key])) {
                             $full_quantity_list[(int) $id_order_detail] += $customizationQtyList[$key];
                         }
                     }
                 }
                 if ($productList || $customizationList) {
                     if ($productList) {
                         $id_cart = Cart::getCartIdByOrderId($order->id);
                         $customization_quantities = Customization::countQuantityByCart($id_cart);
                         foreach ($productList as $key => $id_order_detail) {
                             $qtyCancelProduct = abs($qtyList[$key]);
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             $order_detail = new OrderDetail($id_order_detail);
                             $customization_quantity = 0;
                             if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                                 $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                             }
                             if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if ($customizationList) {
                         $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             $customization_quantity = $customization_quantities[$id_customization];
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if (!count($this->errors) && $productList) {
                         foreach ($productList as $key => $id_order_detail) {
                             $qty_cancel_product = abs($qtyList[$key]);
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $qty_cancel_product > 0) {
                                 $this->reinjectQuantity($order_detail, $qty_cancel_product);
                             }
                             // Delete product
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->deleteProduct($order, $order_detail, $qty_cancel_product)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
                             }
                             // Update weight SUM
                             $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                             if (Validate::isLoadedObject($order_carrier)) {
                                 $order_carrier->weight = (double) $order->getTotalWeight();
                                 if ($order_carrier->update()) {
                                     $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                                 }
                             }
                             Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => (int) $id_order_detail), null, false, true, false, $order->id_shop);
                         }
                     }
                     if (!count($this->errors) && $customizationList) {
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete product customization.') . ' ' . $id_customization;
                             }
                         }
                     }
                     // E-mail params
                     if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
                         $customer = new Customer((int) $order->id_customer);
                         $params['{lastname}'] = $customer->lastname;
                         $params['{firstname}'] = $customer->firstname;
                         $params['{id_order}'] = $order->id;
                         $params['{order_name}'] = $order->getUniqReference();
                     }
                     // Generate credit slip
                     if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
                         if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
                             $this->errors[] = Tools::displayError('A credit slip cannot be generated. ');
                         } else {
                             Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list), null, false, true, false, $order->id_shop);
                             @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                         }
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
                         $cartrule = new CartRule();
                         $languages = Language::getLanguages($order);
                         $cartrule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cartrule->name[$language['id_lang']] = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         }
                         // Define a temporary code
                         $cartrule->code = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         $cartrule->quantity = 1;
                         $cartrule->quantity_per_user = 1;
                         // Specific to the customer
                         $cartrule->id_customer = $order->id_customer;
                         $now = time();
                         $cartrule->date_from = date('Y-m-d H:i:s', $now);
                         $cartrule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cartrule->active = 1;
                         $products = $order->getProducts(false, $full_product_list, $full_quantity_list);
                         $total = 0;
                         foreach ($products as $product) {
                             $total += $product['unit_price_tax_incl'] * $product['product_quantity'];
                         }
                         if (Tools::isSubmit('shippingBack')) {
                             $total += $order->total_shipping;
                         }
                         $cartrule->reduction_amount = $total;
                         $cartrule->reduction_tax = true;
                         $cartrule->minimum_amount_currency = $order->id_currency;
                         $cartrule->reduction_currency = $order->id_currency;
                         if (!$cartrule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cartrule->name[$language['id_lang']] = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             }
                             $cartrule->code = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             if (!$cartrule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $params['{voucher_amount}'] = Tools::displayPrice($cartrule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cartrule->code;
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('No product or quantity has been selected.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=31&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('messageReaded')) {
         Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
     } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
             $currency = new Currency(Tools::getValue('payment_currency'));
             $order_has_invoice = $order->hasInvoice();
             if ($order_has_invoice) {
                 $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
             } else {
                 $order_invoice = null;
             }
             if (!Validate::isLoadedObject($order)) {
                 $this->errors[] = Tools::displayError('The order cannot be found');
             } elseif (!Validate::isNegativePrice($amount) || !(double) $amount) {
                 $this->errors[] = Tools::displayError('The amount is invalid.');
             } elseif (!Validate::isGenericName(Tools::getValue('payment_method'))) {
                 $this->errors[] = Tools::displayError('The selected payment method is invalid.');
             } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
                 $this->errors[] = Tools::displayError('The transaction ID is invalid.');
             } elseif (!Validate::isLoadedObject($currency)) {
                 $this->errors[] = Tools::displayError('The selected currency is invalid.');
             } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
                 $this->errors[] = Tools::displayError('The invoice is invalid.');
             } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
                 $this->errors[] = Tools::displayError('The date is invalid');
             } else {
                 if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
                     $this->errors[] = Tools::displayError('An error occurred during payment.');
                 } else {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitEditNote')) {
         $note = Tools::getValue('note');
         $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
         if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
             if ($this->tabAccess['edit'] === '1') {
                 $order_invoice->note = $note;
                 if ($order_invoice->save()) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('The invoice note was not saved.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             $this->errors[] = Tools::displayError('The invoice for edit note was unable to load. ');
         }
     } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             $payment_module = Module::getInstanceByName($module_name);
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $employee = new Employee((int) Context::getContext()->cookie->id_employee);
             $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
             if ($payment_module->currentOrder) {
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $address = new Address(Tools::getValue('id_address'));
             if (Validate::isLoadedObject($address)) {
                 // Update the address on order
                 if (Tools::isSubmit('submitAddressShipping')) {
                     $order->id_address_delivery = $address->id;
                 } elseif (Tools::isSubmit('submitAddressInvoice')) {
                     $order->id_address_invoice = $address->id;
                 }
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('This address can\'t be loaded');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
                 $old_currency = new Currency($order->id_currency);
                 $currency = new Currency(Tools::getValue('new_currency'));
                 if (!Validate::isLoadedObject($currency)) {
                     throw new PrestaShopException('Can\'t load Currency object');
                 }
                 // Update order detail amount
                 foreach ($order->getOrderDetailList() as $row) {
                     $order_detail = new OrderDetail($row['id_order_detail']);
                     $fields = array('ecotax', 'product_price', 'reduction_amount', 'total_shipping_price_tax_excl', 'total_shipping_price_tax_incl', 'total_price_tax_incl', 'total_price_tax_excl', 'product_quantity_discount', 'purchase_supplier_price', 'reduction_amount', 'reduction_amount_tax_incl', 'reduction_amount_tax_excl', 'unit_price_tax_incl', 'unit_price_tax_excl', 'original_product_price');
                     foreach ($fields as $field) {
                         $order_detail->{$field} = Tools::convertPriceFull($order_detail->{$field}, $old_currency, $currency);
                     }
                     $order_detail->update();
                     $order_detail->updateTaxAmount($order);
                 }
                 $id_order_carrier = (int) $order->getIdOrderCarrier();
                 if ($id_order_carrier) {
                     $order_carrier = $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                     $order_carrier->shipping_cost_tax_excl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
                     $order_carrier->shipping_cost_tax_incl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
                     $order_carrier->update();
                 }
                 // Update order && order_invoice amount
                 $fields = array('total_discounts', 'total_discounts_tax_incl', 'total_discounts_tax_excl', 'total_discount_tax_excl', 'total_discount_tax_incl', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real', 'total_products', 'total_products_wt', 'total_shipping', 'total_shipping_tax_incl', 'total_shipping_tax_excl', 'total_wrapping', 'total_wrapping_tax_incl', 'total_wrapping_tax_excl');
                 $invoices = $order->getInvoicesCollection();
                 if ($invoices) {
                     foreach ($invoices as $invoice) {
                         foreach ($fields as $field) {
                             if (isset($invoice->{$field})) {
                                 $invoice->{$field} = Tools::convertPriceFull($invoice->{$field}, $old_currency, $currency);
                             }
                         }
                         $invoice->save();
                     }
                 }
                 foreach ($fields as $field) {
                     if (isset($order->{$field})) {
                         $order->{$field} = Tools::convertPriceFull($order->{$field}, $old_currency, $currency);
                     }
                 }
                 // Update currency in order
                 $order->id_currency = $currency->id;
                 // Update exchange rate
                 $order->conversion_rate = (double) $currency->conversion_rate;
                 $order->update();
             } else {
                 $this->errors[] = Tools::displayError('You cannot change the currency.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
         if (!Configuration::get('PS_INVOICE', null, null, $order->id_shop)) {
             $this->errors[] = Tools::displayError('Invoice management has been disabled.');
         } elseif ($order->hasInvoice()) {
             $this->errors[] = Tools::displayError('This order already has an invoice.');
         } else {
             $order->setInvoice(true);
             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
         }
     } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
             if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
                 if ($order_cart_rule->id_order_invoice) {
                     $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
                     if (!Validate::isLoadedObject($order_invoice)) {
                         throw new PrestaShopException('Can\'t load Order Invoice object');
                     }
                     // Update amounts of Order Invoice
                     $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
                     $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
                     $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                     $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
                     // Update Order Invoice
                     $order_invoice->update();
                 }
                 // Update amounts of order
                 $order->total_discounts -= $order_cart_rule->value;
                 $order->total_discounts_tax_incl -= $order_cart_rule->value;
                 $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
                 $order->total_paid += $order_cart_rule->value;
                 $order->total_paid_tax_incl += $order_cart_rule->value;
                 $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                 // Delete Order Cart Rule and update Order
                 $order_cart_rule->delete();
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('You cannot edit this cart rule.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitNewVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Tools::getValue('discount_name')) {
                 $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount.');
             } else {
                 if ($order->hasInvoice()) {
                     // If the discount is for only one invoice
                     if (!Tools::isSubmit('discount_all_invoices')) {
                         $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
                         if (!Validate::isLoadedObject($order_invoice)) {
                             throw new PrestaShopException('Can\'t load Order Invoice object');
                         }
                     }
                 }
                 $cart_rules = array();
                 $discount_value = (double) str_replace(',', '.', Tools::getValue('discount_value'));
                 switch (Tools::getValue('discount_type')) {
                     // Percent type
                     case 1:
                         if ($discount_value < 100) {
                             if (isset($order_invoice)) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             } elseif ($order->hasInvoice()) {
                                 $order_invoices_collection = $order->getInvoicesCollection();
                                 foreach ($order_invoices_collection as $order_invoice) {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * $discount_value / 100, 2);
                             }
                         } else {
                             $this->errors[] = Tools::displayError('The discount value is invalid.');
                         }
                         break;
                         // Amount type
                     // Amount type
                     case 2:
                         if (isset($order_invoice)) {
                             if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.');
                             } else {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                     $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop) . ')';
                                 } else {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             }
                         } else {
                             if ($discount_value > $order->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order total.');
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                             }
                         }
                         break;
                         // Free shipping type
                     // Free shipping type
                     case 3:
                         if (isset($order_invoice)) {
                             if ($order_invoice->total_shipping_tax_incl > 0) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($order_invoice->total_shipping_tax_incl <= 0) {
                                     continue;
                                 }
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } else {
                             $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
                             $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
                         }
                         break;
                     default:
                         $this->errors[] = Tools::displayError('The discount type is invalid.');
                 }
                 $res = true;
                 foreach ($cart_rules as &$cart_rule) {
                     $cartRuleObj = new CartRule();
                     $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
                     $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
                     $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
                     $cartRuleObj->quantity = 0;
                     $cartRuleObj->quantity_per_user = 1;
                     if (Tools::getValue('discount_type') == 1) {
                         $cartRuleObj->reduction_percent = $discount_value;
                     } elseif (Tools::getValue('discount_type') == 2) {
                         $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
                     } elseif (Tools::getValue('discount_type') == 3) {
                         $cartRuleObj->free_shipping = 1;
                     }
                     $cartRuleObj->active = 0;
                     if ($res = $cartRuleObj->add()) {
                         $cart_rule['id'] = $cartRuleObj->id;
                     } else {
                         break;
                     }
                 }
                 if ($res) {
                     foreach ($cart_rules as $id_order_invoice => $cart_rule) {
                         // Create OrderCartRule
                         $order_cart_rule = new OrderCartRule();
                         $order_cart_rule->id_order = $order->id;
                         $order_cart_rule->id_cart_rule = $cart_rule['id'];
                         $order_cart_rule->id_order_invoice = $id_order_invoice;
                         $order_cart_rule->name = Tools::getValue('discount_name');
                         $order_cart_rule->value = $cart_rule['value_tax_incl'];
                         $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
                         $res &= $order_cart_rule->add();
                         $order->total_discounts += $order_cart_rule->value;
                         $order->total_discounts_tax_incl += $order_cart_rule->value;
                         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
                         $order->total_paid -= $order_cart_rule->value;
                         $order->total_paid_tax_incl -= $order_cart_rule->value;
                         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
                     }
                     // Update Order
                     $res &= $order->update();
                 }
                 if ($res) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred during the OrderCartRule creation');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     }
     parent::postProcess();
 }
Example #24
0
 public function hookdisplayCategorySlider($params)
 {
     $module_name = '';
     if (Validate::isModuleName(Tools::getValue('module'))) {
         $module_name = Tools::getValue('module');
     }
     //if (!$this->isCached('categoryslider.tpl', $this->getCacheId()))
     if (!empty($this->context->controller->php_self)) {
         $page_name = $this->context->controller->php_self;
     } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) {
         $page_name = 'module-payment-submit';
     } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {
         $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]);
     } else {
         $page_name = Dispatcher::getInstance()->getController();
         $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name;
     }
     if (strlen($page_name) <= 0) {
         return '';
     }
     if ($page_name == 'category') {
         $id_category = (int) Tools::getValue('id_category');
     } elseif ($page_name == 'product') {
         $id_product = (int) Tools::getValue('id_product');
         $product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);
         $id_category = $product->id_category_default;
     } else {
         return '';
     }
     $slider = array('width' => Configuration::get('CATESLIDER_WIDTH'), 'height' => Configuration::get('CATESLIDER_HEIGHT'), 'speed' => Configuration::get('CATESLIDER_SPEED'), 'pause' => Configuration::get('CATESLIDER_PAUSE'), 'loop' => Configuration::get('CATESLIDER_LOOP'));
     if (isset($id_category) && $id_category && Validate::isUnsignedId($id_category)) {
         $slides = $this->getSlides(true, $id_category);
     } else {
         return '';
     }
     $check_slide = true;
     if (!$slides && count($slides) < 1) {
         $check_slide = false;
     }
     $this->smarty->assign('categoryslider_slides', $slides);
     $this->smarty->assign('categoryslider', $slider);
     if (!$check_slide) {
         return '';
     }
     // Check if not a mobile theme
     if ($this->context->getMobileDevice() != false) {
         return false;
     }
     return $this->display(__FILE__, 'categoryslider.tpl');
 }
Example #25
0
 public static function getModulesDirOnDisk()
 {
     $moduleList = array();
     $modules = scandir(_PS_MODULE_DIR_);
     foreach ($modules as $name) {
         if (is_dir(_PS_MODULE_DIR_ . $name) && Tools::file_exists_cache(_PS_MODULE_DIR_ . $name . '/' . $name . '.php')) {
             if (!Validate::isModuleName($name)) {
                 die(Tools::displayError() . ' (Module ' . $name . ')');
             }
             $moduleList[] = $name;
         }
     }
     return $moduleList;
 }
Example #26
0
 /**
 * Show correct re_write url on BlockLanguage module
 * http://ps_1609_test/vn/index.php?controller=blog?id=9&fc=module&module=leoblog
 * 	$default_rewrite = array(
  '1' => 'http://ps_1609_test/en/blog/lang-en-b9.html',
  '2' => 'http://ps_1609_test/vn/blog/lang-vn-b9.html',
  '3' => 'http://ps_1609_test/cb/blog/lang-cb-b9.html',
  );
 * 
 */
 public function hookDisplayBanner()
 {
     if (Module::isEnabled('blocklanguages')) {
         $default_rewrite = array();
         $module = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';
         $controller = Tools::getValue('controller');
         if ($module == 'leoblog' && $controller == 'blog' && ($id_blog = (int) Tools::getValue('id'))) {
             $languages = Language::getLanguages(true, $this->context->shop->id);
             if (!count($languages)) {
                 return false;
             }
             $link = new Link();
             foreach ($languages as $lang) {
                 $config = LeoBlogConfig::getInstance();
                 $config->cur_id_lang = $lang['id_lang'];
                 $cur_key = 'link_rewrite' . '_' . Context::getContext()->language->id;
                 $cur_prefix = '/' . ($config->cur_prefix_rewrite = $config->get($cur_key, 'blog') . '/');
                 $other_key = 'link_rewrite' . '_' . $lang['id_lang'];
                 $other_prefix = '/' . ($config->cur_prefix_rewrite = $config->get($other_key, 'blog') . '/');
                 $blog = new LeoBlogBlog($id_blog, $lang['id_lang']);
                 $temp_link = $link->getModuleLink($module, $controller, array('id' => $id_blog, 'rewrite' => $blog->link_rewrite), null, $lang['id_lang']);
                 $default_rewrite[$lang['id_lang']] = str_replace($cur_prefix, $other_prefix, $temp_link);
                 //					$default_rewrite[$lang['id_lang']] = $link->getModuleLink($module, $controller, array('id'=>$id_blog, 'rewrite'=>$blog->link_rewrite), null, $lang['id_lang']);
             }
         } elseif ($module == 'leoblog' && $controller == 'category' && ($id_blog = (int) Tools::getValue('id'))) {
             $languages = Language::getLanguages(true, $this->context->shop->id);
             if (!count($languages)) {
                 return false;
             }
             $link = new Link();
             foreach ($languages as $lang) {
                 $config = LeoBlogConfig::getInstance();
                 $config->cur_id_lang = $lang['id_lang'];
                 $cur_key = 'link_rewrite' . '_' . Context::getContext()->language->id;
                 $cur_prefix = '/' . ($config->cur_prefix_rewrite = $config->get($cur_key, 'blog') . '/');
                 $other_key = 'link_rewrite' . '_' . $lang['id_lang'];
                 $other_prefix = '/' . ($config->cur_prefix_rewrite = $config->get($other_key, 'blog') . '/');
                 $blog = new Leoblogcat($id_blog, $lang['id_lang']);
                 $temp_link = $link->getModuleLink($module, $controller, array('id' => $id_blog, 'rewrite' => $blog->link_rewrite), null, $lang['id_lang']);
                 $default_rewrite[$lang['id_lang']] = str_replace($cur_prefix, $other_prefix, $temp_link);
                 //					$default_rewrite[$lang['id_lang']] = $link->getModuleLink($module, $controller, array('id'=>$id_blog, 'rewrite'=>$blog->link_rewrite), null, $lang['id_lang']);
             }
         } elseif ($module == 'leoblog' && $controller == 'list') {
             $languages = Language::getLanguages(true, $this->context->shop->id);
             if (!count($languages)) {
                 return false;
             }
             $link = new Link();
             foreach ($languages as $lang) {
                 $config = LeoBlogConfig::getInstance();
                 $config->cur_id_lang = $lang['id_lang'];
                 $cur_key = 'link_rewrite' . '_' . Context::getContext()->language->id;
                 $cur_prefix = '/' . ($config->cur_prefix_rewrite = $config->get($cur_key, 'blog') . '');
                 $other_key = 'link_rewrite' . '_' . $lang['id_lang'];
                 $other_prefix = '/' . ($config->cur_prefix_rewrite = $config->get($other_key, 'blog') . '');
                 $temp_link = $link->getModuleLink($module, $controller, array(), null, $lang['id_lang']);
                 $default_rewrite[$lang['id_lang']] = str_replace($cur_prefix, $other_prefix, $temp_link);
             }
         }
         $this->context->smarty->assign('lang_leo_rewrite_urls', $default_rewrite);
     }
 }
 public function postProcess()
 {
     $this->context = Context::getContext();
     $this->query = trim(Tools::getValue('bo_query'));
     $searchType = (int) Tools::getValue('bo_search_type');
     /* Handle empty search field */
     if (!empty($this->query)) {
         if (!$searchType && strlen($this->query) > 1) {
             $this->searchFeatures();
         }
         /* Product research */
         if (!$searchType || $searchType == 1) {
             /* Handle product ID */
             if ($searchType == 1 && (int) $this->query && Validate::isUnsignedInt((int) $this->query)) {
                 if (($product = new Product($this->query)) && Validate::isLoadedObject($product)) {
                     Tools::redirectAdmin('index.php?tab=AdminProducts&id_product=' . (int) $product->id . '&addproduct' . '&token=' . Tools::getAdminTokenLite('AdminProducts'));
                 }
             }
             /* Normal catalog search */
             $this->searchCatalog();
         }
         /* Customer */
         if (!$searchType || $searchType == 2 || $searchType == 6) {
             if (!$searchType || $searchType == 2) {
                 /* Handle customer ID */
                 if ($searchType && (int) $this->query && Validate::isUnsignedInt((int) $this->query)) {
                     if (($customer = new Customer($this->query)) && Validate::isLoadedObject($customer)) {
                         Tools::redirectAdmin('index.php?tab=AdminCustomers&id_customer=' . (int) $customer->id . '&viewcustomer' . '&token=' . Tools::getAdminToken('AdminCustomers' . (int) Tab::getIdFromClassName('AdminCustomers') . (int) $this->context->employee->id));
                     }
                 }
                 /* Normal customer search */
                 $this->searchCustomer();
             }
             if ($searchType == 6) {
                 $this->searchIP();
             }
         }
         /* Order */
         if (!$searchType || $searchType == 3) {
             if (Validate::isUnsignedInt(trim($this->query)) && (int) $this->query && ($order = new Order((int) $this->query)) && Validate::isLoadedObject($order)) {
                 if ($searchType == 3) {
                     Tools::redirectAdmin('index.php?tab=AdminOrders&id_order=' . (int) $order->id . '&vieworder' . '&token=' . Tools::getAdminTokenLite('AdminOrders'));
                 } else {
                     $row = get_object_vars($order);
                     $row['id_order'] = $row['id'];
                     $customer = $order->getCustomer();
                     $row['customer'] = $customer->firstname . ' ' . $customer->lastname;
                     $order_state = $order->getCurrentOrderState();
                     $row['osname'] = $order_state->name[$this->context->language->id];
                     $this->_list['orders'] = array($row);
                 }
             } else {
                 $orders = Order::getByReference($this->query);
                 $nb_orders = count($orders);
                 if ($nb_orders == 1 && $searchType == 3) {
                     Tools::redirectAdmin('index.php?tab=AdminOrders&id_order=' . (int) $orders[0]->id . '&vieworder' . '&token=' . Tools::getAdminTokenLite('AdminOrders'));
                 } elseif ($nb_orders) {
                     $this->_list['orders'] = array();
                     foreach ($orders as $order) {
                         $row = get_object_vars($order);
                         $row['id_order'] = $row['id'];
                         $customer = $order->getCustomer();
                         $row['customer'] = $customer->firstname . ' ' . $customer->lastname;
                         $order_state = $order->getCurrentOrderState();
                         $row['osname'] = $order_state->name[$this->context->language->id];
                         $this->_list['orders'][] = $row;
                     }
                 } elseif ($searchType == 3) {
                     $this->errors[] = Tools::displayError('No order was found with this ID:') . ' ' . Tools::htmlentitiesUTF8($this->query);
                 }
             }
         }
         /* Invoices */
         if ($searchType == 4) {
             if (Validate::isOrderInvoiceNumber($this->query) && ($invoice = OrderInvoice::getInvoiceByNumber($this->query))) {
                 Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf') . '&submitAction=generateInvoicePDF&id_order=' . (int) $invoice->id_order);
             }
             $this->errors[] = Tools::displayError('No invoice was found with this ID:') . ' ' . Tools::htmlentitiesUTF8($this->query);
         }
         /* Cart */
         if ($searchType == 5) {
             if ((int) $this->query && Validate::isUnsignedInt((int) $this->query) && ($cart = new Cart($this->query)) && Validate::isLoadedObject($cart)) {
                 Tools::redirectAdmin('index.php?tab=AdminCarts&id_cart=' . (int) $cart->id . '&viewcart' . '&token=' . Tools::getAdminToken('AdminCarts' . (int) Tab::getIdFromClassName('AdminCarts') . (int) $this->context->employee->id));
             }
             $this->errors[] = Tools::displayError('No cart was found with this ID:') . ' ' . Tools::htmlentitiesUTF8($this->query);
         }
         /* IP */
         // 6 - but it is included in the customer block
         /* Module search */
         if (!$searchType || $searchType == 7) {
             /* Handle module name */
             if ($searchType == 7 && Validate::isModuleName($this->query) and ($module = Module::getInstanceByName($this->query)) && Validate::isLoadedObject($module)) {
                 Tools::redirectAdmin('index.php?tab=AdminModules&tab_module=' . $module->tab . '&module_name=' . $module->name . '&anchor=' . ucfirst($module->name) . '&token=' . Tools::getAdminTokenLite('AdminModules'));
             }
             /* Normal catalog search */
             $this->searchModule();
         }
     }
     $this->display = 'view';
 }
Example #28
0
 public function getPageName()
 {
     // Are we in a payment module
     $module_name = '';
     if (Validate::isModuleName(Tools::getValue('module'))) {
         $module_name = Tools::getValue('module');
     }
     if (!empty($this->page_name)) {
         $page_name = $this->page_name;
     } elseif (!empty($this->php_self)) {
         $page_name = $this->php_self;
     } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) {
         $page_name = 'module-payment-submit';
     } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {
         // @retrocompatibility Are we in a module ?
         $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]);
     } else {
         $page_name = Dispatcher::getInstance()->getController();
         $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name;
     }
     return $page_name;
 }
Example #29
0
 public function init()
 {
     /*
      * Globals are DEPRECATED as of version 1.5.
      * Use the Context to access objects instead.
      * Example: $this->context->cart
      */
     global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;
     if (self::$initialized) {
         return;
     }
     self::$initialized = true;
     parent::init();
     // If current URL use SSL, set it true (used a lot for module redirect)
     if (Tools::usingSecureMode()) {
         $useSSL = true;
     }
     // For compatibility with globals, DEPRECATED as of version 1.5
     $css_files = $this->css_files;
     $js_files = $this->js_files;
     // If we call a SSL controller without SSL or a non SSL controller with SSL, we redirect with the right protocol
     if (Configuration::get('PS_SSL_ENABLED') && $_SERVER['REQUEST_METHOD'] != 'POST' && $this->ssl != Tools::usingSecureMode()) {
         header('HTTP/1.1 301 Moved Permanently');
         header('Cache-Control: no-cache');
         if ($this->ssl) {
             header('Location: ' . Tools::getShopDomainSsl(true) . $_SERVER['REQUEST_URI']);
         } else {
             header('Location: ' . Tools::getShopDomain(true) . $_SERVER['REQUEST_URI']);
         }
         exit;
     }
     if ($this->ajax) {
         $this->display_header = false;
         $this->display_footer = false;
     }
     // if account created with the 2 steps register process, remove 'accoun_created' from cookie
     if (isset($this->context->cookie->account_created)) {
         $this->context->smarty->assign('account_created', 1);
         unset($this->context->cookie->account_created);
     }
     ob_start();
     // Init cookie language
     // @TODO This method must be moved into switchLanguage
     Tools::setCookieLanguage($this->context->cookie);
     $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://';
     $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false;
     $protocol_content = $useSSL ? 'https://' : 'http://';
     $link = new Link($protocol_link, $protocol_content);
     $this->context->link = $link;
     if ($id_cart = (int) $this->recoverCart()) {
         $this->context->cookie->id_cart = (int) $id_cart;
     }
     if ($this->auth && !$this->context->customer->isLogged($this->guestAllowed)) {
         Tools::redirect('index.php?controller=authentication' . ($this->authRedirection ? '&back=' . $this->authRedirection : ''));
     }
     /* Theme is missing */
     if (!is_dir(_PS_THEME_DIR_)) {
         throw new PrestaShopException(sprintf(Tools::displayError('Current theme unavailable "%s". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\'))));
     }
     if (Configuration::get('PS_GEOLOCATION_ENABLED')) {
         if (($newDefault = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($newDefault)) {
             $this->context->country = $newDefault;
         }
     }
     $currency = Tools::setCurrency($this->context->cookie);
     if (isset($_GET['logout']) || $this->context->customer->logged && Customer::isBanned($this->context->customer->id)) {
         $this->context->customer->logout();
         Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     } elseif (isset($_GET['mylogout'])) {
         $this->context->customer->mylogout();
         Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     }
     /* Cart already exists */
     if ((int) $this->context->cookie->id_cart) {
         $cart = new Cart($this->context->cookie->id_cart);
         if ($cart->OrderExists()) {
             unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);
             $this->context->cookie->check_cgv = false;
         } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && $cart->nbProducts() && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 && !FrontController::isInWhitelistForGeolocation() && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {
             unset($this->context->cookie->id_cart, $cart);
         } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {
             if ($this->context->cookie->id_customer) {
                 $cart->id_customer = (int) $this->context->cookie->id_customer;
             }
             $cart->id_lang = (int) $this->context->cookie->id_lang;
             $cart->id_currency = (int) $currency->id;
             $cart->update();
         }
         /* Select an address if not set */
         if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 || !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {
             $to_update = false;
             if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {
                 $to_update = true;
                 $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             }
             if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {
                 $to_update = true;
                 $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             }
             if ($to_update) {
                 $cart->update();
             }
         }
     }
     if (!isset($cart) || !$cart->id) {
         $cart = new Cart();
         $cart->id_lang = (int) $this->context->cookie->id_lang;
         $cart->id_currency = (int) $this->context->cookie->id_currency;
         $cart->id_guest = (int) $this->context->cookie->id_guest;
         $cart->id_shop_group = (int) $this->context->shop->id_shop_group;
         $cart->id_shop = $this->context->shop->id;
         if ($this->context->cookie->id_customer) {
             $cart->id_customer = (int) $this->context->cookie->id_customer;
             $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             $cart->id_address_invoice = $cart->id_address_delivery;
         } else {
             $cart->id_address_delivery = 0;
             $cart->id_address_invoice = 0;
         }
         // Needed if the merchant want to give a free product to every visitors
         $this->context->cart = $cart;
         CartRule::autoAddToCart($this->context);
     } else {
         $this->context->cart = $cart;
     }
     /* get page name to display it in body id */
     // Are we in a payment module
     $module_name = '';
     if (Validate::isModuleName(Tools::getValue('module'))) {
         $module_name = Tools::getValue('module');
     }
     if (!empty($this->page_name)) {
         $page_name = $this->page_name;
     } elseif (!empty($this->php_self)) {
         $page_name = $this->php_self;
     } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) {
         $page_name = 'module-payment-submit';
     } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {
         $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]);
     } else {
         $page_name = Dispatcher::getInstance()->getController();
         $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name;
     }
     $this->context->smarty->assign(Meta::getMetaTags($this->context->language->id, $page_name));
     $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
     /* Breadcrumb */
     $navigationPipe = Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>';
     $this->context->smarty->assign('navigationPipe', $navigationPipe);
     // Automatically redirect to the canonical URL if needed
     if (!empty($this->php_self) && !Tools::getValue('ajax')) {
         $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));
     }
     Product::initPricesComputation();
     $display_tax_label = $this->context->country->display_tax_label;
     if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {
         $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $country = new Country((int) $infos['id_country']);
         $this->context->country = $country;
         if (Validate::isLoadedObject($country)) {
             $display_tax_label = $country->display_tax_label;
         }
     }
     $languages = Language::getLanguages(true, $this->context->shop->id);
     $meta_language = array();
     foreach ($languages as $lang) {
         $meta_language[] = $lang['iso_code'];
     }
     $compared_products = array();
     if (Configuration::get('PS_COMPARATOR_MAX_ITEM') && isset($this->context->cookie->id_compare)) {
         $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
     }
     $this->context->smarty->assign(array('mobile_device' => $this->context->getMobileDevice(), 'link' => $link, 'cart' => $cart, 'currency' => $currency, 'cookie' => $this->context->cookie, 'page_name' => $page_name, 'hide_left_column' => !$this->display_column_left, 'hide_right_column' => !$this->display_column_right, 'base_dir' => _PS_BASE_URL_ . __PS_BASE_URI__, 'base_dir_ssl' => $protocol_link . Tools::getShopDomainSsl() . __PS_BASE_URI__, 'content_dir' => $protocol_content . Tools::getHttpHost() . __PS_BASE_URI__, 'base_uri' => $protocol_content . Tools::getHttpHost() . __PS_BASE_URI__ . (!Configuration::get('PS_REWRITING_SETTINGS') ? 'index.php' : ''), 'tpl_dir' => _PS_THEME_DIR_, 'modules_dir' => _MODULE_DIR_, 'mail_dir' => _MAIL_DIR_, 'lang_iso' => $this->context->language->iso_code, 'come_from' => Tools::getHttpHost(true, true) . Tools::htmlentitiesUTF8(str_replace(array('\'', '\\'), '', urldecode($_SERVER['REQUEST_URI']))), 'cart_qties' => (int) $cart->nbProducts(), 'currencies' => Currency::getCurrencies(), 'languages' => $languages, 'meta_language' => implode(',', $meta_language), 'priceDisplay' => Product::getTaxCalculationMethod((int) $this->context->cookie->id_customer), 'is_logged' => (bool) $this->context->customer->isLogged(), 'is_guest' => (bool) $this->context->customer->isGuest(), 'add_prod_display' => (int) Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'shop_name' => Configuration::get('PS_SHOP_NAME'), 'roundMode' => (int) Configuration::get('PS_PRICE_ROUND_MODE'), 'use_taxes' => (int) Configuration::get('PS_TAX'), 'show_taxes' => (int) (Configuration::get('PS_TAX_DISPLAY') == 1 && (int) Configuration::get('PS_TAX')), 'display_tax_label' => (bool) $display_tax_label, 'vat_management' => (int) Configuration::get('VATNUMBER_MANAGEMENT'), 'opc' => (bool) Configuration::get('PS_ORDER_PROCESS_TYPE'), 'PS_CATALOG_MODE' => (bool) Configuration::get('PS_CATALOG_MODE') || !(bool) Group::getCurrent()->show_prices, 'b2b_enable' => (bool) Configuration::get('PS_B2B_ENABLE'), 'request' => $link->getPaginationLink(false, false, false, true), 'PS_STOCK_MANAGEMENT' => Configuration::get('PS_STOCK_MANAGEMENT'), 'quick_view' => (bool) Configuration::get('PS_QUICK_VIEW'), 'shop_phone' => Configuration::get('PS_SHOP_PHONE'), 'compared_products' => is_array($compared_products) ? $compared_products : array(), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     // Add the tpl files directory for mobile
     if ($this->useMobileTheme()) {
         $this->context->smarty->assign(array('tpl_mobile_uri' => _PS_THEME_MOBILE_DIR_));
     }
     // Deprecated
     $this->context->smarty->assign(array('id_currency_cookie' => (int) $currency->id, 'logged' => $this->context->customer->isLogged(), 'customerName' => $this->context->customer->logged ? $this->context->cookie->customer_firstname . ' ' . $this->context->cookie->customer_lastname : false));
     $assign_array = array('img_ps_dir' => _PS_IMG_, 'img_cat_dir' => _THEME_CAT_DIR_, 'img_lang_dir' => _THEME_LANG_DIR_, 'img_prod_dir' => _THEME_PROD_DIR_, 'img_manu_dir' => _THEME_MANU_DIR_, 'img_sup_dir' => _THEME_SUP_DIR_, 'img_ship_dir' => _THEME_SHIP_DIR_, 'img_store_dir' => _THEME_STORE_DIR_, 'img_col_dir' => _THEME_COL_DIR_, 'img_dir' => _THEME_IMG_DIR_, 'css_dir' => _THEME_CSS_DIR_, 'js_dir' => _THEME_JS_DIR_, 'pic_dir' => _THEME_PROD_PIC_DIR_);
     // Add the images directory for mobile
     if ($this->useMobileTheme()) {
         $assign_array['img_mobile_dir'] = _THEME_MOBILE_IMG_DIR_;
     }
     // Add the CSS directory for mobile
     if ($this->useMobileTheme()) {
         $assign_array['css_mobile_dir'] = _THEME_MOBILE_CSS_DIR_;
     }
     foreach ($assign_array as $assign_key => $assign_value) {
         if (substr($assign_value, 0, 1) == '/' || $protocol_content == 'https://') {
             $this->context->smarty->assign($assign_key, $protocol_content . Tools::getMediaServer($assign_value) . $assign_value);
         } else {
             $this->context->smarty->assign($assign_key, $assign_value);
         }
     }
     /*
      * These shortcuts are DEPRECATED as of version 1.5.
      * Use the Context to access objects instead.
      * Example: $this->context->cart
      */
     self::$cookie = $this->context->cookie;
     self::$cart = $cart;
     self::$smarty = $this->context->smarty;
     self::$link = $link;
     $defaultCountry = $this->context->country;
     $this->displayMaintenancePage();
     if ($this->restrictedCountry) {
         $this->displayRestrictedCountryPage();
     }
     if (Tools::isSubmit('live_edit') && !$this->checkLiveEditAccess()) {
         Tools::redirect('index.php?controller=404');
     }
     $this->iso = $iso;
     $this->context->cart = $cart;
     $this->context->currency = $currency;
 }
Example #30
0
 /**
  * Get collection from module name
  * @static
  * @param $module string Module name
  * @param null $id_lang integer Language ID
  * @return array|Collection Collection of tabs (or empty array)
  */
 public static function getCollectionFromModule($module, $id_lang = null)
 {
     if (is_null($id_lang)) {
         $id_lang = Context::getContext()->language->id;
     }
     if (!Validate::isModuleName($module)) {
         return array();
     }
     $tabs = new Collection('Tab', (int) $id_lang);
     $tabs->where('module', '=', $module);
     return $tabs;
 }