protected function setUp()
 {
     parent::setUp();
     \ContextCore::getContext()->employee = new \Employee(1);
     $this->moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $this->moduleManager = $this->moduleManagerBuilder->build();
     $this->moduleNames = ['pscsx3241', 'pscsx32412'];
 }
 public function __construct()
 {
     $this->bootstrap = true;
     parent::__construct();
     $id_shop = Context::getContext()->shop->id;
     /* Get all modules then select only payment ones */
     $modules = Module::getModulesOnDisk(true);
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleRepository = $moduleManagerBuilder->buildRepository();
     foreach ($modules as $module) {
         $addonModule = $moduleRepository->getModule($module->name);
         if ($addonModule->attributes->get('parent_class') == 'PaymentModule') {
             if ($module->id) {
                 if (!get_class($module) == 'SimpleXMLElement') {
                     $module->country = array();
                 }
                 $sql = new DbQuery();
                 $sql->select('`id_country`');
                 $sql->from('module_country');
                 $sql->where('`id_module` = ' . (int) $module->id);
                 $sql->where('`id_shop` = ' . (int) $id_shop);
                 $countries = Db::getInstance()->executeS($sql);
                 foreach ($countries as $country) {
                     $module->country[] = $country['id_country'];
                 }
                 if (!get_class($module) == 'SimpleXMLElement') {
                     $module->currency = array();
                 }
                 $sql = new DbQuery();
                 $sql->select('`id_currency`');
                 $sql->from('module_currency');
                 $sql->where('`id_module` = ' . (int) $module->id);
                 $sql->where('`id_shop` = ' . (int) $id_shop);
                 $currencies = Db::getInstance()->executeS($sql);
                 foreach ($currencies as $currency) {
                     $module->currency[] = $currency['id_currency'];
                 }
                 if (!get_class($module) == 'SimpleXMLElement') {
                     $module->group = array();
                 }
                 $sql = new DbQuery();
                 $sql->select('`id_group`');
                 $sql->from('module_group');
                 $sql->where('`id_module` = ' . (int) $module->id);
                 $sql->where('`id_shop` = ' . (int) $id_shop);
                 $groups = Db::getInstance()->executeS($sql);
                 foreach ($groups as $group) {
                     $module->group[] = $group['id_group'];
                 }
                 if (!get_class($module) == 'SimpleXMLElement') {
                     $module->reference = array();
                 }
                 $sql = new DbQuery();
                 $sql->select('`id_reference`');
                 $sql->from('module_carrier');
                 $sql->where('`id_module` = ' . (int) $module->id);
                 $sql->where('`id_shop` = ' . (int) $id_shop);
                 $carriers = Db::getInstance()->executeS($sql);
                 foreach ($carriers as $carrier) {
                     $module->reference[] = $carrier['id_reference'];
                 }
             } else {
                 $module->country = null;
                 $module->currency = null;
                 $module->group = null;
             }
             $this->payment_modules[] = $module;
         }
     }
 }
 public function renderView()
 {
     if (Tools::isSubmit('profitability_conf')) {
         return parent::renderOptions();
     }
     // $translations = array(
     // 	'Calendar' => $this->trans('Calendar', array(),'Admin.Global'),
     // 	'Day' => $this->trans('Day', array(), 'Admin.Global'),
     // 	'Month' => $this->trans('Month', array(), 'Admin.Global'),
     // 	'Year' => $this->trans('Year', array(), 'Admin.Global'),
     // 	'From' => $this->trans('From:', array(), 'Admin.Global'),
     // 	'To' => $this->trans('To:', array(), 'Admin.Global'),
     // 	'Save' => $this->trans('Save', array(), 'Admin.Global')
     // );
     if ($this->context->cookie->__get('stats_date_update') < strtotime(date('Y-m-d'))) {
         switch ($this->context->employee->preselect_date_range) {
             case 'day':
                 $date_from = date('Y-m-d');
                 $date_to = date('Y-m-d');
                 break;
             case 'prev-day':
                 $date_from = date('Y-m-d', strtotime('-1 day'));
                 $date_to = date('Y-m-d', strtotime('-1 day'));
                 break;
             case 'month':
             default:
                 $date_from = date('Y-m-01');
                 $date_to = date('Y-m-d');
                 break;
             case 'prev-month':
                 $date_from = date('Y-m-01', strtotime('-1 month'));
                 $date_to = date('Y-m-t', strtotime('-1 month'));
                 break;
             case 'year':
                 $date_from = date('Y-01-01');
                 $date_to = date('Y-m-d');
                 break;
             case 'prev-year':
                 $date_from = date('Y-m-01', strtotime('-1 year'));
                 $date_to = date('Y-12-t', strtotime('-1 year'));
                 break;
         }
         $this->context->employee->stats_date_from = $date_from;
         $this->context->employee->stats_date_to = $date_to;
         $this->context->employee->update();
         $this->context->cookie->__set('stats_date_update', strtotime(date('Y-m-d')));
         $this->context->cookie->write();
     }
     $calendar_helper = new HelperCalendar();
     $calendar_helper->setDateFrom(Tools::getValue('date_from', $this->context->employee->stats_date_from));
     $calendar_helper->setDateTo(Tools::getValue('date_to', $this->context->employee->stats_date_to));
     $stats_compare_from = $this->context->employee->stats_compare_from;
     $stats_compare_to = $this->context->employee->stats_compare_to;
     if (is_null($stats_compare_from) || $stats_compare_from == '0000-00-00') {
         $stats_compare_from = null;
     }
     if (is_null($stats_compare_to) || $stats_compare_to == '0000-00-00') {
         $stats_compare_to = null;
     }
     $calendar_helper->setCompareDateFrom($stats_compare_from);
     $calendar_helper->setCompareDateTo($stats_compare_to);
     $calendar_helper->setCompareOption(Tools::getValue('compare_date_option', $this->context->employee->stats_compare_option));
     $params = array('date_from' => $this->context->employee->stats_date_from, 'date_to' => $this->context->employee->stats_date_to);
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     $this->tpl_view_vars = array('date_from' => $this->context->employee->stats_date_from, 'date_to' => $this->context->employee->stats_date_to, 'hookDashboardZoneOne' => Hook::exec('dashboardZoneOne', $params), 'hookDashboardZoneTwo' => Hook::exec('dashboardZoneTwo', $params), 'action' => '#', 'warning' => $this->getWarningDomainName(), 'new_version_url' => Tools::getCurrentUrlProtocolPrefix() . _PS_API_DOMAIN_ . '/version/check_version.php?v=' . _PS_VERSION_ . '&lang=' . $this->context->language->iso_code . '&autoupgrade=' . (int) ($moduleManager->isInstalled('autoupgrade') && $moduleManager->isEnabled('autoupgrade')) . '&hosted_mode=' . (int) defined('_PS_HOST_MODE_'), 'dashboard_use_push' => Configuration::get('PS_DASHBOARD_USE_PUSH'), 'calendar' => $calendar_helper->generate(), 'PS_DASHBOARD_SIMULATION' => Configuration::get('PS_DASHBOARD_SIMULATION'), 'datepickerFrom' => Tools::getValue('datepickerFrom', $this->context->employee->stats_date_from), 'datepickerTo' => Tools::getValue('datepickerTo', $this->context->employee->stats_date_to), 'preselect_date_range' => Tools::getValue('preselectDateRange', $this->context->employee->preselect_date_range));
     return parent::renderView();
 }
Esempio n. 4
0
 /**
  * Install/Uninstall a module from a localization file
  * <modules>
  *	<module name="module_name" [install="0|1"] />
  *
  * @param SimpleXMLElement $xml
  * @return bool
  */
 protected function installModules($xml)
 {
     if (isset($xml->modules)) {
         foreach ($xml->modules->module as $data) {
             /** @var SimpleXMLElement $data */
             $attributes = $data->attributes();
             $name = (string) $attributes['name'];
             if (isset($name) && ($module = Module::getInstanceByName($name))) {
                 $install = $attributes['install'] == 1 ? true : false;
                 $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
                 $moduleManager = $moduleManagerBuilder->build();
                 if ($install) {
                     if (!$moduleManager->isInstalled($name)) {
                         if (!$module->install()) {
                             $this->_errors[] = Tools::displayError('An error occurred while installing the module:') . $name;
                         }
                     }
                 } elseif ($moduleManager->isInstalled($name)) {
                     if (!$module->uninstall()) {
                         $this->_errors[] = Tools::displayError('An error occurred while uninstalling the module:') . $name;
                     }
                 }
                 unset($module);
             } else {
                 $this->_errors[] = Tools::displayError('An error has occurred, this module does not exist:') . $name;
             }
         }
     }
     return true;
 }
Esempio n. 5
0
 /**
  * This will allow you to retrieve an HTML code with a list of recommended modules depending on the domain.
  *
  * @Template
  * @param string $domain
  * @param integer $limit
  * @param integer $randomize
  * @return array Template vars
  */
 public function recommendedModulesAction($domain, $limit = 0, $randomize = 0)
 {
     $recommendedModules = $this->container->get('prestashop.data_provider.modules.recommended');
     /* @var $recommendedModules RecommendedModules */
     $moduleIdList = $recommendedModules->getRecommendedModuleIdList($domain, $randomize == 1);
     $modulesProvider = $this->container->get('prestashop.core.admin.data_provider.module_interface');
     /* @var $modulesProvider AdminModuleDataProvider */
     $modulesRepository = ModuleManagerBuilder::getInstance()->buildRepository();
     $modules = array();
     foreach ($moduleIdList as $id) {
         try {
             $module = $modulesRepository->getModule($id);
         } catch (\Exception $e) {
             continue;
         }
         $modules[] = $module;
     }
     if ($randomize == 1) {
         shuffle($modules);
     }
     $modules = $recommendedModules->filterInstalledAndBadModules($modules);
     $modules = $modulesProvider->generateAddonsUrls($modules);
     return array('domain' => $domain, 'modules' => array_slice($modules, 0, $limit, true));
 }
Esempio n. 6
0
 private function doEnableModules(array $modules)
 {
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     foreach ($modules as $key => $moduleName) {
         if (!$moduleManager->isInstalled($moduleName)) {
             $moduleManager->install($moduleName);
         }
         if (!$moduleManager->isEnabled($moduleName)) {
             $moduleManager->enable($moduleName);
         }
     }
     return $this;
 }
Esempio n. 7
0
 /**
  * Returns a link to a product image for display
  * Note: the new image filesystem stores product images in subdirectories of img/p/.
  *
  * @param string $name rewrite link of the image
  * @param string $ids  id part of the image filename - can be "id_product-id_image" (legacy support, recommended) or "id_image" (new)
  * @param string $type
  *
  * @return string
  */
 public function getImageLink($name, $ids, $type = null)
 {
     $notDefault = false;
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     // Check if module is installed, enabled, customer is logged in and watermark logged option is on
     if (Configuration::get('WATERMARK_LOGGED') && ($moduleManager->isInstalled('watermark') && $moduleManager->isEnabled('watermark')) && isset(Context::getContext()->customer->id)) {
         $type .= '-' . Configuration::get('WATERMARK_HASH');
     }
     // legacy mode or default image
     $theme = Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_ . $ids . ($type ? '-' . $type : '') . '-' . Context::getContext()->shop->theme_name . '.jpg') ? '-' . Context::getContext()->shop->theme_name : '';
     if (Configuration::get('PS_LEGACY_IMAGES') && file_exists(_PS_PROD_IMG_DIR_ . $ids . ($type ? '-' . $type : '') . $theme . '.jpg') || ($notDefault = strpos($ids, 'default') !== false)) {
         if ($this->allow == 1 && !$notDefault) {
             $uriPath = __PS_BASE_URI__ . $ids . ($type ? '-' . $type : '') . $theme . '/' . $name . '.jpg';
         } else {
             $uriPath = _THEME_PROD_DIR_ . $ids . ($type ? '-' . $type : '') . $theme . '.jpg';
         }
     } else {
         // if ids if of the form id_product-id_image, we want to extract the id_image part
         $splitIds = explode('-', $ids);
         $idImage = isset($splitIds[1]) ? $splitIds[1] : $splitIds[0];
         $theme = Shop::isFeatureActive() && file_exists(_PS_PROD_IMG_DIR_ . Image::getImgFolderStatic($idImage) . $idImage . ($type ? '-' . $type : '') . '-' . (int) Context::getContext()->shop->theme_name . '.jpg') ? '-' . Context::getContext()->shop->theme_name : '';
         if ($this->allow == 1) {
             $uriPath = __PS_BASE_URI__ . $idImage . ($type ? '-' . $type : '') . $theme . '/' . $name . '.jpg';
         } else {
             $uriPath = _THEME_PROD_DIR_ . Image::getImgFolderStatic($idImage) . $idImage . ($type ? '-' . $type : '') . $theme . '.jpg';
         }
     }
     return $this->protocol_content . Tools::getMediaServer($uriPath) . $uriPath;
 }
Esempio n. 8
0
 public function generate()
 {
     $this->tpl = $this->createTemplate($this->base_tpl);
     if (is_null($this->submit_action)) {
         $this->submit_action = 'submitAdd' . $this->table;
     }
     $categories = true;
     $color = true;
     $date = true;
     $tinymce = true;
     $textarea_autosize = true;
     $file = true;
     foreach ($this->fields_form as $fieldset_key => &$fieldset) {
         if (isset($fieldset['form']['tabs'])) {
             $tabs[] = $fieldset['form']['tabs'];
         }
         if (isset($fieldset['form']['input'])) {
             foreach ($fieldset['form']['input'] as $key => &$params) {
                 // If the condition is not met, the field will not be displayed
                 if (isset($params['condition']) && !$params['condition']) {
                     unset($this->fields_form[$fieldset_key]['form']['input'][$key]);
                 }
                 switch ($params['type']) {
                     case 'select':
                         $field_name = (string) $params['name'];
                         // If multiple select check that 'name' field is suffixed with '[]'
                         if (isset($params['multiple']) && $params['multiple'] && stripos($field_name, '[]') === false) {
                             $params['name'] .= '[]';
                         }
                         break;
                     case 'categories':
                         if ($categories) {
                             if (!isset($params['tree']['id'])) {
                                 throw new PrestaShopException('Id must be filled for categories tree');
                             }
                             $tree = new HelperTreeCategories($params['tree']['id'], isset($params['tree']['title']) ? $params['tree']['title'] : null);
                             if (isset($params['name'])) {
                                 $tree->setInputName($params['name']);
                             }
                             if (isset($params['tree']['selected_categories'])) {
                                 $tree->setSelectedCategories($params['tree']['selected_categories']);
                             }
                             if (isset($params['tree']['disabled_categories'])) {
                                 $tree->setDisabledCategories($params['tree']['disabled_categories']);
                             }
                             if (isset($params['tree']['root_category'])) {
                                 $tree->setRootCategory($params['tree']['root_category']);
                             }
                             if (isset($params['tree']['use_search'])) {
                                 $tree->setUseSearch($params['tree']['use_search']);
                             }
                             if (isset($params['tree']['use_checkbox'])) {
                                 $tree->setUseCheckBox($params['tree']['use_checkbox']);
                             }
                             if (isset($params['tree']['set_data'])) {
                                 $tree->setData($params['tree']['set_data']);
                             }
                             $this->context->smarty->assign('categories_tree', $tree->render());
                             $categories = false;
                         }
                         break;
                     case 'file':
                         $uploader = new HelperUploader();
                         $uploader->setId(isset($params['id']) ? $params['id'] : null);
                         $uploader->setName($params['name']);
                         $uploader->setUrl(isset($params['url']) ? $params['url'] : null);
                         $uploader->setMultiple(isset($params['multiple']) ? $params['multiple'] : false);
                         $uploader->setUseAjax(isset($params['ajax']) ? $params['ajax'] : false);
                         $uploader->setMaxFiles(isset($params['max_files']) ? $params['max_files'] : null);
                         if (isset($params['files']) && $params['files']) {
                             $uploader->setFiles($params['files']);
                         } elseif (isset($params['image']) && $params['image']) {
                             // Use for retrocompatibility
                             $uploader->setFiles(array(0 => array('type' => HelperUploader::TYPE_IMAGE, 'image' => isset($params['image']) ? $params['image'] : null, 'size' => isset($params['size']) ? $params['size'] : null, 'delete_url' => isset($params['delete_url']) ? $params['delete_url'] : null)));
                         }
                         if (isset($params['file']) && $params['file']) {
                             // Use for retrocompatibility
                             $uploader->setFiles(array(0 => array('type' => HelperUploader::TYPE_FILE, 'size' => isset($params['size']) ? $params['size'] : null, 'delete_url' => isset($params['delete_url']) ? $params['delete_url'] : null, 'download_url' => isset($params['file']) ? $params['file'] : null)));
                         }
                         if (isset($params['thumb']) && $params['thumb']) {
                             // Use for retrocompatibility
                             $uploader->setFiles(array(0 => array('type' => HelperUploader::TYPE_IMAGE, 'image' => isset($params['thumb']) ? '<img src="' . $params['thumb'] . '" alt="' . (isset($params['title']) ? $params['title'] : '') . '" title="' . (isset($params['title']) ? $params['title'] : '') . '" />' : null)));
                         }
                         $uploader->setTitle(isset($params['title']) ? $params['title'] : null);
                         $params['file'] = $uploader->render();
                         break;
                     case 'color':
                         if ($color) {
                             // Added JS file
                             $this->context->controller->addJqueryPlugin('colorpicker');
                             $color = false;
                         }
                         break;
                     case 'date':
                         if ($date) {
                             $this->context->controller->addJqueryUI('ui.datepicker');
                             $date = false;
                         }
                         break;
                     case 'textarea':
                         if ($tinymce) {
                             $iso = $this->context->language->iso_code;
                             $this->tpl_vars['iso'] = file_exists(_PS_CORE_DIR_ . '/js/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en';
                             $this->tpl_vars['path_css'] = _THEME_CSS_DIR_;
                             $this->tpl_vars['ad'] = __PS_BASE_URI__ . basename(_PS_ADMIN_DIR_);
                             $this->tpl_vars['tinymce'] = true;
                             $this->context->controller->addJS(_PS_JS_DIR_ . 'tiny_mce/tiny_mce.js');
                             $this->context->controller->addJS(_PS_JS_DIR_ . 'admin/tinymce.inc.js');
                             $tinymce = false;
                         }
                         if ($textarea_autosize) {
                             $this->context->controller->addJqueryPlugin('autosize');
                             $textarea_autosize = false;
                         }
                         break;
                     case 'shop':
                         $disable_shops = isset($params['disable_shared']) ? $params['disable_shared'] : false;
                         $params['html'] = $this->renderAssoShop($disable_shops);
                         if (Shop::getTotalShops(false) == 1) {
                             if (isset($this->fields_form[$fieldset_key]['form']['force']) && !$this->fields_form[$fieldset_key]['form']['force'] || !isset($this->fields_form[$fieldset_key]['form']['force'])) {
                                 unset($this->fields_form[$fieldset_key]['form']['input'][$key]);
                             }
                         }
                         break;
                 }
             }
         }
     }
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     $this->tpl->assign(array('title' => $this->title, 'toolbar_btn' => $this->toolbar_btn, 'show_toolbar' => $this->show_toolbar, 'toolbar_scroll' => $this->toolbar_scroll, 'submit_action' => $this->submit_action, 'firstCall' => $this->first_call, 'current' => $this->currentIndex, 'token' => $this->token, 'table' => $this->table, 'identifier' => $this->identifier, 'name_controller' => $this->name_controller, 'languages' => $this->languages, 'current_id_lang' => $this->context->language->id, 'defaultFormLanguage' => $this->default_form_language, 'allowEmployeeFormLang' => $this->allow_employee_form_lang, 'form_id' => $this->id, 'tabs' => isset($tabs) ? $tabs : null, 'fields' => $this->fields_form, 'fields_value' => $this->fields_value, 'required_fields' => $this->getFieldsRequired(), 'vat_number' => $moduleManager->isInstalled('vatnumber') && file_exists(_PS_MODULE_DIR_ . 'vatnumber/ajax.php'), 'module_dir' => _MODULE_DIR_, 'base_url' => $this->context->shop->getBaseURL(), 'contains_states' => isset($this->fields_value['id_country']) && isset($this->fields_value['id_state']) ? Country::containsStates($this->fields_value['id_country']) : null, 'show_cancel_button' => $this->show_cancel_button, 'back_url' => $this->back_url));
     return parent::generate();
 }
 public function renderKpis()
 {
     $time = time();
     $kpis = array();
     /* The data generation is located in AdminStatsControllerCore */
     if (Configuration::get('PS_STOCK_MANAGEMENT')) {
         $helper = new HelperKpi();
         $helper->id = 'box-products-stock';
         $helper->icon = 'icon-archive';
         $helper->color = 'color1';
         $helper->title = $this->l('Out of stock items', null, null, false);
         if (ConfigurationKPI::get('PERCENT_PRODUCT_OUT_OF_STOCK') !== false) {
             $helper->value = ConfigurationKPI::get('PERCENT_PRODUCT_OUT_OF_STOCK');
         }
         $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=percent_product_out_of_stock';
         $helper->tooltip = $this->l('X% of your products for sale are out of stock.', null, null, false);
         $helper->refresh = (bool) (ConfigurationKPI::get('PERCENT_PRODUCT_OUT_OF_STOCK_EXPIRE') < $time);
         $helper->href = Context::getContext()->link->getAdminLink('AdminProducts') . '&productFilter_sav!quantity=0&productFilter_active=1&submitFilterproduct=1';
         $kpis[] = $helper->generate();
     }
     $helper = new HelperKpi();
     $helper->id = 'box-avg-gross-margin';
     $helper->icon = 'icon-tags';
     $helper->color = 'color2';
     $helper->title = $this->l('Average Gross Margin', null, null, false);
     if (ConfigurationKPI::get('PRODUCT_AVG_GROSS_MARGIN') !== false) {
         $helper->value = ConfigurationKPI::get('PRODUCT_AVG_GROSS_MARGIN');
     }
     $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=product_avg_gross_margin';
     $helper->tooltip = $this->l('The gross margin is the difference between the retail price and the wholesale price, on all your products for sale.', null, null, false);
     $helper->refresh = (bool) (ConfigurationKPI::get('PRODUCT_AVG_GROSS_MARGIN_EXPIRE') < $time);
     $kpis[] = $helper->generate();
     $helper = new HelperKpi();
     $helper->id = 'box-8020-sales-catalog';
     $helper->icon = 'icon-beaker';
     $helper->color = 'color3';
     $helper->title = $this->l('Purchased references', null, null, false);
     $helper->subtitle = $this->l('30 days', null, null, false);
     if (ConfigurationKPI::get('8020_SALES_CATALOG') !== false) {
         $helper->value = ConfigurationKPI::get('8020_SALES_CATALOG');
     }
     $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=8020_sales_catalog';
     $helper->tooltip = $this->l('X% of your references have been purchased for the past 30 days', null, null, false);
     $helper->refresh = (bool) (ConfigurationKPI::get('8020_SALES_CATALOG_EXPIRE') < $time);
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     if ($moduleManager->isInstalled('statsbestproducts')) {
         $helper->href = Context::getContext()->link->getAdminLink('AdminStats') . '&module=statsbestproducts&datepickerFrom=' . date('Y-m-d', strtotime('-30 days')) . '&datepickerTo=' . date('Y-m-d');
     }
     $kpis[] = $helper->generate();
     $helper = new HelperKpi();
     $helper->id = 'box-disabled-products';
     $helper->icon = 'icon-off';
     $helper->color = 'color4';
     $helper->href = $this->context->link->getAdminLink('AdminProducts');
     $helper->title = $this->l('Disabled Products', null, null, false);
     if (ConfigurationKPI::get('DISABLED_PRODUCTS') !== false) {
         $helper->value = ConfigurationKPI::get('DISABLED_PRODUCTS');
     }
     $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=disabled_products';
     $helper->refresh = (bool) (ConfigurationKPI::get('DISABLED_PRODUCTS_EXPIRE') < $time);
     $helper->tooltip = $this->l('X% of your products are disabled and not visible to your customers', null, null, false);
     $helper->href = Context::getContext()->link->getAdminLink('AdminProducts') . '&productFilter_active=0&submitFilterproduct=1';
     $kpis[] = $helper->generate();
     $helper = new HelperKpiRow();
     $helper->kpis = $kpis;
     return $helper->generate();
 }
Esempio n. 10
0
 /**
  * Initialize product controller.
  *
  * @see FrontController::init()
  */
 public function init()
 {
     parent::init();
     $id_product = (int) Tools::getValue('id_product');
     $this->setTemplate('catalog/product', array('entity' => 'product', 'id' => $id_product));
     if ($id_product) {
         $this->product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);
     }
     if (!Validate::isLoadedObject($this->product)) {
         Tools::redirect('index.php?controller=404');
     } else {
         $this->canonicalRedirection();
         /*
          * If the product is associated to the shop
          * and is active or not active but preview mode (need token + file_exists)
          * allow showing the product
          * In all the others cases => 404 "Product is no longer available"
          */
         if (!$this->product->isAssociatedToShop() || !$this->product->active) {
             if (Tools::getValue('adtoken') == Tools::getAdminToken('AdminProducts' . (int) Tab::getIdFromClassName('AdminProducts') . (int) Tools::getValue('id_employee')) && $this->product->isAssociatedToShop()) {
                 $this->adminNotifications['inactive_product'] = array('type' => 'warning', 'message' => $this->trans('This product is not visible to your customers.', array(), 'Shop.Notifications.Warning'));
             } else {
                 if (!$this->product->id_product_redirected || $this->product->id_product_redirected == $this->product->id) {
                     $this->product->redirect_type = '404';
                 }
                 switch ($this->product->redirect_type) {
                     case '301':
                         header('HTTP/1.1 301 Moved Permanently');
                         header('Location: ' . $this->context->link->getProductLink($this->product->id_product_redirected));
                         exit;
                         break;
                     case '302':
                         header('HTTP/1.1 302 Moved Temporarily');
                         header('Cache-Control: no-cache');
                         header('Location: ' . $this->context->link->getProductLink($this->product->id_product_redirected));
                         exit;
                         break;
                     case '404':
                     default:
                         header('HTTP/1.1 404 Not Found');
                         header('Status: 404 Not Found');
                         $this->errors[] = $this->trans('This product is no longer available.', array(), 'Shop.Notifications.Error');
                         $this->setTemplate('errors/404');
                         break;
                 }
             }
         } elseif (!$this->product->checkAccess(isset($this->context->customer->id) && $this->context->customer->id ? (int) $this->context->customer->id : 0)) {
             header('HTTP/1.1 403 Forbidden');
             header('Status: 403 Forbidden');
             $this->errors[] = $this->trans('You do not have access to this product.', array(), 'Shop.Notifications.Error');
         } else {
             // Load category
             $id_category = false;
             if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == Tools::secureReferrer($_SERVER['HTTP_REFERER']) && preg_match('~^.*(?<!\\/content)\\/([0-9]+)\\-(.*[^\\.])|(.*)id_(category|product)=([0-9]+)(.*)$~', $_SERVER['HTTP_REFERER'], $regs)) {
                 // If the previous page was a category and is a parent category of the product use this category as parent category
                 $id_object = false;
                 if (isset($regs[1]) && is_numeric($regs[1])) {
                     $id_object = (int) $regs[1];
                 } elseif (isset($regs[5]) && is_numeric($regs[5])) {
                     $id_object = (int) $regs[5];
                 }
                 if ($id_object) {
                     $referers = array($_SERVER['HTTP_REFERER'], urldecode($_SERVER['HTTP_REFERER']));
                     if (in_array($this->context->link->getCategoryLink($id_object), $referers)) {
                         $id_category = (int) $id_object;
                     } elseif (isset($this->context->cookie->last_visited_category) && (int) $this->context->cookie->last_visited_category && in_array($this->context->link->getProductLink($id_object), $referers)) {
                         $id_category = (int) $this->context->cookie->last_visited_category;
                     }
                 }
             }
             if (!$id_category || !Category::inShopStatic($id_category, $this->context->shop) || !Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => $id_category)))) {
                 $id_category = (int) $this->product->id_category_default;
             }
             $this->category = new Category((int) $id_category, (int) $this->context->cookie->id_lang);
             $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
             $moduleManager = $moduleManagerBuilder->build();
             if (isset($this->context->cookie) && isset($this->category->id_category) && !($moduleManager->isInstalled('ps_categorytree') && $moduleManager->isEnabled('ps_categorytree'))) {
                 $this->context->cookie->last_visited_category = (int) $this->category->id_category;
             }
         }
     }
 }
Esempio n. 11
0
 public function postProcess()
 {
     if (!Tools::getIsset('configure') && !Tools::getIsset('module_name')) {
         Tools::redirectAdmin($this->context->link->getAdminLink('AdminModulesSf'));
     }
     // Parent Post Process
     parent::postProcess();
     // Get the list of installed module ans prepare it for ajax call.
     if ($list = Tools::getValue('installed_modules')) {
         Context::getContext()->smarty->assign('installed_modules', json_encode(explode('|', $list)));
     }
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     // If redirect parameter is present and module already installed, we redirect on configuration module page
     if (Tools::getValue('redirect') == 'config' && Tools::getValue('module_name') != '' && $moduleManager->isInstalled(pSQL(Tools::getValue('module_name')))) {
         Tools::redirectAdmin('index.php?controller=adminmodules&configure=' . Tools::getValue('module_name') . '&token=' . Tools::getValue('token') . '&module_name=' . Tools::getValue('module_name'));
     }
     // Execute filter or callback methods
     $filter_methods = array('filterModules', 'resetFilterModules', 'filterCategory', 'unfilterCategory');
     $callback_methods = array('reset', 'download', 'enable', 'delete', 'enable_device', 'disable_device');
     $post_process_methods_list = array_merge((array) $filter_methods, (array) $callback_methods);
     foreach ($post_process_methods_list as $ppm) {
         if (Tools::isSubmit($ppm)) {
             $ppm = 'postProcess' . ucfirst($ppm);
             if (method_exists($this, $ppm)) {
                 $ppm_return = $this->{$ppm}();
             }
         }
     }
     // Call appropriate module callback
     if (!isset($ppm_return)) {
         $this->postProcessCallback();
     }
     if ($back = Tools::getValue('back')) {
         Tools::redirectAdmin($back);
     }
 }
Esempio n. 12
0
 public function renderKpis()
 {
     $time = time();
     $kpis = array();
     /* The data generation is located in AdminStatsControllerCore */
     if (Configuration::get('PS_STOCK_MANAGEMENT')) {
         $helper = new HelperKpi();
         $helper->id = 'box-products-stock';
         $helper->icon = 'local_shipping';
         $helper->color = 'color1';
         $helper->title = $this->l('Out of stock items', null, null, false);
         if (ConfigurationKPI::get('PERCENT_PRODUCT_OUT_OF_STOCK') !== false) {
             $helper->value = ConfigurationKPI::get('PERCENT_PRODUCT_OUT_OF_STOCK');
         }
         $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=percent_product_out_of_stock';
         $helper->tooltip = sprintf($this->l('%s of your products for sale are out of stock.', null, null, false), $helper->value);
         $helper->refresh = (bool) (ConfigurationKPI::get('PERCENT_PRODUCT_OUT_OF_STOCK_EXPIRE') < $time);
         $product_token = Tools::getAdminToken('AdminProducts' . (int) Tab::getIdFromClassName('AdminProducts') . (int) Context::getContext()->employee->id);
         $urlParams = ['filter_column_sav_quantity' => '<=0', 'filter_column_active' => '1', 'token' => $product_token, 'submitFilterproduct' => 1];
         $helper->href = preg_replace("/\\?.*\$/", '?tab=AdminProducts&productFilter_sav!quantity=0&productFilter_active=1&submitFilterproduct=1&token=' . $product_token, Context::getContext()->link->getAdminLink('AdminProducts', true, $urlParams));
         $kpis[] = $helper->generate();
     }
     $helper = new HelperKpi();
     $helper->id = 'box-avg-gross-margin';
     $helper->icon = 'label';
     $helper->color = 'color2';
     $helper->title = $this->l('Average Gross Margin %', null, null, false);
     if (ConfigurationKPI::get('PRODUCT_AVG_GROSS_MARGIN') !== false) {
         $helper->value = ConfigurationKPI::get('PRODUCT_AVG_GROSS_MARGIN');
     }
     $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=product_avg_gross_margin';
     $helper->tooltip = sprintf($this->l('Gross margin expressed in percentage assesses how cost-effectively you sell your goods. Out of $100, you will retain $%s to cover profit and expenses.', null, null, false), str_replace('%', '', $helper->value));
     $helper->refresh = (bool) (ConfigurationKPI::get('PRODUCT_AVG_GROSS_MARGIN_EXPIRE') < $time);
     $kpis[] = $helper->generate();
     $helper = new HelperKpi();
     $helper->id = 'box-8020-sales-catalog';
     $helper->icon = 'whatshot';
     $helper->color = 'color3';
     $helper->title = $this->l('Catalog popularity', null, null, false);
     $helper->subtitle = $this->l('30 days', null, null, false);
     if (ConfigurationKPI::get('8020_SALES_CATALOG') !== false) {
         $helper->value = ConfigurationKPI::get('8020_SALES_CATALOG');
     }
     $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=8020_sales_catalog';
     $helper->tooltip = sprintf($this->l('Within your catalog, %s of your products have had sales in the last 30 days', null, null, false), $helper->value);
     $helper->refresh = (bool) (ConfigurationKPI::get('8020_SALES_CATALOG_EXPIRE') < $time);
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     if ($moduleManager->isInstalled('statsbestproducts')) {
         $helper->href = Context::getContext()->link->getAdminLink('AdminStats') . '&module=statsbestproducts&datepickerFrom=' . date('Y-m-d', strtotime('-30 days')) . '&datepickerTo=' . date('Y-m-d');
     }
     $kpis[] = $helper->generate();
     $helper = new HelperKpi();
     $helper->id = 'box-disabled-products';
     $helper->icon = 'visibility_off';
     $helper->color = 'color4';
     $helper->title = $this->l('Disabled Products', null, null, false);
     if (ConfigurationKPI::get('DISABLED_PRODUCTS') !== false) {
         $helper->value = ConfigurationKPI::get('DISABLED_PRODUCTS');
     }
     $helper->source = $this->context->link->getAdminLink('AdminStats') . '&ajax=1&action=getKpi&kpi=disabled_products';
     $helper->refresh = (bool) (ConfigurationKPI::get('DISABLED_PRODUCTS_EXPIRE') < $time);
     $helper->tooltip = sprintf($this->l('%s of your products are disabled and not visible to your customers', null, null, false), $helper->value);
     $product_token = Tools::getAdminToken('AdminProducts' . (int) Tab::getIdFromClassName('AdminProducts') . (int) Context::getContext()->employee->id);
     $urlParams = ['filter_column_active' => '0', 'token' => $product_token, 'submitFilterproduct' => 1];
     $helper->href = preg_replace("/\\?.*\$/", '?tab=AdminProducts&productFilter_active=0&submitFilterproduct=1&token=' . $product_token, Context::getContext()->link->getAdminLink('AdminProducts', true, $urlParams));
     $kpis[] = $helper->generate();
     $helper = new HelperKpiRow();
     $helper->kpis = $kpis;
     return $helper->generate();
 }
Esempio n. 13
0
    public function displayAjaxGetKpi()
    {
        $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
        $tooltip = null;
        switch (Tools::getValue('kpi')) {
            case 'conversion_rate':
                $visitors = AdminStatsController::getVisits(true, date('Y-m-d', strtotime('-31 day')), date('Y-m-d', strtotime('-1 day')), false);
                $orders = AdminStatsController::getOrders(date('Y-m-d', strtotime('-31 day')), date('Y-m-d', strtotime('-1 day')), false);
                // $data = array();
                // $from = strtotime(date('Y-m-d 00:00:00', strtotime('-31 day')));
                // $to = strtotime(date('Y-m-d 23:59:59', strtotime('-1 day')));
                // for ($date = $from; $date <= $to; $date = strtotime('+1 day', $date))
                // if (isset($visitors[$date]) && $visitors[$date])
                // $data[$date] = round(100 * ((isset($orders[$date]) && $orders[$date]) ? $orders[$date] : 0) / $visitors[$date], 2);
                // else
                // $data[$date] = 0;
                $visits_sum = $visitors;
                //array_sum($visitors);
                $orders_sum = $orders;
                //array_sum($orders);
                if ($visits_sum) {
                    $value = round(100 * $orders_sum / $visits_sum, 2);
                } elseif ($orders_sum) {
                    $value = '&infin;';
                } else {
                    $value = 0;
                }
                $value .= '%';
                // ConfigurationKPI::updateValue('CONVERSION_RATE_CHART', json_encode($data));
                ConfigurationKPI::updateValue('CONVERSION_RATE', $value);
                ConfigurationKPI::updateValue('CONVERSION_RATE_EXPIRE', strtotime(date('Y-m-d 00:00:00', strtotime('+1 day'))));
                break;
            case 'abandoned_cart':
                $value = AdminStatsController::getAbandonedCarts(date('Y-m-d H:i:s', strtotime('-2 day')), date('Y-m-d H:i:s', strtotime('-1 day')));
                ConfigurationKPI::updateValue('ABANDONED_CARTS', $value);
                ConfigurationKPI::updateValue('ABANDONED_CARTS_EXPIRE', strtotime('+1 hour'));
                break;
            case 'installed_modules':
                $value = AdminStatsController::getInstalledModules();
                ConfigurationKPI::updateValue('INSTALLED_MODULES', $value);
                ConfigurationKPI::updateValue('INSTALLED_MODULES_EXPIRE', strtotime('+2 min'));
                break;
            case 'disabled_modules':
                $value = AdminStatsController::getDisabledModules();
                ConfigurationKPI::updateValue('DISABLED_MODULES', $value);
                ConfigurationKPI::updateValue('DISABLED_MODULES_EXPIRE', strtotime('+2 min'));
                break;
            case 'update_modules':
                $value = AdminStatsController::getModulesToUpdate();
                ConfigurationKPI::updateValue('UPDATE_MODULES', $value);
                ConfigurationKPI::updateValue('UPDATE_MODULES_EXPIRE', strtotime('+2 min'));
                break;
            case 'percent_product_stock':
                $value = AdminStatsController::getPercentProductStock();
                ConfigurationKPI::updateValue('PERCENT_PRODUCT_STOCK', $value);
                ConfigurationKPI::updateValue('PERCENT_PRODUCT_STOCK_EXPIRE', strtotime('+4 hour'));
                break;
            case 'percent_product_out_of_stock':
                $value = AdminStatsController::getPercentProductOutOfStock();
                $tooltip = $this->trans('%s of your products for sale are out of stock.', array($value), 'Admin.Stats.Help');
                ConfigurationKPI::updateValue('PERCENT_PRODUCT_OUT_OF_STOCK', $value);
                ConfigurationKPI::updateValue('PERCENT_PRODUCT_OUT_OF_STOCK_EXPIRE', strtotime('+4 hour'));
                break;
            case 'product_avg_gross_margin':
                $value = AdminStatsController::getProductAverageGrossMargin();
                $tooltip = $this->trans('Gross margin expressed in percentage assesses how cost-effectively you sell your goods. Out of $100, you will retain $%s to cover profit and expenses.', array(str_replace('%', '', $value)), 'Admin.Stats.Help');
                ConfigurationKPI::updateValue('PRODUCT_AVG_GROSS_MARGIN', $value);
                ConfigurationKPI::updateValue('PRODUCT_AVG_GROSS_MARGIN_EXPIRE', strtotime('+6 hour'));
                break;
            case 'disabled_categories':
                $value = AdminStatsController::getDisabledCategories();
                ConfigurationKPI::updateValue('DISABLED_CATEGORIES', $value);
                ConfigurationKPI::updateValue('DISABLED_CATEGORIES_EXPIRE', strtotime('+2 hour'));
                break;
            case 'disabled_products':
                $value = round(100 * AdminStatsController::getDisabledProducts() / AdminStatsController::getTotalProducts(), 2) . '%';
                $tooltip = sprintf($this->trans('%s of your products are disabled and not visible to your customers', array(), 'Admin.Stats.Help'), $value);
                ConfigurationKPI::updateValue('DISABLED_PRODUCTS', $value);
                ConfigurationKPI::updateValue('DISABLED_PRODUCTS_EXPIRE', strtotime('+2 hour'));
                break;
            case '8020_sales_catalog':
                $value = AdminStatsController::get8020SalesCatalog(date('Y-m-d', strtotime('-30 days')), date('Y-m-d'));
                $tooltip = sprintf($this->trans('Within your catalog, %s of your products have had sales in the last 30 days', array(), 'Admin.Stats.Help'), $value);
                $value = sprintf($this->trans('%d%% of your Catalog', array(), 'Admin.Stats.Feature'), $value);
                ConfigurationKPI::updateValue('8020_SALES_CATALOG', $value);
                ConfigurationKPI::updateValue('8020_SALES_CATALOG_EXPIRE', strtotime('+12 hour'));
                break;
            case 'empty_categories':
                $value = AdminStatsController::getEmptyCategories();
                ConfigurationKPI::updateValue('EMPTY_CATEGORIES', $value);
                ConfigurationKPI::updateValue('EMPTY_CATEGORIES_EXPIRE', strtotime('+2 hour'));
                break;
            case 'customer_main_gender':
                $value = AdminStatsController::getCustomerMainGender();
                if ($value === false) {
                    $value = $this->trans('No customers', array(), 'Admin.Stats.Feature');
                } elseif ($value['type'] == 'female') {
                    $value = sprintf($this->trans('%d%% Female Customers', array(), 'Admin.Stats.Feature'), $value['value']);
                } elseif ($value['type'] == 'male') {
                    $value = sprintf($this->trans('%d%% Male Customers', array(), 'Admin.Stats.Feature'), $value['value']);
                } else {
                    $value = sprintf($this->trans('%d%% Neutral Customers', array(), 'Admin.Stats.Feature'), $value['value']);
                }
                ConfigurationKPI::updateValue('CUSTOMER_MAIN_GENDER', array($this->context->language->id => $value));
                ConfigurationKPI::updateValue('CUSTOMER_MAIN_GENDER_EXPIRE', array($this->context->language->id => strtotime('+1 day')));
                break;
            case 'avg_customer_age':
                $value = sprintf($this->trans('%d years', array(), 'Admin.Stats.Feature'), AdminStatsController::getAverageCustomerAge(), 1);
                ConfigurationKPI::updateValue('AVG_CUSTOMER_AGE', array($this->context->language->id => $value));
                ConfigurationKPI::updateValue('AVG_CUSTOMER_AGE_EXPIRE', array($this->context->language->id => strtotime('+1 day')));
                break;
            case 'pending_messages':
                $value = (int) AdminStatsController::getPendingMessages();
                ConfigurationKPI::updateValue('PENDING_MESSAGES', $value);
                ConfigurationKPI::updateValue('PENDING_MESSAGES_EXPIRE', strtotime('+5 min'));
                break;
            case 'avg_msg_response_time':
                $value = sprintf($this->trans('%.1f hours', array(), 'Admin.Stats.Feature'), AdminStatsController::getAverageMessageResponseTime(date('Y-m-d', strtotime('-31 day')), date('Y-m-d', strtotime('-1 day'))));
                ConfigurationKPI::updateValue('AVG_MSG_RESPONSE_TIME', $value);
                ConfigurationKPI::updateValue('AVG_MSG_RESPONSE_TIME_EXPIRE', strtotime('+4 hour'));
                break;
            case 'messages_per_thread':
                $value = round(AdminStatsController::getMessagesPerThread(date('Y-m-d', strtotime('-31 day')), date('Y-m-d', strtotime('-1 day'))), 1);
                ConfigurationKPI::updateValue('MESSAGES_PER_THREAD', $value);
                ConfigurationKPI::updateValue('MESSAGES_PER_THREAD_EXPIRE', strtotime('+12 hour'));
                break;
            case 'newsletter_registrations':
                $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
                $moduleManager = $moduleManagerBuilder->build();
                $value = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
				SELECT COUNT(*)
				FROM `' . _DB_PREFIX_ . 'customer`
				WHERE newsletter = 1
				' . Shop::addSqlRestriction(Shop::SHARE_ORDER));
                if ($moduleManager->isInstalled('ps_emailsubscription')) {
                    $value += Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
					SELECT COUNT(*)
					FROM `' . _DB_PREFIX_ . 'emailsubscription`
					WHERE active = 1
					' . Shop::addSqlRestriction(Shop::SHARE_ORDER));
                }
                ConfigurationKPI::updateValue('NEWSLETTER_REGISTRATIONS', $value);
                ConfigurationKPI::updateValue('NEWSLETTER_REGISTRATIONS_EXPIRE', strtotime('+6 hour'));
                break;
            case 'enabled_languages':
                $value = Language::countActiveLanguages();
                ConfigurationKPI::updateValue('ENABLED_LANGUAGES', $value);
                ConfigurationKPI::updateValue('ENABLED_LANGUAGES_EXPIRE', strtotime('+1 min'));
                break;
            case 'frontoffice_translations':
                $themes = (new ThemeManagerBuilder($this->context, Db::getInstance()))->buildRepository()->getList();
                $languages = Language::getLanguages();
                $total = $translated = 0;
                foreach ($themes as $theme) {
                    /** @var Theme $theme */
                    foreach ($languages as $language) {
                        $kpi_key = substr(strtoupper($theme->getName() . '_' . $language['iso_code']), 0, 16);
                        $total += ConfigurationKPI::get('TRANSLATE_TOTAL_' . $kpi_key);
                        $translated += ConfigurationKPI::get('TRANSLATE_DONE_' . $kpi_key);
                    }
                }
                $value = 0;
                if ($translated) {
                    $value = round(100 * $translated / $total, 1);
                }
                $value .= '%';
                ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS', $value);
                ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', strtotime('+2 min'));
                break;
            case 'main_country':
                if (!($row = AdminStatsController::getMainCountry(date('Y-m-d', strtotime('-30 day')), date('Y-m-d')))) {
                    $value = $this->trans('No orders', array(), 'Admin.Stats.Feature');
                } else {
                    $country = new Country($row['id_country'], $this->context->language->id);
                    $value = $this->trans('%d%% %s', array('%d%%' => $row['orders'], '%s' => $country->name), 'Admin.Stats.Feature');
                }
                ConfigurationKPI::updateValue('MAIN_COUNTRY', array($this->context->language->id => $value));
                ConfigurationKPI::updateValue('MAIN_COUNTRY_EXPIRE', array($this->context->language->id => strtotime('+1 day')));
                break;
            case 'orders_per_customer':
                $value = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
				SELECT COUNT(*)
				FROM `' . _DB_PREFIX_ . 'customer` c
				WHERE c.active = 1
				' . Shop::addSqlRestriction());
                if ($value) {
                    $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
					SELECT COUNT(*)
					FROM `' . _DB_PREFIX_ . 'orders` o
					WHERE o.valid = 1
					' . Shop::addSqlRestriction());
                    $value = round($orders / $value, 2);
                }
                ConfigurationKPI::updateValue('ORDERS_PER_CUSTOMER', $value);
                ConfigurationKPI::updateValue('ORDERS_PER_CUSTOMER_EXPIRE', strtotime('+1 day'));
                break;
            case 'average_order_value':
                $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
				SELECT
					COUNT(`id_order`) as orders,
					SUM(`total_paid_tax_excl` / `conversion_rate`) as total_paid_tax_excl
				FROM `' . _DB_PREFIX_ . 'orders`
				WHERE `invoice_date` BETWEEN "' . pSQL(date('Y-m-d', strtotime('-31 day'))) . ' 00:00:00" AND "' . pSQL(date('Y-m-d', strtotime('-1 day'))) . ' 23:59:59"
				' . Shop::addSqlRestriction());
                $value = Tools::displayPrice($row['orders'] ? $row['total_paid_tax_excl'] / $row['orders'] : 0, $currency);
                ConfigurationKPI::updateValue('AVG_ORDER_VALUE', $value);
                ConfigurationKPI::updateValue('AVG_ORDER_VALUE_EXPIRE', strtotime(date('Y-m-d 00:00:00', strtotime('+1 day'))));
                break;
            case 'netprofit_visit':
                $date_from = date('Y-m-d', strtotime('-31 day'));
                $date_to = date('Y-m-d', strtotime('-1 day'));
                $total_visitors = AdminStatsController::getVisits(false, $date_from, $date_to);
                $net_profits = AdminStatsController::getTotalSales($date_from, $date_to);
                $net_profits -= AdminStatsController::getExpenses($date_from, $date_to);
                $net_profits -= AdminStatsController::getPurchases($date_from, $date_to);
                if ($total_visitors) {
                    $value = Tools::displayPrice($net_profits / $total_visitors, $currency);
                } elseif ($net_profits) {
                    $value = '&infin;';
                } else {
                    $value = Tools::displayPrice(0, $currency);
                }
                ConfigurationKPI::updateValue('NETPROFIT_VISIT', $value);
                ConfigurationKPI::updateValue('NETPROFIT_VISIT_EXPIRE', strtotime(date('Y-m-d 00:00:00', strtotime('+1 day'))));
                break;
            case 'products_per_category':
                $products = AdminStatsController::getTotalProducts();
                $categories = AdminStatsController::getTotalCategories();
                $value = round($products / $categories);
                ConfigurationKPI::updateValue('PRODUCTS_PER_CATEGORY', $value);
                ConfigurationKPI::updateValue('PRODUCTS_PER_CATEGORY_EXPIRE', strtotime('+1 hour'));
                break;
            case 'top_category':
                if (!($id_category = AdminStatsController::getBestCategory(date('Y-m-d', strtotime('-1 month')), date('Y-m-d')))) {
                    $value = $this->trans('No category', array(), 'Admin.Stats.Feature');
                } else {
                    $category = new Category($id_category, $this->context->language->id);
                    $value = $category->name;
                }
                ConfigurationKPI::updateValue('TOP_CATEGORY', array($this->context->language->id => $value));
                ConfigurationKPI::updateValue('TOP_CATEGORY_EXPIRE', array($this->context->language->id => strtotime('+1 day')));
                break;
            default:
                $value = false;
        }
        if ($value !== false) {
            $array = array('value' => $value, 'tooltip' => $tooltip);
            if (isset($data)) {
                $array['data'] = $data;
            }
            die(json_encode($array));
        }
        die(json_encode(array('has_errors' => true)));
    }
Esempio n. 14
0
    public function renderForm()
    {
        $uri = Tools::getHttpHost(true, true) . __PS_BASE_URI__;
        $this->fields_form[0] = array('form' => array('legend' => array('title' => $this->l('Affiliate'), 'icon' => 'icon-group'), 'input' => array(array('type' => 'text', 'label' => $this->trans('Name', array(), 'Admin.Global'), 'name' => 'name', 'required' => true, 'autocomplete' => false), array('type' => 'password', 'label' => $this->l('Password'), 'name' => 'passwd', 'desc' => $this->l('Leave blank if no change.'), 'autocomplete' => false)), 'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions'))));
        $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
        $moduleManager = $moduleManagerBuilder->build();
        if ($moduleManager->isInstalled('trackingfront')) {
            $this->fields_form[0]['form']['desc'] = array($this->l('Affiliates can access their data with this name and password.'), $this->l('Front access:') . ' <a class="btn btn-link" href="' . $uri . 'modules/trackingfront/stats.php" onclick="return !window.open(this.href);"><i class="icon-external-link-sign"></i> ' . $uri . 'modules/trackingfront/stats.php</a>');
        } else {
            $this->fields_form[0]['form']['desc'] = array(sprintf($this->l('Please install the "%s" module in order to give your affiliates access their own statistics.'), Module::getModuleName('trackingfront')));
        }
        $this->fields_form[1] = array('form' => array('legend' => array('title' => $this->l('Commission plan'), 'icon' => 'icon-dollar'), 'input' => array(array('type' => 'text', 'label' => $this->l('Click fee'), 'name' => 'click_fee', 'desc' => $this->l('Fee given for each visit.')), array('type' => 'text', 'label' => $this->l('Base fee'), 'name' => 'base_fee', 'desc' => $this->l('Fee given for each order placed.')), array('type' => 'text', 'label' => $this->l('Percent fee'), 'name' => 'percent_fee', 'desc' => $this->l('Percent of the sales.'))), 'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions'))));
        if (Shop::isFeatureActive()) {
            $this->fields_form[1]['form']['input'][] = array('type' => 'shop', 'label' => $this->l('Shop association'), 'name' => 'checkBoxShopAsso');
        }
        $this->fields_form[2] = array('form' => array('legend' => array('title' => $this->l('Technical information -- Simple mode'), 'icon' => 'icon-cogs'), 'help' => true, 'input' => array(array('type' => 'textarea', 'label' => $this->l('Include'), 'name' => 'http_referer_like', 'cols' => 40, 'rows' => 1, 'legend' => $this->l('HTTP referrer')), array('type' => 'textarea', 'label' => $this->l('Exclude'), 'name' => 'http_referer_like_not', 'cols' => 40, 'rows' => 1), array('type' => 'textarea', 'label' => $this->l('Include'), 'name' => 'request_uri_like', 'cols' => 40, 'rows' => 1, 'legend' => $this->l('Request URI')), array('type' => 'textarea', 'label' => $this->l('Exclude'), 'name' => 'request_uri_like_not', 'cols' => 40, 'rows' => 1)), 'desc' => $this->l('If you know how to use MySQL regular expressions, you can use the') . '
					<a style="cursor: pointer; font-weight: bold;" onclick="$(\'#tracking_expert\').slideToggle();">' . $this->l('expert mode') . '.</a>', 'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions'))));
        $this->fields_form[3] = array('form' => array('legend' => array('title' => $this->l('Technical information -- Expert mode'), 'icon' => 'icon-cogs'), 'input' => array(array('type' => 'textarea', 'label' => $this->l('Include'), 'name' => 'http_referer_regexp', 'cols' => 40, 'rows' => 1, 'legend' => $this->l('HTTP referrer')), array('type' => 'textarea', 'label' => $this->l('Exclude'), 'name' => 'http_referer_regexp_not', 'cols' => 40, 'rows' => 1), array('type' => 'textarea', 'label' => $this->l('Include'), 'name' => 'request_uri_regexp', 'cols' => 40, 'rows' => 1, 'legend' => $this->l('Request URI')), array('type' => 'textarea', 'label' => $this->l('Exclude'), 'name' => 'request_uri_regexp_not', 'cols' => 40, 'rows' => 1))));
        $this->multiple_fieldsets = true;
        if (!($obj = $this->loadObject(true))) {
            return;
        }
        $this->fields_value = array('click_fee' => number_format((double) $this->getFieldValue($obj, 'click_fee'), 2), 'base_fee' => number_format((double) $this->getFieldValue($obj, 'base_fee'), 2), 'percent_fee' => number_format((double) $this->getFieldValue($obj, 'percent_fee'), 2), 'http_referer_like' => str_replace('\\', '\\\\', htmlentities($this->getFieldValue($obj, 'http_referer_like'), ENT_COMPAT, 'UTF-8')), 'http_referer_like_not' => str_replace('\\', '\\\\', htmlentities($this->getFieldValue($obj, 'http_referer_like_not'), ENT_COMPAT, 'UTF-8')), 'request_uri_like' => str_replace('\\', '\\\\', htmlentities($this->getFieldValue($obj, 'request_uri_like'), ENT_COMPAT, 'UTF-8')), 'request_uri_like_not' => str_replace('\\', '\\\\', htmlentities($this->getFieldValue($obj, 'request_uri_like_not'), ENT_COMPAT, 'UTF-8')));
        $this->tpl_form_vars = array('uri' => $uri);
        return parent::renderForm();
    }
 public function ajaxProcessCronjobLiveExchangeRate()
 {
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     if (!$moduleManager->isInstalled('cronjobs')) {
         die(json_encode(array()));
     }
     $enable = (int) Tools::getValue('enable');
     $config = Configuration::get('PS_ACTIVE_CRONJOB_EXCHANGE_RATE', null, null, $this->context->shop->id);
     $cronJobUrl = 'http://' . ShopUrl::getMainShopDomain($this->context->shop->id) . __PS_BASE_URI__ . basename(_PS_ADMIN_DIR_) . '/cron_currency_rates.php?secure_key=' . md5(_COOKIE_KEY_ . Configuration::get('PS_SHOP_NAME'));
     if ($config && $enable == 0) {
         Configuration::updateValue('PS_ACTIVE_CRONJOB_EXCHANGE_RATE', 0, false, null, $this->context->shop->id);
         Db::getInstance()->execute('DELETE FROM ' . _DB_PREFIX_ . 'cronjobs WHERE `id_cronjob` = \'' . (int) $config . '\'');
     }
     //The cronjob is not defined, create it
     if ($enable == 1 && (!$config || $config == 0)) {
         $cronJobs = new CronJobs();
         $cronJobs->addOneShotTask($cronJobUrl, sprintf($this->l('Live exchange Rate for %s'), Configuration::get('PS_SHOP_NAME')));
         Configuration::updateValue('PS_ACTIVE_CRONJOB_EXCHANGE_RATE', Db::getInstance()->Insert_ID(), false, null, $this->context->shop->id);
     } else {
         $cronJob = Db::getInstance()->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'cronjobs WHERE `id_cronjob` = \'' . (int) $config . '\'');
         //if cronjob do not exsit anymore OR cronjob dis disabled => disable conf
         if (!$cronJob || $cronJob[0]['active'] == 0) {
             Configuration::updateValue('PS_ACTIVE_CRONJOB_EXCHANGE_RATE', 0, false, null, $this->context->shop->id);
         }
     }
     die(json_encode(array()));
 }
Esempio n. 16
0
 /**
  * PROCESS : installModules
  * Download module from addons and Install all modules in ~/modules/ directory
  */
 public function installModules($module = null)
 {
     if ($module && !is_array($module)) {
         $module = array($module);
     }
     $modules = $module ? $module : $this->getModulesList();
     Module::updateTranslationsAfterInstall(false);
     $moduleManagerBuilder = ModuleManagerBuilder::getInstance();
     $moduleManager = $moduleManagerBuilder->build();
     $errors = array();
     foreach ($modules as $module_name) {
         if (!file_exists(_PS_MODULE_DIR_ . $module_name . '/' . $module_name . '.php')) {
             continue;
         }
         if (!$moduleManager->install($module_name)) {
             /*$module_errors = $module->getErrors();
               if (empty($module_errors)) {*/
             $module_errors = [$this->translator->trans('Cannot install module "%module%"', array('%module%' => $module_name), 'Install')];
             /*}*/
             $errors[$module_name] = $module_errors;
         }
     }
     if ($errors) {
         $this->setError($errors);
         return false;
     }
     Module::updateTranslationsAfterInstall(true);
     Language::updateModulesTranslations($modules);
     return true;
 }