public function downloadAddonsThemes()
 {
     if (!$this->logged_on_addons) {
         return false;
     }
     if (!$this->isFresh(self::CACHE_FILE_CUSTOMER_THEMES_LIST, 86400)) {
         file_put_contents(_PS_ROOT_DIR_ . self::CACHE_FILE_CUSTOMER_THEMES_LIST, Tools::addonsRequest('customer_themes'));
     }
     $customer_themes_list = file_get_contents(_PS_ROOT_DIR_ . self::CACHE_FILE_CUSTOMER_THEMES_LIST);
     if (!empty($customer_themes_list) && ($customer_themes_list_xml = @simplexml_load_string($customer_themes_list))) {
         foreach ($customer_themes_list_xml->theme as $addons_theme) {
             //get addons theme if folder does not exist
             $ids_themes = Tools::unSerialize(Configuration::get('PS_ADDONS_THEMES_IDS'));
             if (!is_array($ids_themes) || is_array($ids_themes) && !in_array((string) $addons_theme->id, $ids_themes)) {
                 $zip_content = Tools::addonsRequest('module', array('id_module' => pSQL($addons_theme->id), 'username_addons' => pSQL(trim($this->context->cookie->username_addons)), 'password_addons' => pSQL(trim($this->context->cookie->password_addons))));
                 $uniqid = uniqid();
                 $sandbox = _PS_CACHE_DIR_ . 'sandbox' . DIRECTORY_SEPARATOR . $uniqid . DIRECTORY_SEPARATOR;
                 mkdir($sandbox);
                 file_put_contents($sandbox . (string) $addons_theme->getName() . '.zip', $zip_content);
                 if ($this->extractTheme($sandbox . (string) $addons_theme->getName() . '.zip', $sandbox)) {
                     if ($theme_directory = $this->installTheme(self::UPLOADED_THEME_DIR_NAME, $sandbox, false)) {
                         $ids_themes[$theme_directory] = (string) $addons_theme->id;
                     }
                 }
                 Tools::deleteDirectory($sandbox);
             }
             Configuration::updateValue('PS_ADDONS_THEMES_IDS', serialize($ids_themes));
         }
     }
 }
Example #2
0
 public function getDeliveryOption($default_country = null, $dontAutoSelectOptions = false, $use_cache = true)
 {
     @session_start();
     if (Module::isInstalled('agilepaypal') && isset($_SESSION['agile_paypal_validating_order']) && $_SESSION['agile_paypal_validating_order'] == 1 && isset($this->delivery_option) && $this->delivery_option != '') {
         $_SESSION['agile_paypal_validating_order'] = 0;
         return Tools::unSerialize($this->delivery_option);
     }
     return parent::getDeliveryOption($default_country, $dontAutoSelectOptions, $use_cache);
 }
 public static function printManifest($module_instance)
 {
     $cookie = Context::getContext()->cookie;
     if (isset($cookie->dpdpoland_packages_ids)) {
         if (version_compare(_PS_VERSION_, '1.5', '<')) {
             $package_ids = unserialize(Context::getContext()->cookie->dpdpoland_packages_ids);
         } else {
             $package_ids = Tools::unSerialize(Context::getContext()->cookie->dpdpoland_packages_ids);
         }
         unset($cookie->dpdpoland_packages_ids);
         $cookie->write();
         $separated_packages = DpdPolandPackage::separatePackagesBySession($package_ids);
         $international_packages = $separated_packages['INTERNATIONAL'];
         $domestic_packages = $separated_packages['DOMESTIC'];
         $manifest_ids = array();
         if ($international_packages) {
             $manifest_ids[] = DpdPolandManifest::getManifestIdWsByPackageIdWs($international_packages[0]);
         }
         if ($domestic_packages) {
             $manifest_ids[] = DpdPolandManifest::getManifestIdWsByPackageIdWs($domestic_packages[0]);
         }
         require_once _DPDPOLAND_CONTROLLERS_DIR_ . 'manifestList.controller.php';
         $manifest_controller = new DpdPolandManifestListController();
         return $manifest_controller->printManifest($manifest_ids);
     }
     if ($package_ids = Tools::getValue('PackagesBox')) {
         if (!DpdPolandManifest::validateSenderAddresses($package_ids)) {
             $error_message = $module_instance->l('Manifests can not have different sender addresses', self::FILENAME);
             $error = $module_instance->displayError($error_message);
             return $module_instance->outputHTML($error);
         }
         $separated_packages = DpdPolandPackage::separatePackagesBySession($package_ids);
         $international_packages = $separated_packages['INTERNATIONAL'];
         $domestic_packages = $separated_packages['DOMESTIC'];
         if ($international_packages) {
             $manifest = new DpdPolandManifest();
             if (!$manifest->generateMultiple($international_packages)) {
                 $error = $module_instance->displayError(reset(DpdPolandManifestWS::$errors));
                 return $module_instance->outputHTML($error);
             }
         }
         if ($domestic_packages) {
             $manifest = new DpdPolandManifest();
             if (!$manifest->generateMultiple($domestic_packages)) {
                 $error = $module_instance->displayError(reset(DpdPolandManifestWS::$errors));
                 return $module_instance->outputHTML($error);
             }
         }
         $cookie->dpdpoland_packages_ids = serialize($package_ids);
         $redirect_uri = $module_instance->module_url . '&menu=packages_list';
         die(Tools::redirectAdmin($redirect_uri));
     }
 }
 public function getErrorMessage()
 {
     $message = $this->cookie->{self::DPD_POLAND_ERROR_MESSAGE};
     if (Validate::isSerializedArray($message)) {
         if (version_compare(_PS_VERSION_, '1.5', '<')) {
             $message = unserialize($message);
         } else {
             $message = Tools::unSerialize($message);
         }
     }
     $this->cookie->__unset(self::DPD_POLAND_ERROR_MESSAGE);
     if (is_array($message)) {
         return array_unique($message);
     }
     return $message ? array($message) : '';
 }
 public function initList()
 {
     //$helper = new HelperList();
     //$helper->title = array($this->module_instance->displayName, $this->module_instance->l('Translation projects', 'translation_projects.view'));
     //return parent::initList($helper);
     $projects = $this->getData();
     $list_total = count($this->getData(false));
     $pagination = array(20, 50, 100, 300);
     $page = (int) Tools::getValue('submitFilterproject');
     if (!$page) {
         $page = 1;
     }
     $total_pages = ceil($list_total / Tools::getValue('pagination', 50));
     if (!$total_pages) {
         $total_pages = 1;
     }
     $selected_pagination = Tools::getValue('pagination', isset($this->context->cookie->{'project_pagination'}) ? $this->context->cookie->{'project_pagination'} : null);
     $this->context->smarty->assign(array('projects' => $projects, 'list_total' => $list_total, 'page' => $page, 'full_url' => TextMaster::CURRENT_INDEX . Tools::getValue('token') . '&configure=' . $this->module_instance->name . '&menu=' . Tools::getValue('menu') . '&token=' . Tools::getAdminTokenLite('AdminModules'), 'menu' => 'translation', 'selected_pagination' => $selected_pagination, 'pagination' => $pagination, 'total_pages' => $total_pages));
     $fields = array('id_project', 'name', 'language_from', 'language_to', 'status');
     foreach ($fields as $key => $values) {
         if ($this->context->cookie->__isset('projectFilter_' . $values)) {
             $this->context->smarty->assign('cookie_projectFilter_' . $values, $this->context->cookie->{'projectFilter_' . $values});
         }
     }
     $fields = array('date_add', 'date_upd');
     foreach ($fields as $key => $values) {
         if ($this->context->cookie->__isset('projectFilter_' . $values)) {
             if (version_compare(_PS_VERSION_, '1.5', '<')) {
                 $date = unserialize($this->context->cookie->{'projectFilter_' . $values});
             } else {
                 $date = Tools::unSerialize($this->context->cookie->{'projectFilter_' . $values});
             }
             if (!empty($date[0])) {
                 $this->context->smarty->assign('cookie_projectFilter_' . $values . '_0', pSQL($date[0]));
             }
             if (!empty($date[1])) {
                 $this->context->smarty->assign('cookie_projectFilter_' . $values . '_1', pSQL($date[1]));
             }
         }
     }
     if (version_compare(_PS_VERSION_, '1.5', '<')) {
         includeDatepicker(array('projectFilter_date_add_0', 'projectFilter_date_add_1', 'projectFilter_date_upd_0', 'projectFilter_date_upd_1'));
     } else {
         $this->context->controller->addJqueryUI('ui.datepicker');
     }
     return $this->context->smarty->fetch(_PS_MODULE_DIR_ . 'textmaster/views/templates/admin/main_list.tpl');
 }
 public function isOrderSelected($id_order)
 {
     /*
      *  true = chechekd
      *  false = unchechekd
      */
     $poutput = '<input type="checkbox" name="selected_orders[]" class="selected_orders" checked="checked" value="' . (int) $id_order . '">';
     if (!empty($this->context->cookie->unselected_orders)) {
         $unselected_orders_array = Tools::unSerialize($this->context->cookie->unselected_orders);
         if (is_array($unselected_orders_array) && !empty($unselected_orders_array)) {
             if (in_array($id_order, $unselected_orders_array)) {
                 $poutput = '<input type="checkbox" name="selected_orders[]" class="selected_orders" value="' . (int) $id_order . '">';
             }
         }
     }
     return $poutput;
 }
Example #7
0
function ps1700_stores()
{
    $stores = Db::getInstance()->executeS('
        SELECT `id_store`, `hours`
        FROM `' . _DB_PREFIX_ . 'store`
    ');
    $result = false;
    foreach ($stores as $store) {
        $hours = Tools::unSerialize($store['hours']);
        if (is_array($hours)) {
            foreach ($hours as $key => $h) {
                $hours[$key] = [$h];
            }
        } else {
            $hours = array();
        }
        $hours = json_encode($hours);
        $result &= Db::getInstance()->execute('
            UPDATE `' . _DB_PREFIX_ . 'store`
            SET `hours` = ' . $hours . '
            WHERE `id_store` = ' . $store['id_store']);
    }
    return $result;
}
Example #8
0
 private function collectFilterRules()
 {
     $rules = array();
     $fields = array('id_project', 'name', 'language_from', 'language_to', 'status');
     foreach ($fields as $key => $values) {
         if ($this->context->cookie->__isset($this->table . 'Filter_' . $values)) {
             $value = $this->context->cookie->{$this->table . 'Filter_' . $values};
             if (!empty($value) || $value == '0') {
                 $rule = array('key' => $values, 'value' => pSQL($value));
                 $rules['find'][] = $rule;
             }
         }
     }
     $fields = array('date_add', 'date_upd');
     foreach ($fields as $key => $values) {
         if ($this->context->cookie->__isset($this->table . 'Filter_' . $values)) {
             if (version_compare(_PS_VERSION_, '1.5', '<')) {
                 $date = unserialize($this->context->cookie->{$this->table . 'Filter_' . $values});
             } else {
                 $date = Tools::unSerialize($this->context->cookie->{$this->table . 'Filter_' . $values});
             }
             if (!empty($date[0])) {
                 $rules['compare'][] = array('key' => $values, 'value' => pSQL($date[0]), 'operator' => '>');
             }
             if (!empty($date[1])) {
                 $rules['compare'][] = array('key' => $values, 'value' => pSQL($date[1]), 'operator' => '<');
             }
         }
     }
     return $rules;
     $rules = array();
     foreach ($this->module_instance->fields_list as $key => $value) {
         $rule = '';
         if ($this->context->cookie->__isset($this->table . 'Filter_' . $key)) {
             $value = $this->context->cookie->{$this->table . 'Filter_' . $key};
             if (Validate::isSerializedArray($value)) {
                 if (version_compare(_PS_VERSION_, '1.5', '<')) {
                     $date = unserialize($value);
                 } else {
                     $date = Tools::unSerialize($value);
                 }
                 if (!empty($date[0])) {
                     $rules['compare'][] = array('key' => $key, 'value' => pSQL($date[0]), 'operator' => '>');
                 }
                 if (!empty($date[1])) {
                     $rules['compare'][] = array('key' => $key, 'value' => pSQL($date[1]), 'operator' => '<');
                 }
             } elseif (!empty($value) || $value == '0') {
                 $rule = array('key' => $key, 'value' => pSQL($value));
                 $rules['find'][] = $rule;
             }
         }
     }
     return $rules;
 }
Example #9
0
    /**
     * Display list header (filtering, pagination and column names)
     */
    public function displayListHeader($token = null)
    {
        $isCms = false;
        if (preg_match('/cms/Ui', $this->identifier)) {
            $isCms = true;
        }
        $id_cat = Tools::getValue('id_' . ($isCms ? 'cms_' : '') . 'category');
        if (!isset($token) || empty($token)) {
            $token = $this->token;
        }
        /* Determine total page number */
        $totalPages = ceil($this->_listTotal / Tools::getValue('pagination', isset($this->context->cookie->{$this->table . '_pagination'}) ? $this->context->cookie->{$this->table . '_pagination'} : $this->_pagination[0]));
        if (!$totalPages) {
            $totalPages = 1;
        }
        echo '<a name="' . $this->table . '">&nbsp;</a>';
        echo '<form method="post" action="' . self::$currentIndex;
        if (Tools::getIsset($this->identifier)) {
            echo '&' . $this->identifier . '=' . (int) Tools::getValue($this->identifier);
        }
        echo '&token=' . $token;
        if (Tools::getIsset($this->table . 'Orderby')) {
            echo '&' . $this->table . 'Orderby=' . urlencode($this->_orderBy) . '&' . $this->table . 'Orderway=' . urlencode(strtolower($this->_orderWay));
        }
        echo '#' . $this->table . '" class="form">
		<input type="hidden" id="submitFilter' . $this->table . '" name="submitFilter' . $this->table . '" value="0">
		<table>
			<tr>
				<td style="vertical-align: bottom;">
					<span style="float: left;">';
        /* Determine current page number */
        $page = (int) Tools::getValue('submitFilter' . $this->table);
        if (!$page) {
            $page = 1;
        }
        if ($page > 1) {
            echo '
						<input type="image" src="../img/admin/list-prev2.gif" onclick="getE(\'submitFilter' . $this->table . '\').value=1"/>
						&nbsp; <input type="image" src="../img/admin/list-prev.gif" onclick="getE(\'submitFilter' . $this->table . '\').value=' . ($page - 1) . '"/> ';
        }
        echo $this->l('Page') . ' <b>' . $page . '</b> / ' . $totalPages;
        if ($page < $totalPages) {
            echo '
						<input type="image" src="../img/admin/list-next.gif" onclick="getE(\'submitFilter' . $this->table . '\').value=' . ($page + 1) . '"/>
						 &nbsp;<input type="image" src="../img/admin/list-next2.gif" onclick="getE(\'submitFilter' . $this->table . '\').value=' . $totalPages . '"/>';
        }
        echo '			| ' . $this->l('Display') . '
						<select name="pagination">';
        /* Choose number of results per page */
        $selectedPagination = Tools::getValue('pagination', isset($this->context->cookie->{$this->table . '_pagination'}) ? $this->context->cookie->{$this->table . '_pagination'} : null);
        foreach ($this->_pagination as $value) {
            echo '<option value="' . (int) $value . '"' . ($selectedPagination == $value ? ' selected="selected"' : ($selectedPagination == null && $value == $this->_pagination[1] ? ' selected="selected2"' : '')) . '>' . (int) $value . '</option>';
        }
        echo '
						</select>
						/ ' . (int) $this->_listTotal . ' ' . $this->l('result(s)') . '
					</span>
					<span style="float: right;">
						<input type="submit" name="submitReset' . $this->table . '" value="' . $this->l('Reset') . '" class="button" />
						<input type="submit" id="submitFilterButton_' . $this->table . '" name="submitFilter" value="' . $this->l('Filter') . '" class="button" />
					</span>
					<span class="clear"></span>
				</td>
			</tr>
			<tr>
				<td>';
        /* Display column names and arrows for ordering (ASC, DESC) */
        if (array_key_exists($this->identifier, $this->identifiersDnd) && $this->_orderBy == 'position') {
            echo '
			<script type="text/javascript" src="../js/jquery/jquery.tablednd_0_5.js"></script>
			<script type="text/javascript">
				var token = \'' . ($token != null ? $token : $this->token) . '\';
				var come_from = \'' . $this->table . '\';
				var alternate = \'' . ($this->_orderWay == 'DESC' ? '1' : '0') . '\';
			</script>
			<script type="text/javascript" src="../js/admin/dnd.js"></script>
			';
        }
        echo '<table' . (array_key_exists($this->identifier, $this->identifiersDnd) ? ' id="' . ((int) Tools::getValue($this->identifiersDnd[$this->identifier], 1) ? Tools::substr($this->identifier, 3, Tools::strlen($this->identifier)) : '') . '"' : '') . ' class="table' . (array_key_exists($this->identifier, $this->identifiersDnd) && ($this->_orderBy != 'position' && $this->_orderWay != 'DESC') ? ' tableDnD' : '') . '" cellpadding="0" cellspacing="0">
			<thead>
				<tr class="nodrag nodrop">
					<th>';
        if ($this->delete) {
            echo '		<input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'' . $this->table . 'Box[]\', this.checked)" />';
        }
        echo '		</th>';
        foreach ($this->fieldsDisplay as $key => $params) {
            echo '	<th ' . (isset($params['widthColumn']) ? 'style="width: ' . $params['widthColumn'] . 'px"' : '') . '>' . $params['title'];
            if (!isset($params['orderby']) || $params['orderby']) {
                // Cleaning links
                if (Tools::getValue($this->table . 'Orderby') && Tools::getValue($this->table . 'Orderway')) {
                    self::$currentIndex = preg_replace('/&' . $this->table . 'Orderby=([a-z _]*)&' . $this->table . 'Orderway=([a-z]*)/i', '', self::$currentIndex);
                }
                echo '	<br />
						<a href="' . self::$currentIndex . '&' . $this->identifier . '=' . $id_cat . '&' . $this->table . 'Orderby=' . urlencode($key) . '&' . $this->table . 'Orderway=desc&token=' . $token . '"><img border="0" src="../img/admin/down' . (isset($this->_orderBy) && $key == $this->_orderBy && $this->_orderWay == 'DESC' ? '_d' : '') . '.gif" /></a>
						<a href="' . self::$currentIndex . '&' . $this->identifier . '=' . $id_cat . '&' . $this->table . 'Orderby=' . urlencode($key) . '&' . $this->table . 'Orderway=asc&token=' . $token . '"><img border="0" src="../img/admin/up' . (isset($this->_orderBy) && $key == $this->_orderBy && $this->_orderWay == 'ASC' ? '_d' : '') . '.gif" /></a>';
            }
            echo '	</th>';
        }
        if ($this->shopLinkType) {
            echo '<th style="width: 80px">' . $this->l($this->shopLinkType == 'shop' ? 'Shop' : 'Shop group') . '</th>';
        }
        /* Check if object can be modified, deleted or detailed */
        if ($this->edit || $this->delete || $this->view && $this->view !== 'noActionColumn') {
            echo '	<th style="width: 52px">' . $this->l('Actions') . '</th>';
        }
        echo '	</tr>
				<tr class="nodrag nodrop" style="height: 35px;">
					<td class="center">';
        if ($this->delete) {
            echo '		--';
        }
        echo '		</td>';
        /* Javascript hack in order to catch ENTER keypress event */
        $keyPress = 'onkeypress="formSubmit(event, \'submitFilterButton_' . $this->table . '\');"';
        /* Filters (input, select, date or bool) */
        foreach ($this->fieldsDisplay as $key => $params) {
            $width = isset($params['width']) ? ' style="width: ' . (int) $params['width'] . 'px;"' : '';
            echo '<td' . (isset($params['align']) ? ' class="' . $params['align'] . '"' : '') . '>';
            if (!isset($params['type'])) {
                $params['type'] = 'text';
            }
            $value = Tools::getValue($this->table . 'Filter_' . (array_key_exists('filter_key', $params) ? $params['filter_key'] : $key));
            if (isset($params['search']) && !$params['search']) {
                echo '--</td>';
                continue;
            }
            switch ($params['type']) {
                case 'bool':
                    echo '
					<select name="' . $this->table . 'Filter_' . $key . '">
						<option value="">-</option>
						<option value="1"' . ($value == 1 ? ' selected="selected"' : '') . '>' . $this->l('Yes') . '</option>
						<option value="0"' . ($value == 0 && $value != '' ? ' selected="selected"' : '') . '>' . $this->l('No') . '</option>
					</select>';
                    break;
                case 'date':
                case 'datetime':
                    if (is_string($value)) {
                        $value = Tools::unSerialize($value);
                    }
                    if (!Validate::isCleanHtml($value[0]) || !Validate::isCleanHtml($value[1])) {
                        $value = '';
                    }
                    $name = $this->table . 'Filter_' . (isset($params['filter_key']) ? $params['filter_key'] : $key);
                    $nameId = str_replace('!', '__', $name);
                    includeDatepicker(array($nameId . '_0', $nameId . '_1'));
                    echo $this->l('From') . ' <input type="text" id="' . $nameId . '_0" name="' . $name . '[0]" value="' . (isset($value[0]) ? $value[0] : '') . '"' . $width . ' ' . $keyPress . ' /><br />
					' . $this->l('To') . ' <input type="text" id="' . $nameId . '_1" name="' . $name . '[1]" value="' . (isset($value[1]) ? $value[1] : '') . '"' . $width . ' ' . $keyPress . ' />';
                    break;
                case 'select':
                    if (isset($params['filter_key'])) {
                        echo '<select onchange="$(\'#submitFilter' . $this->table . '\').focus();$(\'#submitFilter' . $this->table . '\').click();" name="' . $this->table . 'Filter_' . $params['filter_key'] . '" ' . (isset($params['width']) ? 'style="width: ' . $params['width'] . 'px"' : '') . '>
								<option value=""' . ($value == 0 && $value != '' ? ' selected="selected"' : '') . '>-</option>';
                        if (isset($params['select']) && is_array($params['select'])) {
                            foreach ($params['select'] as $optionValue => $optionDisplay) {
                                echo '<option value="' . $optionValue . '"' . (isset($_POST[$this->table . 'Filter_' . $params['filter_key']]) && Tools::getValue($this->table . 'Filter_' . $params['filter_key']) == $optionValue && Tools::getValue($this->table . 'Filter_' . $params['filter_key']) != '' ? ' selected="selected"' : '') . '>' . $optionDisplay . '</option>';
                            }
                        }
                        echo '</select>';
                        break;
                    }
                case 'text':
                default:
                    if (!Validate::isCleanHtml($value)) {
                        $value = '';
                    }
                    echo '<input type="text" name="' . $this->table . 'Filter_' . (isset($params['filter_key']) ? $params['filter_key'] : $key) . '" value="' . htmlentities($value, ENT_COMPAT, 'UTF-8') . '"' . $width . ' ' . $keyPress . ' />';
            }
            echo '</td>';
        }
        if ($this->shopLinkType) {
            echo '<td>--</td>';
        }
        if ($this->edit || $this->delete || $this->view && $this->view !== 'noActionColumn') {
            echo '<td class="center">--</td>';
        }
        echo '</tr>
			</thead>';
    }
 public static function setOrderStatusCapturedSuccesfully($order_ref)
 {
     $oid = self::getOrdersIdFromOrderRef($order_ref);
     if ($oid) {
         $amz_payments = new AmzPayments();
         $new_status = $amz_payments->capture_success_status_id;
         self::setOrderStatus($oid, $new_status);
     } else {
         if (!isset(Context::getContext()->cookie->amzSetStatusCaptured)) {
             Context::getContext()->cookie->amzSetStatusCaptured = serialize(array());
         }
         $tmpData = Tools::unSerialize(Context::getContext()->cookie->amzSetStatusCaptured);
         $tmpData[] = $order_ref;
         Context::getContext()->cookie->amzSetStatusCaptured = serialize($tmpData);
     }
 }
Example #11
0
 /**
  * load the last version informations stocked in base
  *
  * @return $this
  */
 public function loadFromConfig()
 {
     $last_version_check = Tools::unSerialize(Configuration::get('PS_LAST_VERSION'));
     if ($last_version_check) {
         if (isset($last_version_check['name'])) {
             $this->version_name = $last_version_check['name'];
         }
         if (isset($last_version_check['num'])) {
             $this->version_num = $last_version_check['num'];
         }
         if (isset($last_version_check['link'])) {
             $this->link = $last_version_check['link'];
         }
         if (isset($last_version_check['autoupgrade'])) {
             $this->autoupgrade = $last_version_check['autoupgrade'];
         }
         if (isset($last_version_check['autoupgrade_module'])) {
             $this->autoupgrade_module = $last_version_check['autoupgrade_module'];
         }
         if (isset($last_version_check['autoupgrade_last_version'])) {
             $this->autoupgrade_last_version = $last_version_check['autoupgrade_last_version'];
         }
         if (isset($last_version_check['autoupgrade_module_link'])) {
             $this->autoupgrade_module_link = $last_version_check['autoupgrade_module_link'];
         }
         if (isset($last_version_check['md5'])) {
             $this->md5 = $last_version_check['md5'];
         }
         if (isset($last_version_check['desc'])) {
             $this->desc = $last_version_check['desc'];
         }
         if (isset($last_version_check['changelog'])) {
             $this->changelog = $last_version_check['changelog'];
         }
     }
     return $this;
 }
Example #12
0
 private function sizeofvar($var)
 {
     $start_memory = memory_get_usage();
     $tmp = Tools::unSerialize(serialize($var));
     $size = memory_get_usage() - $start_memory;
     return $size;
 }
Example #13
0
 public function init()
 {
     self::$amz_payments = new AmzPayments();
     $this->isLogged = (bool) $this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer);
     parent::init();
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     $this->display_column_left = false;
     $this->display_column_right = false;
     $this->service = self::$amz_payments->getService();
     $this->nbProducts = $this->context->cart->nbProducts();
     if (Configuration::get('PS_CATALOG_MODE')) {
         $this->errors[] = Tools::displayError('This store has not accepted your new order.');
     }
     if ($this->nbProducts) {
         if (CartRule::isFeatureActive()) {
             if (Tools::isSubmit('submitAddDiscount')) {
                 if (!($code = trim(Tools::getValue('discount_name')))) {
                     $this->errors[] = Tools::displayError('You must enter a voucher code.');
                 } elseif (!Validate::isCleanHtml($code)) {
                     $this->errors[] = Tools::displayError('The voucher code is invalid.');
                 } else {
                     if (($cart_rule = new CartRule(CartRule::getIdByCode($code))) && Validate::isLoadedObject($cart_rule)) {
                         if ($error = $cart_rule->checkValidity($this->context, false, true)) {
                             $this->errors[] = $error;
                         } else {
                             $this->context->cart->addCartRule($cart_rule->id);
                             if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                                 Tools::redirect('index.php?controller=order-opc&addingCartRule=1');
                             }
                             Tools::redirect('index.php?controller=order&addingCartRule=1');
                         }
                     } else {
                         $this->errors[] = Tools::displayError('This voucher does not exists.');
                     }
                 }
                 $this->context->smarty->assign(array('errors' => $this->errors, 'discount_name' => Tools::safeOutput($code)));
             } elseif (($id_cart_rule = (int) Tools::getValue('deleteDiscount')) && Validate::isUnsignedId($id_cart_rule)) {
                 $this->context->cart->removeCartRule($id_cart_rule);
                 Tools::redirect('index.php?controller=order-opc');
             }
         }
         if ($this->context->cart->isVirtualCart()) {
             $this->setNoCarrier();
         }
     } else {
         Tools::redirect('index.php?controller=order-opc');
     }
     $this->context->smarty->assign('back', Tools::safeOutput(Tools::getValue('back')));
     if ($this->nbProducts) {
         $this->context->smarty->assign('virtual_cart', $this->context->cart->isVirtualCart());
     }
     $this->context->smarty->assign('is_multi_address_delivery', $this->context->cart->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1);
     $this->context->smarty->assign('open_multishipping_fancybox', (int) Tools::getValue('multi-shipping') == 1);
     if ($this->context->cart->nbProducts()) {
         if (Tools::isSubmit('ajax')) {
             if (Tools::isSubmit('method')) {
                 switch (Tools::getValue('method')) {
                     case 'setsession':
                         $this->context->cookie->amazon_id = Tools::getValue('amazon_id');
                         $this->context->cookie->amz_access_token = AmzPayments::prepareCookieValueForPrestaShopUse(Tools::getValue('access_token'));
                         $this->context->cookie->amz_access_token_set_time = time();
                         if (!$this->context->customer->isLogged() && self::$amz_payments->lpa_mode != 'pay') {
                             $d = self::$amz_payments->requestTokenInfo(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                             if ($d->aud != self::$amz_payments->client_id) {
                                 error_log('auth error LPA');
                                 die('error');
                             }
                             $d = self::$amz_payments->requestProfile(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                             $customer_userid = $d->user_id;
                             $customer_name = $d->name;
                             $customer_email = $d->email;
                             if ($customers_local_id = AmazonPaymentsCustomerHelper::findByAmazonCustomerId($customer_userid)) {
                                 Hook::exec('actionBeforeAuthentication');
                                 $customer = new Customer();
                                 $authentication = AmazonPaymentsCustomerHelper::getByCustomerID($customers_local_id, true, $customer);
                                 if (isset($authentication->active) && !$authentication->active) {
                                     exit;
                                 } elseif (!$authentication || !$customer->id) {
                                     exit;
                                 } else {
                                     $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                                     $this->context->cookie->id_customer = (int) $customer->id;
                                     $this->context->cookie->customer_lastname = $customer->lastname;
                                     $this->context->cookie->customer_firstname = $customer->firstname;
                                     $this->context->cookie->logged = 1;
                                     $customer->logged = 1;
                                     $this->context->cookie->is_guest = $customer->isGuest();
                                     $this->context->cookie->passwd = $customer->passwd;
                                     $this->context->cookie->email = $customer->email;
                                     // Add customer to the context
                                     $this->context->customer = $customer;
                                     if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                                         $this->context->cart = new Cart($id_cart);
                                     } else {
                                         $id_carrier = (int) $this->context->cart->id_carrier;
                                         $this->context->cart->id_carrier = 0;
                                         $this->context->cart->setDeliveryOption(null);
                                         $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                                         $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                                     }
                                     $this->context->cart->id_customer = (int) $customer->id;
                                     $this->context->cart->secure_key = $customer->secure_key;
                                     if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                                         $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ',');
                                         $this->context->cart->setDeliveryOption($delivery_option);
                                     }
                                     $this->context->cart->save();
                                     $this->context->cookie->id_cart = (int) $this->context->cart->id;
                                     $this->context->cookie->write();
                                     $this->context->cart->autosetProductAddress();
                                     Hook::exec('actionAuthentication');
                                     // Login information have changed, so we check if the cart rules still apply
                                     CartRule::autoRemoveFromCart($this->context);
                                     CartRule::autoAddToCart($this->context);
                                 }
                             }
                         }
                         exit;
                     case 'updateMessage':
                         if (Tools::isSubmit('message')) {
                             $txt_message = urldecode(Tools::getValue('message'));
                             $this->_updateMessage($txt_message);
                             if (count($this->errors)) {
                                 die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             die(true);
                         }
                         break;
                     case 'updateCarrierAndGetPayments':
                         if ((Tools::isSubmit('delivery_option') || Tools::isSubmit('id_carrier')) && Tools::isSubmit('recyclable') && Tools::isSubmit('gift') && Tools::isSubmit('gift_message')) {
                             $this->_assignWrappingAndTOS();
                             if ($this->_processCarrier()) {
                                 $carriers = $this->context->cart->simulateCarriersOutput();
                                 $return = array_merge(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'carrier_data' => $this->_getCarrierList(), 'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array('carriers' => $carriers))), $this->getFormatedSummaryDetail());
                                 Cart::addExtraCarriers($return);
                                 die(Tools::jsonEncode($return));
                             } else {
                                 $this->errors[] = Tools::displayError('An error occurred while updating the cart.');
                             }
                             if (count($this->errors)) {
                                 die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             exit;
                         }
                         break;
                     case 'updateTOSStatusAndGetPayments':
                         if (Tools::isSubmit('checked')) {
                             $this->context->cookie->checkedTOS = (int) Tools::getValue('checked');
                             die(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods())));
                         }
                         break;
                     case 'getCarrierList':
                         die(Tools::jsonEncode($this->_getCarrierList()));
                     case 'getAddressBlockAndCarriersAndPayments':
                         if ($this->context->customer->isLogged()) {
                             if (!Customer::getAddressesTotalById($this->context->customer->id)) {
                                 die(Tools::jsonEncode(array('no_address' => 1)));
                             }
                             if (file_exists(_PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php')) {
                                 include_once _PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php';
                                 $block_user_info = new BlockUserInfo();
                             }
                             $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                             $this->_processAddressFormat();
                             $this->_assignAddress();
                             $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                             $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
                             $return = array_merge(array('order_opc_adress' => $this->context->smarty->fetch(_PS_THEME_DIR_ . 'order-address.tpl'), 'block_user_info' => isset($block_user_info) ? $block_user_info->hookTop(array()) : '', 'carrier_data' => $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'no_address' => 0, 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency)))), $this->getFormatedSummaryDetail());
                             die(Tools::jsonEncode($return));
                         }
                         die(Tools::displayError());
                     case 'makeFreeOrder':
                         if (($id_order = $this->_checkFreeOrder()) && $id_order) {
                             $order = new Order((int) $id_order);
                             $email = $this->context->customer->email;
                             if ($this->context->customer->is_guest) {
                                 $this->context->customer->logout();
                             }
                             die('freeorder:' . $order->reference . ':' . $email);
                         }
                         exit;
                     case 'updateAddressesSelected':
                         $get_order_reference_details_request = new OffAmazonPaymentsService_Model_GetOrderReferenceDetailsRequest();
                         $get_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                         $get_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                         if (isset($this->context->cookie->amz_access_token)) {
                             $get_order_reference_details_request->setAddressConsentToken(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                         }
                         $reference_details_result_wrapper = $this->service->getOrderReferenceDetails($get_order_reference_details_request);
                         $physical_destination = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getDestination()->getPhysicalDestination();
                         $iso_code = (string) $physical_destination->GetCountryCode();
                         $city = (string) $physical_destination->GetCity();
                         $postcode = (string) $physical_destination->GetPostalCode();
                         $state = (string) $physical_destination->GetStateOrRegion();
                         $address_delivery = AmazonPaymentsAddressHelper::findByAmazonOrderReferenceIdOrNew(Tools::getValue('amazonOrderReferenceId'));
                         $address_delivery->id_country = Country::getByIso($iso_code);
                         $address_delivery->alias = 'Amazon Payments Delivery';
                         $address_delivery->lastname = 'amzLastname';
                         $address_delivery->firstname = 'amzFirstname';
                         $address_delivery->address1 = 'amzAddress1';
                         $address_delivery->city = $city;
                         $address_delivery->postcode = $postcode;
                         if ($state != '') {
                             $state_id = State::getIdByIso($state, Country::getByIso($iso_code));
                             if (!$state_id) {
                                 $state_id = State::getIdByName($state);
                             }
                             if ($state_id) {
                                 $address_delivery->id_state = $state_id;
                             }
                         }
                         $address_delivery->save();
                         AmazonPaymentsAddressHelper::saveAddressAmazonReference($address_delivery, Tools::getValue('amazonOrderReferenceId'));
                         $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                         $old_delivery_address_id = $this->context->cart->id_address_delivery;
                         $this->context->cart->id_address_delivery = $address_delivery->id;
                         $this->context->cart->id_address_invoice = $address_delivery->id;
                         $this->context->cart->setNoMultishipping();
                         $this->context->cart->updateAddressId($old_delivery_address_id, $address_delivery->id);
                         if (!$this->context->cart->update()) {
                             $this->errors[] = Tools::displayError('An error occurred while updating your cart.');
                         }
                         $infos = Address::getCountryAndState((int) $this->context->cart->id_address_delivery);
                         if (isset($infos['id_country']) && $infos['id_country']) {
                             $country = new Country((int) $infos['id_country']);
                             $this->context->country = $country;
                         }
                         $cart_rules = $this->context->cart->getCartRules();
                         CartRule::autoRemoveFromCart($this->context);
                         CartRule::autoAddToCart($this->context);
                         if ((int) Tools::getValue('allow_refresh')) {
                             $cart_rules2 = $this->context->cart->getCartRules();
                             if (count($cart_rules2) != count($cart_rules)) {
                                 $this->ajax_refresh = true;
                             } else {
                                 $rule_list = array();
                                 foreach ($cart_rules2 as $rule) {
                                     $rule_list[] = $rule['id_cart_rule'];
                                 }
                                 foreach ($cart_rules as $rule) {
                                     if (!in_array($rule['id_cart_rule'], $rule_list)) {
                                         $this->ajax_refresh = true;
                                         break;
                                     }
                                 }
                             }
                         }
                         if (!$this->context->cart->isMultiAddressDelivery()) {
                             $this->context->cart->setNoMultishipping();
                         }
                         if (!count($this->errors)) {
                             $result = $this->_getCarrierList();
                             if (isset($result['hasError'])) {
                                 unset($result['hasError']);
                             }
                             if (isset($result['errors'])) {
                                 unset($result['errors']);
                             }
                             $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                             $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
                             $result = array_merge($result, array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency))), 'carrier_data' => $this->_getCarrierList(), 'refresh' => (bool) $this->ajax_refresh), $this->getFormatedSummaryDetail());
                             die(Tools::jsonEncode($result));
                         }
                         if (count($this->errors)) {
                             die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
                         }
                         break;
                     case 'multishipping':
                         $this->_assignSummaryInformations();
                         $this->context->smarty->assign('product_list', $this->context->cart->getProducts());
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping-products.tpl');
                         $this->display();
                         die;
                     case 'cartReload':
                         $this->_assignSummaryInformations();
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->context->smarty->assign('opc', true);
                         $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl');
                         $this->display();
                         die;
                     case 'noMultiAddressDelivery':
                         $this->context->cart->setNoMultishipping();
                         die;
                     case 'executeOrder':
                         $customer = new Customer((int) $this->context->cart->id_customer);
                         if (!Validate::isLoadedObject($customer)) {
                             $customer->is_guest = true;
                             $customer->lastname = 'AmazonPayments';
                             $customer->firstname = 'AmazonPayments';
                             $customer->email = 'amazon' . time() . '@localshop.xyz';
                             $customer->passwd = Tools::substr(md5(time()), 0, 10);
                             $customer->save();
                         }
                         if (Tools::getValue('confirm')) {
                             $total = $this->context->cart->getOrderTotal(true, Cart::BOTH);
                             $currency_order = new Currency((int) $this->context->cart->id_currency);
                             $currency_code = $currency_order->iso_code;
                             if (!AmazonTransactions::isAlreadyConfirmedOrder(Tools::getValue('amazonOrderReferenceId'))) {
                                 $set_order_reference_details_request = new OffAmazonPaymentsService_Model_SetOrderReferenceDetailsRequest();
                                 $set_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                                 $set_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 $set_order_reference_details_request->setOrderReferenceAttributes(new OffAmazonPaymentsService_Model_OrderReferenceAttributes());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->setOrderTotal(new OffAmazonPaymentsService_Model_OrderTotal());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getOrderTotal()->setCurrencyCode($currency_code);
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getOrderTotal()->setAmount($total);
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->setPlatformId(self::$amz_payments->getPfId());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->setSellerOrderAttributes(new OffAmazonPaymentsService_Model_SellerOrderAttributes());
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getSellerOrderAttributes()->setSellerOrderId(self::$amz_payments->createUniqueOrderId((int) $this->context->cart->id));
                                 $set_order_reference_details_request->getOrderReferenceAttributes()->getSellerOrderAttributes()->setStoreName(Configuration::get('PS_SHOP_NAME'));
                                 $this->service->setOrderReferenceDetails($set_order_reference_details_request);
                                 $confirm_order_reference_request = new OffAmazonPaymentsService_Model_ConfirmOrderReferenceRequest();
                                 $confirm_order_reference_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 $confirm_order_reference_request->setSellerId(self::$amz_payments->merchant_id);
                                 $this->service->confirmOrderReference($confirm_order_reference_request);
                                 $get_order_reference_details_request = new OffAmazonPaymentsService_Model_GetOrderReferenceDetailsRequest();
                                 $get_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                                 $get_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 if (isset($this->context->cookie->amz_access_token)) {
                                     $get_order_reference_details_request->setAddressConsentToken(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                                 }
                                 $reference_details_result_wrapper = $this->service->getOrderReferenceDetails($get_order_reference_details_request);
                                 $sql_arr = array('amz_tx_time' => pSQL(time()), 'amz_tx_type' => 'order_ref', 'amz_tx_status' => pSQL($reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getOrderReferenceStatus()->getState()), 'amz_tx_order_reference' => pSQL(Tools::getValue('amazonOrderReferenceId')), 'amz_tx_expiration' => pSQL(strtotime($reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getExpirationTimestamp())), 'amz_tx_reference' => pSQL(Tools::getValue('amazonOrderReferenceId')), 'amz_tx_amz_id' => pSQL(Tools::getValue('amazonOrderReferenceId')), 'amz_tx_last_change' => pSQL(time()), 'amz_tx_amount' => pSQL($reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getOrderTotal()->getAmount()));
                                 Db::getInstance()->insert('amz_transactions', $sql_arr);
                             } else {
                                 $get_order_reference_details_request = new OffAmazonPaymentsService_Model_GetOrderReferenceDetailsRequest();
                                 $get_order_reference_details_request->setSellerId(self::$amz_payments->merchant_id);
                                 $get_order_reference_details_request->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                 if (isset($this->context->cookie->amz_access_token)) {
                                     $get_order_reference_details_request->setAddressConsentToken(AmzPayments::prepareCookieValueForAmazonPaymentsUse($this->context->cookie->amz_access_token));
                                 }
                                 $reference_details_result_wrapper = $this->service->getOrderReferenceDetails($get_order_reference_details_request);
                             }
                             $physical_destination = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getDestination()->getPhysicalDestination();
                             $iso_code = (string) $physical_destination->GetCountryCode();
                             $city = (string) $physical_destination->GetCity();
                             $postcode = (string) $physical_destination->GetPostalCode();
                             $state = (string) $physical_destination->GetStateOrRegion();
                             $names_array = explode(' ', (string) $physical_destination->getName(), 2);
                             $regex = '/[^a-zA-ZäöüÄÖÜßÂâÀÁáàÇçÈÉËëéèÎîÏïÙÛùúòóûêôíÍŸÿªñÑ\\s]/u';
                             $names_array[0] = preg_replace($regex, '', $names_array[0]);
                             $names_array[1] = preg_replace($regex, '', $names_array[1]);
                             if ($customer->is_guest) {
                                 $customer->lastname = $names_array[1];
                                 $customer->firstname = $names_array[0];
                                 $customer->email = (string) $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getBuyer()->getEmail();
                                 $customer->save();
                                 $this->context->cart->id_customer = $customer->id;
                                 $this->context->cart->save();
                             }
                             $s_company_name = '';
                             if ((string) $physical_destination->getAddressLine3() != '') {
                                 $s_street = Tools::substr($physical_destination->getAddressLine3(), 0, Tools::strrpos($physical_destination->getAddressLine3(), ' '));
                                 $s_street_nr = Tools::substr($physical_destination->getAddressLine3(), Tools::strrpos($physical_destination->getAddressLine3(), ' ') + 1);
                                 $s_company_name = trim($physical_destination->getAddressLine1() . $physical_destination->getAddressLine2());
                             } else {
                                 if ((string) $physical_destination->getAddressLine2() != '') {
                                     $s_street = Tools::substr($physical_destination->getAddressLine2(), 0, Tools::strrpos($physical_destination->getAddressLine2(), ' '));
                                     $s_street_nr = Tools::substr($physical_destination->getAddressLine2(), Tools::strrpos($physical_destination->getAddressLine2(), ' ') + 1);
                                     $s_company_name = trim($physical_destination->getAddressLine1());
                                 } else {
                                     $s_street = Tools::substr($physical_destination->getAddressLine1(), 0, Tools::strrpos($physical_destination->getAddressLine1(), ' '));
                                     $s_street_nr = Tools::substr($physical_destination->getAddressLine1(), Tools::strrpos($physical_destination->getAddressLine1(), ' ') + 1);
                                 }
                             }
                             $phone = '';
                             if ((string) $physical_destination->getPhone() != '' && ValidateCore::isPhoneNumber((string) $physical_destination->getPhone())) {
                                 $phone = (string) $physical_destination->getPhone();
                             }
                             $address_delivery = AmazonPaymentsAddressHelper::findByAmazonOrderReferenceIdOrNew(Tools::getValue('amazonOrderReferenceId'));
                             $address_delivery->lastname = $names_array[1];
                             $address_delivery->firstname = $names_array[0];
                             if ($s_company_name != '') {
                                 $address_delivery->company = $s_company_name;
                             }
                             $address_delivery->address1 = (string) $s_street . ' ' . (string) $s_street_nr;
                             $address_delivery->postcode = (string) $physical_destination->getPostalCode();
                             $address_delivery->id_country = Country::getByIso((string) $physical_destination->getCountryCode());
                             if ($phone != '') {
                                 $address_delivery->phone = $phone;
                             }
                             if ($state != '') {
                                 $state_id = State::getIdByIso($state, Country::getByIso((string) $physical_destination->getCountryCode()));
                                 if (!$state_id) {
                                     $state_id = State::getIdByName($state);
                                 }
                                 if ($state_id) {
                                     $address_delivery->id_state = $state_id;
                                 }
                             }
                             $address_delivery->save();
                             AmazonPaymentsAddressHelper::saveAddressAmazonReference($address_delivery, Tools::getValue('amazonOrderReferenceId'));
                             $this->context->cart->id_address_delivery = $address_delivery->id;
                             $billing_address_object = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getBillingAddress();
                             if (method_exists($billing_address_object, 'getPhysicalAddress')) {
                                 $amz_billing_address = $reference_details_result_wrapper->GetOrderReferenceDetailsResult->getOrderReferenceDetails()->getBillingAddress()->getPhysicalAddress();
                                 $iso_code = (string) $amz_billing_address->GetCountryCode();
                                 $city = (string) $amz_billing_address->GetCity();
                                 $postcode = (string) $amz_billing_address->GetPostalCode();
                                 $state = (string) $amz_billing_address->GetStateOrRegion();
                                 $invoice_names_array = explode(' ', (string) $amz_billing_address->getName(), 2);
                                 $regex = '/[^a-zA-ZäöüÄÖÜßÂâÀÁáàÇçÈÉËëéèÎîÏïÙÛùúòóûêôíÍŸÿªñÑ\\s]/u';
                                 $invoice_names_array[0] = preg_replace($regex, '', $invoice_names_array[0]);
                                 $invoice_names_array[1] = preg_replace($regex, '', $invoice_names_array[1]);
                                 $s_company_name = '';
                                 if ((string) $amz_billing_address->getAddressLine3() != '') {
                                     $s_street = Tools::substr($amz_billing_address->getAddressLine3(), 0, Tools::strrpos($amz_billing_address->getAddressLine3(), ' '));
                                     $s_street_nr = Tools::substr($amz_billing_address->getAddressLine3(), Tools::strrpos($amz_billing_address->getAddressLine3(), ' ') + 1);
                                     $s_company_name = trim($amz_billing_address->getAddressLine1() . $amz_billing_address->getAddressLine2());
                                 } else {
                                     if ((string) $amz_billing_address->getAddressLine2() != '') {
                                         $s_street = Tools::substr($amz_billing_address->getAddressLine2(), 0, Tools::strrpos($amz_billing_address->getAddressLine2(), ' '));
                                         $s_street_nr = Tools::substr($amz_billing_address->getAddressLine2(), Tools::strrpos($amz_billing_address->getAddressLine2(), ' ') + 1);
                                         $s_company_name = trim($amz_billing_address->getAddressLine1());
                                     } else {
                                         $s_street = Tools::substr($amz_billing_address->getAddressLine1(), 0, Tools::strrpos($amz_billing_address->getAddressLine1(), ' '));
                                         $s_street_nr = Tools::substr($amz_billing_address->getAddressLine1(), Tools::strrpos($amz_billing_address->getAddressLine1(), ' ') + 1);
                                     }
                                 }
                                 $phone = '';
                                 if ((string) $amz_billing_address->getPhone() != '' && ValidateCore::isPhoneNumber((string) $amz_billing_address->getPhone())) {
                                     $phone = (string) $amz_billing_address->getPhone();
                                 }
                                 $address_invoice = AmazonPaymentsAddressHelper::findByAmazonOrderReferenceIdOrNew(Tools::getValue('amazonOrderReferenceId') . '-inv');
                                 $address_invoice->alias = 'Amazon Payments Invoice';
                                 $address_invoice->lastname = $invoice_names_array[1];
                                 $address_invoice->firstname = $invoice_names_array[0];
                                 if ($s_company_name != '') {
                                     $address_invoice->company = $s_company_name;
                                 }
                                 $address_invoice->address1 = (string) $s_street . ' ' . (string) $s_street_nr;
                                 $address_invoice->postcode = (string) $amz_billing_address->getPostalCode();
                                 $address_invoice->city = $city;
                                 $address_invoice->id_country = Country::getByIso((string) $amz_billing_address->getCountryCode());
                                 if ($phone != '') {
                                     $address_invoice->phone = $phone;
                                 }
                                 if ($state != '') {
                                     $state_id = State::getIdByIso($state, Country::getByIso((string) $amz_billing_address->getCountryCode()));
                                     if (!$state_id) {
                                         $state_id = State::getIdByName($state);
                                     }
                                     if ($state_id) {
                                         $address_invoice->id_state = $state_id;
                                     }
                                 }
                                 $address_invoice->save();
                                 AmazonPaymentsAddressHelper::saveAddressAmazonReference($address_invoice, Tools::getValue('amazonOrderReferenceId') . '-inv');
                                 $this->context->cart->id_address_invoice = $address_invoice->id;
                             } else {
                                 $this->context->cart->id_address_invoice = $address_delivery->id;
                                 $address_invoice = $address_delivery;
                             }
                             $this->context->cart->save();
                             if (self::$amz_payments->authorization_mode == 'fast_auth') {
                                 $authorization_reference_id = Tools::getValue('amazonOrderReferenceId');
                                 if (isset($this->context->cookie->setHadErrorNowWallet) && $this->context->cookie->setHadErrorNowWallet == 1) {
                                     $confirm_order_ref_req_model = new OffAmazonPaymentsService_Model_ConfirmOrderReferenceRequest();
                                     $confirm_order_ref_req_model->setAmazonOrderReferenceId(Tools::getValue('amazonOrderReferenceId'));
                                     $confirm_order_ref_req_model->setSellerId(self::$amz_payments->merchant_id);
                                     try {
                                         $this->service->confirmOrderReference($confirm_order_ref_req_model);
                                     } catch (OffAmazonPaymentsService_Exception $e) {
                                         echo 'ERROR: ' . $e->getMessage();
                                     }
                                     unset($this->context->cookie->setHadErrorNowWallet);
                                 }
                                 $authorization_response_wrapper = AmazonTransactions::fastAuth(self::$amz_payments, $this->service, $authorization_reference_id, $total, $currency_code);
                                 if (is_object($authorization_response_wrapper)) {
                                     $details = $authorization_response_wrapper->getAuthorizeResult()->getAuthorizationDetails();
                                     $status = $details->getAuthorizationStatus()->getState();
                                     if ($status == 'Declined') {
                                         $reason = $details->getAuthorizationStatus()->getReasonCode();
                                         if ($reason == 'InvalidPaymentMethod') {
                                             $this->context->cookie->setHadErrorNowWallet = 1;
                                             die(Tools::jsonEncode(array('hasError' => true, 'errors' => array(Tools::displayError(self::$amz_payments->l('Your selected payment method is currently not available. Please select another one.'))))));
                                         } else {
                                             die(Tools::jsonEncode(array('hasError' => true, 'redirection' => 'index.php?controller=order', 'errors' => array(Tools::displayError(self::$amz_payments->l('Your selected payment method has been declined. Please chose another one.'))))));
                                         }
                                     }
                                     $amazon_authorization_id = $authorization_response_wrapper->getAuthorizeResult()->getAuthorizationDetails()->getAmazonAuthorizationId();
                                     /*
                                     if (self::$amz_payments->capture_mode == 'after_auth') {
                                         $amazon_capture_response = AmazonTransactions::capture(self::$amz_payments, $this->service, $amazon_authorization_id, $total, $currency_code);
                                         if (is_object($amazon_capture_response)) {
                                             $amazon_capture_id = $amazon_capture_response->getCaptureResult()
                                                 ->getCaptureDetails()
                                                 ->getAmazonCaptureId();
                                             $amazon_capture_reference_id = $amazon_capture_response->getCaptureResult()
                                                 ->getCaptureDetails()
                                                 ->getCaptureReferenceId();
                                         }
                                     }
                                     */
                                 }
                             }
                             if ($this->context->cart->secure_key == '') {
                                 $this->context->cart->secure_key = $customer->secure_key;
                                 $this->context->cart->save();
                             }
                             $new_order_status_id = (int) Configuration::get('PS_OS_PREPARATION');
                             if ((int) Configuration::get('AMZ_ORDER_STATUS_ID') > 0) {
                                 $new_order_status_id = Configuration::get('AMZ_ORDER_STATUS_ID');
                             }
                             $this->module->validateOrder((int) $this->context->cart->id, $new_order_status_id, $total, $this->module->displayName, null, array(), null, false, $customer->secure_key);
                             if (self::$amz_payments->authorization_mode == 'after_checkout') {
                                 $authorization_reference_id = Tools::getValue('amazonOrderReferenceId');
                                 $authorization_response_wrapper = AmazonTransactions::authorize(self::$amz_payments, $this->service, $authorization_reference_id, $total, $currency_code);
                                 $amazon_authorization_id = @$authorization_response_wrapper->getAuthorizeResult()->getAuthorizationDetails()->getAmazonAuthorizationId();
                                 /*
                                 if (self::$amz_payments->capture_mode == 'after_auth' && isset($amazon_authorization_id) && $amazon_authorization_id !== false && $amazon_authorization_id != null) {
                                     $amazon_capture_response = AmazonTransactions::capture(self::$amz_payments, $this->service, $amazon_authorization_id, $total, $currency_code);
                                     if (is_object($amazon_capture_response)) {
                                         $amazon_capture_id = $amazon_capture_response->getCaptureResult()
                                             ->getCaptureDetails()
                                             ->getAmazonCaptureId();
                                         $amazon_capture_reference_id = $amazon_capture_response->getCaptureResult()
                                             ->getCaptureDetails()
                                             ->getCaptureReferenceId();
                                     }
                                 }
                                 */
                             }
                             self::$amz_payments->setAmazonReferenceIdForOrderId(Tools::getValue('amazonOrderReferenceId'), $this->module->currentOrder);
                             self::$amz_payments->setAmazonReferenceIdForOrderTransactionId(Tools::getValue('amazonOrderReferenceId'), $this->module->currentOrder);
                             if (isset($authorization_reference_id)) {
                                 self::$amz_payments->setAmazonAuthorizationReferenceIdForOrderId($authorization_reference_id, $this->module->currentOrder);
                             }
                             if (isset($amazon_authorization_id)) {
                                 self::$amz_payments->setAmazonAuthorizationIdForOrderId($amazon_authorization_id, $this->module->currentOrder);
                             }
                             /*
                             if (isset($amazon_capture_reference_id)) {
                                 self::$amz_payments->setAmazonCaptureReferenceIdForOrderId($amazon_capture_reference_id, $this->module->currentOrder);
                             }
                             if (isset($amazon_capture_id)) {
                                 self::$amz_payments->setAmazonCaptureIdForOrderId($amazon_capture_id, $this->module->currentOrder);
                             }
                             */
                             if (isset($this->context->cookie->amzSetStatusAuthorized)) {
                                 $tmpOrderRefs = Tools::unSerialize($this->context->cookie->amzSetStatusAuthorized);
                                 if (is_array($tmpOrderRefs)) {
                                     foreach ($tmpOrderRefs as $order_ref) {
                                         AmazonTransactions::setOrderStatusAuthorized($order_ref);
                                     }
                                 }
                                 unset($this->context->cookie->amzSetStatusAuthorized);
                             }
                             if (isset($this->context->cookie->amzSetStatusCaptured)) {
                                 $tmpOrderRefs = Tools::unSerialize($this->context->cookie->amzSetStatusCaptured);
                                 if (is_array($tmpOrderRefs)) {
                                     foreach ($tmpOrderRefs as $order_ref) {
                                         AmazonTransactions::setOrderStatusCaptured($order_ref);
                                     }
                                 }
                                 unset($this->context->cookie->amzSetStatusCaptured);
                             }
                             if (Tools::getValue('connect_amz_account') == '1') {
                                 $this->context->cookie->amz_connect_order = $this->module->currentOrder;
                                 $this->context->cookie->amz_payments_address_id = $address_delivery->id;
                                 $this->context->cookie->amz_payments_invoice_address_id = $address_invoice->id;
                                 $login_redirect = $this->context->link->getModuleLink('amzpayments', 'process_login');
                                 $login_redirect = str_replace('http://', 'https://', $login_redirect);
                                 $login_redirect .= '?fromCheckout=1&access_token=' . $this->context->cookie->amz_access_token;
                                 die(Tools::jsonEncode(array('orderSucceed' => true, 'redirection' => $login_redirect)));
                             }
                             if (!$customer->is_guest) {
                                 if (!AmzPayments::addressAlreadyExists($address_delivery, $customer)) {
                                     $address_delivery->id_customer = $customer->id;
                                     $address_delivery->save();
                                 }
                                 if (!AmzPayments::addressAlreadyExists($address_invoice, $customer)) {
                                     $address_invoice->id_customer = $customer->id;
                                     $address_invoice->save();
                                 }
                             } else {
                                 if ($registered_customer = AmazonPaymentsCustomerHelper::findByEmailAddress($customer->email)) {
                                     if (!AmzPayments::addressAlreadyExists($address_delivery, $registered_customer)) {
                                         $address_delivery->id_customer = $registered_customer->id;
                                         $address_delivery->save();
                                     }
                                     if (!AmzPayments::addressAlreadyExists($address_invoice, $registered_customer)) {
                                         $address_invoice->id_customer = $registered_customer->id;
                                         $address_invoice->save();
                                     }
                                 }
                                 $this->context->cookie->show_success_amz_message = true;
                             }
                             die(Tools::jsonEncode(array('orderSucceed' => true, 'redirection' => __PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . (int) $this->context->cart->id . '&id_module=' . $this->module->id . '&id_order=' . $this->module->currentOrder . '&key=' . $customer->secure_key)));
                         }
                         die;
                     default:
                         throw new PrestaShopException('Unknown method "' . Tools::getValue('method') . '"');
                 }
             } else {
                 throw new PrestaShopException('Method is not defined');
             }
         }
     } elseif (Tools::isSubmit('ajax')) {
         throw new PrestaShopException('Method is not defined');
     }
 }
Example #14
0
 /**
  * Display list header (filtering, pagination and column names)
  */
 public function displayListHeader()
 {
     if (!isset($this->list_id)) {
         $this->list_id = $this->table;
     }
     $id_cat = (int) Tools::getValue('id_' . ($this->is_cms ? 'cms_' : '') . 'category');
     if (!isset($token) || empty($token)) {
         $token = $this->token;
     }
     /* Determine total page number */
     $pagination = $this->_default_pagination;
     if (in_array((int) Tools::getValue($this->list_id . '_pagination'), $this->_pagination)) {
         $pagination = (int) Tools::getValue($this->list_id . '_pagination');
     } elseif (isset($this->context->cookie->{$this->list_id . '_pagination'}) && $this->context->cookie->{$this->list_id . '_pagination'}) {
         $pagination = $this->context->cookie->{$this->list_id . '_pagination'};
     }
     $total_pages = max(1, ceil($this->listTotal / $pagination));
     $identifier = Tools::getIsset($this->identifier) ? '&' . $this->identifier . '=' . (int) Tools::getValue($this->identifier) : '';
     $order = '';
     if (Tools::getIsset($this->table . 'Orderby')) {
         $order = '&' . $this->table . 'Orderby=' . urlencode($this->orderBy) . '&' . $this->table . 'Orderway=' . urlencode(strtolower($this->orderWay));
     }
     $action = $this->currentIndex . $identifier . '&token=' . $token . '#' . $this->list_id;
     /* Determine current page number */
     $page = (int) Tools::getValue('submitFilter' . $this->list_id);
     if (!$page) {
         $page = 1;
     }
     if ($page > $total_pages) {
         $page = $total_pages;
     }
     $this->page = (int) $page;
     /* Choose number of results per page */
     $selected_pagination = Tools::getValue($this->list_id . '_pagination', isset($this->context->cookie->{$this->list_id . '_pagination'}) ? $this->context->cookie->{$this->list_id . '_pagination'} : $this->_default_pagination);
     if (!isset($this->table_id) && $this->position_identifier && (int) Tools::getValue($this->position_identifier, 1)) {
         $this->table_id = substr($this->identifier, 3, strlen($this->identifier));
     }
     if ($this->position_identifier && ($this->orderBy == 'position' && $this->orderWay != 'DESC')) {
         $table_dnd = true;
     }
     $prefix = isset($this->controller_name) ? str_replace(array('admin', 'controller'), '', Tools::strtolower($this->controller_name)) : '';
     $ajax = false;
     foreach ($this->fields_list as $key => $params) {
         if (!isset($params['type'])) {
             $params['type'] = 'text';
         }
         $value_key = $prefix . $this->list_id . 'Filter_' . (array_key_exists('filter_key', $params) && $key != 'active' ? $params['filter_key'] : $key);
         $value = Context::getContext()->cookie->{$value_key};
         if (!$value && Tools::getIsset($value_key)) {
             $value = Tools::getValue($value_key);
         }
         switch ($params['type']) {
             case 'bool':
                 if (isset($params['ajax']) && $params['ajax']) {
                     $ajax = true;
                 }
                 break;
             case 'date':
             case 'datetime':
                 if (is_string($value)) {
                     $value = Tools::unSerialize($value);
                 }
                 if (!Validate::isCleanHtml($value[0]) || !Validate::isCleanHtml($value[1])) {
                     $value = '';
                 }
                 $name = $this->list_id . 'Filter_' . (isset($params['filter_key']) ? $params['filter_key'] : $key);
                 $name_id = str_replace('!', '__', $name);
                 $params['id_date'] = $name_id;
                 $params['name_date'] = $name;
                 $this->context->controller->addJqueryUI('ui.datepicker');
                 break;
             case 'select':
                 foreach ($params['list'] as $option_value => $option_display) {
                     if (isset(Context::getContext()->cookie->{$prefix . $this->list_id . 'Filter_' . $params['filter_key']}) && Context::getContext()->cookie->{$prefix . $this->list_id . 'Filter_' . $params['filter_key']} == $option_value && Context::getContext()->cookie->{$prefix . $this->list_id . 'Filter_' . $params['filter_key']} != '') {
                         $this->fields_list[$key]['select'][$option_value]['selected'] = 'selected';
                     }
                 }
                 break;
             case 'text':
                 if (!Validate::isCleanHtml($value)) {
                     $value = '';
                 }
         }
         $params['value'] = $value;
         $this->fields_list[$key] = $params;
     }
     $has_value = false;
     $has_search_field = false;
     foreach ($this->fields_list as $key => $field) {
         if (isset($field['value']) && $field['value'] !== false && $field['value'] !== '') {
             if (is_array($field['value']) && trim(implode('', $field['value'])) == '') {
                 continue;
             }
             $has_value = true;
             break;
         }
         if (!(isset($field['search']) && $field['search'] === false)) {
             $has_search_field = true;
         }
     }
     Context::getContext()->smarty->assign(array('page' => $page, 'simple_header' => $this->simple_header, 'total_pages' => $total_pages, 'selected_pagination' => $selected_pagination, 'pagination' => $this->_pagination, 'list_total' => $this->listTotal, 'sql' => isset($this->sql) && $this->sql ? str_replace('\\n', ' ', str_replace('\\r', '', $this->sql)) : false, 'token' => $this->token, 'table' => $this->table, 'bulk_actions' => $this->bulk_actions, 'show_toolbar' => $this->show_toolbar, 'toolbar_scroll' => $this->toolbar_scroll, 'toolbar_btn' => $this->toolbar_btn, 'has_bulk_actions' => $this->hasBulkActions($has_value), 'filters_has_value' => (bool) $has_value));
     $this->header_tpl->assign(array_merge(array('ajax' => $ajax, 'title' => array_key_exists('title', $this->tpl_vars) ? $this->tpl_vars['title'] : $this->title, 'show_filters' => count($this->_list) > 1 && $has_search_field || $has_value, 'currentIndex' => $this->currentIndex, 'action' => $action, 'is_order_position' => $this->position_identifier && $this->orderBy == 'position', 'order_way' => $this->orderWay, 'order_by' => $this->orderBy, 'fields_display' => $this->fields_list, 'delete' => in_array('delete', $this->actions), 'identifier' => $this->identifier, 'id_cat' => $id_cat, 'shop_link_type' => $this->shopLinkType, 'has_actions' => !empty($this->actions), 'table_id' => isset($this->table_id) ? $this->table_id : null, 'table_dnd' => isset($table_dnd) ? $table_dnd : null, 'name' => isset($name) ? $name : null, 'name_id' => isset($name_id) ? $name_id : null, 'row_hover' => $this->row_hover, 'list_id' => isset($this->list_id) ? $this->list_id : $this->table), $this->tpl_vars));
     return $this->header_tpl->fetch();
 }
 public function renderForm()
 {
     if (!($obj = $this->loadObject(true))) {
         return;
     }
     $image = _PS_STORE_IMG_DIR_ . $obj->id . '.jpg';
     $image_url = ImageManager::thumbnail($image, $this->table . '_' . (int) $obj->id . '.' . $this->imageType, 350, $this->imageType, true, true);
     $image_size = file_exists($image) ? filesize($image) / 1000 : false;
     $tmp_addr = new Address();
     $res = $tmp_addr->getFieldsRequiredDatabase();
     $required_fields = array();
     foreach ($res as $row) {
         $required_fields[(int) $row['id_required_field']] = $row['field_name'];
     }
     $this->fields_form = array('legend' => array('title' => $this->l('Stores'), 'icon' => 'icon-home'), 'input' => array(array('type' => 'text', 'label' => $this->l('Name'), 'name' => 'name', 'required' => false, 'hint' => array($this->l('Store name (e.g. City Center Mall Store).'), $this->l('Allowed characters: letters, spaces and %s'))), array('type' => 'text', 'label' => $this->l('Address'), 'name' => 'address1', 'required' => true), array('type' => 'text', 'label' => $this->l('Address (2)'), 'name' => 'address2'), array('type' => 'text', 'label' => $this->l('Zip/postal Code'), 'name' => 'postcode', 'required' => in_array('postcode', $required_fields)), array('type' => 'text', 'label' => $this->l('City'), 'name' => 'city', 'required' => true), array('type' => 'select', 'label' => $this->l('Country'), 'name' => 'id_country', 'required' => true, 'default_value' => (int) $this->context->country->id, 'options' => array('query' => Country::getCountries($this->context->language->id), 'id' => 'id_country', 'name' => 'name')), array('type' => 'select', 'label' => $this->l('State'), 'name' => 'id_state', 'required' => true, 'options' => array('id' => 'id_state', 'name' => 'name', 'query' => null)), array('type' => 'latitude', 'label' => $this->l('Latitude / Longitude'), 'name' => 'latitude', 'required' => true, 'maxlength' => 12, 'hint' => $this->l('Store coordinates (e.g. 45.265469/-47.226478).')), array('type' => 'text', 'label' => $this->l('Phone'), 'name' => 'phone'), array('type' => 'text', 'label' => $this->l('Fax'), 'name' => 'fax'), array('type' => 'text', 'label' => $this->l('Email address'), 'name' => 'email'), array('type' => 'textarea', 'label' => $this->l('Note'), 'name' => 'note', 'cols' => 42, 'rows' => 4), array('type' => 'switch', 'label' => $this->l('Status'), 'name' => 'active', 'required' => false, 'is_bool' => true, 'values' => array(array('id' => 'active_on', 'value' => 1, 'label' => $this->l('Enabled')), array('id' => 'active_off', 'value' => 0, 'label' => $this->l('Disabled'))), 'hint' => $this->l('Whether or not to display this store.')), array('type' => 'file', 'label' => $this->l('Picture'), 'name' => 'image', 'display_image' => true, 'image' => $image_url ? $image_url : false, 'size' => $image_size, 'hint' => $this->l('Storefront picture.'))), 'hours' => array(), 'submit' => array('title' => $this->l('Save')));
     if (Shop::isFeatureActive()) {
         $this->fields_form['input'][] = array('type' => 'shop', 'label' => $this->l('Shop association'), 'name' => 'checkBoxShopAsso');
     }
     $days = array();
     $days[1] = $this->l('Monday');
     $days[2] = $this->l('Tuesday');
     $days[3] = $this->l('Wednesday');
     $days[4] = $this->l('Thursday');
     $days[5] = $this->l('Friday');
     $days[6] = $this->l('Saturday');
     $days[7] = $this->l('Sunday');
     $hours = $this->getFieldValue($obj, 'hours');
     if (!empty($hours)) {
         $hours_unserialized = Tools::unSerialize($hours);
     }
     $this->fields_value = array('latitude' => $this->getFieldValue($obj, 'latitude') ? $this->getFieldValue($obj, 'latitude') : Configuration::get('PS_STORES_CENTER_LAT'), 'longitude' => $this->getFieldValue($obj, 'longitude') ? $this->getFieldValue($obj, 'longitude') : Configuration::get('PS_STORES_CENTER_LONG'), 'days' => $days, 'hours' => isset($hours_unserialized) ? $hours_unserialized : false);
     return parent::renderForm();
 }
Example #16
0
 private function displaySettingsForm()
 {
     $db_version = Configuration::get('yotpo_db_version');
     if (is_bool($db_version) && !$db_version) {
         if (!Configuration::get('yotpo_rich_snippet_cache_created')) {
             YotpoSnippetCache::createDB();
             Configuration::updateValue('yotpo_rich_snippet_cache_created', 1);
         } else {
             $this->registerHook('yotpoProductAvarageScore');
             $this->registerHook('yotpoProductReviewCount');
             YotpoSnippetCache::updateDB();
             Configuration::updateValue('yotpo_db_version', $this->db_version);
         }
     }
     $smarty = $this->context->smarty;
     $all_statuses = OrderState::getOrderStates($this->getLanguageId());
     //no configuration found -- use default
     if (Configuration::get('yotpo_map_status') == false) {
         Configuration::updateValue('yotpo_map_status', serialize($this->getAcceptedMapStatuses()), false);
     }
     if (method_exists('Tools', "unSerialize")) {
         $selected_statuses = Tools::unSerialize(Configuration::get('yotpo_map_status'));
     } else {
         $selected_statuses = @unserialize(Configuration::get('yotpo_map_status'));
     }
     foreach ($all_statuses as &$status) {
         $status['selected'] = in_array($status['id_order_state'], $selected_statuses) ? '1' : '0';
     }
     $smarty->assign(array('yotpo_action' => $_SERVER['REQUEST_URI'], 'yotpo_appKey' => Tools::getValue('yotpo_app_key', Configuration::get('yotpo_app_key')), 'yotpo_oauthToken' => Tools::getValue('yotpo_oauth_token', Configuration::get('yotpo_oauth_token')), 'yotpo_widgetLocation' => Configuration::get('yotpo_widget_location'), 'yotpo_showPastOrdersButton' => Configuration::get('yotpo_past_orders') != 1 ? true : false, 'yotpo_tabName' => Configuration::get('yotpo_widget_tab_name'), 'yotpo_bottomLineEnabled' => Configuration::get('yotpo_bottom_line_enabled'), 'yotpo_bottomLineLocation' => Configuration::get('yotpo_bottom_line_location'), 'yotpo_widget_language_code' => Configuration::get('yotpo_language'), 'yotpo_language_as_site' => Configuration::get('yotpo_language_as_site'), 'yotpo_rich_snippets' => Configuration::get('yotpo_rich_snippets'), 'yotpo_all_statuses' => $all_statuses));
     $settings_template = $this->display(__FILE__, 'views/templates/admin/settingsForm.tpl');
     if (strpos($settings_template, 'yotpo_map_enabled') != false || strpos($settings_template, 'yotpo_language_as_site') == false || strpos($settings_template, 'yotpo_rich_snippets') == false) {
         $settings_template = $this->getNonCachedTemplate('views/templates/admin/settingsForm.tpl');
     }
     $this->_html .= $settings_template;
 }
 public function processDelete()
 {
     $obj = $this->loadObject();
     if ($obj) {
         if ($obj->isUsed()) {
             $this->errors[] = $this->l('The theme is being used by at least one shop. Please choose another theme before continuing.');
             return false;
         }
         $themes = array();
         foreach (Theme::getThemes() as $theme) {
             if ($theme->id != $obj->id) {
                 $themes[] = $theme->directory;
             }
         }
         if (is_dir(_PS_ALL_THEMES_DIR_ . $obj->directory) && !in_array($obj->directory, $themes)) {
             Tools::deleteDirectory(_PS_ALL_THEMES_DIR_ . $obj->directory . '/');
         }
         $ids_themes = Tools::unSerialize(Configuration::get('PS_ADDONS_THEMES_IDS'));
         if (array_key_exists($obj->directory, $ids_themes)) {
             unset($ids_themes[$obj->directory]);
         }
         $obj->removeMetas();
     } elseif ($obj === false && ($theme_dir = Tools::getValue('theme_dir'))) {
         $theme_dir = basename($theme_dir);
         if (Tools::deleteDirectory(_PS_ALL_THEMES_DIR_ . $theme_dir . '/')) {
             Tools::redirectAdmin(Context::getContext()->link->getAdminLink('AdminThemes') . '&conf=2');
         } else {
             $this->errors[] = Tools::displayError('The folder cannot be deleted');
         }
     }
     return parent::processDelete();
 }
Example #18
0
 public function converParams($old_params = '')
 {
     $result = '';
     if ($old_params != '') {
         $data = Tools::unSerialize($old_params);
         $result = SliderLayer::base64Encode(Tools::jsonEncode($data));
     }
     return $result;
 }
 public function renderForm()
 {
     $this->fields_form = array('legend' => array('title' => $this->l('Stores'), 'image' => '../img/admin/home.gif'), 'input' => array(array('type' => 'text', 'label' => $this->l('Name'), 'name' => 'name', 'size' => 33, 'required' => false, 'hint' => sprintf($this->l('Allowed characters: letters, spaces and %s'), '().-'), 'desc' => $this->l('Store name (e.g. Citycentre Mall Store)')), array('type' => 'text', 'label' => $this->l('Address'), 'name' => 'address1', 'size' => 33, 'required' => true), array('type' => 'text', 'label' => $this->l('Address (2)'), 'name' => 'address2', 'size' => 33), array('type' => 'text', 'label' => $this->l('Postal Code/Zip Code'), 'name' => 'postcode', 'size' => 6, 'required' => true), array('type' => 'text', 'label' => $this->l('City'), 'name' => 'city', 'size' => 33, 'required' => true), array('type' => 'select', 'label' => $this->l('Country'), 'name' => 'id_country', 'required' => true, 'default_value' => (int) $this->context->country->id, 'options' => array('query' => Country::getCountries($this->context->language->id), 'id' => 'id_country', 'name' => 'name')), array('type' => 'select', 'label' => $this->l('State'), 'name' => 'id_state', 'required' => true, 'options' => array('id' => 'id_state', 'name' => 'name', 'query' => null)), array('type' => 'latitude', 'label' => $this->l('Latitude / Longitude'), 'name' => 'latitude', 'required' => true, 'size' => 11, 'maxlength' => 12, 'desc' => $this->l('Store coordinates (e.g. 45.265469/-47.226478)')), array('type' => 'text', 'label' => $this->l('Phone'), 'name' => 'phone', 'size' => 33), array('type' => 'text', 'label' => $this->l('Fax'), 'name' => 'fax', 'size' => 33), array('type' => 'text', 'label' => $this->l('E-mail address'), 'name' => 'email', 'size' => 33), array('type' => 'textarea', 'label' => $this->l('Note'), 'name' => 'note', 'cols' => 42, 'rows' => 4), array('type' => 'radio', 'label' => $this->l('Status'), 'name' => 'active', 'required' => false, 'class' => 't', 'is_bool' => true, 'values' => array(array('id' => 'active_on', 'value' => 1, 'label' => $this->l('Enabled')), array('id' => 'active_off', 'value' => 0, 'label' => $this->l('Disabled'))), 'desc' => $this->l('Whether or not to display this store'))), 'rightCols' => array('input' => array('type' => 'file', 'label' => $this->l('Picture'), 'name' => 'image', 'desc' => $this->l('Storefront picture'))), 'submit' => array('title' => $this->l('   Save   '), 'class' => 'button'));
     if (Shop::isFeatureActive()) {
         $this->fields_form['input'][] = array('type' => 'shop', 'label' => $this->l('Shop association:'), 'name' => 'checkBoxShopAsso');
     }
     if (!($obj = $this->loadObject(true))) {
         return;
     }
     $image = ImageManager::thumbnail(_PS_STORE_IMG_DIR_ . '/' . $obj->id . '.jpg', $this->table . '_' . (int) $obj->id . '.' . $this->imageType, 350, $this->imageType, true);
     $days = array();
     $days[1] = $this->l('Monday');
     $days[2] = $this->l('Tuesday');
     $days[3] = $this->l('Wednesday');
     $days[4] = $this->l('Thursday');
     $days[5] = $this->l('Friday');
     $days[6] = $this->l('Saturday');
     $days[7] = $this->l('Sunday');
     $hours = $this->getFieldValue($obj, 'hours');
     if (!empty($hours)) {
         $hours_unserialized = Tools::unSerialize($hours);
     }
     $this->fields_value = array('latitude' => $this->getFieldValue($obj, 'latitude') ? $this->getFieldValue($obj, 'latitude') : Configuration::get('PS_STORES_CENTER_LAT'), 'longitude' => $this->getFieldValue($obj, 'longitude') ? $this->getFieldValue($obj, 'longitude') : Configuration::get('PS_STORES_CENTER_LONG'), 'image' => $image ? $image : false, 'size' => $image ? filesize(_PS_STORE_IMG_DIR_ . '/' . $obj->id . '.jpg') / 1000 : false, 'days' => $days, 'hours' => isset($hours_unserialized) ? $hours_unserialized : false);
     return parent::renderForm();
 }
Example #20
0
 public function correctData()
 {
     $groups = LeoManageWidgetGroup::getAllGroupId(-1);
     foreach ($groups as $group_id) {
         $groupObj = new LeoManageWidgetGroup($group_id);
         if (Validate::isLoadedObject($groupObj)) {
             $tmp = Tools::unSerialize($groupObj->params);
             if ($tmp) {
                 $groupObj->params = call_user_func('base64' . '_encode', Tools::jsonEncode($tmp));
                 $groupObj->save();
             }
         }
     }
     $columns = LeoManageWidgetColumn::getAllColumnId(-1);
     foreach ($columns as $column_id) {
         $columnObj = new LeoManageWidgetColumn($column_id);
         if (Validate::isLoadedObject($columnObj)) {
             $tmp = Tools::unSerialize($columnObj->params);
             if ($tmp) {
                 $columnObj->params = call_user_func('base64' . '_encode', Tools::jsonEncode($tmp));
                 $columnObj->save();
             }
         }
     }
     $this->_html = $this->displayConfirmation($this->l('Correct data done.'));
 }
Example #21
0
 /**
  * Set the filters used for the list display
  */
 public function processFilter()
 {
     if (!isset($this->list_id)) {
         $this->list_id = $this->table;
     }
     $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
     if (isset($this->list_id)) {
         foreach ($_POST as $key => $value) {
             if ($value === '') {
                 unset($this->context->cookie->{$prefix . $key});
             } elseif (stripos($key, $this->list_id . 'Filter_') === 0) {
                 $this->context->cookie->{$prefix . $key} = !is_array($value) ? $value : serialize($value);
             } elseif (stripos($key, 'submitFilter') === 0) {
                 $this->context->cookie->{$key} = !is_array($value) ? $value : serialize($value);
             }
         }
         foreach ($_GET as $key => $value) {
             if (stripos($key, $this->list_id . 'Filter_') === 0) {
                 $this->context->cookie->{$prefix . $key} = !is_array($value) ? $value : serialize($value);
             } elseif (stripos($key, 'submitFilter') === 0) {
                 $this->context->cookie->{$key} = !is_array($value) ? $value : serialize($value);
             }
             if (stripos($key, $this->list_id . 'Orderby') === 0 && Validate::isOrderBy($value)) {
                 if ($value === '' || $value == $this->_defaultOrderBy) {
                     unset($this->context->cookie->{$prefix . $key});
                 } else {
                     $this->context->cookie->{$prefix . $key} = $value;
                 }
             } elseif (stripos($key, $this->list_id . 'Orderway') === 0 && Validate::isOrderWay($value)) {
                 if ($value === '' || $value == $this->_defaultOrderWay) {
                     unset($this->context->cookie->{$prefix . $key});
                 } else {
                     $this->context->cookie->{$prefix . $key} = $value;
                 }
             }
         }
     }
     $filters = $this->context->cookie->getFamily($prefix . $this->list_id . 'Filter_');
     foreach ($filters as $key => $value) {
         /* Extracting filters from $_POST on key filter_ */
         if ($value != null && !strncmp($key, $prefix . $this->list_id . 'Filter_', 7 + Tools::strlen($prefix . $this->list_id))) {
             $key = Tools::substr($key, 7 + Tools::strlen($prefix . $this->list_id));
             /* Table alias could be specified using a ! eg. alias!field */
             $tmp_tab = explode('!', $key);
             $filter = count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0];
             if ($field = $this->filterToField($key, $filter)) {
                 $type = array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false);
                 if (($type == 'date' || $type == 'datetime') && is_string($value)) {
                     $value = Tools::unSerialize($value);
                 }
                 $key = isset($tmp_tab[1]) ? $tmp_tab[0] . '.`' . $tmp_tab[1] . '`' : '`' . $tmp_tab[0] . '`';
                 // Assignement by reference
                 if (array_key_exists('tmpTableFilter', $field)) {
                     $sql_filter =& $this->_tmpTableFilter;
                 } elseif (array_key_exists('havingFilter', $field)) {
                     $sql_filter =& $this->_filterHaving;
                 } else {
                     $sql_filter =& $this->_filter;
                 }
                 /* Only for date filtering (from, to) */
                 if (is_array($value)) {
                     if (isset($value[0]) && !empty($value[0])) {
                         if (!Validate::isDate($value[0])) {
                             $this->errors[] = Tools::displayError('The \'From\' date format is invalid (YYYY-MM-DD)');
                         } else {
                             $sql_filter .= ' AND ' . pSQL($key) . ' >= \'' . pSQL(Tools::dateFrom($value[0])) . '\'';
                         }
                     }
                     if (isset($value[1]) && !empty($value[1])) {
                         if (!Validate::isDate($value[1])) {
                             $this->errors[] = Tools::displayError('The \'To\' date format is invalid (YYYY-MM-DD)');
                         } else {
                             $sql_filter .= ' AND ' . pSQL($key) . ' <= \'' . pSQL(Tools::dateTo($value[1])) . '\'';
                         }
                     }
                 } else {
                     $sql_filter .= ' AND ';
                     $check_key = $key == $this->identifier || $key == '`' . $this->identifier . '`';
                     if ($type == 'int' || $type == 'bool') {
                         $sql_filter .= ($check_key || $key == '`active`' ? 'a.' : '') . pSQL($key) . ' = ' . (int) $value . ' ';
                     } elseif ($type == 'decimal') {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' = ' . (double) $value . ' ';
                     } elseif ($type == 'select') {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' = \'' . pSQL($value) . '\' ';
                     } else {
                         if ($type == 'price') {
                             $value = (double) str_replace(',', '.', $value);
                         }
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' LIKE \'%' . pSQL($value) . '%\' ';
                     }
                 }
             }
         }
     }
 }
Example #22
0
 private function getSelectedFilters()
 {
     $home_category = Configuration::get('PS_HOME_CATEGORY');
     $id_parent = (int) Tools::getValue('id_category', Tools::getValue('id_category_layered', $home_category));
     if ($id_parent == $home_category) {
         return;
     }
     // Force attributes selection (by url '.../2-mycategory/color-blue' or by get parameter 'selected_filters')
     if (strpos($_SERVER['SCRIPT_FILENAME'], 'blocklayered-ajax.php') === false || Tools::getValue('selected_filters') !== false) {
         if (Tools::getValue('selected_filters')) {
             $url = Tools::getValue('selected_filters');
         } else {
             $url = preg_replace('/\\/(?:\\w*)\\/(?:[0-9]+[-\\w]*)([^\\?]*)\\??.*/', '$1', Tools::safeOutput($_SERVER['REQUEST_URI'], true));
         }
         $url_attributes = explode('/', ltrim($url, '/'));
         $selected_filters = array('category' => array());
         if (!empty($url_attributes)) {
             foreach ($url_attributes as $url_attribute) {
                 /* Pagination uses - as separator, can be different from $this->getAnchor()*/
                 if (strpos($url_attribute, 'page-') === 0) {
                     $url_attribute = str_replace('-', $this->getAnchor(), $url_attribute);
                 }
                 $url_parameters = explode($this->getAnchor(), $url_attribute);
                 $attribute_name = array_shift($url_parameters);
                 if ($attribute_name == 'page') {
                     $this->page = (int) $url_parameters[0];
                 } else {
                     if (in_array($attribute_name, array('price', 'weight'))) {
                         $selected_filters[$attribute_name] = array($this->filterVar($url_parameters[0]), $this->filterVar($url_parameters[1]));
                     } else {
                         foreach ($url_parameters as $url_parameter) {
                             $data = Db::getInstance()->getValue('SELECT data FROM `' . _DB_PREFIX_ . 'layered_friendly_url` WHERE `url_key` = \'' . md5('/' . $attribute_name . $this->getAnchor() . $url_parameter) . '\'');
                             if ($data) {
                                 foreach (Tools::unSerialize($data) as $key_params => $params) {
                                     if (!isset($selected_filters[$key_params])) {
                                         $selected_filters[$key_params] = array();
                                     }
                                     foreach ($params as $key_param => $param) {
                                         if (!isset($selected_filters[$key_params][$key_param])) {
                                             $selected_filters[$key_params][$key_param] = array();
                                         }
                                         $selected_filters[$key_params][$key_param] = $this->filterVar($param);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             return $selected_filters;
         }
     }
     /* Analyze all the filters selected by the user and store them into a tab */
     $selected_filters = array('category' => array(), 'manufacturer' => array(), 'quantity' => array(), 'condition' => array());
     foreach ($_GET as $key => $value) {
         if (substr($key, 0, 8) == 'layered_') {
             preg_match('/^(.*)_([0-9]+|new|used|refurbished|slider)$/', substr($key, 8, strlen($key) - 8), $res);
             if (isset($res[1])) {
                 $tmp_tab = explode('_', $this->filterVar($value));
                 $value = $this->filterVar($tmp_tab[0]);
                 $id_key = false;
                 if (isset($tmp_tab[1])) {
                     $id_key = $tmp_tab[1];
                 }
                 if ($res[1] == 'condition' && in_array($value, array('new', 'used', 'refurbished'))) {
                     $selected_filters['condition'][] = $value;
                 } else {
                     if ($res[1] == 'quantity' && (!$value || $value == 1)) {
                         $selected_filters['quantity'][] = $value;
                     } else {
                         if (in_array($res[1], array('category', 'manufacturer'))) {
                             if (!isset($selected_filters[$res[1] . ($id_key ? '_' . $id_key : '')])) {
                                 $selected_filters[$res[1] . ($id_key ? '_' . $id_key : '')] = array();
                             }
                             $selected_filters[$res[1] . ($id_key ? '_' . $id_key : '')][] = (int) $value;
                         } else {
                             if (in_array($res[1], array('id_attribute_group', 'id_feature'))) {
                                 if (!isset($selected_filters[$res[1]])) {
                                     $selected_filters[$res[1]] = array();
                                 }
                                 $selected_filters[$res[1]][(int) $value] = $id_key . '_' . (int) $value;
                             } else {
                                 if ($res[1] == 'weight') {
                                     $selected_filters[$res[1]] = $tmp_tab;
                                 } else {
                                     if ($res[1] == 'price') {
                                         $selected_filters[$res[1]] = $tmp_tab;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $selected_filters;
 }
 public function renderStoreWorkingHours($store)
 {
     global $smarty;
     $days[1] = 'Monday';
     $days[2] = 'Tuesday';
     $days[3] = 'Wednesday';
     $days[4] = 'Thursday';
     $days[5] = 'Friday';
     $days[6] = 'Saturday';
     $days[7] = 'Sunday';
     $days_datas = array();
     $hours = array();
     if ($store['hours']) {
         $hours = Tools::unSerialize($store['hours']);
         if (is_array($hours)) {
             $hours = array_filter($hours);
         }
     }
     if (!empty($hours)) {
         for ($i = 1; $i < 8; $i++) {
             if (isset($hours[(int) $i - 1])) {
                 $hours_datas = array();
                 $hours_datas['hours'] = $hours[(int) $i - 1];
                 $hours_datas['day'] = $days[$i];
                 $days_datas[] = $hours_datas;
             }
         }
         $smarty->assign('days_datas', $days_datas);
         $smarty->assign('id_country', $store['id_country']);
         return $this->context->smarty->fetch(_PS_THEME_DIR_ . 'store_infos.tpl');
     }
     return false;
 }
Example #24
0
 /**
  * Define our own Tools::unSerialize() (since 1.5), to be available in PrestaShop 1.4
  */
 protected static function unSerialize($serialized)
 {
     if (method_exists('Tools', 'unserialize')) {
         return Tools::unSerialize($serialized);
     }
     if (is_string($serialized) && (strpos($serialized, 'O:') === false || !preg_match('/(^|;|{|})O:[0-9]+:"/', $serialized))) {
         return @unserialize($serialized);
     }
     return false;
 }
Example #25
0
    public function buildLayeredCategories()
    {
        // Get all filter template
        $res = Db::getInstance()->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'layered_filter ORDER BY date_add DESC');
        $categories = array();
        // Remove all from layered_category
        Db::getInstance()->execute('TRUNCATE ' . _DB_PREFIX_ . 'layered_category');
        if (!count($res)) {
            // No filters templates defined, nothing else to do
            return true;
        }
        $sql_to_insert = 'INSERT INTO ' . _DB_PREFIX_ . 'layered_category (id_category, id_shop, id_value, type, position, filter_show_limit, filter_type) VALUES ';
        $values = false;
        foreach ($res as $filter_template) {
            $data = Tools::unSerialize($filter_template['filters']);
            foreach ($data['categories'] as $id_category) {
                $n = 0;
                if (!in_array($id_category, $categories)) {
                    $categories[] = $id_category;
                    foreach ($data as $key => $value) {
                        if (substr($key, 0, 17) == 'layered_selection') {
                            $values = true;
                            $type = $value['filter_type'];
                            $limit = $value['filter_show_limit'];
                            $n++;
                            foreach ($data['shop_list'] as $id_shop) {
                                if ($key == 'layered_selection_stock') {
                                    $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', NULL,\'quantity\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                } else {
                                    if ($key == 'layered_selection_subcategories') {
                                        $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', NULL,\'category\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                    } else {
                                        if ($key == 'layered_selection_condition') {
                                            $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', NULL,\'condition\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                        } else {
                                            if ($key == 'layered_selection_weight_slider') {
                                                $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', NULL,\'weight\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                            } else {
                                                if ($key == 'layered_selection_price_slider') {
                                                    $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', NULL,\'price\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                                } else {
                                                    if ($key == 'layered_selection_manufacturer') {
                                                        $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', NULL,\'manufacturer\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                                    } else {
                                                        if (substr($key, 0, 21) == 'layered_selection_ag_') {
                                                            $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', ' . (int) str_replace('layered_selection_ag_', '', $key) . ',
										\'id_attribute_group\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                                        } else {
                                                            if (substr($key, 0, 23) == 'layered_selection_feat_') {
                                                                $sql_to_insert .= '(' . (int) $id_category . ', ' . (int) $id_shop . ', ' . (int) str_replace('layered_selection_feat_', '', $key) . ',
										\'id_feature\',' . (int) $n . ', ' . (int) $limit . ', ' . (int) $type . '),';
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if ($values) {
            Db::getInstance()->execute(rtrim($sql_to_insert, ','));
        }
    }
Example #26
0
 /**
  * Display list header (filtering, pagination and column names)
  */
 public function displayListHeader()
 {
     $id_cat = (int) Tools::getValue('id_' . ($this->is_cms ? 'cms_' : '') . 'category');
     if (!isset($token) || empty($token)) {
         $token = $this->token;
     }
     /* Determine total page number */
     if (isset($this->context->cookie->{$this->table . '_pagination'}) && $this->context->cookie->{$this->table . '_pagination'}) {
         $default_pagination = $this->context->cookie->{$this->table . '_pagination'};
     } else {
         $default_pagination = $this->_pagination[0];
     }
     $total_pages = ceil($this->listTotal / Tools::getValue('pagination', $default_pagination));
     if (!$total_pages) {
         $total_pages = 1;
     }
     $identifier = Tools::getIsset($this->identifier) ? '&' . $this->identifier . '=' . (int) Tools::getValue($this->identifier) : '';
     $order = '';
     if (Tools::getIsset($this->table . 'Orderby')) {
         $order = '&' . $this->table . 'Orderby=' . urlencode($this->orderBy) . '&' . $this->table . 'Orderway=' . urlencode(strtolower($this->orderWay));
     }
     $action = $this->currentIndex . $identifier . '&token=' . $token . $order . '#' . $this->table;
     /* Determine current page number */
     $page = (int) Tools::getValue('submitFilter' . $this->table);
     if (!$page) {
         $page = 1;
     }
     /* Choose number of results per page */
     $selected_pagination = Tools::getValue('pagination', isset($this->context->cookie->{$this->table . '_pagination'}) ? $this->context->cookie->{$this->table . '_pagination'} : null);
     // Cleaning links
     if (Tools::getValue($this->table . 'Orderby') && Tools::getValue($this->table . 'Orderway')) {
         $this->currentIndex = preg_replace('/&' . $this->table . 'Orderby=([a-z _]*)&' . $this->table . 'Orderway=([a-z]*)/i', '', $this->currentIndex);
     }
     if ($this->position_identifier && (int) Tools::getValue($this->position_identifier, 1)) {
         $table_id = substr($this->identifier, 3, strlen($this->identifier));
     }
     if ($this->position_identifier && ($this->orderBy == 'position' && $this->orderWay != 'DESC')) {
         $table_dnd = true;
     }
     foreach ($this->fields_list as $key => $params) {
         if (!isset($params['type'])) {
             $params['type'] = 'text';
         }
         $value = Context::getContext()->cookie->{$this->table . 'Filter_' . (array_key_exists('filter_key', $params) ? $params['filter_key'] : $key)};
         switch ($params['type']) {
             case 'bool':
                 break;
             case 'date':
             case 'datetime':
                 if (is_string($value)) {
                     $value = Tools::unSerialize($value);
                 }
                 if (!Validate::isCleanHtml($value[0]) || !Validate::isCleanHtml($value[1])) {
                     $value = '';
                 }
                 $name = $this->table . 'Filter_' . (isset($params['filter_key']) ? $params['filter_key'] : $key);
                 $name_id = str_replace('!', '__', $name);
                 $params['id_date'] = $name_id;
                 $params['name_date'] = $name;
                 $this->context->controller->addJqueryUI('ui.datepicker');
                 break;
             case 'select':
                 foreach ($params['list'] as $option_value => $option_display) {
                     if (isset(Context::getContext()->cookie->{$this->table . 'Filter_' . $params['filter_key']}) && Context::getContext()->cookie->{$this->table . 'Filter_' . $params['filter_key']} == $option_value && Context::getContext()->cookie->{$this->table . 'Filter_' . $params['filter_key']} != '') {
                         $this->fields_list[$key]['select'][$option_value]['selected'] = 'selected';
                     }
                 }
                 break;
             case 'text':
                 if (!Validate::isCleanHtml($value)) {
                     $value = '';
                 }
         }
         $params['value'] = $value;
         $this->fields_list[$key] = $params;
     }
     $this->header_tpl->assign(array_merge($this->tpl_vars, array('title' => $this->title, 'show_toolbar' => $this->show_toolbar, 'toolbar_scroll' => $this->toolbar_scroll, 'toolbar_btn' => $this->toolbar_btn, 'table' => $this->table, 'currentIndex' => $this->currentIndex, 'action' => $action, 'page' => $page, 'simple_header' => $this->simple_header, 'total_pages' => $total_pages, 'selected_pagination' => $selected_pagination, 'pagination' => $this->_pagination, 'list_total' => $this->listTotal, 'is_order_position' => $this->position_identifier && $this->orderBy == 'position', 'order_way' => $this->orderWay, 'order_by' => $this->orderBy, 'token' => $this->token, 'fields_display' => $this->fields_list, 'delete' => in_array('delete', $this->actions), 'identifier' => $this->identifier, 'id_cat' => $id_cat, 'shop_link_type' => $this->shopLinkType, 'has_actions' => !empty($this->actions), 'has_bulk_actions' => !empty($this->bulk_actions), 'bulk_actions' => $this->bulk_actions, 'table_id' => isset($table_id) ? $table_id : null, 'table_dnd' => isset($table_dnd) ? $table_dnd : null, 'name' => isset($name) ? $name : null, 'name_id' => isset($name_id) ? $name_id : null, 'row_hover' => $this->row_hover)));
     return $this->header_tpl->fetch();
 }
Example #27
0
 /**
  * Get the delivery option seleted, or if no delivery option was selected, the cheapest option for each address
  * @return array delivery option
  */
 public function getDeliveryOption($default_country = null, $dontAutoSelectOptions = false, $use_cache = true)
 {
     static $cache = array();
     $cache_id = (int) (is_object($default_country) ? $default_country->id : 0) . '-' . (int) $dontAutoSelectOptions;
     if (isset($cache[$cache_id]) && $use_cache) {
         return $cache[$cache_id];
     }
     $delivery_option_list = $this->getDeliveryOptionList($default_country);
     // The delivery option was selected
     if (isset($this->delivery_option) && $this->delivery_option != '') {
         $delivery_option = Tools::unSerialize($this->delivery_option);
         $validated = true;
         foreach ($delivery_option as $id_address => $key) {
             if (!isset($delivery_option_list[$id_address][$key])) {
                 $validated = false;
                 break;
             }
         }
         if ($validated) {
             $cache[$cache_id] = $delivery_option;
             return $delivery_option;
         }
     }
     if ($dontAutoSelectOptions) {
         return false;
     }
     // No delivery option selected or delivery option selected is not valid, get the better for all options
     $delivery_option = array();
     foreach ($delivery_option_list as $id_address => $options) {
         foreach ($options as $key => $option) {
             if (Configuration::get('PS_CARRIER_DEFAULT') == -1 && $option['is_best_price']) {
                 $delivery_option[$id_address] = $key;
                 break;
             } elseif (Configuration::get('PS_CARRIER_DEFAULT') == -2 && $option['is_best_grade']) {
                 $delivery_option[$id_address] = $key;
                 break;
             } elseif ($option['unique_carrier'] && in_array(Configuration::get('PS_CARRIER_DEFAULT'), array_keys($option['carrier_list']))) {
                 $delivery_option[$id_address] = $key;
                 break;
             }
         }
         reset($options);
         if (!isset($delivery_option[$id_address])) {
             $delivery_option[$id_address] = key($options);
         }
     }
     $cache[$cache_id] = $delivery_option;
     return $delivery_option;
 }
Example #28
0
 public function getWsHours()
 {
     return implode(';', Tools::unSerialize($this->hours));
 }
 private function getVarSize($var)
 {
     $start_memory = memory_get_usage();
     try {
         $tmp = Tools::unSerialize(serialize($var));
     } catch (Exception $e) {
         $tmp = $this->getVarData($var);
     }
     $size = memory_get_usage() - $start_memory;
     return $size;
 }
Example #30
0
 /**
  * Set the filters used for the list display
  */
 public function processFilter()
 {
     $filters = $this->context->cookie->getFamily($this->table . 'Filter_');
     foreach ($filters as $key => $value) {
         /* Extracting filters from $_POST on key filter_ */
         if ($value != null && !strncmp($key, $this->table . 'Filter_', 7 + Tools::strlen($this->table))) {
             $key = Tools::substr($key, 7 + Tools::strlen($this->table));
             /* Table alias could be specified using a ! eg. alias!field */
             $tmp_tab = explode('!', $key);
             $filter = count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0];
             if ($field = $this->filterToField($key, $filter)) {
                 $type = array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false);
                 if (($type == 'date' || $type == 'datetime') && is_string($value)) {
                     $value = Tools::unSerialize($value);
                 }
                 $key = isset($tmp_tab[1]) ? $tmp_tab[0] . '.`' . $tmp_tab[1] . '`' : '`' . $tmp_tab[0] . '`';
                 // Assignement by reference
                 if (array_key_exists('tmpTableFilter', $field)) {
                     $sql_filter =& $this->_tmpTableFilter;
                 } elseif (array_key_exists('havingFilter', $field)) {
                     $sql_filter =& $this->_filterHaving;
                 } else {
                     $sql_filter =& $this->_filter;
                 }
                 /* Only for date filtering (from, to) */
                 if (is_array($value)) {
                     if (isset($value[0]) && !empty($value[0])) {
                         if (!Validate::isDate($value[0])) {
                             $this->errors[] = Tools::displayError('\'From:\' date format is invalid (YYYY-MM-DD)');
                         } else {
                             $sql_filter .= ' AND ' . pSQL($key) . ' >= \'' . pSQL(Tools::dateFrom($value[0])) . '\'';
                         }
                     }
                     if (isset($value[1]) && !empty($value[1])) {
                         if (!Validate::isDate($value[1])) {
                             $this->errors[] = Tools::displayError('\'To:\' date format is invalid (YYYY-MM-DD)');
                         } else {
                             $sql_filter .= ' AND ' . pSQL($key) . ' <= \'' . pSQL(Tools::dateTo($value[1])) . '\'';
                         }
                     }
                 } else {
                     $sql_filter .= ' AND ';
                     $check_key = $key == $this->identifier || $key == '`' . $this->identifier . '`';
                     if ($type == 'int' || $type == 'bool') {
                         $sql_filter .= ($check_key || $key == '`active`' ? 'a.' : '') . pSQL($key) . ' = ' . (int) $value . ' ';
                     } elseif ($type == 'decimal') {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' = ' . (double) $value . ' ';
                     } elseif ($type == 'select') {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' = \'' . pSQL($value) . '\' ';
                     } else {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' LIKE \'%' . pSQL($value) . '%\' ';
                     }
                 }
             }
         }
     }
 }