public function renderForm()
 {
     $update_htaccess = Tools::modRewriteActive() && (file_exists('.htaccess') && is_writable('.htaccess') || is_writable(dirname('.htaccess')));
     $this->multiple_fieldsets = true;
     if (!$update_htaccess) {
         $desc_virtual_uri = array('<span class="warning_mod_rewrite">' . $this->l('You need to activate URL Rewriting if you want to add a virtual URL.') . '</span>');
     } else {
         $desc_virtual_uri = array($this->l('You can use this option if you want to create a store with a URL that doesn\'t exist on your server (e.g. if you want your store to be available with the URL www.my-prestashop.com/my-store/shoes/, you have to set shoes/ in this field, assuming that my-store/ is your Physical URL).'), '<strong>' . $this->l('URL rewriting must be activated on your server to use this feature.') . '</strong>');
     }
     $this->fields_form = array(array('form' => array('legend' => array('title' => $this->l('URL options'), 'icon' => 'icon-cogs'), 'input' => array(array('type' => 'select', 'label' => $this->l('Shop'), 'name' => 'id_shop', 'onchange' => 'checkMainUrlInfo(this.value);', 'options' => array('optiongroup' => array('query' => Shop::getTree(), 'label' => 'name'), 'options' => array('query' => 'shops', 'id' => 'id_shop', 'name' => 'name'))), array('type' => 'switch', 'label' => $this->l('Main URL'), 'name' => 'main', 'class' => 't', 'values' => array(array('id' => 'main_on', 'value' => 1), array('id' => 'main_off', 'value' => 0)), 'desc' => array($this->l('If you set this URL as the Main URL for the selected shop, all URLs set to this shop will be redirected to this URL (you can only have one Main URL per shop).'), array('text' => $this->l('Since the selected shop has no main URL, you have to set this URL as the Main URL.'), 'id' => 'mainUrlInfo'), array('text' => $this->l('The selected shop already has a Main URL. Therefore, if you set this one as the Main URL, the older of the two will be set as the normal URL.'), 'id' => 'mainUrlInfoExplain'))), array('type' => 'switch', 'label' => $this->l('Enabled'), 'name' => 'active', 'required' => false, 'class' => 't', 'values' => array(array('id' => 'active_on', 'value' => 1), array('id' => 'active_off', 'value' => 0)))), 'submit' => array('title' => $this->l('Save')))), array('form' => array('legend' => array('title' => $this->l('Shop URL'), 'icon' => 'icon-shopping-cart'), 'input' => array(array('type' => 'text', 'label' => $this->l('Domain'), 'name' => 'domain', 'size' => 50), array('type' => 'text', 'label' => $this->l('Domain SSL'), 'name' => 'domain_ssl', 'size' => 50)), 'submit' => array('title' => $this->l('Save')))));
     if (!defined('_PS_HOST_MODE_')) {
         $this->fields_form[1]['form']['input'] = array_merge($this->fields_form[1]['form']['input'], array(array('type' => 'text', 'label' => $this->l('Physical URL'), 'name' => 'physical_uri', 'desc' => $this->l('This is the physical folder for your store on the server. Leave this field empty if your store is installed on the root path (e.g. if your store is available at www.my-prestashop.com/my-store/, you input my-store/ in this field).'), 'size' => 50)));
     }
     $this->fields_form[1]['form']['input'] = array_merge($this->fields_form[1]['form']['input'], array(array('type' => 'text', 'label' => $this->l('Virtual URL'), 'name' => 'virtual_uri', 'desc' => $desc_virtual_uri, 'size' => 50, 'hint' => !$update_htaccess ? $this->l('Warning: URL rewriting (e.g. mod_rewrite for Apache) seems to be disabled. If your URL doesn\'t work, please check with your host provider on how to activate URL rewriting.') : null), array('type' => 'text', 'label' => $this->l('Your final URL will be'), 'name' => 'final_url', 'size' => 76, 'readonly' => true)));
     if (!($obj = $this->loadObject(true))) {
         return;
     }
     self::$currentIndex = self::$currentIndex . '&id_shop=' . $obj->id;
     $current_shop = Shop::initialize();
     $list_shop_with_url = array();
     foreach (Shop::getShops(false, null, true) as $id) {
         $list_shop_with_url[$id] = (bool) count(ShopUrl::getShopUrls($id));
     }
     $this->tpl_form_vars = array('js_shop_url' => Tools::jsonEncode($list_shop_with_url));
     $this->fields_value = array('domain' => Validate::isLoadedObject($obj) ? $this->getFieldValue($obj, 'domain') : $current_shop->domain, 'domain_ssl' => Validate::isLoadedObject($obj) ? $this->getFieldValue($obj, 'domain_ssl') : $current_shop->domain_ssl, 'physical_uri' => Validate::isLoadedObject($obj) ? $this->getFieldValue($obj, 'physical_uri') : $current_shop->physical_uri, 'active' => true);
     return parent::renderForm();
 }
 /**
  * Update shop physical uri for mono shop)
  *
  * @param string $value
  *
  * @throws PrestaShopException
  */
 public function updateOptionUri($value)
 {
     if (!Shop::isFeatureActive() && $this->url && $this->url->physical_uri != $value) {
         $this->url->physical_uri = $value;
         $this->url->update();
     }
 }
Beispiel #3
0
 private function generateRewriteRules()
 {
     if (Configuration::get('PS_REWRITING_SETTINGS')) {
         $rules = "#start_prestanews - not remove this comment \n";
         $physical_uri = array();
         foreach (ShopUrl::getShopUrls() as $shop_url) {
             if (in_array($shop_url->physical_uri, $physical_uri)) {
                 continue;
             }
             $rules .= "RewriteRule ^(.*)news\$ " . $shop_url->physical_uri . "index.php?fc=module&module=psnews&controller=news [QSA,L] \n";
             $rules .= "RewriteRule ^(.*)news/([0-9]+)\\-([a-zA-Z0-9-]*) " . $shop_url->physical_uri . "index.php?fc=module&module=psnews&controller=news&news=\$2 [QSA,L] \n";
             $physical_uri[] = $shop_url->physical_uri;
         }
         $rules .= "#end_prestanews \n\n";
         $path = _PS_ROOT_DIR_ . '/.htaccess';
         if (is_writable($path)) {
             $existingRules = file_get_contents($path);
             if (!strpos($existingRules, "start_prestanews")) {
                 $handle = fopen($path, 'w');
                 fwrite($handle, $rules . $existingRules);
                 fclose($handle);
             }
         }
     }
 }
 public function __construct()
 {
     parent::__construct();
     $this->ht_file = _PS_ROOT_DIR_ . '/.htaccess';
     $this->rb_file = _PS_ROOT_DIR_ . '/robots.txt';
     $this->sm_file = _PS_ROOT_DIR_ . '/sitemap.xml';
     $this->rb_data = $this->getRobotsContent();
     $this->explicitSelect = true;
     $this->addRowAction('edit');
     $this->addRowAction('delete');
     $this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'), 'confirm' => $this->l('Delete selected items?')));
     $this->fields_list = array('id_meta' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25), 'page' => array('title' => $this->l('Page'), 'width' => 120), 'title' => array('title' => $this->l('Title'), 'width' => 120), 'url_rewrite' => array('title' => $this->l('Friendly URL'), 'width' => 120));
     $this->_group = 'GROUP BY a.id_meta';
     // Options to generate friendly urls
     $mod_rewrite = Tools::modRewriteActive();
     $general_fields = array('PS_REWRITING_SETTINGS' => array('title' => $this->l('Friendly URL'), 'desc' => $mod_rewrite ? $this->l('Enable only if your server allows URL rewriting (recommended).') : '', 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'rewriting_settings', 'mod_rewrite' => $mod_rewrite), 'PS_ALLOW_ACCENTED_CHARS_URL' => array('title' => $this->l('Accented URL'), 'desc' => $this->l('Enable if you want to allow accented characters in your friendly URLs.') . ' ' . $this->l('You should only activate this option if you are using non-latin characters ; for all the latin charsets, your SEO will be better without this option.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_CANONICAL_REDIRECT' => array('title' => $this->l('Automatically redirect to the canonical URL'), 'desc' => $this->l('Recommended, but your theme must be compliant.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'));
     $url_description = '';
     if ($this->checkConfiguration($this->ht_file)) {
         $general_fields['PS_HTACCESS_DISABLE_MULTIVIEWS'] = array('title' => $this->l('Disable apache multiviews'), 'desc' => $this->l('Enable this option only if you have problems with URL rewriting.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool');
         $general_fields['PS_HTACCESS_DISABLE_MODSEC'] = array('title' => $this->l('Disable apache mod security'), 'desc' => $this->l('Some features could not work correctly with a specific configuration of apache mod security. We recommend to turn it off.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool');
     } else {
         $url_description = $this->l('Before being able to use this tool, you need to:');
         $url_description .= '<br />- ' . $this->l('Create a blank .htaccess in your root directory.');
         $url_description .= '<br />- ' . $this->l('Give it write permissions (CHMOD 666 on Unix system)');
     }
     // Options to generate robot.txt
     $robots_description = $this->l('Your robots.txt file MUST be in your website\'s root directory and nowhere else (e.g. http://www.yoursite.com/robots.txt).');
     if ($this->checkConfiguration($this->rb_file)) {
         $robots_description .= '<br />' . $this->l('Generate your "robots.txt" file by clicking on the following button (this will erase the old robots.txt file)');
         $robots_submit = array('name' => 'submitRobots', 'title' => $this->l('Generate robots.txt file'));
     } else {
         $robots_description .= '<br />' . $this->l('Before being able to use this tool, you need to:');
         $robots_description .= '<br />- ' . $this->l('Create a blank robots.txt file in your root directory.');
         $robots_description .= '<br />- ' . $this->l('Give it write permissions (CHMOD 666 on Unix system)');
     }
     $robots_options = array('title' => $this->l('Robots file generation'), 'description' => $robots_description);
     if (isset($robots_submit)) {
         $robots_options['submit'] = $robots_submit;
     }
     // Options for shop URL if multishop is disabled
     $shop_url_options = array('title' => $this->l('Set shop URL'), 'fields' => array());
     if (!Shop::isFeatureActive()) {
         $this->url = ShopUrl::getShopUrls($this->context->shop->id)->where('main', '=', 1)->getFirst();
         if ($this->url) {
             $shop_url_options['description'] = $this->l('Here you can set the URL for your shop. If you migrate your shop to a new URL, remember to change the values below.');
             $shop_url_options['fields'] = array('domain' => array('title' => $this->l('Shop domain'), 'validation' => 'isString', 'type' => 'text', 'size' => 70, 'defaultValue' => $this->url->domain), 'domain_ssl' => array('title' => $this->l('SSL domain'), 'validation' => 'isString', 'type' => 'text', 'size' => 70, 'defaultValue' => $this->url->domain_ssl), 'uri' => array('title' => $this->l('Base URI'), 'validation' => 'isString', 'type' => 'text', 'size' => 70, 'defaultValue' => $this->url->physical_uri));
         }
     } else {
         $shop_url_options['description'] = $this->l('The multistore option is enabled. If you want to change the URL of your shop, you must go to the "Multistore" page under the "Advanced Parameters" menu.');
     }
     // List of options
     $this->fields_options = array('general' => array('title' => $this->l('Set up URLs'), 'description' => $url_description, 'fields' => $general_fields, 'submit' => array()), 'shop_url' => $shop_url_options);
     // Add display route options to options form
     if (Configuration::get('PS_REWRITING_SETTINGS')) {
         $this->fields_options['routes'] = array('title' => $this->l('Schema of URLs'), 'description' => $this->l('Change the pattern of your links. There are some available keywords for each route listed below, keywords with * are required. To add a keyword in your URL use {keyword} syntax. You can add text before or after the keyword if the keyword is not empty with syntax {prepend:keyword:append}. For example {-hey-:meta_title} will add "-hey-my-title" in the URL if the meta title is set. Friendly URL and rewriting Apache option must be activated on your web server to use this functionality.'), 'fields' => array());
         $this->addAllRouteFields();
     }
     $this->fields_options['robots'] = $robots_options;
 }
 public function ajaxProcessInfoQuery()
 {
     $this->content_only = true;
     $result = array('status' => false);
     if (time() > (int) Configuration::get('PP_INFO_CHECK_TIME')) {
         $protocol = Tools::getCurrentUrlProtocolPrefix();
         $iso_lang = Context::getContext()->language->iso_code;
         $iso_country = Context::getContext()->country->iso_code;
         $stream_context = @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 3)));
         $old_content = $this->getInfo();
         $msg = $old_content === false ? 0 : $old_content[0];
         $shop_url = ShopUrl::getShopUrls($this->context->shop->id)->where('main', '=', 1)->getFirst();
         $shop = $shop_url ? $shop_url->getURL() : Tools::getShopDomain();
         $date = Db::getInstance()->getValue('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'configuration` WHERE `name` = \'PSM_ID_' . Tools::strtoupper($this->module->name) . '\'');
         $psm_date = $date ? urlencode(date('Y-m-d H:i:s', strtotime($date))) : '';
         $plugins_string = '';
         $plugins = $this->module->plugins();
         foreach ($plugins as $name => $api_version) {
             if (Module::isInstalled($name)) {
                 $plugins_string .= '&' . $name . '=' . $this->moduleVersion($name);
             }
         }
         $url = $protocol . 'store.psandmore.com/query/?key=' . $this->module->name . '&ver=' . $this->module->version . '&psm=' . PSM::getPSMId($this->module) . '&psm_date=' . $psm_date . $plugins_string . '&msg=' . $msg . '&iso_country=' . $iso_country . '&iso_lang=' . $iso_lang . '&shop=' . urlencode($shop);
         $contents = Tools::file_get_contents($url, false, $stream_context);
         $check_info_offset = 3600;
         if ($contents !== false) {
             $content = explode('|', $contents);
             if (is_numeric($content[0])) {
                 if (!$this->infoIgnore(false, $content[0])) {
                     if (Validate::isCleanHtml($content[1])) {
                         $this->putInfo($contents);
                         $check_info_offset = 86400;
                     }
                 }
             } else {
                 if ($content[0] == 'hide') {
                     Configuration::deleteByName('PP_INFO_CONTENT');
                 }
             }
         }
         Configuration::updateValue('PP_INFO_CHECK_TIME', time() + $check_info_offset);
     }
     $content = $this->getInfo();
     if ($content !== false) {
         if (!$this->infoIgnore($content)) {
             if (Validate::isCleanHtml($content[1])) {
                 $result['status'] = 'success';
                 $result['content'] = $content[1];
             }
         }
     }
     $this->content = Tools::jsonEncode($result);
 }
Beispiel #6
0
 /**
  * PROCESS : installDefaultData
  * Create default shop and languages
  */
 public function processInstallDefaultData()
 {
     $this->initializeContext();
     if (!($res = $this->model_install->installDefaultData($this->datas->shop_name, $this->datas->shop_country, (int) $this->datas->all_languages, true))) {
         return false;
     }
     if ($this->datas->base_uri != '/') {
         $shop_url = new ShopUrl(1);
         $shop_url->physical_uri = $this->datas->base_uri;
         $shop_url->save();
     }
     return $res;
 }
Beispiel #7
0
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
             if (!Validate::isLoadedObject($order_carrier)) {
                 $this->errors[] = Tools::displayError('The order carrier ID is invalid.');
             } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                 $this->errors[] = Tools::displayError('The tracking number is incorrect.');
             } else {
                 // update shipping number
                 // Keep these two following lines for backward compatibility, remove on 1.6 version
                 $order->shipping_number = Tools::getValue('tracking_number');
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                 if ($order_carrier->update()) {
                     // Send mail to customer
                     $customer = new Customer((int) $order->id_customer);
                     $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                     if (!Validate::isLoadedObject($customer)) {
                         throw new PrestaShopException('Can\'t load Customer object');
                     }
                     if (!Validate::isLoadedObject($carrier)) {
                         throw new PrestaShopException('Can\'t load Carrier object');
                     }
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{shipping_number}' => $order->shipping_number, '{order_name}' => $order->getUniqReference());
                     if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                         Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order, 'customer' => $customer, 'carrier' => $carrier), null, false, true, false, $order->id_shop);
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                     } else {
                         $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('The order carrier cannot be updated.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitState') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_state = new OrderState(Tools::getValue('id_order_state'));
             if (!Validate::isLoadedObject($order_state)) {
                 $this->errors[] = Tools::displayError('The new order status is invalid.');
             } else {
                 $current_order_state = $order->getCurrentOrderState();
                 if ($current_order_state->id != $order_state->id) {
                     // Create new OrderHistory
                     $history = new OrderHistory();
                     $history->id_order = $order->id;
                     $history->id_employee = (int) $this->context->employee->id;
                     $use_existings_payment = false;
                     if (!$order->hasInvoice()) {
                         $use_existings_payment = true;
                     }
                     $history->changeIdOrderState((int) $order_state->id, $order, $use_existings_payment);
                     $carrier = new Carrier($order->id_carrier, $order->id_lang);
                     $templateVars = array();
                     if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
                         $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                     }
                     // Save all changes
                     if ($history->addWithemail(true, $templateVars)) {
                         // synchronizes quantities if needed..
                         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                             foreach ($order->getProducts() as $product) {
                                 if (StockAvailable::dependsOnStock($product['product_id'])) {
                                     StockAvailable::synchronize($product['product_id'], (int) $product['id_shop']);
                                 }
                             }
                         }
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                     }
                     $this->errors[] = Tools::displayError('An error occurred while changing order status, or we were unable to send an email to the customer.');
                 } else {
                     $this->errors[] = Tools::displayError('The order has already been assigned this status.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $customer = new Customer(Tools::getValue('id_customer'));
             if (!Validate::isLoadedObject($customer)) {
                 $this->errors[] = Tools::displayError('The customer is invalid.');
             } elseif (!Tools::getValue('message')) {
                 $this->errors[] = Tools::displayError('The message cannot be blank.');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false && (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
                             $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $field);
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->errors[] = sprintf(Tools::displayError('field %1$s is too long (%2$d chars max).'), $field, $maxLength);
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $field);
                         }
                     }
                 }
                 if (!count($this->errors)) {
                     //check if a thread already exist
                     $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                     if (!$id_customer_thread) {
                         $customer_thread = new CustomerThread();
                         $customer_thread->id_contact = 0;
                         $customer_thread->id_customer = (int) $order->id_customer;
                         $customer_thread->id_shop = (int) $this->context->shop->id;
                         $customer_thread->id_order = (int) $order->id;
                         $customer_thread->id_lang = (int) $this->context->language->id;
                         $customer_thread->email = $customer->email;
                         $customer_thread->status = 'open';
                         $customer_thread->token = Tools::passwdGen(12);
                         $customer_thread->add();
                     } else {
                         $customer_thread = new CustomerThread((int) $id_customer_thread);
                     }
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = (int) $this->context->employee->id;
                     $customer_message->message = Tools::getValue('message');
                     $customer_message->private = Tools::getValue('visibility');
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving the message.');
                     } elseif ($customer_message->private) {
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
                     } else {
                         $message = $customer_message->message;
                         if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
                             $message = Tools::nl2br($customer_message->message);
                         }
                         $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => $message);
                         if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
                         }
                     }
                     $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
         if ($this->tabAccess['edit'] == '1') {
             if (is_array($_POST['partialRefundProduct'])) {
                 $amount = 0;
                 $order_detail_list = array();
                 foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
                     $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
                     if (empty($amount_detail)) {
                         $order_detail = new OrderDetail((int) $id_order_detail);
                         $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity'];
                     } else {
                         $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail);
                     }
                     $amount += $order_detail_list[$id_order_detail]['amount'];
                     $order_detail = new OrderDetail((int) $id_order_detail);
                     if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $order_detail_list[$id_order_detail]['quantity'] > 0) {
                         $this->reinjectQuantity($order_detail, $order_detail_list[$id_order_detail]['quantity']);
                     }
                 }
                 $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost'));
                 if ($shipping_cost_amount > 0) {
                     $amount += $shipping_cost_amount;
                 }
                 $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                 if (Validate::isLoadedObject($order_carrier)) {
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     if ($order_carrier->update()) {
                         $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                     }
                 }
                 if ($amount > 0) {
                     if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
                         $this->errors[] = Tools::displayError('You cannot generate a partial credit slip.');
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) {
                         $cart_rule = new CartRule();
                         $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id);
                         $languages = Language::getLanguages(false);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cart_rule->name[$language['id_lang']] = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         }
                         // Define a temporary code
                         $cart_rule->code = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         $cart_rule->quantity = 1;
                         $cart_rule->quantity_per_user = 1;
                         // Specific to the customer
                         $cart_rule->id_customer = $order->id_customer;
                         $now = time();
                         $cart_rule->date_from = date('Y-m-d H:i:s', $now);
                         $cart_rule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cart_rule->partial_use = 1;
                         $cart_rule->active = 1;
                         $cart_rule->reduction_amount = $amount;
                         $cart_rule->reduction_tax = true;
                         $cart_rule->minimum_amount_currency = $order->id_currency;
                         $cart_rule->reduction_currency = $order->id_currency;
                         if (!$cart_rule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cart_rule->name[$language['id_lang']] = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             }
                             $cart_rule->code = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             if (!$cart_rule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $customer = new Customer((int) $order->id_customer);
                                 $params['{lastname}'] = $customer->lastname;
                                 $params['{firstname}'] = $customer->firstname;
                                 $params['{id_order}'] = $order->id;
                                 $params['{order_name}'] = $order->getUniqReference();
                                 $params['{voucher_amount}'] = Tools::displayPrice($cart_rule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cart_rule->code;
                                 $customer = new Customer((int) $order->id_customer);
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('You have to enter an amount if you want to create a partial credit slip.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=30&token=' . $this->token);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The partial refund data is incorrect.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
         if ($this->tabAccess['delete'] === '1') {
             if (!Tools::isSubmit('id_order_detail') && !Tools::isSubmit('id_customization')) {
                 $this->errors[] = Tools::displayError('You must select a product.');
             } elseif (!Tools::isSubmit('cancelQuantity') && !Tools::isSubmit('cancelCustomizationQuantity')) {
                 $this->errors[] = Tools::displayError('You must enter a quantity.');
             } else {
                 $productList = Tools::getValue('id_order_detail');
                 if ($productList) {
                     $productList = array_map('intval', $productList);
                 }
                 $customizationList = Tools::getValue('id_customization');
                 if ($customizationList) {
                     $customizationList = array_map('intval', $customizationList);
                 }
                 $qtyList = Tools::getValue('cancelQuantity');
                 if ($qtyList) {
                     $qtyList = array_map('intval', $qtyList);
                 }
                 $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
                 if ($customizationQtyList) {
                     $customizationQtyList = array_map('intval', $customizationQtyList);
                 }
                 $full_product_list = $productList;
                 $full_quantity_list = $qtyList;
                 if ($customizationList) {
                     foreach ($customizationList as $key => $id_order_detail) {
                         $full_product_list[(int) $id_order_detail] = $id_order_detail;
                         if (isset($customizationQtyList[$key])) {
                             $full_quantity_list[(int) $id_order_detail] += $customizationQtyList[$key];
                         }
                     }
                 }
                 if ($productList || $customizationList) {
                     if ($productList) {
                         $id_cart = Cart::getCartIdByOrderId($order->id);
                         $customization_quantities = Customization::countQuantityByCart($id_cart);
                         foreach ($productList as $key => $id_order_detail) {
                             $qtyCancelProduct = abs($qtyList[$key]);
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             $order_detail = new OrderDetail($id_order_detail);
                             $customization_quantity = 0;
                             if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                                 $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                             }
                             if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if ($customizationList) {
                         $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             $customization_quantity = $customization_quantities[$id_customization];
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if (!count($this->errors) && $productList) {
                         foreach ($productList as $key => $id_order_detail) {
                             $qty_cancel_product = abs($qtyList[$key]);
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $qty_cancel_product > 0) {
                                 $this->reinjectQuantity($order_detail, $qty_cancel_product);
                             }
                             // Delete product
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->deleteProduct($order, $order_detail, $qty_cancel_product)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
                             }
                             // Update weight SUM
                             $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                             if (Validate::isLoadedObject($order_carrier)) {
                                 $order_carrier->weight = (double) $order->getTotalWeight();
                                 if ($order_carrier->update()) {
                                     $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                                 }
                             }
                             Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => (int) $id_order_detail), null, false, true, false, $order->id_shop);
                         }
                     }
                     if (!count($this->errors) && $customizationList) {
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete product customization.') . ' ' . $id_customization;
                             }
                         }
                     }
                     // E-mail params
                     if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
                         $customer = new Customer((int) $order->id_customer);
                         $params['{lastname}'] = $customer->lastname;
                         $params['{firstname}'] = $customer->firstname;
                         $params['{id_order}'] = $order->id;
                         $params['{order_name}'] = $order->getUniqReference();
                     }
                     // Generate credit slip
                     if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
                         if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
                             $this->errors[] = Tools::displayError('A credit slip cannot be generated. ');
                         } else {
                             Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list), null, false, true, false, $order->id_shop);
                             @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                         }
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
                         $cartrule = new CartRule();
                         $languages = Language::getLanguages($order);
                         $cartrule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cartrule->name[$language['id_lang']] = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         }
                         // Define a temporary code
                         $cartrule->code = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         $cartrule->quantity = 1;
                         $cartrule->quantity_per_user = 1;
                         // Specific to the customer
                         $cartrule->id_customer = $order->id_customer;
                         $now = time();
                         $cartrule->date_from = date('Y-m-d H:i:s', $now);
                         $cartrule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cartrule->active = 1;
                         $products = $order->getProducts(false, $full_product_list, $full_quantity_list);
                         $total = 0;
                         foreach ($products as $product) {
                             $total += $product['unit_price_tax_incl'] * $product['product_quantity'];
                         }
                         if (Tools::isSubmit('shippingBack')) {
                             $total += $order->total_shipping;
                         }
                         $cartrule->reduction_amount = $total;
                         $cartrule->reduction_tax = true;
                         $cartrule->minimum_amount_currency = $order->id_currency;
                         $cartrule->reduction_currency = $order->id_currency;
                         if (!$cartrule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cartrule->name[$language['id_lang']] = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             }
                             $cartrule->code = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             if (!$cartrule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $params['{voucher_amount}'] = Tools::displayPrice($cartrule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cartrule->code;
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('No product or quantity has been selected.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=31&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('messageReaded')) {
         Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
     } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
             $currency = new Currency(Tools::getValue('payment_currency'));
             $order_has_invoice = $order->hasInvoice();
             if ($order_has_invoice) {
                 $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
             } else {
                 $order_invoice = null;
             }
             if (!Validate::isLoadedObject($order)) {
                 $this->errors[] = Tools::displayError('The order cannot be found');
             } elseif (!Validate::isNegativePrice($amount) || !(double) $amount) {
                 $this->errors[] = Tools::displayError('The amount is invalid.');
             } elseif (!Validate::isGenericName(Tools::getValue('payment_method'))) {
                 $this->errors[] = Tools::displayError('The selected payment method is invalid.');
             } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
                 $this->errors[] = Tools::displayError('The transaction ID is invalid.');
             } elseif (!Validate::isLoadedObject($currency)) {
                 $this->errors[] = Tools::displayError('The selected currency is invalid.');
             } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
                 $this->errors[] = Tools::displayError('The invoice is invalid.');
             } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
                 $this->errors[] = Tools::displayError('The date is invalid');
             } else {
                 if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
                     $this->errors[] = Tools::displayError('An error occurred during payment.');
                 } else {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitEditNote')) {
         $note = Tools::getValue('note');
         $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
         if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
             if ($this->tabAccess['edit'] === '1') {
                 $order_invoice->note = $note;
                 if ($order_invoice->save()) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('The invoice note was not saved.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             $this->errors[] = Tools::displayError('The invoice for edit note was unable to load. ');
         }
     } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             $payment_module = Module::getInstanceByName($module_name);
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $employee = new Employee((int) Context::getContext()->cookie->id_employee);
             $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
             if ($payment_module->currentOrder) {
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $address = new Address(Tools::getValue('id_address'));
             if (Validate::isLoadedObject($address)) {
                 // Update the address on order
                 if (Tools::isSubmit('submitAddressShipping')) {
                     $order->id_address_delivery = $address->id;
                 } elseif (Tools::isSubmit('submitAddressInvoice')) {
                     $order->id_address_invoice = $address->id;
                 }
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('This address can\'t be loaded');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
                 $old_currency = new Currency($order->id_currency);
                 $currency = new Currency(Tools::getValue('new_currency'));
                 if (!Validate::isLoadedObject($currency)) {
                     throw new PrestaShopException('Can\'t load Currency object');
                 }
                 // Update order detail amount
                 foreach ($order->getOrderDetailList() as $row) {
                     $order_detail = new OrderDetail($row['id_order_detail']);
                     $fields = array('ecotax', 'product_price', 'reduction_amount', 'total_shipping_price_tax_excl', 'total_shipping_price_tax_incl', 'total_price_tax_incl', 'total_price_tax_excl', 'product_quantity_discount', 'purchase_supplier_price', 'reduction_amount', 'reduction_amount_tax_incl', 'reduction_amount_tax_excl', 'unit_price_tax_incl', 'unit_price_tax_excl', 'original_product_price');
                     foreach ($fields as $field) {
                         $order_detail->{$field} = Tools::convertPriceFull($order_detail->{$field}, $old_currency, $currency);
                     }
                     $order_detail->update();
                     $order_detail->updateTaxAmount($order);
                 }
                 $id_order_carrier = (int) $order->getIdOrderCarrier();
                 if ($id_order_carrier) {
                     $order_carrier = $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                     $order_carrier->shipping_cost_tax_excl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
                     $order_carrier->shipping_cost_tax_incl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
                     $order_carrier->update();
                 }
                 // Update order && order_invoice amount
                 $fields = array('total_discounts', 'total_discounts_tax_incl', 'total_discounts_tax_excl', 'total_discount_tax_excl', 'total_discount_tax_incl', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real', 'total_products', 'total_products_wt', 'total_shipping', 'total_shipping_tax_incl', 'total_shipping_tax_excl', 'total_wrapping', 'total_wrapping_tax_incl', 'total_wrapping_tax_excl');
                 $invoices = $order->getInvoicesCollection();
                 if ($invoices) {
                     foreach ($invoices as $invoice) {
                         foreach ($fields as $field) {
                             if (isset($invoice->{$field})) {
                                 $invoice->{$field} = Tools::convertPriceFull($invoice->{$field}, $old_currency, $currency);
                             }
                         }
                         $invoice->save();
                     }
                 }
                 foreach ($fields as $field) {
                     if (isset($order->{$field})) {
                         $order->{$field} = Tools::convertPriceFull($order->{$field}, $old_currency, $currency);
                     }
                 }
                 // Update currency in order
                 $order->id_currency = $currency->id;
                 // Update exchange rate
                 $order->conversion_rate = (double) $currency->conversion_rate;
                 $order->update();
             } else {
                 $this->errors[] = Tools::displayError('You cannot change the currency.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
         if (!Configuration::get('PS_INVOICE', null, null, $order->id_shop)) {
             $this->errors[] = Tools::displayError('Invoice management has been disabled.');
         } elseif ($order->hasInvoice()) {
             $this->errors[] = Tools::displayError('This order already has an invoice.');
         } else {
             $order->setInvoice(true);
             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
         }
     } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
             if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
                 if ($order_cart_rule->id_order_invoice) {
                     $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
                     if (!Validate::isLoadedObject($order_invoice)) {
                         throw new PrestaShopException('Can\'t load Order Invoice object');
                     }
                     // Update amounts of Order Invoice
                     $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
                     $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
                     $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                     $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
                     // Update Order Invoice
                     $order_invoice->update();
                 }
                 // Update amounts of order
                 $order->total_discounts -= $order_cart_rule->value;
                 $order->total_discounts_tax_incl -= $order_cart_rule->value;
                 $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
                 $order->total_paid += $order_cart_rule->value;
                 $order->total_paid_tax_incl += $order_cart_rule->value;
                 $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                 // Delete Order Cart Rule and update Order
                 $order_cart_rule->delete();
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('You cannot edit this cart rule.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitNewVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Tools::getValue('discount_name')) {
                 $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount.');
             } else {
                 if ($order->hasInvoice()) {
                     // If the discount is for only one invoice
                     if (!Tools::isSubmit('discount_all_invoices')) {
                         $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
                         if (!Validate::isLoadedObject($order_invoice)) {
                             throw new PrestaShopException('Can\'t load Order Invoice object');
                         }
                     }
                 }
                 $cart_rules = array();
                 $discount_value = (double) str_replace(',', '.', Tools::getValue('discount_value'));
                 switch (Tools::getValue('discount_type')) {
                     // Percent type
                     case 1:
                         if ($discount_value < 100) {
                             if (isset($order_invoice)) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             } elseif ($order->hasInvoice()) {
                                 $order_invoices_collection = $order->getInvoicesCollection();
                                 foreach ($order_invoices_collection as $order_invoice) {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * $discount_value / 100, 2);
                             }
                         } else {
                             $this->errors[] = Tools::displayError('The discount value is invalid.');
                         }
                         break;
                         // Amount type
                     // Amount type
                     case 2:
                         if (isset($order_invoice)) {
                             if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.');
                             } else {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                     $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop) . ')';
                                 } else {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             }
                         } else {
                             if ($discount_value > $order->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order total.');
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                             }
                         }
                         break;
                         // Free shipping type
                     // Free shipping type
                     case 3:
                         if (isset($order_invoice)) {
                             if ($order_invoice->total_shipping_tax_incl > 0) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($order_invoice->total_shipping_tax_incl <= 0) {
                                     continue;
                                 }
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } else {
                             $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
                             $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
                         }
                         break;
                     default:
                         $this->errors[] = Tools::displayError('The discount type is invalid.');
                 }
                 $res = true;
                 foreach ($cart_rules as &$cart_rule) {
                     $cartRuleObj = new CartRule();
                     $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
                     $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
                     $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
                     $cartRuleObj->quantity = 0;
                     $cartRuleObj->quantity_per_user = 1;
                     if (Tools::getValue('discount_type') == 1) {
                         $cartRuleObj->reduction_percent = $discount_value;
                     } elseif (Tools::getValue('discount_type') == 2) {
                         $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
                     } elseif (Tools::getValue('discount_type') == 3) {
                         $cartRuleObj->free_shipping = 1;
                     }
                     $cartRuleObj->active = 0;
                     if ($res = $cartRuleObj->add()) {
                         $cart_rule['id'] = $cartRuleObj->id;
                     } else {
                         break;
                     }
                 }
                 if ($res) {
                     foreach ($cart_rules as $id_order_invoice => $cart_rule) {
                         // Create OrderCartRule
                         $order_cart_rule = new OrderCartRule();
                         $order_cart_rule->id_order = $order->id;
                         $order_cart_rule->id_cart_rule = $cart_rule['id'];
                         $order_cart_rule->id_order_invoice = $id_order_invoice;
                         $order_cart_rule->name = Tools::getValue('discount_name');
                         $order_cart_rule->value = $cart_rule['value_tax_incl'];
                         $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
                         $res &= $order_cart_rule->add();
                         $order->total_discounts += $order_cart_rule->value;
                         $order->total_discounts_tax_incl += $order_cart_rule->value;
                         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
                         $order->total_paid -= $order_cart_rule->value;
                         $order->total_paid_tax_incl -= $order_cart_rule->value;
                         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
                     }
                     // Update Order
                     $res &= $order->update();
                 }
                 if ($res) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred during the OrderCartRule creation');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     }
     parent::postProcess();
 }
Beispiel #8
0
 public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
 {
     if (self::DEBUG_MODE) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true);
     }
     if (!isset($this->context)) {
         $this->context = Context::getContext();
     }
     $this->context->cart = new Cart($id_cart);
     $this->context->customer = new Customer($this->context->cart->id_customer);
     // The tax cart is loaded before the customer so re-cache the tax calculation method
     $this->context->cart->setTaxCalculationMethod();
     $this->context->language = new Language($this->context->cart->id_lang);
     $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop);
     ShopUrl::resetMainDomainCache();
     $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
     $this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
         $context_country = $this->context->country;
     }
     $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
     if (!Validate::isLoadedObject($order_status)) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true);
         throw new PrestaShopException('Can\'t load Order status');
     }
     if (!$this->active) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true);
         die(Tools::displayError());
     }
     // Does order already exists ?
     if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
         if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true);
             die(Tools::displayError());
         }
         // For each package, generate an order
         $delivery_option_list = $this->context->cart->getDeliveryOptionList();
         $package_list = $this->context->cart->getPackageList();
         $cart_delivery_option = $this->context->cart->getDeliveryOption();
         // If some delivery options are not defined, or not valid, use the first valid option
         foreach ($delivery_option_list as $id_address => $package) {
             if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
                 foreach ($package as $key => $val) {
                     $cart_delivery_option[$id_address] = $key;
                     break;
                 }
             }
         }
         $order_list = array();
         $order_detail_list = array();
         do {
             $reference = Order::generateReference();
         } while (Order::getByReference($reference)->count());
         $this->currentOrderReference = $reference;
         $order_creation_failed = false;
         $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
         foreach ($cart_delivery_option as $id_address => $key_carriers) {
             foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
                 foreach ($data['package_list'] as $id_package) {
                     // Rewrite the id_warehouse
                     $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier);
                     $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
                 }
             }
         }
         // Make sure CartRule caches are empty
         CartRule::cleanCache();
         $cart_rules = $this->context->cart->getCartRules();
         foreach ($cart_rules as $cart_rule) {
             if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) {
                 if ($error = $rule->checkValidity($this->context, true, true)) {
                     $this->context->cart->removeCartRule((int) $rule->id);
                     if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) {
                         if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                             Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
                         }
                         Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
                     } else {
                         $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code;
                         $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name));
                         PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id);
                     }
                 }
             }
         }
         foreach ($package_list as $id_address => $packageByAddress) {
             foreach ($packageByAddress as $id_package => $package) {
                 $order = new Order();
                 $order->product_list = $package['product_list'];
                 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
                     $address = new Address($id_address);
                     $this->context->country = new Country($address->id_country, $this->context->cart->id_lang);
                     if (!$this->context->country->active) {
                         throw new PrestaShopException('The delivery address country is not active.');
                     }
                 }
                 $carrier = null;
                 if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
                     $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang);
                     $order->id_carrier = (int) $carrier->id;
                     $id_carrier = (int) $carrier->id;
                 } else {
                     $order->id_carrier = 0;
                     $id_carrier = 0;
                 }
                 $order->id_customer = (int) $this->context->cart->id_customer;
                 $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
                 $order->id_address_delivery = (int) $id_address;
                 $order->id_currency = $this->context->currency->id;
                 $order->id_lang = (int) $this->context->cart->id_lang;
                 $order->id_cart = (int) $this->context->cart->id;
                 $order->reference = $reference;
                 $order->id_shop = (int) $this->context->shop->id;
                 $order->id_shop_group = (int) $this->context->shop->id_shop_group;
                 $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key);
                 $order->payment = $payment_method;
                 if (isset($this->name)) {
                     $order->module = $this->name;
                 }
                 $order->recyclable = $this->context->cart->recyclable;
                 $order->gift = (int) $this->context->cart->gift;
                 $order->gift_message = $this->context->cart->gift_message;
                 $order->mobile_theme = $this->context->cart->mobile_theme;
                 $order->conversion_rate = $this->context->currency->conversion_rate;
                 $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid;
                 $order->total_paid_real = 0;
                 $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts = $order->total_discounts_tax_incl;
                 $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list);
                 $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list);
                 $order->total_shipping = $order->total_shipping_tax_incl;
                 if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
                     $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
                 }
                 $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping = $order->total_wrapping_tax_incl;
                 $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
                 $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
                 $order->total_paid = $order->total_paid_tax_incl;
                 $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
                 $order->invoice_date = '0000-00-00 00:00:00';
                 $order->delivery_date = '0000-00-00 00:00:00';
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Creating order
                 $result = $order->add();
                 if (!$result) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true);
                     throw new PrestaShopException('Can\'t save Order');
                 }
                 // Amount paid by customer is not the right one -> Status = payment error
                 // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
                 // if ($order->total_paid != $order->total_paid_real)
                 // We use number_format in order to compare two string
                 if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
                     $id_order_state = Configuration::get('PS_OS_ERROR');
                 }
                 $order_list[] = $order;
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Insert new Order detail list using cart for the current order
                 $order_detail = new OrderDetail(null, null, $this->context);
                 $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
                 $order_detail_list[] = $order_detail;
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Adding an entry in order_carrier table
                 if (!is_null($carrier)) {
                     $order_carrier = new OrderCarrier();
                     $order_carrier->id_order = (int) $order->id;
                     $order_carrier->id_carrier = (int) $id_carrier;
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl;
                     $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl;
                     $order_carrier->add();
                 }
             }
         }
         // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
             $this->context->country = $context_country;
         }
         if (!$this->context->country->active) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true);
             throw new PrestaShopException('The order address country is not active.');
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true);
         }
         // Register Payment only if the order status validate the order
         if ($order_status->logable) {
             // $order is the last order loop in the foreach
             // The method addOrderPayment of the class Order make a create a paymentOrder
             //     linked to the order reference and not to the order id
             if (isset($extra_vars['transaction_id'])) {
                 $transaction_id = $extra_vars['transaction_id'];
             } else {
                 $transaction_id = null;
             }
             if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
                 PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true);
                 throw new PrestaShopException('Can\'t save Order Payment');
             }
         }
         // Next !
         $only_one_gift = false;
         $cart_rule_used = array();
         $products = $this->context->cart->getProducts();
         // Make sure CarRule caches are empty
         CartRule::cleanCache();
         foreach ($order_detail_list as $key => $order_detail) {
             $order = $order_list[$key];
             if (!$order_creation_failed && isset($order->id)) {
                 if (!$secure_key) {
                     $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
                 }
                 // Optional message to attach to this order
                 if (isset($message) & !empty($message)) {
                     $msg = new Message();
                     $message = strip_tags($message, '<br>');
                     if (Validate::isCleanHtml($message)) {
                         if (self::DEBUG_MODE) {
                             PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                         }
                         $msg->message = $message;
                         $msg->id_order = (int) $order->id;
                         $msg->private = 1;
                         $msg->add();
                     }
                 }
                 // Insert new Order detail list using cart for the current order
                 //$orderDetail = new OrderDetail(null, null, $this->context);
                 //$orderDetail->createList($order, $this->context->cart, $id_order_state);
                 // Construct order detail table for the email
                 $products_list = '';
                 $virtual_product = true;
                 $ppropertiessmartprice_hook1 = null;
                 $product_var_tpl_list = array();
                 foreach ($order->product_list as $product) {
                     PP::smartyPPAssign(array('cart' => $product, 'currency' => $this->context->currency));
                     $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $ppropertiessmartprice_hook2 = '';
                     $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . PP::smartyDisplayProductName(array('name' => '')) . $ppropertiessmartprice_hook2, 'unit_price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt)), 'price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total'] : $product['total_wt'], 'quantity' => (int) $product['cart_quantity'], 'm' => 'total')), 'quantity' => PP::smartyDisplayQty(array('quantity' => (int) $product['cart_quantity'])), 'customization' => array());
                     $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart);
                     $productHasCustomizedDatas = Product::hasCustomizedDatas($product, $customized_datas);
                     if ($productHasCustomizedDatas && isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                         $product_var_tpl['customization'] = array();
                         foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
                             if ($product['id_cart_product'] == $customization['id_cart_product']) {
                                 $customization_text = '';
                                 if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                     foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                         $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
                                     }
                                 }
                                 if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                     $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />';
                                 }
                                 $customization_quantity = (int) $product['customization_quantity'];
                                 $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => PP::smartyDisplayQty(array('quantity' => $customization_quantity)), 'quantity' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total_customization'] : $product['total_customization_wt'], 'm' => 'total')));
                             }
                         }
                     }
                     $product_var_tpl_list[] = $product_var_tpl;
                     // Check if is not a virutal product for the displaying of shipping
                     if (!$product['is_virtual']) {
                         $virtual_product &= false;
                     }
                 }
                 // end foreach ($products)
                 PP::smartyPPAssign();
                 $product_list_txt = '';
                 $product_list_html = '';
                 if (count($product_var_tpl_list) > 0) {
                     $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
                     $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
                 }
                 $cart_rules_list = array();
                 $total_reduction_value_ti = 0;
                 $total_reduction_value_tex = 0;
                 foreach ($cart_rules as $cart_rule) {
                     $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
                     $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package));
                     // If the reduction is not applicable to this order, then continue with the next one
                     if (!$values['tax_excl']) {
                         continue;
                     }
                     // IF
                     //     This is not multi-shipping
                     //     The value of the voucher is greater than the total of the order
                     //     Partial use is allowed
                     //     This is an "amount" reduction, not a reduction in % or a gift
                     // THEN
                     //     The voucher is cloned with a new value corresponding to the remainder
                     if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
                         // Create a new voucher from the original
                         $voucher = new CartRule($cart_rule['obj']->id);
                         // We need to instantiate the CartRule without lang parameter to allow saving it
                         unset($voucher->id);
                         // Set a new voucher code
                         $voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
                         if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
                             $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (int) ($matches[1] + 1), $voucher->code);
                         }
                         // Set the new voucher value
                         if ($voucher->reduction_tax) {
                             $voucher->reduction_amount = $total_reduction_value_ti + $values['tax_incl'] - $order->total_products_wt;
                             // Add total shipping amout only if reduction amount > total shipping
                             if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) {
                                 $voucher->reduction_amount -= $order->total_shipping_tax_incl;
                             }
                         } else {
                             $voucher->reduction_amount = $total_reduction_value_tex + $values['tax_excl'] - $order->total_products;
                             // Add total shipping amout only if reduction amount > total shipping
                             if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) {
                                 $voucher->reduction_amount -= $order->total_shipping_tax_excl;
                             }
                         }
                         if ($voucher->reduction_amount <= 0) {
                             continue;
                         }
                         $voucher->id_customer = $order->id_customer;
                         $voucher->quantity = 1;
                         $voucher->quantity_per_user = 1;
                         $voucher->free_shipping = 0;
                         if ($voucher->add()) {
                             // If the voucher has conditions, they are now copied to the new voucher
                             CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
                             $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference());
                             Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                         }
                         $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti;
                         $values['tax_excl'] = $order->total_products - $total_reduction_value_tex;
                     }
                     $total_reduction_value_ti += $values['tax_incl'];
                     $total_reduction_value_tex += $values['tax_excl'];
                     $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
                     if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
                         $cart_rule_used[] = $cart_rule['obj']->id;
                         // Create a new instance of Cart Rule without id_lang, in order to update its quantity
                         $cart_rule_to_update = new CartRule($cart_rule['obj']->id);
                         $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
                         $cart_rule_to_update->update();
                     }
                     $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false));
                 }
                 $cart_rules_list_txt = '';
                 $cart_rules_list_html = '';
                 if (count($cart_rules_list) > 0) {
                     $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
                     $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
                 }
                 // Specify order id for message
                 $old_message = Message::getMessageByCartId((int) $this->context->cart->id);
                 if ($old_message) {
                     $update_message = new Message((int) $old_message['id_message']);
                     $update_message->id_order = (int) $order->id;
                     $update_message->update();
                     // Add this message in the customer thread
                     $customer_thread = new CustomerThread();
                     $customer_thread->id_contact = 0;
                     $customer_thread->id_customer = (int) $order->id_customer;
                     $customer_thread->id_shop = (int) $this->context->shop->id;
                     $customer_thread->id_order = (int) $order->id;
                     $customer_thread->id_lang = (int) $this->context->language->id;
                     $customer_thread->email = $this->context->customer->email;
                     $customer_thread->status = 'open';
                     $customer_thread->token = Tools::passwdGen(12);
                     $customer_thread->add();
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = 0;
                     $customer_message->message = $update_message->message;
                     $customer_message->private = 0;
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving message');
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Hook validate order
                 Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status));
                 foreach ($this->context->cart->getProducts() as $product) {
                     if ($order_status->logable) {
                         ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Set the order status
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState((int) $id_order_state, $order, true);
                 $new_history->addWithemail(true, $extra_vars);
                 // Switch to back order if needed
                 if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
                     $history = new OrderHistory();
                     $history->id_order = (int) $order->id;
                     $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
                     $history->addWithemail();
                 }
                 unset($order_detail);
                 // Order is reloaded because the status just changed
                 $order = new Order($order->id);
                 // Send an e-mail to customer (one order = one email)
                 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
                     $invoice = new Address($order->id_address_invoice);
                     $delivery = new Address($order->id_address_delivery);
                     $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
                     $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
                     $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false));
                     if (is_array($extra_vars)) {
                         $data = array_merge($data, $extra_vars);
                     }
                     // Join PDF invoice
                     if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
                         $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
                         $file_attachement = array();
                         $file_attachement['content'] = $pdf->render(false);
                         $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                         $file_attachement['mime'] = 'application/pdf';
                     } else {
                         $file_attachement = null;
                     }
                     if (self::DEBUG_MODE) {
                         PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true);
                     }
                     if (Validate::isEmail($this->context->customer->email)) {
                         Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                     }
                 }
                 // updates stock in shops
                 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                     $product_list = $order->getProducts();
                     foreach ($product_list as $product) {
                         // if the available quantities depends on the physical stock
                         if (StockAvailable::dependsOnStock($product['product_id'])) {
                             // synchronizes
                             StockAvailable::synchronize($product['product_id'], $order->id_shop);
                         }
                     }
                 }
             } else {
                 $error = Tools::displayError('Order creation failed');
                 PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart);
                 die($error);
             }
         }
         // End foreach $order_detail_list
         // Update Order Details Tax in case cart rules have free shipping
         foreach ($order->getOrderDetailList() as $detail) {
             $order_detail = new OrderDetail($detail['id_order_detail']);
             $order_detail->updateTaxAmount($order);
         }
         // Use the last order as currentOrder
         if (isset($order) && $order->id) {
             $this->currentOrder = (int) $order->id;
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true);
         }
         return true;
     } else {
         $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
         PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id);
         die($error);
     }
 }
Beispiel #9
0
 public function getPreviewUrl(Product $product)
 {
     $id_lang = Configuration::get('PS_LANG_DEFAULT', null, null, Context::getContext()->shop->id);
     if (!ShopUrl::getMainShopDomain()) {
         return false;
     }
     $is_rewrite_active = (bool) Configuration::get('PS_REWRITING_SETTINGS');
     $preview_url = $this->context->link->getProductLink($product, $this->getFieldValue($product, 'link_rewrite', $this->context->language->id), Category::getLinkRewrite($this->getFieldValue($product, 'id_category_default'), $this->context->language->id), null, $id_lang, (int) Context::getContext()->shop->id, 0, $is_rewrite_active);
     if (!$product->active) {
         $admin_dir = dirname($_SERVER['PHP_SELF']);
         $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
         $preview_url .= (strpos($preview_url, '?') === false ? '?' : '&') . 'adtoken=' . $this->token . '&ad=' . $admin_dir . '&id_employee=' . (int) $this->context->employee->id;
     }
     return $preview_url;
 }
Beispiel #10
0
    private function _displayForm()
    {
        $values = isset($_POST) && isset($_POST['submitPsblog']) ? Tools::getValue('pref') : array_merge(self::$default_values, self::getPreferences());
        $this->_html .= '
		
		<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
		<fieldset>
		<legend>' . $this->l('General') . '</legend>
			
		
		<label>' . $this->l('Active categories') . '</label>  
		<div class="margin-form">
		<input type="checkbox" name="pref[category_active]" value="1" ' . (isset($values['category_active']) && $values['category_active'] == '1' ? 'checked' : '') . ' />
		</div>
		<div class="clear"></div>
		
		<label>' . $this->l('Active products') . '</label>  
		<div class="margin-form">
		<input type="checkbox" name="pref[product_active]" value="1" ' . (isset($values['product_active']) && $values['product_active'] == '1' ? 'checked' : '') . ' />
		</div>
		<div class="clear"></div>
		
		<label>' . $this->l('Active comments') . '</label>  
		<div class="margin-form">
		<input type="checkbox" name="pref[comment_active]" value="1" ' . (isset($values['comment_active']) && $values['comment_active'] == '1' ? 'checked' : '') . ' />
		</div>
		<div class="clear"></div>
		
		<label>' . $this->l('Enable related articles') . '</label>  
		<div class="margin-form">
		<input type="checkbox" name="pref[related_active]" value="1" ' . (isset($values['related_active']) && $values['related_active'] == '1' ? 'checked' : '') . ' />
		</div>';
        $this->_html .= '
			</fieldset>
			<br /><div class="clear"></div>';
        $this->_html .= '<fieldset>
                <legend>' . $this->l('List settings') . '</legend>

                <label>' . $this->l('Number of articles per page') . '</label> 
                <div class="margin-form">
                <input type="text" name="pref[list_limit_page]" value="' . $values['list_limit_page'] . '" size="3" />
                </div><div class="clear"></div><br />

                <label>' . $this->l('Display date') . '</label>  
                <div class="margin-form">
                <input type="checkbox" name="pref[list_display_date]" value="1" ' . (isset($values['list_display_date']) && $values['list_display_date'] == '1' ? 'checked' : '') . '/>
                </div><div class="clear"></div><br />

                <label>' . $this->l('Image width in lists') . '</label>
                <div class="margin-form">
                        <input type="text" name="pref[img_list_width]" value="' . $values['img_list_width'] . '" size="3" /> px
                </div>';
        $this->_html .= '</fieldset><br /><div class="clear"></div>';
        $this->_html .= '<fieldset>
				
                                <legend>' . $this->l('View settings') . '</legend>
		
				<label>' . $this->l('Image width in article detail') . '</label>
				<div class="margin-form">
					<input type="text" name="pref[img_width]" value="' . $values['img_width'] . '" size="3" /> px
				</div><div class="clear"></div><br />
				
				<label>' . $this->l('Enable popin for images') . '</label>  
					<div class="margin-form">
					<input type="checkbox" name="pref[view_display_popin]" value="1" ' . (isset($values['view_display_popin']) && $values['view_display_popin'] == '1' ? 'checked' : '') . '/>
				</div>
				
				<div class="clear"></div><br />
				
				<label>' . $this->l('Display date') . '</label>  
				<div class="margin-form">
				<input type="checkbox" name="pref[view_display_date]" value="1" ' . (isset($values['view_display_date']) && $values['view_display_date'] == '1' ? 'checked' : '') . '/>
				</div>
				
				<div class="clear"></div><br />';
        $this->_html .= '<label>' . $this->l('Active Addthis') . '</label>  
				<div class="margin-form">
					<input type="checkbox" name="pref[share_active]" value="1" ' . (isset($values['share_active']) && $values['share_active'] == '1' ? 'checked' : '') . ' />
				</div>
				
				</fieldset>
				<div class="clear"></div><br />';
        $this->_html .= '<fieldset>
                                <legend>' . $this->l('Related products settings') . '</legend>
				
                                <label>' . $this->l('Enable related articles in product page') . '</label>  
                                <div class="margin-form">
                                <input type="checkbox" name="pref[product_page_related]" value="1" ' . (isset($values['product_page_related']) && $values['product_page_related'] == '1' ? 'checked' : '') . '/>
                                </div><div class="clear"></div><br />';
        $formats = ImageType::getImagesTypes();
        $this->_html .= '<label>' . $this->l('Product image format') . '</label>  
                                  <div class="margin-form">
                                      <select name="pref[product_img_format]">';
        foreach ($formats as $f) {
            $this->_html .= '<option value="' . $f['name'] . '" ' . ($values['product_img_format'] == $f['name'] ? "selected" : "") . '>' . $f['name'] . ' &nbsp;</option>';
        }
        $this->_html .= '</select>
                                 </div>';
        $this->_html .= '</fieldset><div class="clear"></div><br />';
        $this->_html .= '<fieldset>
                                        
                                <legend>' . $this->l('Comments settings') . '</legend>

                                <label>' . $this->l('All comments must be validated by an employee') . '</label>  
                                <div class="margin-form">
                                <input type="checkbox" name="pref[comment_moderate]" value="1" ' . (isset($values['comment_moderate']) && $values['comment_moderate'] == '1' ? 'checked' : '') . '/>
                                </div>

                                <div class="clear"></div><br />

                                <label>' . $this->l('Allow guest comments') . '</label>  
                                <div class="margin-form">
                                <input type="checkbox" name="pref[comment_guest]" value="1" ' . (isset($values['comment_guest']) && $values['comment_guest'] == '1' ? 'checked' : '') . '/>
                                </div>

                                <div class="clear"></div><br />

                                <label>' . $this->l('Minimum time between 2 comments from the same user') . '</label>
                                <div class="margin-form">
                                        <input name="pref[comment_min_time]" type="text" class="text" value="' . $values['comment_min_time'] . '" style="width: 40px; text-align: right;" /> ' . $this->l('seconds') . '
                                </div>

                                <div class="clear"></div><br />

                                <label>' . $this->l('Minimum length of user name') . '</label>
                                <div class="margin-form">
                                        <input name="pref[comment_name_min_length]" type="text" class="text" value="' . $values['comment_name_min_length'] . '" style="width: 40px; text-align: right;" /> ' . $this->l('characters') . '
                                </div>';
        $this->_html .= '</fieldset>';
        $this->_html .= '<div class="clear"></div><br />';
        $this->_html .= '<fieldset>
                            
                            <legend>' . $this->l('RSS settings') . '</legend>

                            <label>' . $this->l('Enable RSS feed') . '</label>  
                            <div class="margin-form">
                            <input type="checkbox" name="pref[rss_active]" value="1" ' . (isset($values['rss_active']) && $values['rss_active'] == '1' ? 'checked' : '') . '/>
                            </div>

                            <div class="clear"></div><br />

                            <label>' . $this->l('Post field used for content') . '</label> 
                            <div class="margin-form">
                                    <select name="pref[rss_display]">
                                            <option value="excerpt" ' . ($values['rss_display'] == "excerpt" ? "selected" : "") . '>' . $this->l('Excerpt') . ' &nbsp;</option>
                                            <option value="content" ' . ($values['rss_display'] == "content" ? "selected" : "") . '>' . $this->l('Content') . ' &nbsp;</option>
                                    </select>
                            </div>';
        $this->_html .= '</fieldset><div class="clear"></div><br />';
        $this->_html .= '<div class="clear"></div>
		
                    <input class="button" name="submitPsblog" value="' . $this->l('Update settings') . '" type="submit" />';
        $this->_html .= '<div class="clear"></div><br /><br />';
        $this->_html .= '<fieldset>
                            
                                <legend>' . $this->l('Tools') . '</legend>
                                
                                 <p>
                                 <input class="button" name="submitGenerateImg" value="' . $this->l('Regenerate all blog images') . '" type="submit" />
                                 &nbsp; ' . $this->l('Useful if you change the images sizes') . '
                                 </p>';
        if (self::isInstalled('gsitemap')) {
            $this->_html .= '<p>
                                        <input class="button" name="submitGenerateSitemap" value="' . $this->l('Regenerate Google sitemap') . '" type="submit" /> 
                                            &nbsp; <a href="' . _PS_BASE_URL_ . __PS_BASE_URI__ . 'modules/psblog/sitemap-blog.xml" target="_blank">' . _PS_BASE_URL_ . __PS_BASE_URI__ . 'modules/psblog/sitemap-blog.xml</a> ' . '
                                    </p>';
        }
        $this->_html .= '<div class="multishop_info">
                            <p>
                            ' . $this->l('If url rewriting doesn\'t works, check that this above lines exist in your current .htaccess file, if no, add it manually on top of your .htaccess file') . ': <br /><br />

                                  <strong>';
        $physical_uri = array();
        foreach (ShopUrl::getShopUrls() as $shop_url) {
            if (in_array($shop_url->physical_uri, $physical_uri)) {
                continue;
            }
            $this->_html .= "RewriteRule ^(.*)blog\$ " . $shop_url->physical_uri . "index.php?fc=module&module=psblog&controller=posts [QSA,L] <br />";
            $this->_html .= "RewriteRule ^(.*)blog/([0-9]+)\\-([a-zA-Z0-9-]*) " . $shop_url->physical_uri . "index.php?fc=module&module=psblog&controller=posts&post=\$2 [QSA,L] <br />";
            $this->_html .= "RewriteRule ^(.*)blog/category/([0-9]+)\\-([a-zA-Z0-9-]*) " . $shop_url->physical_uri . "index.php?fc=module&module=psblog&controller=posts&category=\$2 [QSA,L] <br />";
            $physical_uri[] = $shop_url->physical_uri;
        }
        $this->_html .= '</strong>
                                </p>
                              </div>';
        $this->_html .= '<div class="multishop_info">
                            <p>
                            ' . $this->l('To declare blog sitemap xml, add this line at the end of your robots.txt file') . ': <br /><br />

                                  <strong>
                                    Sitemap ' . _PS_BASE_URL_ . __PS_BASE_URI__ . 'modules/psblog/sitemap-blog.xml
                                 </strong>
                            </p>
                </div>';
        $this->_html .= '</fieldset>
                    						
		</form>';
    }
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <*****@*****.**>
 *  @copyright 2007-2015 PrestaShop SA
 *  @version  Release: $Revision: 14390 $
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */
// Workaround for redirection on init
$_POST['id_shop'] = 1;
require_once 'config/config.inc.php';
if (!defined('_PS_VERSION_')) {
    exit;
}
// First, we get the URL used to reach this page.
$domain = Tools::getHttpHost();
$old_domain = Configuration::get('PS_SHOP_DOMAIN');
if (version_compare(_PS_VERSION_, '1.5', '>=') && $domain != $old_domain && !Shop::isFeatureActive()) {
    $url = ShopUrl::getShopUrls(Configuration::get('PS_SHOP_DEFAULT'))->where('main', '=', 1)->getFirst();
    if ($url) {
        $url->domain = $domain;
        $url->domain_ssl = $domain;
        $url->save();
        // Then, we update the configuration table
        Configuration::updateValue('PS_SHOP_DOMAIN', $domain);
        Configuration::updateValue('PS_SHOP_DOMAIN_SSL', $domain);
    }
}
unlink(__FILE__);
Tools::redirect("index.php");
die;
Beispiel #12
0
 public function getAgileSellerLink($id_seller, $alias = NULL, $id_lang = NULL)
 {
     if (!$id_seller) {
         return '';
     }
     include_once _PS_ROOT_DIR_ . "/modules/agilemultipleseller/SellerInfo.php";
     $sellerinfo = new SellerInfo(SellerInfo::getIdBSellerId($id_seller));
     $id_shopurl = Shop::get_main_url_id($sellerinfo->id_shop);
     $shopurl = new ShopUrl($id_shopurl);
     $url = $shopurl->getURL() . $this->getLangLink();
     if (Module::IsInstalled('agilemultipleshop')) {
         include_once _PS_ROOT_DIR_ . "/modules/agilemultipleshop/agilemultipleshop.php";
         if ((int) Configuration::get('ASP_SHOP_URL_MODE') == AgileMultipleShop::SHOP_URL_MODE_DOMAIN) {
             return $url;
         }
     }
     if ($this->allow) {
         return $url;
     } else {
         return _PS_BASE_URL_SSL_ . __PS_BASE_URI__ . 'index.php?controller=agileseller&id_seller=' . (int) $id_seller;
     }
 }
                    $sql = 'SELECT distinct LOWER(TRIM(sil.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ')) AS id, TRIM(sil.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ') AS name 
			            FROM `' . _DB_PREFIX_ . 'sellerinfo_lang` sil 
						WHERE sil.id_lang = ' . $context->cookie->id_lang . ' AND LENGTH(TRIM(sil.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ')) > 0
					    ORDER BY sil.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ' ASC
		            ';
                } else {
                    $sql = 'SELECT distinct LOWER(TRIM(si.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ')) AS id, TRIM(si.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ') AS name 
			            FROM `' . _DB_PREFIX_ . 'sellerinfo` si
					    ORDER BY si.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . ' ASC
		            ';
                }
                break;
        }
        if (empty($sql)) {
            return array();
        }
        return Db::getInstance()->ExecuteS($sql);
    }
    public static function init_shop_header()
    {
        $main_shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));
        include_once _PS_ROOT_DIR_ . "/modules/agilemultipleseller/SellerInfo.php";
        Context::getContext()->smarty->assign(array('is_agilemultipleshop_installed' => 1, 'header_logo_mode' => intval(Configuration::get('ASP_HEADER_LOGO_MODE')), 'base_dir_default' => $main_shop->getBaseURL(), 'seller_shop_name' => Context::getContext()->shop->name, 'id_shop_owner' => Shop::$id_shop_owner, 'seller_logo_url' => isset(Shop::$sellerinfo) ? SellerInfo::get_seller_logo_url_static(Shop::$sellerinfo->id) : ''));
    }
    public static function clear_blockcategory_cache()
    {
        @session_start();
        if (!isset($_SESSION['id_shop_owner'])) {
            $_SESSION['id_shop_owner'] = 0;
        }
        if ($_SESSION['id_shop_owner'] != Shop::$id_shop_owner) {
            $_SESSION['id_shop_owner'] = Shop::$id_shop_owner;
            Context::getContext()->smarty->clearAllCache();
        }
    }
    public static function get_rewrite_rules()
    {
Beispiel #14
0
 /**
  * Send Email
  *
  * @param int $id_lang Language ID of the email (to translate the template)
  * @param string $template Template: the name of template not be a var but a string !
  * @param string $subject Subject of the email
  * @param string $template_vars Template variables for the email
  * @param string $to To email
  * @param string $to_name To name
  * @param string $from From email
  * @param string $from_name To email
  * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files
  * @param bool $mode_smtp SMTP mode (deprecated)
  * @param string $template_path Template path
  * @param bool $die Die after error
  * @param string $bcc Bcc recipient
  * @return bool|int Whether sending was successful. If not at all, false, otherwise amount of recipients succeeded.
  */
 public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = null, $reply_to = null)
 {
     if (!$id_shop) {
         $id_shop = Context::getContext()->shop->id;
     }
     $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_TYPE'), null, null, $id_shop);
     // Returns immediatly if emails are deactivated
     if ($configuration['PS_MAIL_METHOD'] == 3) {
         return true;
     }
     $theme_path = _PS_THEME_DIR_;
     // Get the path of theme by id_shop if exist
     if (is_numeric($id_shop) && $id_shop) {
         $shop = new Shop((int) $id_shop);
         $theme_name = $shop->getTheme();
         if (_THEME_NAME_ != $theme_name) {
             $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/';
         }
     }
     if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION']) || Tools::strtolower($configuration['PS_MAIL_SMTP_ENCRYPTION']) === 'off') {
         $configuration['PS_MAIL_SMTP_ENCRYPTION'] = false;
     }
     if (!isset($configuration['PS_MAIL_SMTP_PORT'])) {
         $configuration['PS_MAIL_SMTP_PORT'] = 'default';
     }
     // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail
     if (!isset($from) || !Validate::isEmail($from)) {
         $from = $configuration['PS_SHOP_EMAIL'];
     }
     if (!Validate::isEmail($from)) {
         $from = null;
     }
     // $from_name is not that important, no need to die if it is not valid
     if (!isset($from_name) || !Validate::isMailName($from_name)) {
         $from_name = $configuration['PS_SHOP_NAME'];
     }
     if (!Validate::isMailName($from_name)) {
         $from_name = null;
     }
     // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem
     if (!is_array($to) && !Validate::isEmail($to)) {
         Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die);
         return false;
     }
     // if bcc is not null, make sure it's a vaild e-mail
     if (!is_null($bcc) && !is_array($bcc) && !Validate::isEmail($bcc)) {
         Tools::dieOrLog(Tools::displayError('Error: parameter "bcc" is corrupted'), $die);
         $bcc = null;
     }
     if (!is_array($template_vars)) {
         $template_vars = array();
     }
     // Do not crash for this error, that may be a complicated customer name
     if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) {
         $to_name = null;
     }
     if (!Validate::isTplName($template)) {
         Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die);
         return false;
     }
     if (!Validate::isMailSubject($subject)) {
         Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die);
         return false;
     }
     /* Construct multiple recipients list if needed */
     $message = Swift_Message::newInstance();
     if (is_array($to) && isset($to)) {
         foreach ($to as $key => $addr) {
             $addr = trim($addr);
             if (!Validate::isEmail($addr)) {
                 Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die);
                 return false;
             }
             if (is_array($to_name) && $to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) {
                 $to_name = $to_name[$key];
             }
             $to_name = $to_name == null || $to_name == $addr ? '' : self::mimeEncode($to_name);
             $message->addTo($addr, $to_name);
         }
         $to_plugin = $to[0];
     } else {
         /* Simple recipient, one address */
         $to_plugin = $to;
         $to_name = $to_name == null || $to_name == $to ? '' : self::mimeEncode($to_name);
         $message->addTo($to, $to_name);
     }
     if (isset($bcc)) {
         $message->addBcc($bcc);
     }
     try {
         /* Connect with the appropriate configuration */
         if ($configuration['PS_MAIL_METHOD'] == 2) {
             if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) {
                 Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die);
                 return false;
             }
             $connection = Swift_SmtpTransport::newInstance($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'])->setUsername($configuration['PS_MAIL_USER'])->setPassword($configuration['PS_MAIL_PASSWD']);
         } else {
             $connection = Swift_MailTransport::newInstance();
         }
         if (!$connection) {
             return false;
         }
         $swift = Swift_Mailer::newInstance($connection);
         /* Get templates content */
         $iso = Language::getIsoById((int) $id_lang);
         if (!$iso) {
             Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die);
             return false;
         }
         $iso_template = $iso . '/' . $template;
         $module_name = false;
         $override_mail = false;
         // get templatePath
         if (preg_match('#' . $shop->physical_uri . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $template_path)) && preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $template_path), $res)) {
             $module_name = $res[1];
         }
         if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $iso_template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $iso_template . '.html'))) {
             $template_path = $theme_path . 'modules/' . $module_name . '/mails/';
         } elseif (file_exists($theme_path . 'mails/' . $iso_template . '.txt') || file_exists($theme_path . 'mails/' . $iso_template . '.html')) {
             $template_path = $theme_path . 'mails/';
             $override_mail = true;
         }
         if (!file_exists($template_path . $iso_template . '.txt') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT)) {
             Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $iso_template . '.txt', $die);
             return false;
         } elseif (!file_exists($template_path . $iso_template . '.html') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML)) {
             Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $iso_template . '.html', $die);
             return false;
         }
         $template_html = '';
         $template_txt = '';
         Hook::exec('actionEmailAddBeforeContent', array('template' => $template, 'template_html' => &$template_html, 'template_txt' => &$template_txt, 'id_lang' => (int) $id_lang), null, true);
         $template_html .= Tools::file_get_contents($template_path . $iso_template . '.html');
         $template_txt .= strip_tags(html_entity_decode(Tools::file_get_contents($template_path . $iso_template . '.txt'), null, 'utf-8'));
         Hook::exec('actionEmailAddAfterContent', array('template' => $template, 'template_html' => &$template_html, 'template_txt' => &$template_txt, 'id_lang' => (int) $id_lang), null, true);
         if ($override_mail && file_exists($template_path . $iso . '/lang.php')) {
             include_once $template_path . $iso . '/lang.php';
         } elseif ($module_name && file_exists($theme_path . 'mails/' . $iso . '/lang.php')) {
             include_once $theme_path . 'mails/' . $iso . '/lang.php';
         } elseif (file_exists(_PS_MAIL_DIR_ . $iso . '/lang.php')) {
             include_once _PS_MAIL_DIR_ . $iso . '/lang.php';
         } else {
             Tools::dieOrLog(Tools::displayError('Error - The language file is missing for:') . ' ' . $iso, $die);
             return false;
         }
         /* Create mail and attach differents parts */
         $subject = '[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject;
         $message->setSubject($subject);
         $message->setCharset('utf-8');
         /* Set Message-ID - getmypid() is blocked on some hosting */
         $message->setId(Mail::generateId());
         if (!($reply_to && Validate::isEmail($reply_to))) {
             $reply_to = $from;
         }
         if (isset($reply_to) && $reply_to) {
             $message->setReplyTo($reply_to);
         }
         $template_vars = array_map(array('Tools', 'htmlentitiesDecodeUTF8'), $template_vars);
         $template_vars = array_map(array('Tools', 'stripslashes'), $template_vars);
         if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop))) {
             $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop);
         } else {
             if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop))) {
                 $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop);
             } else {
                 $template_vars['{shop_logo}'] = '';
             }
         }
         ShopUrl::cacheMainDomainForShop((int) $id_shop);
         /* don't attach the logo as */
         if (isset($logo)) {
             $template_vars['{shop_logo}'] = $message->embed(Swift_Image::fromPath($logo));
         }
         if (Context::getContext()->link instanceof Link === false) {
             Context::getContext()->link = new Link();
         }
         $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME', null, null, $id_shop));
         $template_vars['{shop_url}'] = Context::getContext()->link->getPageLink('index', true, Context::getContext()->language->id, null, false, $id_shop);
         $template_vars['{my_account_url}'] = Context::getContext()->link->getPageLink('my-account', true, Context::getContext()->language->id, null, false, $id_shop);
         $template_vars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink('guest-tracking', true, Context::getContext()->language->id, null, false, $id_shop);
         $template_vars['{history_url}'] = Context::getContext()->link->getPageLink('history', true, Context::getContext()->language->id, null, false, $id_shop);
         $template_vars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $id_shop));
         // Get extra template_vars
         $extra_template_vars = array();
         Hook::exec('actionGetExtraMailTemplateVars', array('template' => $template, 'template_vars' => $template_vars, 'extra_template_vars' => &$extra_template_vars, 'id_lang' => (int) $id_lang), null, true);
         $template_vars = array_merge($template_vars, $extra_template_vars);
         $swift->registerPlugin(new Swift_Plugins_DecoratorPlugin(array($to_plugin => $template_vars)));
         if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) {
             $message->addPart($template_txt, 'text/plain', 'utf-8');
         }
         if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) {
             $message->addPart($template_html, 'text/html', 'utf-8');
         }
         if ($file_attachment && !empty($file_attachment)) {
             // Multiple attachments?
             if (!is_array(current($file_attachment))) {
                 $file_attachment = array($file_attachment);
             }
             foreach ($file_attachment as $attachment) {
                 if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) {
                     $message->attach(Swift_Attachment::newInstance()->setFilename($attachment['name'])->setContentType($attachment['mime'])->setBody($attachment['content']));
                 }
             }
         }
         /* Send mail */
         $message->setFrom(array($from => $from_name));
         $send = $swift->send($message);
         ShopUrl::resetMainDomainCache();
         if ($send && Configuration::get('PS_LOG_EMAILS')) {
             $mail = new Mail();
             $mail->template = Tools::substr($template, 0, 62);
             $mail->subject = Tools::substr($subject, 0, 254);
             $mail->id_lang = (int) $id_lang;
             $recipients_to = $message->getTo();
             $recipients_cc = $message->getCc();
             $recipients_bcc = $message->getBcc();
             if (!is_array($recipients_to)) {
                 $recipients_to = array();
             }
             if (!is_array($recipients_cc)) {
                 $recipients_cc = array();
             }
             if (!is_array($recipients_bcc)) {
                 $recipients_bcc = array();
             }
             foreach (array_merge($recipients_to, $recipients_cc, $recipients_bcc) as $email => $recipient_name) {
                 /** @var Swift_Address $recipient */
                 $mail->id = null;
                 $mail->recipient = Tools::substr($email, 0, 126);
                 $mail->add();
             }
         }
         return $send;
     } catch (Swift_SwiftException $e) {
         PrestaShopLogger::addLog('Swift Error: ' . $e->getMessage(), 3, null, 'Swift_Message');
         return false;
     }
 }
 public function execCapture()
 {
     $context = Context::getContext();
     $hipay = new HiPay_Tpp();
     $hipay_redirect_status = 'ok';
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             throw new PrestaShopException('Can\'t load Order object');
         }
         if (version_compare(_PS_VERSION_, '1.5.6', '>')) {
             ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
         }
         if (Tools::isSubmit('id_emp') && Tools::getValue('id_emp') > 0) {
             $id_employee = Tools::getValue('id_emp');
         } else {
             $id_employee = '1';
         }
     }
     if (Tools::isSubmit('hipay_capture_type')) {
         $refund_type = Tools::getValue('hipay_capture_type');
         $refund_amount = Tools::getValue('hipay_capture_amount');
         $refund_amount = str_replace(' ', '', $refund_amount);
         $refund_amount = floatval(str_replace(',', '.', $refund_amount));
     }
     // First check
     if (Tools::isSubmit('hipay_capture_submit') && $refund_type == 'partial') {
         $hipay_redirect_status = false;
         $hipay = new HiPay_Tpp();
         $orderLoaded = new OrderCore(Tools::getValue('id_order'));
         // v1.5 // $orderTotal = $orderLoaded->total_products_wt + $orderLoaded->total_shipping_tax_incl + $orderLoaded->total_wrapping_tax_incl;
         $orderTotal = $orderLoaded->total_products_wt + $orderLoaded->total_shipping + $orderLoaded->total_wrapping;
         $totalEncaissement = $hipay->getOrderTotalAmountCaptured($orderLoaded->id);
         $stillToCapture = floatval($orderTotal - $totalEncaissement);
         if (!$refund_amount) {
             $hipay_redirect_status = $hipay->l('Please enter an amount', 'capture');
             Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
             die('');
         }
         if ($refund_amount < 0) {
             $hipay_redirect_status = $hipay->l('Please enter an amount greater than zero', 'capture');
             Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
             die('');
         }
         if ($refund_amount > $stillToCapture) {
             $hipay_redirect_status = $hipay->l('Amount exceeding authorized amount', 'capture');
             Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
             die('');
         }
     }
     if (Tools::isSubmit('hipay_capture_submit') && isset($order)) {
         $sql = "SELECT * FROM `" . _DB_PREFIX_ . "hipay_transactions` WHERE `cart_id`='" . (int) $order->id_cart . "'";
         $result = Db::getInstance()->getRow($sql);
         $reference = $result['transaction_reference'];
         if ($refund_type == 'complete') {
             // Appel HiPay
             $data = HipayMaintenance::getMaintenanceData('capture', '0');
             $response = HipayMaintenance::restMaintenanceApi($reference, $data);
             // Ajout commentaire
             $msg = new Message();
             $message = 'HIPAY_CAPTURE_REQUESTED ' . $orderTotal;
             $message = strip_tags($message, '<br>');
             if (Validate::isCleanHtml($message)) {
                 $msg->message = $message;
                 $msg->id_order = intval($order->id);
                 $msg->private = 1;
                 $msg->add();
             }
         } else {
             // 'partial';
             // Appel HiPay
             /**
              * VERIFICATION
              */
             // v1.5 // $orderTotal = $order->total_products_wt + $order->total_shipping_tax_incl + $order->total_wrapping_tax_incl;
             $orderTotal = $order->total_products_wt + $order->total_shipping + $order->total_wrapping;
             $totalEncaissement = $this->getOrderTotalAmountCaptured($order->id);
             $stillToCapture = $orderTotal - $totalEncaissement;
             $orderLoaded = new OrderCore(Tools::getValue('id_order'));
             $currentState = $orderLoaded->getCurrentState();
             $stateLoaded = new OrderState($currentState);
             if (round($stillToCapture, 2) < round($refund_amount, 2)) {
                 $hipay_redirect_status = $hipay->l('Error, you are trying to capture more than the amount remaining', 'capture');
             } else {
                 $data = HipayMaintenance::getMaintenanceData('capture', $refund_amount);
                 $response = HipayMaintenance::restMaintenanceApi($reference, $data);
                 // Ajout commentaire
                 $msg = new Message();
                 $message = 'HIPAY_CAPTURE_REQUESTED ' . $refund_amount;
                 $message = strip_tags($message, '<br>');
                 if (Validate::isCleanHtml($message)) {
                     $msg->message = $message;
                     $msg->id_order = intval($order->id);
                     $msg->private = 1;
                     $msg->add();
                 }
                 $hipay_redirect_status = 'ok';
             }
         }
     } else {
         $hipay_redirect_status = $hipay->l('You do not have permission to do this.', 'capture');
     }
     Tools::redirectAdmin('../../' . Tools::getValue('adminDir') . '/index.php?tab=AdminOrders' . '&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getValue('token') . '&hipay_err=' . $hipay_redirect_status . '#hipay');
 }
 public function postProcess()
 {
     if (isset($_GET['dobirkaorder']) && Tools::getValue('id_order') > 0) {
         return $this->processDobirka();
     }
     if (isset($_GET['exportedorder']) && Tools::getValue('id_order') > 0) {
         return $this->processExported();
     }
     if (Tools::isSubmit('updateorder') && Tools::getValue('id_order')) {
         $link = Context::getContext()->link->getAdminLink('AdminOrders');
         $link .= '&id_order=' . Tools::getValue('id_order') . '&vieworder';
         Tools::redirectAdmin($link);
     }
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             throw new PrestaShopException('Can\'t load Order object');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     parent::postProcess();
 }
Beispiel #17
0
 public function createShop($shop_name)
 {
     // Create default group shop
     $shop_group = new ShopGroup();
     $shop_group->name = 'Default';
     $shop_group->active = true;
     if (!$shop_group->add()) {
         $this->setError($this->language->l('Cannot create group shop') . ' / ' . Db::getInstance()->getMsgError());
         return false;
     }
     // Create default shop
     $shop = new Shop();
     $shop->active = true;
     $shop->id_shop_group = $shop_group->id;
     $shop->id_category = 2;
     $shop->id_theme = 1;
     $shop->name = $shop_name;
     if (!$shop->add()) {
         $this->setError($this->language->l('Cannot create shop') . ' / ' . Db::getInstance()->getMsgError());
         return false;
     }
     Context::getContext()->shop = $shop;
     // Create default shop URL
     $shop_url = new ShopUrl();
     $shop_url->domain = Tools::getHttpHost();
     $shop_url->domain_ssl = Tools::getHttpHost();
     $shop_url->physical_uri = __PS_BASE_URI__;
     $shop_url->id_shop = $shop->id;
     $shop_url->main = true;
     $shop_url->active = true;
     if (!$shop_url->add()) {
         $this->setError($this->language->l('Cannot create shop URL') . ' / ' . Db::getInstance()->getMsgError());
         return false;
     }
     return true;
 }
Beispiel #18
0
 /**
  * Send Email
  * 
  * @param int $id_lang Language of the email (to translate the template)
  * @param string $template Template: the name of template not be a var but a string !
  * @param string $subject
  * @param string $template_vars
  * @param string $to
  * @param string $to_name
  * @param string $from
  * @param string $from_name
  * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files
  * @param bool $modeSMTP
  * @param string $template_path
  * @param bool $die
  * @param string $bcc Bcc recipient
  */
 public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = null)
 {
     $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_TYPE'), null, null, $id_shop);
     // Returns immediatly if emails are deactivated
     if ($configuration['PS_MAIL_METHOD'] == 3) {
         return true;
     }
     $theme_path = _PS_THEME_DIR_;
     // Get the path of theme by id_shop if exist
     if (is_numeric($id_shop) && $id_shop) {
         $shop = new Shop((int) $id_shop);
         $theme_name = $shop->getTheme();
         if (_THEME_NAME_ != $theme_name) {
             $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/';
         }
     }
     if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION'])) {
         $configuration['PS_MAIL_SMTP_ENCRYPTION'] = 'off';
     }
     if (!isset($configuration['PS_MAIL_SMTP_PORT'])) {
         $configuration['PS_MAIL_SMTP_PORT'] = 'default';
     }
     // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail
     if (!isset($from) || !Validate::isEmail($from)) {
         $from = $configuration['PS_SHOP_EMAIL'];
     }
     if (!Validate::isEmail($from)) {
         $from = null;
     }
     // $from_name is not that important, no need to die if it is not valid
     if (!isset($from_name) || !Validate::isMailName($from_name)) {
         $from_name = $configuration['PS_SHOP_NAME'];
     }
     if (!Validate::isMailName($from_name)) {
         $from_name = null;
     }
     // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem
     if (!is_array($to) && !Validate::isEmail($to)) {
         Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die);
         return false;
     }
     if (!is_array($template_vars)) {
         $template_vars = array();
     }
     // Do not crash for this error, that may be a complicated customer name
     if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) {
         $to_name = null;
     }
     if (!Validate::isTplName($template)) {
         Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die);
         return false;
     }
     if (!Validate::isMailSubject($subject)) {
         Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die);
         return false;
     }
     /* Construct multiple recipients list if needed */
     $to_list = new Swift_RecipientList();
     if (is_array($to) && isset($to)) {
         foreach ($to as $key => $addr) {
             $addr = trim($addr);
             if (!Validate::isEmail($addr)) {
                 Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die);
                 return false;
             }
             if (is_array($to_name)) {
                 if ($to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) {
                     $to_name = $to_name[$key];
                 }
             }
             if ($to_name == null || $to_name == $addr) {
                 $to_name = '';
             } else {
                 if (function_exists('mb_encode_mimeheader')) {
                     $to_name = mb_encode_mimeheader($to_name, 'utf-8');
                 } else {
                     $to_name = self::mimeEncode($to_name);
                 }
             }
             $to_list->addTo($addr, $to_name);
         }
         $to_plugin = $to[0];
     } else {
         /* Simple recipient, one address */
         $to_plugin = $to;
         if ($to_name == null || $to_name == $to) {
             $to_name = '';
         } else {
             if (function_exists('mb_encode_mimeheader')) {
                 $to_name = mb_encode_mimeheader($to_name, 'utf-8');
             } else {
                 $to_name = self::mimeEncode($to_name);
             }
         }
         $to_list->addTo($to, $to_name);
     }
     if (isset($bcc)) {
         $to_list->addBcc($bcc);
     }
     $to = $to_list;
     try {
         /* Connect with the appropriate configuration */
         if ($configuration['PS_MAIL_METHOD'] == 2) {
             if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) {
                 Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die);
                 return false;
             }
             $connection = new Swift_Connection_SMTP($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : ($configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF));
             $connection->setTimeout(4);
             if (!$connection) {
                 return false;
             }
             if (!empty($configuration['PS_MAIL_USER'])) {
                 $connection->setUsername($configuration['PS_MAIL_USER']);
             }
             if (!empty($configuration['PS_MAIL_PASSWD'])) {
                 $connection->setPassword($configuration['PS_MAIL_PASSWD']);
             }
         } else {
             $connection = new Swift_Connection_NativeMail();
         }
         if (!$connection) {
             return false;
         }
         $swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN', null, null, $id_shop));
         /* Get templates content */
         $iso = Language::getIsoById((int) $id_lang);
         if (!$iso) {
             Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die);
             return false;
         }
         $template = $iso . '/' . $template;
         $module_name = false;
         $override_mail = false;
         // get templatePath
         if (preg_match('#' . __PS_BASE_URI__ . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $template_path)) && preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $template_path), $res)) {
             $module_name = $res[1];
         }
         if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.html'))) {
             $template_path = $theme_path . 'modules/' . $module_name . '/mails/';
         } elseif (file_exists($theme_path . 'mails/' . $template . '.txt') || file_exists($theme_path . 'mails/' . $template . '.html')) {
             $template_path = $theme_path . 'mails/';
             $override_mail = true;
         }
         if (!file_exists($template_path . $template . '.txt') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT)) {
             Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.txt', $die);
             return false;
         } else {
             if (!file_exists($template_path . $template . '.html') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML)) {
                 Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.html', $die);
                 return false;
             }
         }
         $template_html = file_get_contents($template_path . $template . '.html');
         $template_txt = strip_tags(html_entity_decode(file_get_contents($template_path . $template . '.txt'), null, 'utf-8'));
         if ($override_mail && file_exists($template_path . $iso . '/lang.php')) {
             include_once $template_path . $iso . '/lang.php';
         } else {
             if ($module_name && file_exists($theme_path . 'mails/' . $iso . '/lang.php')) {
                 include_once $theme_path . 'mails/' . $iso . '/lang.php';
             } else {
                 if (file_exists(_PS_MAIL_DIR_ . $iso . '/lang.php')) {
                     include_once _PS_MAIL_DIR_ . $iso . '/lang.php';
                 } else {
                     Tools::dieOrLog(Tools::displayError('Error - The lang file is missing for :') . ' ' . $iso, $die);
                     return false;
                 }
             }
         }
         /* Create mail and attach differents parts */
         $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject);
         $message->setCharset('utf-8');
         /* Set Message-ID - getmypid() is blocked on some hosting */
         $message->setId(Mail::generateId());
         $message->headers->setEncoding('Q');
         if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop))) {
             $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop);
         } else {
             if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop))) {
                 $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop);
             } else {
                 $template_vars['{shop_logo}'] = '';
             }
         }
         ShopUrl::cacheMainDomainForShop((int) $id_shop);
         /* don't attach the logo as */
         if (isset($logo)) {
             $template_vars['{shop_logo}'] = $message->attach(new Swift_Message_EmbeddedFile(new Swift_File($logo), null, ImageManager::getMimeTypeByExtension($logo)));
         }
         if (Context::getContext()->link instanceof Link === false) {
             Context::getContext()->link = new Link();
         }
         $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME', null, null, $id_shop));
         $template_vars['{shop_url}'] = Context::getContext()->link->getPageLink('index', true, Context::getContext()->language->id);
         $template_vars['{my_account_url}'] = Context::getContext()->link->getPageLink('my-account', true, Context::getContext()->language->id);
         $template_vars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink('guest-tracking', true, Context::getContext()->language->id);
         $template_vars['{history_url}'] = Context::getContext()->link->getPageLink('history', true, Context::getContext()->language->id);
         $template_vars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $id_shop));
         $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $template_vars)), 'decorator');
         if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) {
             $message->attach(new Swift_Message_Part($template_txt, 'text/plain', '8bit', 'utf-8'));
         }
         if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) {
             $message->attach(new Swift_Message_Part($template_html, 'text/html', '8bit', 'utf-8'));
         }
         if ($file_attachment && !empty($file_attachment)) {
             // Multiple attachments?
             if (!is_array(current($file_attachment))) {
                 $file_attachment = array($file_attachment);
             }
             foreach ($file_attachment as $attachment) {
                 if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) {
                     $message->attach(new Swift_Message_Attachment($attachment['content'], $attachment['name'], $attachment['mime']));
                 }
             }
         }
         /* Send mail */
         $send = $swift->send($message, $to, new Swift_Address($from, $from_name));
         $swift->disconnect();
         ShopUrl::resetMainDomainCache();
         return $send;
     } catch (Swift_Exception $e) {
         return false;
     }
 }
 public function getPreviewUrl(SmartBlogPost $smart_blog_post)
 {
     $id_lang = Configuration::get('PS_LANG_DEFAULT', null, null, Context::getContext()->shop->id);
     if (!ShopUrl::getMainShopDomain()) {
         return false;
     }
     $is_rewrite_active = (bool) Configuration::get('PS_REWRITING_SETTINGS');
     $blog_url = $preview_url = smartblog::GetSmartBlogLink('smartblog_post', array('id_post' => $smart_blog_post->id, 'slug' => $smart_blog_post->link_rewrite[$id_lang]));
     if (!$smart_blog_post->active) {
         $admin_dir = dirname($_SERVER['PHP_SELF']);
         $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
         $preview_url .= (strpos($preview_url, '?') === false ? '?' : '&') . 'adtoken=' . $this->token . '&ad=' . $admin_dir . '&id_employee=' . (int) $this->context->employee->id;
     }
     return $preview_url;
 }
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Configuration::get('PS_CATALOG_MODE')) {
                 $payment_module = Module::getInstanceByName($module_name);
             } else {
                 $payment_module = new BoOrder();
             }
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $bad_delivery = false;
             if (($bad_delivery = (bool) (!Address::isCountryActiveById((int) $cart->id_address_delivery))) || !Address::isCountryActiveById((int) $cart->id_address_invoice)) {
                 if ($bad_delivery) {
                     $this->errors[] = Tools::displayError('This delivery address country is not active.');
                 } else {
                     $this->errors[] = Tools::displayError('This invoice address country is not active.');
                 }
             } else {
                 $employee = new Employee((int) Context::getContext()->cookie->id_employee);
                 $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
                 if ($payment_module->currentOrder) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } else {
         parent::postProcess();
     }
 }
Beispiel #21
0
    /**
     * return the link elements for the CMS object
     *
     * @param array  $link_sitemap contain all the links for the Google Sitemap file to be generated
     * @param string $lang         the language of link to add
     * @param int    $index        the index of the current Google Sitemap file
     * @param int    $i            the count of elements added to sitemap main array
     * @param int    $id_cms       the CMS object identifier
     *
     * @return bool
     */
    private function _getCmsLink(&$link_sitemap, $lang, &$index, &$i, $id_cms = 0)
    {
        $link = new Link();
        if (method_exists('ShopUrl', 'resetMainDomainCache')) {
            ShopUrl::resetMainDomainCache();
        }
        $cmss_id = Db::getInstance()->ExecuteS('SELECT c.`id_cms` FROM `' . _DB_PREFIX_ . 'cms` c INNER JOIN `' . _DB_PREFIX_ . 'cms_lang` cl ON c.`id_cms` = cl.`id_cms` ' . ($this->tableColumnExists(_DB_PREFIX_ . 'supplier_shop') ? 'INNER JOIN `' . _DB_PREFIX_ . 'cms_shop` cs ON c.`id_cms` = cs.`id_cms` ' : '') . 'INNER JOIN `' . _DB_PREFIX_ . 'cms_category` cc ON c.id_cms_category = cc.id_cms_category AND cc.active = 1
				WHERE c.`active` =1 AND c.`id_cms` > ' . (int) $id_cms . ($this->tableColumnExists(_DB_PREFIX_ . 'supplier_shop') ? ' AND cs.id_shop = ' . (int) $this->context->shop->id : '') . ' AND cl.`id_lang` = ' . (int) $lang['id_lang'] . ' ORDER BY c.`id_cms` ASC');
        foreach ($cmss_id as $cms_id) {
            $cms = new CMS((int) $cms_id['id_cms'], $lang['id_lang']);
            $cms->link_rewrite = urlencode(is_array($cms->link_rewrite) ? $cms->link_rewrite[(int) $lang['id_lang']] : $cms->link_rewrite);
            $url = $link->getCMSLink($cms, null, null, $lang['id_lang']);
            if (!$this->_addLinkToSitemap($link_sitemap, array('type' => 'cms', 'page' => 'cms', 'link' => $url, 'image' => false), $lang['iso_code'], $index, $i, $cms_id['id_cms'])) {
                return false;
            }
        }
        return true;
    }
 public function __construct()
 {
     $this->table = 'meta';
     $this->className = 'Meta';
     $this->bootstrap = true;
     $this->identifier_name = 'page';
     $this->ht_file = _PS_ROOT_DIR_ . '/.htaccess';
     $this->rb_file = _PS_ROOT_DIR_ . '/robots.txt';
     $this->rb_data = $this->getRobotsContent();
     $this->explicitSelect = true;
     $this->addRowAction('edit');
     $this->addRowAction('delete');
     $this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'), 'confirm' => $this->l('Delete selected items?'), 'icon' => 'icon-trash'));
     $this->fields_list = array('id_meta' => array('title' => $this->l('ID'), 'align' => 'center', 'class' => 'fixed-width-xs'), 'page' => array('title' => $this->l('Page')), 'title' => array('title' => $this->l('Page title')), 'url_rewrite' => array('title' => $this->l('Friendly URL')));
     $this->_where = ' AND a.configurable = 1';
     $this->_group = 'GROUP BY a.id_meta';
     parent::__construct();
     $this->sm_file = _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $this->context->shop->id . '_index_sitemap.xml';
     // Options to generate friendly urls
     $mod_rewrite = Tools::modRewriteActive();
     $general_fields = array('PS_REWRITING_SETTINGS' => array('title' => $this->l('Friendly URL'), 'hint' => $mod_rewrite ? $this->l('Enable this option only if your server allows URL rewriting (recommended).') : '', 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'desc' => !$mod_rewrite ? $this->l('URL rewriting (mod_rewrite) is not active on your server, or it is not possible to check your server configuration. If you want to use Friendly URLs, you must activate this mod.') : ''), 'PS_ALLOW_ACCENTED_CHARS_URL' => array('title' => $this->l('Accented URL'), 'hint' => $this->l('Enable this option if you want to allow accented characters in your friendly URLs.') . ' ' . $this->l('You should only activate this option if you are using non-latin characters ; for all the latin charsets, your SEO will be better without this option.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_CANONICAL_REDIRECT' => array('title' => $this->l('Redirect to the canonical URL'), 'validation' => 'isUnsignedInt', 'cast' => 'intval', 'type' => 'select', 'list' => array(array('value' => 0, 'name' => $this->l('No redirection (you may have duplicate content issues)')), array('value' => 1, 'name' => $this->l('302 Moved Temporarily (recommended while setting up your store)')), array('value' => 2, 'name' => $this->l('301 Moved Permanently (recommended once you have gone live)'))), 'identifier' => 'value'));
     $url_description = '';
     if (!defined('_PS_HOST_MODE_')) {
         if ($this->checkConfiguration($this->ht_file)) {
             $general_fields['PS_HTACCESS_DISABLE_MULTIVIEWS'] = array('title' => $this->l('Disable Apache\'s MultiViews option'), 'hint' => $this->l('Enable this option only if you have problems with URL rewriting.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool');
             $general_fields['PS_HTACCESS_DISABLE_MODSEC'] = array('title' => $this->l('Disable Apache\'s mod_security module'), 'hint' => $this->l('Some of PrestaShop\'s features might not work correctly with a specific configuration of Apache\'s mod_security module. We recommend to turn it off.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool');
         } else {
             $url_description = $this->l('Before you can use this tool, you need to:');
             $url_description .= $this->l('1) Create a blank .htaccess file in your root directory.');
             $url_description .= $this->l('2) Give it write permissions (CHMOD 666 on Unix system).');
         }
     }
     // Options to generate robot.txt
     $robots_description = $this->l('Your robots.txt file MUST be in your website\'s root directory and nowhere else (e.g. http://www.example.com/robots.txt).');
     if ($this->checkConfiguration($this->rb_file)) {
         $robots_description .= $this->l('Generate your "robots.txt" file by clicking on the following button (this will erase the old robots.txt file)');
         $robots_submit = array('name' => 'submitRobots', 'title' => $this->l('Generate robots.txt file'));
     } else {
         $robots_description .= $this->l('Before you can use this tool, you need to:');
         $robots_description .= $this->l('1) Create a blank robots.txt file in your root directory.');
         $robots_description .= $this->l('2) Give it write permissions (CHMOD 666 on Unix system).');
     }
     $robots_options = array('title' => $this->l('Robots file generation'), 'description' => $robots_description);
     if (isset($robots_submit)) {
         $robots_options['submit'] = $robots_submit;
     }
     if (!defined('_PS_HOST_MODE_')) {
         // Options for shop URL if multishop is disabled
         $shop_url_options = array('title' => $this->l('Set shop URL'), 'fields' => array());
         if (!Shop::isFeatureActive()) {
             $this->url = ShopUrl::getShopUrls($this->context->shop->id)->where('main', '=', 1)->getFirst();
             if ($this->url) {
                 $shop_url_options['description'] = $this->l('Here you can set the URL for your shop. If you migrate your shop to a new URL, remember to change the values below.');
                 $shop_url_options['fields'] = array('domain' => array('title' => $this->l('Shop domain'), 'validation' => 'isString', 'type' => 'text', 'defaultValue' => $this->url->domain), 'domain_ssl' => array('title' => $this->l('SSL domain'), 'validation' => 'isString', 'type' => 'text', 'defaultValue' => $this->url->domain_ssl), 'uri' => array('title' => $this->l('Base URI'), 'validation' => 'isString', 'type' => 'text', 'defaultValue' => $this->url->physical_uri));
                 $shop_url_options['submit'] = array('title' => $this->l('Save'));
             }
         } else {
             $shop_url_options['description'] = $this->l('The multistore option is enabled. If you want to change the URL of your shop, you must go to the "Multistore" page under the "Advanced Parameters" menu.');
         }
     }
     // List of options
     $this->fields_options = array('general' => array('title' => $this->l('Set up URLs'), 'description' => $url_description, 'fields' => $general_fields, 'submit' => array('title' => $this->l('Save'))));
     if (!defined('_PS_HOST_MODE_')) {
         $this->fields_options['shop_url'] = $shop_url_options;
     } else {
         $this->fields_options['manage_domain_name'] = array('title' => $this->l('Manage domain name'), 'description' => $this->l('You can search for a new domain name or add a domain name that you already own. You will be redirected to your PrestaShop.com account.'), 'buttons' => array(array('title' => $this->l('Add a domain name'), 'href' => 'https://www.prestashop.com/cloud/', 'class' => 'pull-right', 'icon' => 'process-icon-new', 'js' => 'return !window.open(this.href);')));
     }
     // Add display route options to options form
     if (Configuration::get('PS_REWRITING_SETTINGS')) {
         $this->fields_options['routes'] = array('title' => $this->l('Schema of URLs'), 'description' => $this->l('This section enables you to change the default pattern of your links. In order to use this functionality, PrestaShop\'s "Friendly URL" option must be enabled, and Apache\'s URL rewriting module (mod_rewrite) must be activated on your web server.') . '<br />' . $this->l('There are several available keywords for each route listed below; note that keywords with * are required!') . '<br />' . $this->l('To add a keyword in your URL, use the {keyword} syntax. If the keyword is not empty, you can add text before or after the keyword with syntax {prepend:keyword:append}. For example {-hey-:meta_title} will add "-hey-my-title" in the URL if the meta title is set.'), 'fields' => array(), 'submit' => array('title' => $this->l('Save')));
         $this->addAllRouteFields();
     }
     $this->fields_options['robots'] = $robots_options;
 }
Beispiel #23
0
 public static function generateHtaccess($path = null, $rewrite_settings = null, $cache_control = null, $specific = '', $disable_multiviews = null, $medias = false, $disable_modsec = null)
 {
     if (defined('PS_INSTALLATION_IN_PROGRESS') && $rewrite_settings === null) {
         return true;
     }
     // Default values for parameters
     if (is_null($path)) {
         $path = _PS_ROOT_DIR_ . '/.htaccess';
     }
     if (is_null($cache_control)) {
         $cache_control = (int) Configuration::get('PS_HTACCESS_CACHE_CONTROL');
     }
     if (is_null($disable_multiviews)) {
         $disable_multiviews = (int) Configuration::get('PS_HTACCESS_DISABLE_MULTIVIEWS');
     }
     if ($disable_modsec === null) {
         $disable_modsec = (int) Configuration::get('PS_HTACCESS_DISABLE_MODSEC');
     }
     // Check current content of .htaccess and save all code outside of prestashop comments
     $specific_before = $specific_after = '';
     if (file_exists($path)) {
         $content = file_get_contents($path);
         if (preg_match('#^(.*)\\# ~~start~~.*\\# ~~end~~[^\\n]*(.*)$#s', $content, $m)) {
             $specific_before = $m[1];
             $specific_after = $m[2];
         } else {
             // For retrocompatibility
             if (preg_match('#\\# http://www\\.prestashop\\.com - http://www\\.prestashop\\.com/forums\\s*(.*)<IfModule mod_rewrite\\.c>#si', $content, $m)) {
                 $specific_before = $m[1];
             } else {
                 $specific_before = $content;
             }
         }
     }
     // Write .htaccess data
     if (!($write_fd = @fopen($path, 'w'))) {
         return false;
     }
     if ($specific_before) {
         fwrite($write_fd, trim($specific_before) . "\n\n");
     }
     $domains = array();
     foreach (ShopUrl::getShopUrls() as $shop_url) {
         if (!isset($domains[$shop_url->domain])) {
             $domains[$shop_url->domain] = array();
         }
         $domains[$shop_url->domain][] = array('physical' => $shop_url->physical_uri, 'virtual' => $shop_url->virtual_uri, 'id_shop' => $shop_url->id_shop);
         if ($shop_url->domain == $shop_url->domain_ssl) {
             continue;
         }
         if (!isset($domains[$shop_url->domain_ssl])) {
             $domains[$shop_url->domain_ssl] = array();
         }
         $domains[$shop_url->domain_ssl][] = array('physical' => $shop_url->physical_uri, 'virtual' => $shop_url->virtual_uri, 'id_shop' => $shop_url->id_shop);
     }
     // Write data in .htaccess file
     fwrite($write_fd, "# ~~start~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again\n");
     fwrite($write_fd, "# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution\n");
     fwrite($write_fd, "# http://www.prestashop.com - http://www.prestashop.com/forums\n\n");
     if ($disable_modsec) {
         fwrite($write_fd, "<IfModule mod_security.c>\nSecFilterEngine Off\nSecFilterScanPOST Off\n</IfModule>\n\n");
     }
     // RewriteEngine
     fwrite($write_fd, "<IfModule mod_rewrite.c>\n");
     // Ensure HTTP_MOD_REWRITE variable is set in environment
     fwrite($write_fd, "<IfModule mod_env.c>\n");
     fwrite($write_fd, "SetEnv HTTP_MOD_REWRITE On\n");
     fwrite($write_fd, "</IfModule>\n\n");
     // Disable multiviews ?
     if ($disable_multiviews) {
         fwrite($write_fd, "\n# Disable Multiviews\nOptions -Multiviews\n\n");
     }
     fwrite($write_fd, "RewriteEngine on\n");
     if (!$medias && defined('_MEDIA_SERVER_1_') && defined('_MEDIA_SERVER_2_') && defined('_MEDIA_SERVER_3_')) {
         $medias = array(_MEDIA_SERVER_1_, _MEDIA_SERVER_2_, _MEDIA_SERVER_3_);
     }
     $media_domains = '';
     if ($medias[0] != '') {
         $media_domains = 'RewriteCond %{HTTP_HOST} ^' . $medias[0] . '$ [OR]' . "\n";
     }
     if ($medias[1] != '') {
         $media_domains .= 'RewriteCond %{HTTP_HOST} ^' . $medias[1] . '$ [OR]' . "\n";
     }
     if ($medias[2] != '') {
         $media_domains .= 'RewriteCond %{HTTP_HOST} ^' . $medias[2] . '$ [OR]' . "\n";
     }
     if (Configuration::get('PS_WEBSERVICE_CGI_HOST')) {
         fwrite($write_fd, "RewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule . - [E=HTTP_AUTHORIZATION:%1]\n\n");
     }
     foreach ($domains as $domain => $list_uri) {
         $physicals = array();
         foreach ($list_uri as $uri) {
             fwrite($write_fd, PHP_EOL . PHP_EOL . '#Domain: ' . $domain . PHP_EOL);
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^' . $domain . '$' . "\n");
             }
             fwrite($write_fd, 'RewriteRule . - [E=REWRITEBASE:' . $uri['physical'] . ']' . "\n");
             // Webservice
             fwrite($write_fd, 'RewriteRule ^api$ api/ [L]' . "\n\n");
             fwrite($write_fd, 'RewriteRule ^api/(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]' . "\n\n");
             if (!$rewrite_settings) {
                 $rewrite_settings = (int) Configuration::get('PS_REWRITING_SETTINGS', null, null, (int) $uri['id_shop']);
             }
             $domain_rewrite_cond = 'RewriteCond %{HTTP_HOST} ^' . $domain . '$' . "\n";
             // Rewrite virtual multishop uri
             if ($uri['virtual']) {
                 if (!$rewrite_settings) {
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^' . trim($uri['virtual'], '/') . '/?$ ' . $uri['physical'] . $uri['virtual'] . "index.php [L,R]\n");
                 } else {
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^' . trim($uri['virtual'], '/') . '$ ' . $uri['physical'] . $uri['virtual'] . " [L,R]\n");
                 }
                 fwrite($write_fd, $media_domains);
                 if (Shop::isFeatureActive()) {
                     fwrite($write_fd, $domain_rewrite_cond);
                 }
                 fwrite($write_fd, 'RewriteRule ^' . ltrim($uri['virtual'], '/') . '(.*) ' . $uri['physical'] . "\$1 [L]\n\n");
             }
             if ($rewrite_settings) {
                 // Compatibility with the old image filesystem
                 fwrite($write_fd, "# Images\n");
                 if (Configuration::get('PS_LEGACY_IMAGES')) {
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^([a-z0-9]+)\\-([a-z0-9]+)(\\-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/p/$1-$2$3$4.jpg [L]' . "\n");
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^([0-9]+)\\-([0-9]+)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/p/$1-$2$3.jpg [L]' . "\n");
                 }
                 // Rewrite product images < 100 millions
                 for ($i = 1; $i <= 8; $i++) {
                     $img_path = $img_name = '';
                     for ($j = 1; $j <= $i; $j++) {
                         $img_path .= '$' . $j . '/';
                         $img_name .= '$' . $j;
                     }
                     $img_name .= '$' . $j;
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^' . str_repeat('([0-9])', $i) . '(\\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/p/' . $img_path . $img_name . '$' . ($j + 1) . ".jpg [L]\n");
                 }
                 fwrite($write_fd, $media_domains);
                 if (Shop::isFeatureActive()) {
                     fwrite($write_fd, $domain_rewrite_cond);
                 }
                 fwrite($write_fd, 'RewriteRule ^c/([0-9]+)(\\-[\\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2$3.jpg [L]' . "\n");
                 fwrite($write_fd, $media_domains);
                 if (Shop::isFeatureActive()) {
                     fwrite($write_fd, $domain_rewrite_cond);
                 }
                 fwrite($write_fd, 'RewriteRule ^c/([a-zA-Z_-]+)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2.jpg [L]' . "\n");
             }
             fwrite($write_fd, "# AlphaImageLoader for IE and fancybox\n");
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, $domain_rewrite_cond);
             }
             fwrite($write_fd, 'RewriteRule ^images_ie/?([^/]+)\\.(jpe?g|png|gif)$ js/jquery/plugins/fancybox/images/$1.$2 [L]' . "\n");
         }
         // Redirections to dispatcher
         if ($rewrite_settings) {
             fwrite($write_fd, "\n# Dispatcher\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -s [OR]\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -l [OR]\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -d\n");
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, $domain_rewrite_cond);
             }
             fwrite($write_fd, "RewriteRule ^.*\$ - [NC,L]\n");
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, $domain_rewrite_cond);
             }
             fwrite($write_fd, "RewriteRule ^.*\$ %{ENV:REWRITEBASE}index.php [NC,L]\n");
         }
     }
     fwrite($write_fd, "</IfModule>\n\n");
     fwrite($write_fd, "AddType application/vnd.ms-fontobject .eot\n");
     fwrite($write_fd, "AddType font/ttf .ttf\n");
     fwrite($write_fd, "AddType font/otf .otf\n");
     fwrite($write_fd, "AddType application/x-font-woff .woff\n");
     fwrite($write_fd, "<IfModule mod_headers.c>\r\n\t<FilesMatch \"\\.(ttf|ttc|otf|eot|woff|svg)\$\">\r\n\t\tHeader add Access-Control-Allow-Origin \"*\"\r\n\t</FilesMatch>\r\n</IfModule>\n\n");
     // Cache control
     if ($cache_control) {
         $cache_control = "<IfModule mod_expires.c>\r\n\tExpiresActive On\r\n\tExpiresByType image/gif \"access plus 1 month\"\r\n\tExpiresByType image/jpeg \"access plus 1 month\"\r\n\tExpiresByType image/png \"access plus 1 month\"\r\n\tExpiresByType text/css \"access plus 1 week\"\r\n\tExpiresByType text/javascript \"access plus 1 week\"\r\n\tExpiresByType application/javascript \"access plus 1 week\"\r\n\tExpiresByType application/x-javascript \"access plus 1 week\"\r\n\tExpiresByType image/x-icon \"access plus 1 year\"\r\n\tExpiresByType image/svg+xml \"access plus 1 year\"\r\n\tExpiresByType image/vnd.microsoft.icon \"access plus 1 year\"\r\n\tExpiresByType application/font-woff \"access plus 1 year\"\r\n\tExpiresByType application/x-font-woff \"access plus 1 year\"\r\n\tExpiresByType application/vnd.ms-fontobject \"access plus 1 year\"\r\n\tExpiresByType font/opentype \"access plus 1 year\"\r\n\tExpiresByType font/ttf \"access plus 1 year\"\r\n\tExpiresByType font/otf \"access plus 1 year\"\r\n\tExpiresByType application/x-font-ttf \"access plus 1 year\"\r\n\tExpiresByType application/x-font-otf \"access plus 1 year\"\r\n</IfModule>\r\n\r\n<IfModule mod_headers.c>\r\n\tHeader unset Etag\r\n</IfModule>\r\nFileETag none\r\n<IfModule mod_deflate.c>\r\n\t<IfModule mod_filter.c>\r\n\t\tAddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/x-javascript font/ttf application/x-font-ttf font/otf application/x-font-otf font/opentype\r\n\t</IfModule>\r\n</IfModule>\n\n";
         fwrite($write_fd, $cache_control);
     }
     // In case the user hasn't rewrite mod enabled
     fwrite($write_fd, "#If rewrite mod isn't enabled\n");
     // Do not remove ($domains is already iterated upper)
     reset($domains);
     $domain = current($domains);
     fwrite($write_fd, 'ErrorDocument 404 ' . $domain[0]['physical'] . "index.php?controller=404\n\n");
     fwrite($write_fd, "# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again");
     if ($specific_after) {
         fwrite($write_fd, "\n\n" . trim($specific_after));
     }
     fclose($write_fd);
     if (!defined('PS_INSTALLATION_IN_PROGRESS')) {
         Hook::exec('actionHtaccessCreate');
     }
     return true;
 }
Beispiel #24
0
    public function sendEmail($order, $template_vars = false)
    {
        $result = Db::getInstance()->getRow('
			SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
			FROM `' . _DB_PREFIX_ . 'order_history` oh
				LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON oh.`id_order` = o.`id_order`
				LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON o.`id_customer` = c.`id_customer`
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON oh.`id_order_state` = os.`id_order_state`
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
			WHERE oh.`id_order_history` = ' . (int) $this->id . ' AND os.`send_email` = 1');
        if (isset($result['template']) && Validate::isEmail($result['email'])) {
            ShopUrl::cacheMainDomainForShop($order->id_shop);
            $topic = $result['osname'];
            $data = array('{lastname}' => $result['lastname'], '{firstname}' => $result['firstname'], '{id_order}' => (int) $this->id_order, '{order_name}' => $order->getUniqReference());
            if ($result['module_name']) {
                $module = Module::getInstanceByName($result['module_name']);
                if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
                    $data = array_merge($data, $module->extra_mail_vars);
                }
            }
            if ($template_vars) {
                $data = array_merge($data, $template_vars);
            }
            $data['{total_paid}'] = Tools::displayPrice((double) $order->total_paid, new Currency((int) $order->id_currency), false);
            if (Validate::isLoadedObject($order)) {
                // Attach invoice and / or delivery-slip if they exists and status is set to attach them
                if ($result['pdf_invoice'] || $result['pdf_delivery']) {
                    $context = Context::getContext();
                    $invoice = $order->getInvoicesCollection();
                    $file_attachement = array();
                    if ($result['pdf_invoice'] && (int) Configuration::get('PS_INVOICE') && $order->invoice_number) {
                        Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
                        $pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
                        $file_attachement['invoice']['content'] = $pdf->render(false);
                        $file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                        $file_attachement['invoice']['mime'] = 'application/pdf';
                    }
                    if ($result['pdf_delivery'] && $order->delivery_number) {
                        $pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
                        $file_attachement['delivery']['content'] = $pdf->render(false);
                        $file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop) . sprintf('%06d', $order->delivery_number) . '.pdf';
                        $file_attachement['delivery']['mime'] = 'application/pdf';
                    }
                } else {
                    $file_attachement = null;
                }
                if (!Mail::Send((int) $order->id_lang, $result['template'], $topic, $data, $result['email'], $result['firstname'] . ' ' . $result['lastname'], null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop)) {
                    return false;
                }
            }
            ShopUrl::resetMainDomainCache();
        }
        return true;
    }
Beispiel #25
0
 public static function generateHtaccess($path = null, $rewrite_settings = null, $cache_control = null, $specific = '', $disable_multiviews = null, $medias = false, $disable_modsec = null)
 {
     if (defined('PS_INSTALLATION_IN_PROGRESS') && $rewrite_settings === null) {
         return true;
     }
     // Default values for parameters
     if (is_null($path)) {
         $path = _PS_ROOT_DIR_ . '/.htaccess';
     }
     if (is_null($cache_control)) {
         $cache_control = (int) Configuration::get('PS_HTACCESS_CACHE_CONTROL');
     }
     if (is_null($disable_multiviews)) {
         $disable_multiviews = (int) Configuration::get('PS_HTACCESS_DISABLE_MULTIVIEWS');
     }
     if ($disable_modsec === null) {
         $disable_modsec = (int) Configuration::get('PS_HTACCESS_DISABLE_MODSEC');
     }
     // Check current content of .htaccess and save all code outside of prestashop comments
     $specific_before = $specific_after = '';
     if (file_exists($path)) {
         $content = file_get_contents($path);
         if (preg_match('#^(.*)\\# ~~start~~.*\\# ~~end~~[^\\n]*(.*)$#s', $content, $m)) {
             $specific_before = $m[1];
             $specific_after = $m[2];
         } else {
             // For retrocompatibility
             if (preg_match('#\\# http://www\\.prestashop\\.com - http://www\\.prestashop\\.com/forums\\s*(.*)<IfModule mod_rewrite\\.c>#si', $content, $m)) {
                 $specific_before = $m[1];
             } else {
                 $specific_before = $content;
             }
         }
     }
     // Write .htaccess data
     if (!($write_fd = fopen($path, 'w'))) {
         return false;
     }
     if ($specific_before) {
         fwrite($write_fd, trim($specific_before) . "\n\n");
     }
     $domains = array();
     foreach (ShopUrl::getShopUrls() as $shop_url) {
         if (!isset($domains[$shop_url->domain])) {
             $domains[$shop_url->domain] = array();
         }
         $domains[$shop_url->domain][] = array('physical' => $shop_url->physical_uri, 'virtual' => $shop_url->virtual_uri, 'id_shop' => $shop_url->id_shop);
         if ($shop_url->domain == $shop_url->domain_ssl) {
             continue;
         }
         if (!isset($domains[$shop_url->domain_ssl])) {
             $domains[$shop_url->domain_ssl] = array();
         }
         $domains[$shop_url->domain_ssl][] = array('physical' => $shop_url->physical_uri, 'virtual' => $shop_url->virtual_uri, 'id_shop' => $shop_url->id_shop);
     }
     // Write data in .htaccess file
     fwrite($write_fd, "# ~~start~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again\n");
     fwrite($write_fd, "# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution\n");
     fwrite($write_fd, "# http://www.prestashop.com - http://www.prestashop.com/forums\n\n");
     if ($disable_modsec) {
         fwrite($write_fd, "<IfModule mod_security.c>\nSecFilterEngine Off\nSecFilterScanPOST Off\n</IfModule>\n\n");
     }
     fwrite($write_fd, "<IfModule mod_headers.c>\n");
     fwrite($write_fd, "Header set Access-Control-Allow-Origin: *\n");
     fwrite($write_fd, 'Header set Access-Control-Allow-Headers: "cache-control"' . "\n");
     fwrite($write_fd, "</IfModule>\n");
     // RewriteEngine
     fwrite($write_fd, "<IfModule mod_rewrite.c>\n");
     // Ensure HTTP_MOD_REWRITE variable is set in environment
     fwrite($write_fd, "<IfModule mod_env.c>\n");
     fwrite($write_fd, "SetEnv HTTP_MOD_REWRITE On\n");
     fwrite($write_fd, "</IfModule>\n\n");
     // Disable multiviews ?
     if ($disable_multiviews) {
         fwrite($write_fd, "\n# Disable Multiviews\nOptions -Multiviews\n\n");
     }
     fwrite($write_fd, "RewriteEngine on\n\n");
     fwrite($write_fd, "RewriteCond %{REQUEST_URI} ^/komplekty\$\n");
     fwrite($write_fd, "RewriteRule ^.*\$ http://decor.etagerca.ru/complects/ [R=301,L]\n\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans\$ /style/klassicheskaja-mebel-provans [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/divany\$ /style/dizajnerskaja-mebel/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/komody\$ /style/dizajnerskaja-mebel/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/kresla\$ /style/dizajnerskaja-mebel/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/krovati\$ /style/dizajnerskaja-mebel/krovati [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/konsoli\$ /style/dizajnerskaja-mebel/konsoli [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/stoly\$ /style/dizajnerskaja-mebel/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/pufi\$ /style/dizajnerskaja-mebel/pufi [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/shkafy\$ /style/dizajnerskaja-mebel/shkafy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^dizajnerskaja-mebel/stulya\$ /style/dizajnerskaja-mebel/stulya [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/bufety\$ /style/klassicheskaja-mebel-provans/bufety [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/divany\$ /style/klassicheskaja-mebel-provans/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/komody\$ /style/klassicheskaja-mebel-provans/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/konsoli\$ /style/klassicheskaja-mebel-provans/konsoli [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/kresla\$ /style/klassicheskaja-mebel-provans/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/krovati\$ /style/klassicheskaja-mebel-provans/krovati [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/obedennye-stoly\$ /style/klassicheskaja-mebel-provans/obedennye-stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/shkafy\$ /style/klassicheskaja-mebel-provans/shkafy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/stoly\$ /style/klassicheskaja-mebel-provans/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/stulya\$ /style/klassicheskaja-mebel-provans/stulya [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/tumbochki\$ /style/klassicheskaja-mebel-provans/tumbochki [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^klassicheskaja-mebel-provans/gazetnicy\$ /style/klassicheskaja-mebel-provans/gazetnicy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-v-stile-loft/divany\$ /style/mebel-v-stile-loft/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-v-stile-loft/stoly\$ /style/mebel-v-stile-loft/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-v-stile-shebbi-shik\$ /style/mebel-v-stile-shebbi-shik [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-v-stile-kantry\$ /style/mebel-v-stile-kantry [R=301,L]\n\n");
     fwrite($write_fd, "RewriteRule ^kozhanaja-mebel/komody\$ /material/kozhanaja-mebel/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^kozhanaja-mebel/kresla\$ /material/kozhanaja-mebel/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^kozhanaja-mebel/divany\$ /material/kozhanaja-mebel/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/divany\$ /material/mebel-iz-massiva/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/komody\$ /material/mebel-iz-massiva/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/kresla\$ /material/mebel-iz-massiva/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/pismennye-stoly\$ /material/mebel-iz-massiva/pismennye-stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/stoly\$ /material/mebel-iz-massiva/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/stulya\$ /material/mebel-iz-massiva/stulya [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-iz-massiva/obedennye-gruppy\$ /material/mebel-iz-massiva/obedennye-gruppy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^myagkaja-mebel/kresla\$ /material/myagkaja-mebel/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^myagkaja-mebel/divany\$ /material/myagkaja-mebel/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^wrought-iron-furniture\$ /material/wrought-iron-furniture [R=301,L]\n\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/divany\$ /type/mebel-dlja-gostinoj/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/komody\$ /type/mebel-dlja-gostinoj/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/kresla\$ /type/mebel-dlja-gostinoj/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/stellazhi\$ /type/mebel-dlja-gostinoj/stellazhi [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/stoly\$ /type/mebel-dlja-gostinoj/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/stulya\$ /type/mebel-dlja-gostinoj/stulya [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-gostinoj/shkafy\$ /type/mebel-dlja-gostinoj/shkafy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/divany\$ /type/mebel-dlja-kabineta/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/kresla\$ /type/mebel-dlja-kabineta/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/shkafy\$ /type/mebel-dlja-kabineta/shkafy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/stoly\$ /type/mebel-dlja-kabineta/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/stulya\$ /type/mebel-dlja-kabineta/stulya [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/komody\$ /type/mebel-dlja-kabineta/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-kabineta/stellazhi\$ /type/mebel-dlja-kabineta/stellazhi [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/divany\$ /type/mebel-dlja-spalny/divany [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/komody\$ /type/mebel-dlja-spalny/komody [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/kresla\$ /type/mebel-dlja-spalny/kresla [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/krovati\$ /type/mebel-dlja-spalny/krovati [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/prikrovatnye-stoliky\$ /type/mebel-dlja-spalny/prikrovatnye-stoliky [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/shkafy\$ /type/mebel-dlja-spalny/shkafy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/stulya\$ /type/mebel-dlja-spalny/stulya [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-spalny/stoly\$ /type/mebel-dlja-spalny/stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-stolovoj/bufety\$ /type/mebel-dlja-stolovoj/bufety [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-stolovoj/obedennye-gruppy\$ /type/mebel-dlja-stolovoj/obedennye-gruppy [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-stolovoj/obedennye-stoly\$ /type/mebel-dlja-stolovoj/obedennye-stoly [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-stolovoj/stellazhi\$ /type/mebel-dlja-stolovoj/stellazhi [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^mebel-dlja-stolovoj/stulya\$ /type/mebel-dlja-stolovoj/stulya [R=301,L]\n\n");
     fwrite($write_fd, "RewriteRule ^leontina\$ /collections/leontina [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^olivia\$ /collections/olivia [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^bruni\$ /collections/bruni [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^aquarelle\$ /collections/aquarelle [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^gouache\$ /collections/gouache [R=301,L]\n");
     fwrite($write_fd, "RewriteRule ^emerson\$ /collections/emerson [R=301,L]\n\n");
     if (!$medias && defined('_MEDIA_SERVER_1_') && defined('_MEDIA_SERVER_2_') && defined('_MEDIA_SERVER_3_')) {
         $medias = array(_MEDIA_SERVER_1_, _MEDIA_SERVER_2_, _MEDIA_SERVER_3_);
     }
     $media_domains = '';
     if ($medias[0] != '') {
         $media_domains = 'RewriteCond %{HTTP_HOST} ^' . $medias[0] . '$ [OR]' . "\n";
     }
     if ($medias[1] != '') {
         $media_domains .= 'RewriteCond %{HTTP_HOST} ^' . $medias[1] . '$ [OR]' . "\n";
     }
     if ($medias[2] != '') {
         $media_domains .= 'RewriteCond %{HTTP_HOST} ^' . $medias[2] . '$ [OR]' . "\n";
     }
     if (Configuration::get('PS_WEBSERVICE_CGI_HOST')) {
         fwrite($write_fd, "RewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule . - [E=HTTP_AUTHORIZATION:%1]\n\n");
     }
     foreach ($domains as $domain => $list_uri) {
         $physicals = array();
         foreach ($list_uri as $uri) {
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^' . $domain . '$' . "\n");
             }
             fwrite($write_fd, 'RewriteRule . - [E=REWRITEBASE:' . $uri['physical'] . ']' . "\n");
             // Webservice
             fwrite($write_fd, 'RewriteRule ^api/?(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]' . "\n\n");
             if (!$rewrite_settings) {
                 $rewrite_settings = (int) Configuration::get('PS_REWRITING_SETTINGS', null, null, (int) $uri['id_shop']);
             }
             $domain_rewrite_cond = 'RewriteCond %{HTTP_HOST} ^' . $domain . '$' . "\n";
             // Rewrite virtual multishop uri
             if ($uri['virtual']) {
                 if (!$rewrite_settings) {
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^' . trim($uri['virtual'], '/') . '/?$ ' . $uri['physical'] . $uri['virtual'] . "index.php [L,R]\n");
                 } else {
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^' . trim($uri['virtual'], '/') . '$ ' . $uri['physical'] . $uri['virtual'] . " [L,R]\n");
                 }
                 fwrite($write_fd, $media_domains);
                 if (Shop::isFeatureActive()) {
                     fwrite($write_fd, $domain_rewrite_cond);
                 }
                 fwrite($write_fd, 'RewriteRule ^' . ltrim($uri['virtual'], '/') . '(.*) ' . $uri['physical'] . "\$1 [L]\n\n");
             }
             if ($rewrite_settings) {
                 fwrite($write_fd, "##редиректы со старого сайта start\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.rudecoration$ http://decor.etagerca.ru [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruaccessories$ http://decor.etagerca.ru/-accessories [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^15-kozhanaja-mebel$ http://etagerca.ru/kozhanaja-mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^30-boxes-and-boxes$ http://decor.etagerca.ru/boxes-and-boxes [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^vases$ http://decor.etagerca.ru/vases [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^frames-for-photos$ http://decor.etagerca.ru/frames-for-photos [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^boxes-and-boxes$ http://decor.etagerca.ru/boxes-and-boxes [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^candles-and-candlesticks$ http://decor.etagerca.ru/candles-and-candlesticks [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^watch$ http://decor.etagerca.ru/watch [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^ornamental-flowerpot$ http://decor.etagerca.ru/ornamental-flowerpot [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^accessories$ http://decor.etagerca.ru/-accessories [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^flowers$ http://decor.etagerca.ru/flowers [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^-korzini-$ http://decor.etagerca.ru/-korzini- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^-shkatulki-$ http://decor.etagerca.ru/-shkatulki- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^-prinadlejnosti-dlia-vanna-$ http://decor.etagerca.ru/-prinadlejnosti-dlia-vanna- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^-dekor-na-stenu-$ http://decor.etagerca.ru/-dekor-na-stenu- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteRule ^dekorativnye-svechi$ http://decor.etagerca.ru/dekorativnye-svechi [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^new/$ http://etagerca.ru/content/-novosti- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^27-vases$ http://decor.etagerca.ru/vases [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^11-mirrors$ http://etagerca.ru/mirrors [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^13--gift-ideas$ http://etagerca.ru/gift-ideas [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^16--wrought-iron-furniture$ http://etagerca.ru/wrought-iron-furniture [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^45-other$ http://etagerca.ru/other [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^48--accessories-$ http://etagerca.ru/gift-ideas [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^70-zonty$ http://etagerca.ru/gift-ideas [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^69--korzini$ http://decor.etagerca.ru/-korzini- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru27-vases$ http://decor.etagerca.ru/vases [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru33-watch$ http://decor.etagerca.ru/watch [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru71-letnyaya-obuv$ http://decor.etagerca.ru/-dekor-na-stenu- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru70-zonty$  http://decor.etagerca.ru/-shkatulki- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru28--frames-for-photos  http://decor.etagerca.ru/frames-for-photos [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru31--candles-and-candlesticks  http://decor.etagerca.ru/candles-and-candlesticks [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru30--panel-  http://decor.etagerca.ru/boxes-and-boxes [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru35-ornamental-flowerpot  http://decor.etagerca.ru/ornamental-flowerpot [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruboxes-and-boxes http://decor.etagerca.ru/dekorativnoe-nastennoe-panno [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.rucandles-and-candlesticks http://decor.etagerca.ru/podsvechniki [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruflowers http://decor.etagerca.ru/iskusstvennye-cvety [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruornamental-flowerpot http://decor.etagerca.ru/kashpo-dlja-cvetov [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru-shkatulki- http://decor.etagerca.ru/sunduki-i-shkatulki [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruvases http://decor.etagerca.ru/vazy-dlja-cvetov [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruwatch http://decor.etagerca.ru/originalnye-nastennye-chasy [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.rucart.php  /cart.php [QSA,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru[a-zA-Z0-9-]*/([0-9]+)\\-[a-zA-Z0-9-]*(\\.html)? /product.php?id_product=$1 [QSA,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ruindex.php  /category.php?id_category=decoration&noredirect=1 [QSA,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru([a-zA-Z0-9-]+)$ /category.php?id_category=$1&noredirect=1 [QSA,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru([0-9]+)\\-[a-zA-Z0-9-]*\\.html /product.php?id_product=$1 [QSA,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^decor\\.etagerca.ru[a-zA-Z0-9-]*/([0-9]+)\\-[a-zA-Z0-9-]*\\.html /product.php?id_product=$1 [QSA,L]' . "\n");
                 // fwrite($write_fd, 'RewriteRule ^63--dizainerskie-komody-$ http://etagerca.ru/dizajnerskie-komody [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^63--dizainerskie-komody-\$ http://etagerca.ru/dizajnerskaja-mebel/komody [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^53--kojanie-komodi-$ http://etagerca.ru/kozhanye-komody [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^53--kojanie-komodi-\$ http://etagerca.ru/kozhanaja-mebel/komody [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^52--kojanie-divani-$ http://etagerca.ru/kozhanye-divany [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^52--kojanie-divani-\$ http://etagerca.ru/kozhanaja-mebel/divany [R=301,L]" . "\n");
                 // fwrite($write_fd, 'RewriteRule ^55--klassicheskie-komody-$ http://etagerca.ru/komody [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^55--klassicheskie-komody-\$ http://etagerca.ru/mebel/komody [R=301,L]" . "\n");
                 // fwrite($write_fd, 'RewriteRule ^57--klassicheskie-stoly-$ http://etagerca.ru/stoly [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^57--klassicheskie-stoly-\$ http://etagerca.ru/mebel/stoly [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^58--klassicheskie-shkafy-$ http://etagerca.ru/shkafy [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^58--klassicheskie-shkafy-\$ http://etagerca.ru/mebel/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteRule ^60--mebel-provans-$ http://etagerca.ru/provans-mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^prices-drop$ http://etagerca.ru/skidki [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^7-furniture$ http://etagerca.ru/mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^15--leather-furniture$ http://etagerca.ru/kozhanaja-mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^18--furniture-provence-$ http://etagerca.ru/klassicheskaja-mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^50--soft-furniture-$ http://etagerca.ru/dizajnerskaja-mebel [R=301,L]' . "\n");
                 // fwrite($write_fd, 'RewriteRule ^61--klassicheskie-gazetnicy-$ http://etagerca.ru/klassicheskie-gazetnicy [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^61--klassicheskie-gazetnicy-\$ http://etagerca.ru/mebel/gazetnicy [R=301,L]" . "\n");
                 //  fwrite($write_fd, 'RewriteRule ^klassicheskie-gazetnicy$ http://etagerca.ru/gazetnicy [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-gazetnicy\$ http://etagerca.ru/mebel/gazetnicy [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteRule ^klassicheskaja-mebel$ http://etagerca.ru/klassicheskaja-mebel-provans [R=301,L]' . "\n");
                 // fwrite($write_fd, 'RewriteRule ^provans-mebel$ http://etagerca.ru/klassicheskaja-mebel-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^provans-mebel\$ http://etagerca.ru/klassicheskaja-mebel-provans [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteRule ^klassicheskaja-mebel/(.*)$ http://etagerca.ru/klassicheskaja-mebel-provans/$1 [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, "RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1037\\ HTTP/" . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1037--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteCond %{HTTP_HOST} ^etagerca.ru" . "\n");
                 fwrite($write_fd, "RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1042\\ HTTP/" . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1042--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteCond %{HTTP_HOST} ^etagerca.ru" . "\n");
                 fwrite($write_fd, "RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1044\\ HTTP/" . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1044--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteCond %{HTTP_HOST} ^etagerca.ru" . "\n");
                 fwrite($write_fd, "RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1035\\ HTTP/" . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1035--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteCond %{HTTP_HOST} ^etagerca.ru" . "\n");
                 fwrite($write_fd, "RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1043\\ HTTP/" . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1043--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1032\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1032--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteCond %{HTTP_HOST} ^etagerca.ru" . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1038\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1038--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1041\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1041--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteCond %{HTTP_HOST} ^etagerca.ru" . "\n");
                 fwrite($write_fd, "RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1039\\ HTTP/" . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/1039--.html? [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^stoly-dlya-stolovoj$ http://etagerca.ru/obedennye-stoly [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^stoly-dlya-stolovoj\$ http://etagerca.ru/mebel-dlja-stolovoj/stoly [R=301,L]" . "\n");
                 //  fwrite($write_fd, 'RewriteRule ^klassicheskie-komody$ http://etagerca.ru/klassicheskie-komody-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-komody\$ http://etagerca.ru/klassicheskaja-mebel-provans/komody [R=301,L]" . "\n");
                 //  fwrite($write_fd, 'RewriteRule ^klasicheskie-konsoli$ http://etagerca.ru/klasicheskie-konsoli-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klasicheskie-konsoli\$ http://etagerca.ru/klassicheskaja-mebel-provans/konsoli [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^klassicheskie-stoly$ http://etagerca.ru/klassicheskie-stoly-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-stoly\$ http://etagerca.ru/klassicheskaja-mebel-provans/stoly [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^klassicheskie-shkafy$ http://etagerca.ru/klassicheskie-shkafy-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-shkafy\$ http://etagerca.ru/klassicheskaja-mebel-provans/shkafy [R=301,L]" . "\n");
                 // fwrite($write_fd, 'RewriteRule ^klassicheskie-stulya$ http://etagerca.ru/klassicheskie-stulya-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-stulya\$ http://etagerca.ru/klassicheskaja-mebel-provans/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteRule ^klassicheskie-gazetnicy$ http://etagerca.ru/klassicheskie-gazetnicy-provans [R=301,L]' . "\n");
                 // fwrite($write_fd, 'RewriteRule ^klassicheskie-divany$ http://etagerca.ru/klassicheskie-divany-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-divany\$ http://etagerca.ru/klassicheskaja-mebel-provans/divany [R=301,L]" . "\n");
                 //fwrite($write_fd, 'RewriteRule ^klassicheskie-kresla$ http://etagerca.ru/klassicheskie-kresla-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-kresla\$ http://etagerca.ru/klassicheskaja-mebel-provans/kresla [R=301,L]" . "\n");
                 // fwrite($write_fd, 'RewriteRule ^klassicheskie-krovati$ http://etagerca.ru/klassicheskie-krovati-provans [R=301,L]'."\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-krovati\$ http://etagerca.ru/klassicheskaja-mebel-provans/krovati [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteRule ^content/-$ http://etagerca.ru/content/-programma-loyalnosti- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^klassicheskie-stulya/(.*)\\.html http://etagerca.ru/klassicheskie-stulya-provans/$1.html [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1128\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/mebel/1128--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=653\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/klassicheskie-stulya/653--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1047\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$  http://etagerca.ru/1047--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1046\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/1046--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1021\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/mebel/1021--candy.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1117\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/1117--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1103\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$  http://etagerca.ru/1103--.html? [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1112\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/1112--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1076\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/1076--portobello-brun.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1102\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/1102--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=87\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/cups-kettles-jars/87--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=715\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/light/715--aurore-.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=90\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/cups-kettles-jars/90--plume.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /product\\.php\\?id_product=1107\\ HTTP/' . "\n");
                 fwrite($write_fd, 'RewriteRule ^(.*)$  http://etagerca.ru/1107--.html? [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^-leather-furniture/138--\\.html http://etagerca.ru/kozhanaja-mebel/138--.html [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^kresla/652--.html http://etagerca.ru/klassicheskie-kresla-provans/652--.html [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^44-glass http://etagerca.ru/glass [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^46-dishes-and-plates- http://etagerca.ru/dishes-and-plates- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^7-mebel http://etagerca.ru/mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^content/5--novosti- http://etagerca.ru/content/-novosti- [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /prices-drop\\.php\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/skidki? [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^etagerca.ru' . "\n");
                 fwrite($write_fd, 'RewriteCond %{THE_REQUEST} GET\\ /best-sales\\.php\\ HTTP/' . "\n");
                 fwrite($write_fd, "RewriteRule ^(.*)\$ http://etagerca.ru/best-sales? [R=301,L]" . "\n");
                 fwrite($write_fd, 'RewriteRule ^home$ http://etagerca.ru/mebel [R=301,L]' . "\n");
                 fwrite($write_fd, 'RewriteRule ^content/contacts$ http://etagerca.ru/content/Contacts [R=301,L]' . "\n");
                 fwrite($write_fd, "##редиректы со старого сайта end\n\n");
                 fwrite($write_fd, "##редиректы после изменения формирования url start\n");
                 fwrite($write_fd, "RewriteRule ^-dizainerskie-divany-\$ http://etagerca.ru/dizajnerskaja-mebel/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizajnerskie-komody\$ http://etagerca.ru/dizajnerskaja-mebel/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizajnerskie-kresla\$ http://etagerca.ru/dizajnerskaja-mebel/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizajnerskie-krovati\$ http://etagerca.ru/dizajnerskaja-mebel/krovati [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizainerskie-konsoli\$ http://etagerca.ru/dizajnerskaja-mebel/konsoli [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizainerskie-stoly\$ http://etagerca.ru/dizajnerskaja-mebel/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizajnerskie-pufi\$ http://etagerca.ru/dizajnerskaja-mebel/pufi [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizajnerskie-shkafy\$ http://etagerca.ru/dizajnerskaja-mebel/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dizajnerskie-stulja\$ http://etagerca.ru/dizajnerskaja-mebel/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^bufety-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/bufety [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-divany-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-komody-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klasicheskie-konsoli-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/konsoli [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-kresla-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-krovati-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/krovati [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^obedennye-stoly-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/obedennye-stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-shkafy-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-stoly-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-stulya-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^tumbochki-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/tumbochki [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^klassicheskie-gazetnicy-provans\$ http://etagerca.ru/klassicheskaja-mebel-provans/gazetnicy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kozhanye-komody\$ http://etagerca.ru/kozhanaja-mebel/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kojanie-kresla\$ http://etagerca.ru/kozhanaja-mebel/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kozhanye-divany\$ http://etagerca.ru/kozhanaja-mebel/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^divany\$ http://etagerca.ru/mebel/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^gazetnicy\$ http://etagerca.ru/mebel/gazetnicy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^komody\$ http://etagerca.ru/mebel/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kresla\$ http://etagerca.ru/mebel/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^krovati\$ http://etagerca.ru/mebel/krovati [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^pufi\$ http://etagerca.ru/mebel/pufi [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stelajy\$ http://etagerca.ru/mebel/stellazhi [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^prikrovatnye-tumbochki\$ http://etagerca.ru/mebel/tumbochki [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^bufety\$ http://etagerca.ru/mebel/bufety [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stoly\$ http://etagerca.ru/mebel/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stulya\$ http://etagerca.ru/mebel/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^shkafy\$ http://etagerca.ru/mebel/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^konsoly\$ http://etagerca.ru/mebel/konsoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^divany-dlja-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^komody-dlja-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kresla-dlja-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stellazhi-dlja-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/stellazhi [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stoly-dlya-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stulja-dlja-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^shkafy-dlja-gostinoj\$ http://etagerca.ru/mebel-dlja-gostinoj/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^divany-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kresla-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^shkafy-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stoly-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stulia-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^komody-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stellaji-dlja-kabineta\$ http://etagerca.ru/mebel-dlja-kabineta/stellazhi [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^divany-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^komody-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kresla-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^krovaty-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/krovati [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^prikrovatnye-stoliky-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/prikrovatnye-stoliky [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^shkafy-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/shkafy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stulja-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stoly-dlja-spalny\$ http://etagerca.ru/mebel-dlja-spalny/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^bufety-dlja-stolovoj\$ http://etagerca.ru/mebel-dlja-stolovoj/bufety [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^obedennye-gruppy\$ http://etagerca.ru/mebel-dlja-stolovoj/obedennye-gruppy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^obedennye-stoly\$ http://etagerca.ru/mebel-dlja-stolovoj/obedennye-stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stellazhi-dlja-stolovoj\$ http://etagerca.ru/mebel-dlja-stolovoj/stellazhi [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stulja-dlja-stolovoj\$ http://etagerca.ru/mebel-dlja-stolovoj/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^divany-iz-massiva\$ http://etagerca.ru/mebel-iz-massiva/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^komody-iz-massiva\$ http://etagerca.ru/mebel-iz-massiva/komody [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^kresla-iz-massiva\$ http://etagerca.ru/mebel-iz-massiva/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^pismennye-stoly-iz-massiva\$ http://etagerca.ru/mebel-iz-massiva/pismennye-stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stoly-iz-massiva\$ http://etagerca.ru/mebel-iz-massiva/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stulja-iz-massiva-dereva\$ http://etagerca.ru/mebel-iz-massiva/stulya [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^obedennye-gruppy-iz-massiva\$ http://etagerca.ru/mebel-iz-massiva/obedennye-gruppy [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^divany-v-stile-loft\$ http://etagerca.ru/mebel-v-stile-loft/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^stoly-v-stile-loft\$ http://etagerca.ru/mebel-v-stile-loft/stoly [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^mjagkie-kresla\$ http://etagerca.ru/myagkaja-mebel/kresla [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^mjagkie-divany\$ http://etagerca.ru/myagkaja-mebel/divany [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^tablecloths\$ http://etagerca.ru/textile/tablecloths [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^pillows\$ http://etagerca.ru/textile/pillows [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^salfetki\$ http://etagerca.ru/textile/salfetki [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^glass\$ http://etagerca.ru/dishes/glass [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^other\$ http://etagerca.ru/dishes/other [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^dishes-and-plates-\$ http://etagerca.ru/dishes/dishes-and-plates [R=301,L]" . "\n");
                 fwrite($write_fd, "RewriteRule ^cups-kettles-jars\$ http://etagerca.ru/dishes/cups-kettles-jars [R=301,L]" . "\n");
                 fwrite($write_fd, "##редиректы после изменения формирования url end\n");
                 // Compatibility with the old image filesystem
                 fwrite($write_fd, "# Images\n");
                 if (Configuration::get('PS_LEGACY_IMAGES')) {
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^([a-z0-9]+)\\-([a-z0-9]+)(\\-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/p/$1-$2$3$4.jpg [L]' . "\n");
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^([0-9]+)\\-([0-9]+)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/p/$1-$2$3.jpg [L]' . "\n");
                 }
                 // Rewrite product images < 100 millions
                 for ($i = 1; $i <= 8; $i++) {
                     $img_path = $img_name = '';
                     for ($j = 1; $j <= $i; $j++) {
                         $img_path .= '$' . $j . '/';
                         $img_name .= '$' . $j;
                     }
                     $img_name .= '$' . $j;
                     fwrite($write_fd, $media_domains);
                     if (Shop::isFeatureActive()) {
                         fwrite($write_fd, $domain_rewrite_cond);
                     }
                     fwrite($write_fd, 'RewriteRule ^' . str_repeat('([0-9])', $i) . '(\\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/p/' . $img_path . $img_name . '$' . ($j + 1) . ".jpg [L]\n");
                 }
                 fwrite($write_fd, $media_domains);
                 if (Shop::isFeatureActive()) {
                     fwrite($write_fd, $domain_rewrite_cond);
                 }
                 fwrite($write_fd, 'RewriteRule ^c/([0-9]+)(\\-[\\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2$3.jpg [L]' . "\n");
                 fwrite($write_fd, $media_domains);
                 if (Shop::isFeatureActive()) {
                     fwrite($write_fd, $domain_rewrite_cond);
                 }
                 fwrite($write_fd, 'RewriteRule ^c/([a-zA-Z_-]+)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2.jpg [L]' . "\n");
             }
             fwrite($write_fd, "# AlphaImageLoader for IE and fancybox\n");
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, $domain_rewrite_cond);
             }
             fwrite($write_fd, 'RewriteRule ^images_ie/?([^/]+)\\.(jpe?g|png|gif)$ js/jquery/plugins/fancybox/images/$1.$2 [L]' . "\n");
         }
         // Redirections to dispatcher
         if ($rewrite_settings) {
             fwrite($write_fd, "\n# Dispatcher\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -s [OR]\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -l [OR]\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -d\n");
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, $domain_rewrite_cond);
             }
             fwrite($write_fd, "RewriteRule ^.*\$ - [NC,L]\n");
             if (Shop::isFeatureActive()) {
                 fwrite($write_fd, $domain_rewrite_cond);
             }
             fwrite($write_fd, "RewriteRule ^.*\$ %{ENV:REWRITEBASE}index.php [NC,L]\n");
         }
     }
     fwrite($write_fd, "</IfModule>\n\n");
     fwrite($write_fd, "AddType application/vnd.ms-fontobject .eot\n");
     fwrite($write_fd, "AddType font/ttf .ttf\n");
     fwrite($write_fd, "AddType font/otf .otf\n");
     fwrite($write_fd, "AddType application/x-font-woff .woff\n\n");
     // Cache control
     if ($cache_control) {
         $cache_control = "<IfModule mod_expires.c>\n\tExpiresActive On\n\tExpiresByType image/gif \"access plus 1 month\"\n\tExpiresByType image/jpeg \"access plus 1 month\"\n\tExpiresByType image/png \"access plus 1 month\"\n\tExpiresByType text/css \"access plus 1 week\"\n\tExpiresByType text/javascript \"access plus 1 week\"\n\tExpiresByType application/javascript \"access plus 1 week\"\n\tExpiresByType application/x-javascript \"access plus 1 week\"\n\tExpiresByType image/x-icon \"access plus 1 year\"\n\tExpiresByType image/svg+xml \"access plus 1 year\"\n\tExpiresByType image/vnd.microsoft.icon \"access plus 1 year\"\n\tExpiresByType application/font-woff \"access plus 1 year\"\n\tExpiresByType application/x-font-woff \"access plus 1 year\"\n\tExpiresByType application/vnd.ms-fontobject \"access plus 1 year\"\n\tExpiresByType font/opentype \"access plus 1 year\"\n\tExpiresByType font/ttf \"access plus 1 year\"\n\tExpiresByType font/otf \"access plus 1 year\"\n\tExpiresByType application/x-font-ttf \"access plus 1 year\"\n\tExpiresByType application/x-font-otf \"access plus 1 year\"\n</IfModule>\n\nFileETag INode MTime Size\n<IfModule mod_deflate.c>\n\t<IfModule mod_filter.c>\n\t\tAddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/x-javascript\n\t</IfModule>\n</IfModule>\n\n";
         fwrite($write_fd, $cache_control);
     }
     // In case the user hasn't rewrite mod enabled
     fwrite($write_fd, "#If rewrite mod isn't enabled\n");
     // Do not remove ($domains is already iterated upper)
     reset($domains);
     $domain = current($domains);
     fwrite($write_fd, 'ErrorDocument 404 ' . $domain[0]['physical'] . "index.php?controller=404\n\n");
     fwrite($write_fd, "# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again");
     if ($specific_after) {
         fwrite($write_fd, "\n\n" . trim($specific_after));
     }
     fclose($write_fd);
     if (!defined('PS_INSTALLATION_IN_PROGRESS')) {
         Hook::exec('actionHtaccessCreate');
     }
     return true;
 }
 /**
  * @param ShopUrl $object
  * @return void
  */
 protected function afterUpdate($object)
 {
     if ($object->id && Tools::getValue('main')) {
         $object->setMain();
     }
     if ($this->redirect_shop_url) {
         $this->redirect_after = $object->getBaseURI() . basename(_PS_ADMIN_DIR_) . '/' . $this->context->link->getAdminLink('AdminShopUrl');
     }
 }
    public function postProcess()
    {
        if ($id_customer_thread = (int) Tools::getValue('id_customer_thread')) {
            if ($id_contact = (int) Tools::getValue('id_contact')) {
                Db::getInstance()->execute('
					UPDATE ' . _DB_PREFIX_ . 'customer_thread
					SET id_contact = ' . (int) $id_contact . '
					WHERE id_customer_thread = ' . (int) $id_customer_thread);
            }
            if ($id_status = (int) Tools::getValue('setstatus')) {
                $status_array = array(1 => 'open', 2 => 'closed', 3 => 'pending1', 4 => 'pending2');
                Db::getInstance()->execute('
					UPDATE ' . _DB_PREFIX_ . 'customer_thread
					SET status = "' . $status_array[$id_status] . '"
					WHERE id_customer_thread = ' . (int) $id_customer_thread . ' LIMIT 1
				');
            }
            if (isset($_POST['id_employee_forward'])) {
                $messages = Db::getInstance()->getRow('
					SELECT ct.*, cm.*, cl.name subject, CONCAT(e.firstname, \' \', e.lastname) employee_name,
						CONCAT(c.firstname, \' \', c.lastname) customer_name, c.firstname
					FROM ' . _DB_PREFIX_ . 'customer_thread ct
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_message cm
						ON (ct.id_customer_thread = cm.id_customer_thread)
					LEFT JOIN ' . _DB_PREFIX_ . 'contact_lang cl
						ON (cl.id_contact = ct.id_contact AND cl.id_lang = ' . (int) $this->context->language->id . ')
					LEFT OUTER JOIN ' . _DB_PREFIX_ . 'employee e
						ON e.id_employee = cm.id_employee
					LEFT OUTER JOIN ' . _DB_PREFIX_ . 'customer c
						ON (c.email = ct.email)
					WHERE ct.id_customer_thread = ' . (int) Tools::getValue('id_customer_thread') . '
					ORDER BY cm.date_add DESC
				');
                $output = $this->displayMessage($messages, true, (int) Tools::getValue('id_employee_forward'));
                $cm = new CustomerMessage();
                $cm->id_employee = (int) $this->context->employee->id;
                $cm->id_customer_thread = (int) Tools::getValue('id_customer_thread');
                $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                $current_employee = $this->context->employee;
                $id_employee = (int) Tools::getValue('id_employee_forward');
                $employee = new Employee($id_employee);
                $email = Tools::getValue('email');
                $message = Tools::getValue('message_forward');
                if (($error = $cm->validateField('message', $message, null, array(), true)) !== true) {
                    $this->errors[] = $error;
                } elseif ($id_employee && $employee && Validate::isLoadedObject($employee)) {
                    $params = array('{messages}' => stripslashes($output), '{employee}' => $current_employee->firstname . ' ' . $current_employee->lastname, '{comment}' => stripslashes(Tools::nl2br($_POST['message_forward'])), '{firstname}' => $employee->firstname, '{lastname}' => $employee->lastname);
                    if (Mail::Send($this->context->language->id, 'forward_msg', Mail::l('Fwd: Customer message', $this->context->language->id), $params, $employee->email, $employee->firstname . ' ' . $employee->lastname, $current_employee->email, $current_employee->firstname . ' ' . $current_employee->lastname, null, null, _PS_MAIL_DIR_, true)) {
                        $cm->private = 1;
                        $cm->message = $this->l('Message forwarded to') . ' ' . $employee->firstname . ' ' . $employee->lastname . "\n" . $this->l('Comment:') . ' ' . $message;
                        $cm->add();
                    }
                } elseif ($email && Validate::isEmail($email)) {
                    $params = array('{messages}' => Tools::nl2br(stripslashes($output)), '{employee}' => $current_employee->firstname . ' ' . $current_employee->lastname, '{comment}' => stripslashes($_POST['message_forward']));
                    if (Mail::Send($this->context->language->id, 'forward_msg', Mail::l('Fwd: Customer message', $this->context->language->id), $params, $email, null, $current_employee->email, $current_employee->firstname . ' ' . $current_employee->lastname, null, null, _PS_MAIL_DIR_, true)) {
                        $cm->message = $this->l('Message forwarded to') . ' ' . $email . "\n" . $this->l('Comment:') . ' ' . $message;
                        $cm->add();
                    }
                } else {
                    $this->errors[] = '<div class="alert error">' . Tools::displayError('The email address is invalid.') . '</div>';
                }
            }
            if (Tools::isSubmit('submitReply')) {
                $ct = new CustomerThread($id_customer_thread);
                ShopUrl::cacheMainDomainForShop((int) $ct->id_shop);
                $cm = new CustomerMessage();
                $cm->id_employee = (int) $this->context->employee->id;
                $cm->id_customer_thread = $ct->id;
                $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                $cm->message = Tools::getValue('reply_message');
                if (($error = $cm->validateField('message', $cm->message, null, array(), true)) !== true) {
                    $this->errors[] = $error;
                } elseif (isset($_FILES) && !empty($_FILES['joinFile']['name']) && $_FILES['joinFile']['error'] != 0) {
                    $this->errors[] = Tools::displayError('An error occurred during the file upload process.');
                } elseif ($cm->add()) {
                    $file_attachment = null;
                    if (!empty($_FILES['joinFile']['name'])) {
                        $file_attachment['content'] = file_get_contents($_FILES['joinFile']['tmp_name']);
                        $file_attachment['name'] = $_FILES['joinFile']['name'];
                        $file_attachment['mime'] = $_FILES['joinFile']['type'];
                    }
                    $customer = new Customer($ct->id_customer);
                    $params = array('{reply}' => Tools::nl2br(Tools::getValue('reply_message')), '{link}' => Tools::url($this->context->link->getPageLink('contact', true), 'id_customer_thread=' . (int) $ct->id . '&token=' . $ct->token), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname);
                    //#ct == id_customer_thread    #tc == token of thread   <== used in the synchronization imap
                    $contact = new Contact((int) $ct->id_contact, (int) $ct->id_lang);
                    if (Validate::isLoadedObject($contact)) {
                        $from_name = $contact->name;
                        $from_email = $contact->email;
                    } else {
                        $from_name = null;
                        $from_email = null;
                    }
                    if (Mail::Send((int) $ct->id_lang, 'reply_msg', sprintf(Mail::l('An answer to your message is available #ct%1$s #tc%2$s', $ct->id_lang), $ct->id, $ct->token), $params, Tools::getValue('msg_email'), null, $from_email, $from_name, $file_attachment, null, _PS_MAIL_DIR_, true)) {
                        $ct->status = 'closed';
                        $ct->update();
                    }
                    Tools::redirectAdmin(self::$currentIndex . '&id_customer_thread=' . (int) $id_customer_thread . '&viewcustomer_thread&token=' . Tools::getValue('token'));
                } else {
                    $this->errors[] = Tools::displayError('An error occurred. Your message was not sent. Please contact your system administrator.');
                }
            }
        }
        return parent::postProcess();
    }
Beispiel #28
0
    /**
     * @param bool $autodate Optional
     * @param array $template_vars Optional
     * @param Context $context Optional
     * @return bool
     */
    public function addWithemail($autodate = true, $template_vars = false, Context $context = null)
    {
        if (!$context) {
            $context = Context::getContext();
        }
        $order = new Order($this->id_order);
        if (!$this->add($autodate)) {
            return false;
        }
        $result = Db::getInstance()->getRow('
			SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`
			FROM `' . _DB_PREFIX_ . 'order_history` oh
				LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON oh.`id_order` = o.`id_order`
				LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON o.`id_customer` = c.`id_customer`
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON oh.`id_order_state` = os.`id_order_state`
				LEFT JOIN `' . _DB_PREFIX_ . 'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
			WHERE oh.`id_order_history` = ' . (int) $this->id . ' AND os.`send_email` = 1');
        if (isset($result['template']) && Validate::isEmail($result['email'])) {
            ShopUrl::cacheMainDomainForShop($order->id_shop);
            $topic = $result['osname'];
            $data = array('{lastname}' => $result['lastname'], '{firstname}' => $result['firstname'], '{id_order}' => (int) $this->id_order, '{order_name}' => $order->getUniqReference());
            if ($template_vars) {
                $data = array_merge($data, $template_vars);
            }
            if ($result['module_name']) {
                $module = Module::getInstanceByName($result['module_name']);
                if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
                    $data = array_merge($data, $module->extra_mail_vars);
                }
            }
            $data['{total_paid}'] = Tools::displayPrice((double) $order->total_paid, new Currency((int) $order->id_currency), false);
            $data['{order_name}'] = $order->getUniqReference();
            if (Validate::isLoadedObject($order)) {
                // Join PDF invoice if order state is "payment accepted"
                if ((int) $result['id_order_state'] === 2 && (int) Configuration::get('PS_INVOICE') && $order->invoice_number) {
                    $context = Context::getContext();
                    $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $context->smarty);
                    $file_attachement['content'] = $pdf->render(false);
                    $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                    $file_attachement['mime'] = 'application/pdf';
                } else {
                    $file_attachement = null;
                }
                Mail::Send((int) $order->id_lang, $result['template'], $topic, $data, $result['email'], $result['firstname'] . ' ' . $result['lastname'], null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
            }
            ShopUrl::resetMainDomainCache();
        }
        return true;
    }
Beispiel #29
0
 public static function getMainShopDomainSSL($id_shop = null)
 {
     ShopUrl::cacheMainDomainForShop($id_shop);
     return self::$main_domain_ssl[(int) $id_shop];
 }
Beispiel #30
0
 public static function generateHtaccess($path = null, $rewrite_settings = null, $cache_control = null, $specific = '', $disable_multiviews = null, $medias = false)
 {
     if (defined('PS_INSTALLATION_IN_PROGRESS')) {
         return true;
     }
     // Default values for parameters
     if (is_null($path)) {
         $path = _PS_ROOT_DIR_ . '/.htaccess';
     }
     if (is_null($cache_control)) {
         $cache_control = (int) Configuration::get('PS_HTACCESS_CACHE_CONTROL');
     }
     if (is_null($disable_multiviews)) {
         $disable_multiviews = (int) Configuration::get('PS_HTACCESS_DISABLE_MULTIVIEWS');
     }
     // Check current content of .htaccess and save all code outside of prestashop comments
     $specific_before = $specific_after = '';
     if (file_exists($path)) {
         $content = file_get_contents($path);
         if (preg_match('#^(.*)\\# ~~start~~.*\\# ~~end~~[^\\n]*(.*)$#s', $content, $m)) {
             $specific_before = $m[1];
             $specific_after = $m[2];
         } else {
             // For retrocompatibility
             if (preg_match('#\\# http://www\\.prestashop\\.com - http://www\\.prestashop\\.com/forums\\s*(.*)<IfModule mod_rewrite\\.c>#si', $content, $m)) {
                 $specific_before = $m[1];
             } else {
                 $specific_before = $content;
             }
         }
     }
     // Write .htaccess data
     if (!($write_fd = @fopen($path, 'w'))) {
         return false;
     }
     fwrite($write_fd, trim($specific_before) . "\n\n");
     $domains = array();
     foreach (ShopUrl::getShopUrls() as $shop_url) {
         if (!isset($domains[$shop_url->domain])) {
             $domains[$shop_url->domain] = array();
         }
         $domains[$shop_url->domain][] = array('physical' => $shop_url->physical_uri, 'virtual' => $shop_url->virtual_uri, 'id_shop' => $shop_url->id_shop);
     }
     // Write data in .htaccess file
     fwrite($write_fd, "# ~~start~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again\n");
     fwrite($write_fd, "# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution\n");
     fwrite($write_fd, "# http://www.prestashop.com - http://www.prestashop.com/forums\n\n");
     // RewriteEngine
     fwrite($write_fd, "<IfModule mod_rewrite.c>\n");
     // Disable multiviews ?
     if ($disable_multiviews) {
         fwrite($write_fd, "\n# Disable Multiviews\nOptions -Multiviews\n\n");
     }
     fwrite($write_fd, "RewriteEngine on\n");
     if (!$medias) {
         $medias = array(_MEDIA_SERVER_1_, _MEDIA_SERVER_2_, _MEDIA_SERVER_3_);
     }
     $media_domains = '';
     if ($medias[0] != '') {
         $media_domains = 'RewriteCond %{HTTP_HOST} ^' . $medias[0] . '$ [OR]' . "\n";
     }
     if ($medias[1] != '') {
         $media_domains .= 'RewriteCond %{HTTP_HOST} ^' . $medias[1] . '$ [OR]' . "\n";
     }
     if ($medias[2] != '') {
         $media_domains .= 'RewriteCond %{HTTP_HOST} ^' . $medias[2] . '$ [OR]' . "\n";
     }
     if (Configuration::get('PS_WEBSERVICE_CGI_HOST')) {
         fwrite($write_fd, "RewriteCond %{HTTP:Authorization} ^(.*)\nRewriteRule . - [E=HTTP_AUTHORIZATION:%1]\n\n");
     }
     foreach ($domains as $domain => $list_uri) {
         $physicals = array();
         foreach ($list_uri as $uri) {
             fwrite($write_fd, 'RewriteCond %{HTTP_HOST} ^' . $domain . '$' . "\n");
             fwrite($write_fd, 'RewriteRule . - [E=REWRITEBASE:' . $uri['physical'] . ']' . "\n");
             // Webservice
             fwrite($write_fd, 'RewriteRule ^api/?(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L]' . "\n\n");
             $rewrite_settings = (int) Configuration::get('PS_REWRITING_SETTINGS', null, null, (int) $uri['id_shop']);
             $domain_rewrite_cond = 'RewriteCond %{HTTP_HOST} ^' . $domain . '$' . "\n";
             // Rewrite virtual multishop uri
             if ($uri['virtual']) {
                 if (!$rewrite_settings) {
                     fwrite($write_fd, $media_domains);
                     fwrite($write_fd, $domain_rewrite_cond);
                     fwrite($write_fd, 'RewriteRule ^' . trim($uri['virtual'], '/') . '/?$ ' . $uri['physical'] . $uri['virtual'] . "index.php [L,R]\n");
                 } else {
                     fwrite($write_fd, $media_domains);
                     fwrite($write_fd, $domain_rewrite_cond);
                     fwrite($write_fd, 'RewriteRule ^' . trim($uri['virtual'], '/') . '$ ' . $uri['physical'] . $uri['virtual'] . " [L,R]\n");
                 }
                 fwrite($write_fd, $media_domains);
                 fwrite($write_fd, $domain_rewrite_cond);
                 fwrite($write_fd, 'RewriteRule ^' . ltrim($uri['virtual'], '/') . '(.*) ' . $uri['physical'] . "\$1 [L]\n\n");
             }
             if ($rewrite_settings) {
                 // Compatibility with the old image filesystem
                 fwrite($write_fd, "# Images\n");
                 if (Configuration::get('PS_LEGACY_IMAGES')) {
                     fwrite($write_fd, $media_domains);
                     fwrite($write_fd, $domain_rewrite_cond);
                     fwrite($write_fd, 'RewriteRule ^([a-z0-9]+)\\-([a-z0-9]+)(\\-[_a-zA-Z0-9-]*)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}' . _PS_PROD_IMG_ . '$1-$2$3$4.jpg [L]' . "\n");
                     fwrite($write_fd, $media_domains);
                     fwrite($write_fd, $domain_rewrite_cond);
                     fwrite($write_fd, 'RewriteRule ^([0-9]+)\\-([0-9]+)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}' . _PS_PROD_IMG_ . '$1-$2$3.jpg [L]' . "\n");
                 }
                 // Rewrite product images < 100 millions
                 for ($i = 1; $i <= 8; $i++) {
                     $img_path = $img_name = '';
                     for ($j = 1; $j <= $i; $j++) {
                         $img_path .= '$' . $j . '/';
                         $img_name .= '$' . $j;
                     }
                     $img_name .= '$' . $j;
                     fwrite($write_fd, $media_domains);
                     fwrite($write_fd, $domain_rewrite_cond);
                     fwrite($write_fd, 'RewriteRule ^' . str_repeat('([0-9])', $i) . '(\\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}' . _PS_PROD_IMG_ . $img_path . $img_name . '$' . ($j + 1) . ".jpg [L]\n");
                 }
                 fwrite($write_fd, $media_domains);
                 fwrite($write_fd, $domain_rewrite_cond);
                 fwrite($write_fd, 'RewriteRule ^c/([0-9]+)(\\-[\\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2$3.jpg [L]' . "\n");
                 fwrite($write_fd, $media_domains);
                 fwrite($write_fd, $domain_rewrite_cond);
                 fwrite($write_fd, 'RewriteRule ^c/([a-zA-Z_-]+)(-[0-9]+)?/.+\\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2.jpg [L]' . "\n");
             }
         }
         // Redirections to dispatcher
         if ($rewrite_settings) {
             fwrite($write_fd, "\n# Dispatcher\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -s [OR]\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -l [OR]\n");
             fwrite($write_fd, "RewriteCond %{REQUEST_FILENAME} -d\n");
             fwrite($write_fd, $domain_rewrite_cond);
             fwrite($write_fd, "RewriteRule ^.*\$ - [NC,L]\n");
             fwrite($write_fd, $domain_rewrite_cond);
             fwrite($write_fd, "RewriteRule ^.*\$ %{ENV:REWRITEBASE}index.php [NC,L]\n");
         }
     }
     fwrite($write_fd, "</IfModule>\n\n");
     // Cache control
     if ($cache_control) {
         $cache_control = "<IfModule mod_expires.c>\n\tExpiresActive On\n\tExpiresByType image/gif \"access plus 1 month\"\n\tExpiresByType image/jpeg \"access plus 1 month\"\n\tExpiresByType image/png \"access plus 1 month\"\n\tExpiresByType text/css \"access plus 1 week\"\n\tExpiresByType text/javascript \"access plus 1 week\"\n\tExpiresByType application/javascript \"access plus 1 week\"\n\tExpiresByType application/x-javascript \"access plus 1 week\"\n\tExpiresByType image/x-icon \"access plus 1 year\"\n</IfModule>\n\nFileETag INode MTime Size\n<IfModule mod_deflate.c>\n\tAddOutputFilterByType DEFLATE text/html\n\tAddOutputFilterByType DEFLATE text/css\n\tAddOutputFilterByType DEFLATE text/javascript\n\tAddOutputFilterByType DEFLATE application/javascript\n\tAddOutputFilterByType DEFLATE application/x-javascript\n</IfModule>\n\n";
         fwrite($write_fd, $cache_control);
     }
     // In case the user hasn't rewrite mod enabled
     fwrite($write_fd, "#If rewrite mod isn't enabled\n");
     // Do not remove ($domains is already iterated upper)
     reset($domains);
     $domain = current($domains);
     fwrite($write_fd, 'ErrorDocument 404 ' . $domain[0]['physical'] . "index.php?controller=404\n\n");
     fwrite($write_fd, "# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again\n");
     fwrite($write_fd, "\n\n" . trim($specific_after));
     fclose($write_fd);
     Hook::exec('actionHtaccessCreate');
     return true;
 }