public function postProcess()
 {
     global $currentIndex;
     if (Tools::isSubmit('submitPrint')) {
         if (!Validate::isDate(Tools::getValue('date_from'))) {
             $this->_errors[] = $this->l('Invalid from date');
         }
         if (!Validate::isDate(Tools::getValue('date_to'))) {
             $this->_errors[] = $this->l('Invalid end date');
         }
         if (!sizeof($this->_errors)) {
             $orders = Order::getOrdersIdInvoiceByDate(Tools::getValue('date_from'), Tools::getValue('date_to'), NULL, 'invoice');
             if (sizeof($orders)) {
                 Tools::redirectAdmin('pdf.php?invoices&date_from=' . urlencode(Tools::getValue('date_from')) . '&date_to=' . urlencode(Tools::getValue('date_to')) . '&token=' . $this->token);
             }
             $this->_errors[] = $this->l('No invoice found for this period');
         }
     } elseif (Tools::isSubmit('submitOptionsinvoice')) {
         if (intval(Tools::getValue('PS_INVOICE_NUMBER')) == 0) {
             $this->_errors[] = $this->l('Invalid invoice number');
         } else {
             parent::postProcess();
         }
     } else {
         parent::postProcess();
     }
 }
Example #2
0
 public function inscription()
 {
     if (!empty($_POST)) {
         $validate = new Validate($_POST);
         if ($validate->isEmpty('cgu')) {
             $validate->notEmpty('nom', "Veuillez entrer un nom");
             $validate->notEmpty('prenom', "Veuillez entrer un prénom");
             $validate->isEmail('email', "L'email n'est pas valide");
             $email = $this->user->emailExist()->fetch();
             $validate->isUnique('email', $email, "L'email est déjà utilisé");
             $validate->doubleCheck('password', 'confirmation', "Les mot de passe ne correspondent pas");
             //Router::debug($validate->error);
             $validate->isVille('ville', "Votre adresse n'est pas valide");
             $validate->isDate('date', 'jour', 'mois', 'année', "Votre date de naissance n'est pas valide");
             if ($validate->isValid()) {
                 $_SESSION["inscription"] = $_POST;
                 $vue = new Vue("CGU", "User");
                 $vue->render();
             } else {
                 $vue = new Vue("Inscription", "User");
                 $vue->render(['errors' => $validate->errors]);
             }
         } else {
             $this->user->inscrireUtilisateur($_SESSION["inscription"]);
             unset($_SESSION["inscription"]);
             $vue = new Vue("Success", "User");
             $vue->render(['msg' => "L'inscription a bien été enregistré.<br> Un email vous a été envoyé."]);
         }
     } else {
         $vue = new Vue("Inscription", "User");
         $vue->setScript('verif.js');
         $vue->render();
     }
 }
 public function postProcess()
 {
     global $currentIndex;
     if (Tools::getValue('submitPrint')) {
         if (!Validate::isDate($_POST['date_from'])) {
             $this->_errors[] = $this->l('Invalid from date');
         }
         if (!Validate::isDate($_POST['date_to'])) {
             $this->_errors[] = $this->l('Invalid end date');
         }
         if (!sizeof($this->_errors)) {
             $orders = Order::getOrdersIdByDate($_POST['date_from'], $_POST['date_to'], NULL, 'delivery');
             if (sizeof($orders)) {
                 Tools::redirectAdmin('pdf.php?deliveryslips=' . urlencode(serialize($orders)) . '&token=' . $this->token);
             } else {
                 $this->_errors[] = $this->l('No delivery slip found for this period');
             }
         }
     } elseif (Tools::getValue('submitOptionsdelivery')) {
         $next_slipnum = abs((int) Tools::getValue('PS_DELIVERY_NUMBER'));
         $_POST['PS_DELIVERY_NUMBER'] = $next_slipnum;
         $max_existing = abs((int) Db::getInstance()->getValue('SELECT MAX(`delivery_number`) FROM `' . _DB_PREFIX_ . 'orders`'));
         if ((int) $next_slipnum < 1 || (int) $next_slipnum > 4294967295) {
             $this->_errors[] = $this->l('The delivery number requires a value between 1 and 4294967295');
         }
         if ($max_existing && $next_slipnum <= abs((int) $max_existing)) {
             $this->_errors[] = $this->l('To avoid duplicating numbers assigned to existing slips, delivery slip number must be greater than') . ' ' . $max_existing;
         }
         if (!count($this->_errors)) {
             parent::postProcess();
         }
     } else {
         parent::postProcess();
     }
 }
Example #4
0
 /** @prototype void public function setTimeMode($from, $to, $granularity) */
 public function setTimeMode($from, $to, $granularity)
 {
     $this->granularity = $granularity;
     if (Validate::isDate($from)) {
         $from = strtotime($from);
     }
     $this->from = $from;
     if (Validate::isDate($to)) {
         $to = strtotime($to);
     }
     $this->to = $to;
     if ($granularity == 'd') {
         $this->format = '%d/%m/%y';
     }
     if ($granularity == 'w') {
         $this->format = '%d/%m/%y';
     }
     if ($granularity == 'm') {
         $this->format = '%m/%y';
     }
     if ($granularity == 'y') {
         $this->format = '%y';
     }
     $this->timeMode = true;
 }
 public function postProcess()
 {
     if (Tools::isSubmit('submitAddinvoice_date')) {
         if (!Validate::isDate(Tools::getValue('date_from'))) {
             $this->errors[] = $this->l('Invalid "From" date');
         }
         if (!Validate::isDate(Tools::getValue('date_to'))) {
             $this->errors[] = $this->l('Invalid "To" date');
         }
         if (!count($this->errors)) {
             if (count(OrderInvoice::getByDateInterval(Tools::getValue('date_from'), Tools::getValue('date_to')))) {
                 Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf') . '&submitAction=generateInvoicesPDF&date_from=' . urlencode(Tools::getValue('date_from')) . '&date_to=' . urlencode(Tools::getValue('date_to')));
             }
             $this->errors[] = $this->l('No invoice has been found for this period.');
         }
     } elseif (Tools::isSubmit('submitAddinvoice_status')) {
         if (!is_array($status_array = Tools::getValue('id_order_state')) || !count($status_array)) {
             $this->errors[] = $this->l('You must select at least one order status.');
         } else {
             foreach ($status_array as $id_order_state) {
                 if (count(OrderInvoice::getByStatus((int) $id_order_state))) {
                     Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf') . '&submitAction=generateInvoicesPDF2&id_order_state=' . implode('-', $status_array));
                 }
             }
             $this->errors[] = $this->l('No invoice has been found for this status.');
         }
     } else {
         parent::postProcess();
     }
 }
 public function hookDisplayLeftColumn()
 {
     if ($this->context->controller->php_self == 'category') {
         if (Tools::isSubmit('filter_search_btn')) {
             $hotel_cat_id = Tools::getValue('hotel_cat_id');
             $check_in = Tools::getValue('check_in_time');
             $check_out = Tools::getValue('check_out_time');
             $error = false;
             if ($hotel_cat_id == '') {
                 $error = 1;
             } elseif ($check_in == '' || !Validate::isDate($check_in)) {
                 $error = 1;
             } elseif ($check_out == '' || !Validate::isDate($check_out)) {
                 $error = 1;
             } elseif ($check_out <= $check_in) {
                 $error = 1;
             }
             if (!$error) {
                 if (Configuration::get('PS_REWRITING_SETTINGS')) {
                     $redirect_link = $this->context->link->getCategoryLink(new Category($hotel_cat_id, $this->context->language->id), null, $this->context->language->id) . '?date_from=' . $check_in . '&date_to=' . $check_out;
                 } else {
                     $redirect_link = $this->context->link->getCategoryLink(new Category($hotel_cat_id, $this->context->language->id), null, $this->context->language->id) . '&date_from=' . $check_in . '&date_to=' . $check_out;
                 }
             } else {
                 if (Configuration::get('PS_REWRITING_SETTINGS')) {
                     $redirect_link = $this->context->link->getCategoryLink(new Category($hotel_cat_id, $this->context->language->id), null, $this->context->language->id) . '?error=' . $error;
                 } else {
                     $redirect_link = $this->context->link->getCategoryLink(new Category($hotel_cat_id, $this->context->language->id), null, $this->context->language->id) . '&error=' . $error;
                 }
             }
             Tools::redirect($redirect_link);
         }
         if (Tools::getValue('error')) {
             $this->context->smarty->assign('error', Tools::getValue('error'));
         }
         $location_enable = Configuration::get('WK_HOTEL_LOCATION_ENABLE');
         $hotel_branch_obj = new HotelBranchInformation();
         $htl_id_category = Tools::getValue('id_category');
         $category = new Category((int) $htl_id_category);
         $parent_dtl = $hotel_branch_obj->getCategoryDataByIdCategory((int) $category->id_parent);
         if (!($date_from = Tools::getValue('date_from'))) {
             $date_from = date('Y-m-d');
             $date_to = date('Y-m-d', strtotime($date_from) + 86400);
         }
         if (!($date_to = Tools::getValue('date_to'))) {
             $date_to = date('Y-m-d', strtotime($date_from) + 86400);
         }
         $search_data['parent_data'] = $parent_dtl;
         $search_data['date_from'] = $date_from;
         $search_data['date_to'] = $date_to;
         $search_data['htl_dtl'] = $hotel_branch_obj->hotelBranchInfoById(HotelBranchInformation::getHotelIdByIdCategory($htl_id_category));
         $hotel_info = $hotel_branch_obj->getActiveHotelBranchesInfo();
         $this->context->smarty->assign(array('search_data' => $search_data, 'all_hotels_info' => $hotel_info, 'location_enable' => $location_enable));
         $this->context->controller->addCSS(_PS_MODULE_DIR_ . $this->name . '/views/css/wkhotelfiltersearchblock.css');
         return $this->display(__FILE__, 'htlfiltersearchblock.tpl');
     }
 }
 public function postProcess()
 {
     global $cookie, $currentIndex;
     if (Tools::isSubmit('submitDatePicker')) {
         if (!Validate::isDate($from = Tools::getValue('datepickerFrom')) or !Validate::isDate($to = Tools::getValue('datepickerTo'))) {
             $this->_errors[] = Tools::displayError('Date specified is invalid');
         }
     }
     if (Tools::isSubmit('submitDateDay')) {
         $from = date('Y-m-d');
         $to = date('Y-m-d');
     }
     if (Tools::isSubmit('submitDateDayPrev')) {
         $yesterday = time() - 60 * 60 * 24;
         $from = date('Y-m-d', $yesterday);
         $to = date('Y-m-d', $yesterday);
     }
     if (Tools::isSubmit('submitDateMonth')) {
         $from = date('Y-m-01');
         $to = date('Y-m-t');
     }
     if (Tools::isSubmit('submitDateMonthPrev')) {
         $m = date('m') == 1 ? 12 : date('m') - 1;
         $y = $m == 12 ? date('Y') - 1 : date('Y');
         $from = $y . '-' . $m . '-01';
         $to = $y . '-' . $m . date('-t', mktime(12, 0, 0, $m, 15, $y));
     }
     if (Tools::isSubmit('submitDateYear')) {
         $from = date('Y-01-01');
         $to = date('Y-12-31');
     }
     if (Tools::isSubmit('submitDateYearPrev')) {
         $from = date('Y') - 1 . date('-01-01');
         $to = date('Y') - 1 . date('-12-31');
     }
     if (isset($from) and isset($to) and !sizeof($this->_errors)) {
         $employee = new Employee($cookie->id_employee);
         $employee->stats_date_from = $from;
         $employee->stats_date_to = $to;
         $employee->update();
         Tools::redirectAdmin($_SERVER['REQUEST_URI']);
     }
     if (Tools::getValue('submitSettings')) {
         if ($this->tabAccess['edit'] === '1') {
             $currentIndex .= '&module=' . Tools::getValue('module');
             $this->_postConfig($this->_fieldsSettings);
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         }
     }
     if (sizeof($this->_errors)) {
         AdminTab::displayErrors();
     }
 }
 public function hookDisplayHeader()
 {
     $is_hotel_room_search = Tools::getValue('is_hotel_rooms_search');
     if (isset($is_hotel_room_search) && $is_hotel_room_search) {
         $hotel_cat_id = Tools::getValue('hotel_cat_id');
         $check_in = Tools::getValue('check_in_time');
         $check_out = Tools::getValue('check_out_time');
         $error = false;
         if ($hotel_cat_id == '') {
             $error = 1;
         } elseif ($check_in == '' || !Validate::isDate($check_in)) {
             $error = 2;
         } elseif ($check_out == '' || !Validate::isDate($check_out)) {
             $error = 3;
         } elseif ($check_out <= $check_in) {
             $error = 4;
         }
         if (!$error) {
             if (Configuration::get('PS_REWRITING_SETTINGS')) {
                 $redirect_link = $this->context->link->getCategoryLink(new Category($hotel_cat_id, $this->context->language->id), null, $this->context->language->id) . '?date_from=' . $check_in . '&date_to=' . $check_out;
             } else {
                 $redirect_link = $this->context->link->getCategoryLink(new Category($hotel_cat_id, $this->context->language->id), null, $this->context->language->id) . '&date_from=' . $check_in . '&date_to=' . $check_out;
             }
             Tools::redirect($redirect_link);
         } else {
             if (Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE')) {
                 Tools::redirect($protocol_link . Tools::getShopDomainSsl() . __PS_BASE_URI__ . "index.php?error=" . $error);
             } else {
                 Tools::redirect(_PS_BASE_URL_ . __PS_BASE_URI__ . "index.php?error=" . $error);
             }
         }
     }
     $location_enable = Configuration::get('WK_HOTEL_LOCATION_ENABLE');
     $hotel_branch_obj = new HotelBranchInformation();
     $hotel_info = $hotel_branch_obj->getActiveHotelBranchesInfo();
     $this->context->smarty->assign('hotel_name', $hotel_info);
     $this->context->smarty->assign('header_block_title', Configuration::get('WK_TITLE_HEADER_BLOCK'));
     $this->context->smarty->assign('header_block_content', Configuration::get('WK_CONTENT_HEADER_BLOCK'));
     $this->context->smarty->assign('location_enable', $location_enable);
     $this->context->controller->addJqueryUI(array('ui.datepicker'));
     $this->context->controller->addCSS(_PS_MODULE_DIR_ . $this->name . '/views/css/searchblock.css');
     $this->context->controller->addJS(_PS_MODULE_DIR_ . $this->name . '/views/js/wksearchblock.js');
 }
Example #9
0
 public function postProcess()
 {
     if (Tools::isSubmit('submitPrint')) {
         if (!Validate::isDate(Tools::getValue('date_from'))) {
             $this->_errors[] = $this->l('Invalid from date');
         }
         if (!Validate::isDate(Tools::getValue('date_to'))) {
             $this->_errors[] = $this->l('Invalid end date');
         }
         if (!sizeof($this->_errors)) {
             $orderSlips = OrderSlip::getSlipsIdByDate(Tools::getValue('date_from'), Tools::getValue('date_to'));
             if (count($orderSlips)) {
                 Tools::redirectAdmin('pdf.php?slips&date_from=' . urlencode(Tools::getValue('date_from')) . '&date_to=' . urlencode(Tools::getValue('date_to')) . '&token=' . $this->token);
             }
             $this->_errors[] = $this->l('No order slips found for this period');
         }
     }
     return parent::postProcess();
 }
Example #10
0
 public function postProcess()
 {
     if (Tools::getValue('submitAddorder_slip')) {
         if (!Validate::isDate(Tools::getValue('date_from'))) {
             $this->errors[] = $this->l('Invalid "From" date');
         }
         if (!Validate::isDate(Tools::getValue('date_to'))) {
             $this->errors[] = $this->l('Invalid "To" date');
         }
         if (!count($this->errors)) {
             $order_slips = OrderSlip::getSlipsIdByDate(Tools::getValue('date_from'), Tools::getValue('date_to'));
             if (count($order_slips)) {
                 Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf') . '&submitAction=generateOrderSlipsPDF&date_from=' . urlencode(Tools::getValue('date_from')) . '&date_to=' . urlencode(Tools::getValue('date_to')));
             }
             $this->errors[] = $this->l('No order slips were found for this period.');
         }
     } else {
         return parent::postProcess();
     }
 }
 public function postProcess()
 {
     if (Tools::isSubmit('submitAdddelivery')) {
         if (!Validate::isDate(Tools::getValue('date_from'))) {
             $this->errors[] = Tools::displayError('Invalid \'from\' date');
         }
         if (!Validate::isDate(Tools::getValue('date_to'))) {
             $this->errors[] = Tools::displayError('Invalid \'to\' date');
         }
         if (!count($this->errors)) {
             if (count(OrderInvoice::getByDeliveryDateInterval(Tools::getValue('date_from'), Tools::getValue('date_to')))) {
                 Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf') . '&submitAction=generateDeliverySlipsPDF&date_from=' . urlencode(Tools::getValue('date_from')) . '&date_to=' . urlencode(Tools::getValue('date_to')));
             } else {
                 $this->errors[] = Tools::displayError('No delivery slip was found for this period.');
             }
         }
     } else {
         parent::postProcess();
     }
 }
Example #12
0
 public function postProcess()
 {
     global $currentIndex;
     if (Tools::getValue('submitPrint')) {
         if (!Validate::isDate($_POST['date_from'])) {
             $this->_errors[] = $this->l('Invalid from date');
         }
         if (!Validate::isDate($_POST['date_to'])) {
             $this->_errors[] = $this->l('Invalid end date');
         }
         if (!sizeof($this->_errors)) {
             $orders = Order::getOrdersIdInvoiceByDate($_POST['date_from'], $_POST['date_to'], NULL, 'invoice');
             if (sizeof($orders)) {
                 Tools::redirectAdmin('pdf.php?invoices&date_from=' . urlencode($_POST['date_from']) . '&date_to=' . urlencode($_POST['date_to']) . '&token=' . $this->token);
             }
             $this->_errors[] = $this->l('No invoice found for this period');
         }
     } else {
         parent::postProcess();
     }
 }
Example #13
0
 public function postProcess()
 {
     global $cookie, $currentIndex;
     if (Tools::isSubmit('submitDatePicker')) {
         if (!Validate::isDate($from = Tools::getValue('datepickerFrom')) or !Validate::isDate($to = Tools::getValue('datepickerTo'))) {
             $this->_errors[] = Tools::displayError('date specified not valid');
         }
     }
     if (Tools::isSubmit('submitDateToday')) {
         $from = date('Y-m-d');
         $to = date('Y-m-d');
     }
     if (Tools::isSubmit('submitDateMonth')) {
         $from = date('Y-m-01');
         $to = date('Y-m-t');
     }
     if (Tools::isSubmit('submitDateYear')) {
         $from = date('Y-01-01');
         $to = date('Y-12-31');
     }
     if (isset($from) and isset($to) and !sizeof($this->_errors)) {
         $employee = new Employee($cookie->id_employee);
         $employee->stats_date_from = $from;
         $employee->stats_date_to = $to;
         $employee->update();
         Tools::redirectAdmin($_SERVER['REQUEST_URI']);
     }
     if (Tools::getValue('submitSettings')) {
         if ($this->tabAccess['edit'] === '1') {
             $currentIndex .= '&module=' . Tools::getValue('module');
             $this->_postConfig($this->_fieldsSettings);
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit something here.');
         }
     }
     if (sizeof($this->_errors)) {
         AdminTab::displayErrors();
     }
 }
 public function update($null_values = false)
 {
     $this->birthday = empty($this->years) ? $this->birthday : (int) $this->years . '-' . (int) $this->months . '-' . (int) $this->days;
     if ($this->newsletter && !Validate::isDate($this->newsletter_date_add)) {
         $this->newsletter_date_add = date('Y-m-d H:i:s');
     }
     if (isset(Context::getContext()->controller) && Context::getContext()->controller->controller_type == 'admin') {
         $this->updateGroup($this->groupBox);
     }
     if ($this->deleted) {
         $addresses = $this->getAddresses((int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($addresses as $address) {
             $obj = new Address((int) $address['id_address']);
             $obj->delete();
         }
     }
     // start of implementation of the module code - taxamo
     $taxamo_iso_country_residence = Tools::getValue('taxamoisocountryresidence');
     $taxamo_cc_prefix = Tools::getValue('taxamoccprefix');
     Taxamoeuvat::updateCCPrefix($this->id, $taxamo_iso_country_residence, $taxamo_cc_prefix);
     // end of code implementation module - taxamo
     return parent::update(true);
 }
 public function processDateRange()
 {
     if (Tools::isSubmit('submitDatePicker')) {
         if (!Validate::isDate($from = Tools::getValue('datepickerFrom')) || !Validate::isDate($to = Tools::getValue('datepickerTo')) || strtotime($from) > strtotime($to)) {
             $this->errors[] = Tools::displayError('The specified date is invalid.');
         }
     }
     if (Tools::isSubmit('submitDateDay')) {
         $from = date('Y-m-d');
         $to = date('Y-m-d');
     }
     if (Tools::isSubmit('submitDateDayPrev')) {
         $yesterday = time() - 60 * 60 * 24;
         $from = date('Y-m-d', $yesterday);
         $to = date('Y-m-d', $yesterday);
     }
     if (Tools::isSubmit('submitDateMonth')) {
         $from = date('Y-m-01');
         $to = date('Y-m-t');
     }
     if (Tools::isSubmit('submitDateMonthPrev')) {
         $m = date('m') == 1 ? 12 : date('m') - 1;
         $y = $m == 12 ? date('Y') - 1 : date('Y');
         $from = $y . '-' . $m . '-01';
         $to = $y . '-' . $m . date('-t', mktime(12, 0, 0, $m, 15, $y));
     }
     if (Tools::isSubmit('submitDateYear')) {
         $from = date('Y-01-01');
         $to = date('Y-12-31');
     }
     if (Tools::isSubmit('submitDateYearPrev')) {
         $from = date('Y') - 1 . date('-01-01');
         $to = date('Y') - 1 . date('-12-31');
     }
     if (isset($from) && isset($to) && !count($this->errors)) {
         $this->context->employee->stats_date_from = $from;
         $this->context->employee->stats_date_to = $to;
         $this->context->employee->update();
         if (!$this->isXmlHttpRequest()) {
             Tools::redirectAdmin($_SERVER['REQUEST_URI']);
         }
     }
 }
Example #16
0
 public function productImport()
 {
     global $cookie;
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
     self::setLocale();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $line = $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         if (array_key_exists('id', $info) and (int) $info['id'] and Product::existsInDatabase((int) $info['id'], 'product')) {
             $product = new Product((int) $info['id']);
             $categoryData = Product::getProductCategories((int) $product->id);
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp;
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         if ((int) $product->id_tax_rules_group != 0) {
             if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                 $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0);
             } else {
                 $this->_addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID, you first need a group with this ID.'));
             }
         }
         if (isset($product->manufacturer) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists((int) $product->manufacturer)) {
             $product->id_manufacturer = (int) $product->manufacturer;
         } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) {
             if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                 $product->id_manufacturer = (int) $manufacturer;
             } else {
                 $manufacturer = new Manufacturer();
                 $manufacturer->name = $product->manufacturer;
                 if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                     $product->id_manufacturer = (int) $manufacturer->id;
                 } else {
                     $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists((int) $product->supplier)) {
             $product->id_supplier = (int) $product->supplier;
         } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) {
             if ($supplier = Supplier::getIdByName($product->supplier)) {
                 $product->id_supplier = (int) $supplier;
             } else {
                 $supplier = new Supplier();
                 $supplier->name = $product->supplier;
                 if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                     $product->id_supplier = (int) $supplier->id;
                 } else {
                     $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->price_tex) and !isset($product->price_tin)) {
             $product->price = $product->price_tex;
         } elseif (isset($product->price_tin) and !isset($product->price_tex)) {
             $product->price = $product->price_tin;
             // If a tax is already included in price, withdraw it from price
             if ($product->tax_rate) {
                 $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
             }
         } elseif (isset($product->price_tin) and isset($product->price_tex)) {
             $product->price = $product->price_tex;
         }
         if (isset($product->category) and is_array($product->category) and sizeof($product->category)) {
             $product->id_category = array();
             // Reset default values array
             foreach ($product->category as $value) {
                 if (is_numeric($value)) {
                     if (Category::categoryExists((int) $value)) {
                         $product->id_category[] = (int) $value;
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->id = (int) $value;
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 } elseif (is_string($value) and !empty($value)) {
                     $category = Category::searchByName($defaultLanguageId, $value, true);
                     if ($category['id_category']) {
                         $product->id_category[] = (int) $category['id_category'];
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
         }
         $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : '';
         $link_rewrite = is_array($product->link_rewrite) && count($product->link_rewrite) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($link_rewrite);
         if (isset($product->link_rewrite[$defaultLanguageId]) and empty($product->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
             if ($link_rewrite == '') {
                 $link_rewrite = 'friendly-url-autogeneration-failed';
             }
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrite link for') . ' ' . $link_rewrite . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $link_rewrite;
         }
         $product->link_rewrite = self::createMultiLangField($link_rewrite);
         $res = false;
         $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
         $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
         if ($fieldError === true and $langFieldError === true) {
             // check quantity
             if ($product->quantity == NULL) {
                 $product->quantity = 0;
             }
             // If match ref is specified AND ref product AND ref product already in base, trying to update
             if (Tools::getValue('match_ref') == 1 and $product->reference and Product::existsRefInDatabase($product->reference)) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add`, `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `reference` = "' . $product->reference . '"');
                 $product->id = pSQL($datas['id_product']);
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             } else {
                 if ($product->id and Product::existsInDatabase((int) $product->id, 'product')) {
                     $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product->id);
                     $product->date_add = pSQL($datas['date_add']);
                     $res = $product->update();
                 }
             }
             // If no id_product or update failed
             if (!$res) {
                 if (isset($product->date_add) && $product->date_add != '') {
                     $res = $product->add(false);
                 } else {
                     $res = $product->add();
                 }
             }
         }
         // If both failed, mysql error
         if (!$res) {
             $this->_errors[] = $info['name'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         } else {
             // SpecificPrice (only the basic reduction feature is supported by the import)
             if (isset($info['reduction_price']) and $info['reduction_price'] > 0 or isset($info['reduction_percent']) and $info['reduction_percent'] > 0) {
                 $specificPrice = new SpecificPrice();
                 $specificPrice->id_product = (int) $product->id;
                 $specificPrice->id_shop = (int) Shop::getCurrentShop();
                 $specificPrice->id_currency = 0;
                 $specificPrice->id_country = 0;
                 $specificPrice->id_group = 0;
                 $specificPrice->price = 0.0;
                 $specificPrice->from_quantity = 1;
                 $specificPrice->reduction = (isset($info['reduction_price']) and $info['reduction_price']) ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                 $specificPrice->reduction_type = (isset($info['reduction_price']) and $info['reduction_price']) ? 'amount' : 'percentage';
                 $specificPrice->from = (isset($info['reduction_from']) and Validate::isDate($info['reduction_from'])) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                 $specificPrice->to = (isset($info['reduction_to']) and Validate::isDate($info['reduction_to'])) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                 if (!$specificPrice->add()) {
                     $this->_addProductWarning($info['name'], $product->id, $this->l('Discount is invalid'));
                 }
             }
             if (isset($product->tags) and !empty($product->tags)) {
                 // Delete tags for this id product, for no duplicating error
                 Tag::deleteTagsForProduct($product->id);
                 $tag = new Tag();
                 if (!is_array($product->tags)) {
                     $product->tags = self::createMultiLangField($product->tags);
                     foreach ($product->tags as $key => $tags) {
                         $isTagAdded = $tag->addTags($key, $product->id, $tags);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, $this->l('Tags list') . ' ' . $this->l('is invalid'));
                             break;
                         }
                     }
                 } else {
                     foreach ($product->tags as $key => $tags) {
                         $str = '';
                         foreach ($tags as $one_tag) {
                             $str .= $one_tag . ',';
                         }
                         $str = rtrim($str, ',');
                         $isTagAdded = $tag->addTags($key, $product->id, $str);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, 'Invalid tag(s) (' . $str . ')');
                             break;
                         }
                     }
                 }
             }
             //delete existing images if "delete_existing_images" is set to 1
             if (isset($product->delete_existing_images)) {
                 if ((bool) $product->delete_existing_images) {
                     $product->deleteImages();
                 } elseif (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                     $product->deleteImages();
                 }
             }
             if (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                 $productHasImages = (bool) Image::getImages((int) $cookie->id_lang, (int) $product->id);
                 foreach ($product->image as $key => $url) {
                     if (!empty($url)) {
                         $image = new Image();
                         $image->id_product = (int) $product->id;
                         $image->position = Image::getHighestPosition($product->id) + 1;
                         $image->cover = (!$key and !$productHasImages) ? true : false;
                         $image->legend = self::createMultiLangField($product->name[$defaultLanguageId]);
                         if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                             if (!self::copyImg($product->id, $image->id, $url)) {
                                 $this->_warnings[] = Tools::displayError('Error copying image: ') . $url;
                             }
                         } else {
                             $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
             if (isset($product->id_category)) {
                 $product->updateCategories(array_map('intval', $product->id_category));
             }
             $features = get_object_vars($product);
             foreach ($features as $feature => $value) {
                 if (!strncmp($feature, '#F_', 3) and Tools::strlen($product->{$feature})) {
                     $feature_name = str_replace('#F_', '', $feature);
                     $id_feature = Feature::addFeatureImport($feature_name);
                     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $product->{$feature});
                     Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                 }
             }
         }
     }
     $this->closeCsvFile($handle);
 }
Example #17
0
 /**
  * Set the filters used for the list display
  */
 public function processFilter()
 {
     if (!isset($this->list_id)) {
         $this->list_id = $this->table;
     }
     $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
     if (isset($this->list_id)) {
         foreach ($_POST as $key => $value) {
             if ($value === '') {
                 unset($this->context->cookie->{$prefix . $key});
             } elseif (stripos($key, $this->list_id . 'Filter_') === 0) {
                 $this->context->cookie->{$prefix . $key} = !is_array($value) ? $value : serialize($value);
             } elseif (stripos($key, 'submitFilter') === 0) {
                 $this->context->cookie->{$key} = !is_array($value) ? $value : serialize($value);
             }
         }
         foreach ($_GET as $key => $value) {
             if (stripos($key, $this->list_id . 'Filter_') === 0) {
                 $this->context->cookie->{$prefix . $key} = !is_array($value) ? $value : serialize($value);
             } elseif (stripos($key, 'submitFilter') === 0) {
                 $this->context->cookie->{$key} = !is_array($value) ? $value : serialize($value);
             }
             if (stripos($key, $this->list_id . 'Orderby') === 0 && Validate::isOrderBy($value)) {
                 if ($value === '' || $value == $this->_defaultOrderBy) {
                     unset($this->context->cookie->{$prefix . $key});
                 } else {
                     $this->context->cookie->{$prefix . $key} = $value;
                 }
             } elseif (stripos($key, $this->list_id . 'Orderway') === 0 && Validate::isOrderWay($value)) {
                 if ($value === '' || $value == $this->_defaultOrderWay) {
                     unset($this->context->cookie->{$prefix . $key});
                 } else {
                     $this->context->cookie->{$prefix . $key} = $value;
                 }
             }
         }
     }
     $filters = $this->context->cookie->getFamily($prefix . $this->list_id . 'Filter_');
     foreach ($filters as $key => $value) {
         /* Extracting filters from $_POST on key filter_ */
         if ($value != null && !strncmp($key, $prefix . $this->list_id . 'Filter_', 7 + Tools::strlen($prefix . $this->list_id))) {
             $key = Tools::substr($key, 7 + Tools::strlen($prefix . $this->list_id));
             /* Table alias could be specified using a ! eg. alias!field */
             $tmp_tab = explode('!', $key);
             $filter = count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0];
             if ($field = $this->filterToField($key, $filter)) {
                 $type = array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false);
                 if (($type == 'date' || $type == 'datetime') && is_string($value)) {
                     $value = Tools::unSerialize($value);
                 }
                 $key = isset($tmp_tab[1]) ? $tmp_tab[0] . '.`' . $tmp_tab[1] . '`' : '`' . $tmp_tab[0] . '`';
                 // Assignement by reference
                 if (array_key_exists('tmpTableFilter', $field)) {
                     $sql_filter =& $this->_tmpTableFilter;
                 } elseif (array_key_exists('havingFilter', $field)) {
                     $sql_filter =& $this->_filterHaving;
                 } else {
                     $sql_filter =& $this->_filter;
                 }
                 /* Only for date filtering (from, to) */
                 if (is_array($value)) {
                     if (isset($value[0]) && !empty($value[0])) {
                         if (!Validate::isDate($value[0])) {
                             $this->errors[] = Tools::displayError('The \'From\' date format is invalid (YYYY-MM-DD)');
                         } else {
                             $sql_filter .= ' AND ' . pSQL($key) . ' >= \'' . pSQL(Tools::dateFrom($value[0])) . '\'';
                         }
                     }
                     if (isset($value[1]) && !empty($value[1])) {
                         if (!Validate::isDate($value[1])) {
                             $this->errors[] = Tools::displayError('The \'To\' date format is invalid (YYYY-MM-DD)');
                         } else {
                             $sql_filter .= ' AND ' . pSQL($key) . ' <= \'' . pSQL(Tools::dateTo($value[1])) . '\'';
                         }
                     }
                 } else {
                     $sql_filter .= ' AND ';
                     $check_key = $key == $this->identifier || $key == '`' . $this->identifier . '`';
                     if ($type == 'int' || $type == 'bool') {
                         $sql_filter .= ($check_key || $key == '`active`' ? 'a.' : '') . pSQL($key) . ' = ' . (int) $value . ' ';
                     } elseif ($type == 'decimal') {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' = ' . (double) $value . ' ';
                     } elseif ($type == 'select') {
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' = \'' . pSQL($value) . '\' ';
                     } else {
                         if ($type == 'price') {
                             $value = (double) str_replace(',', '.', $value);
                         }
                         $sql_filter .= ($check_key ? 'a.' : '') . pSQL($key) . ' LIKE \'%' . pSQL($value) . '%\' ';
                     }
                 }
             }
         }
     }
 }
Example #18
0
    /**
     * Return carts thats have not been converted in orders
     *
     * @param string $dateFrom Select only cart updated after this date
     * @param string $dateTo Select only cart updated before this date
     * @return array Carts
     * @deprecated
     */
    static function getNonOrderedCarts($dateFrom, $dateTo)
    {
        Tools::displayAsDeprecated();
        if (!Validate::isDate($dateFrom) or !Validate::isDate($dateTo)) {
            die(Tools::displayError());
        }
        return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT cart.`id_cart`, cart.`date_upd`, c.`id_customer` AS id_customer, c.`lastname` AS customer_lastname, c.`firstname` AS customer_firstname,
		SUM(cp.`quantity`) AS nb_products,
		COUNT(cd.`id_cart`) AS nb_discounts
		FROM `' . _DB_PREFIX_ . 'cart` cart
		LEFT JOIN `' . _DB_PREFIX_ . 'cart_product` cp ON cart.`id_cart` = cp.`id_cart`
		LEFT JOIN `' . _DB_PREFIX_ . 'cart_discount` cd ON cart.`id_cart` = cd.`id_cart`
		LEFT JOIN `' . _DB_PREFIX_ . 'customer` c ON cart.`id_customer` = c.`id_customer`
		WHERE cart.`id_cart` NOT IN (SELECT `id_cart` FROM `' . _DB_PREFIX_ . 'orders`)
		AND TO_DAYS(cart.`date_upd`) >= TO_DAYS(\'' . pSQL(strftime('%Y-%m-%d %H:%M:%S', strtotime($dateFrom))) . '\')
		AND TO_DAYS(cart.`date_upd`) <= TO_DAYS(\'' . pSQL(strftime('%Y-%m-%d %H:%M:%S', strtotime($dateTo))) . '\')
		GROUP BY cart.`id_cart`, cp.`id_cart`, cd.`id_cart`
		ORDER BY cart.`date_upd` DESC');
    }
Example #19
0
 /**
  * Display date regarding to language preferences
  *
  * @param string $date Date to display format UNIX
  * @param integer $id_lang Language id
  * @param boolean $full With time or not (optional)
  * @return string Date
  */
 public static function displayDate($date, $id_lang, $full = false, $separator = '-')
 {
     if (!$date or !($time = strtotime($date))) {
         return $date;
     }
     if (!Validate::isDate($date) or !Validate::isBool($full)) {
         die(self::displayError('Invalid date'));
     }
     $language = Language::getLanguage((int) $id_lang);
     return date($full ? $language['date_format_full'] : $language['date_format_lite'], $time);
 }
Example #20
0
 /**
  * Update product download
  *
  * @param object $product Product
  * @return bool
  */
 public function updateDownloadProduct($product, $edit = 0)
 {
     if ((int) Tools::getValue('is_virtual_file') == 1) {
         if (isset($_FILES['virtual_product_file_uploader']) && $_FILES['virtual_product_file_uploader']['size'] > 0) {
             $virtual_product_filename = ProductDownload::getNewFilename();
             $helper = new HelperUploader('virtual_product_file_uploader');
             $files = $helper->setPostMaxSize(Tools::getOctets(ini_get('upload_max_filesize')))->setSavePath(_PS_DOWNLOAD_DIR_)->upload($_FILES['virtual_product_file_uploader'], $virtual_product_filename);
         } else {
             $virtual_product_filename = Tools::getValue('virtual_product_filename', ProductDownload::getNewFilename());
         }
         $product->setDefaultAttribute(0);
         //reset cache_default_attribute
         if (Tools::getValue('virtual_product_expiration_date') && !Validate::isDate(Tools::getValue('virtual_product_expiration_date'))) {
             if (!Tools::getValue('virtual_product_expiration_date')) {
                 $this->errors[] = Tools::displayError('The expiration-date attribute is required.');
                 return false;
             }
         }
         // Trick's
         if ($edit == 1) {
             $id_product_download = (int) ProductDownload::getIdFromIdProduct((int) $product->id);
             if (!$id_product_download) {
                 $id_product_download = (int) Tools::getValue('virtual_product_id');
             }
         } else {
             $id_product_download = Tools::getValue('virtual_product_id');
         }
         $is_shareable = Tools::getValue('virtual_product_is_shareable');
         $virtual_product_name = Tools::getValue('virtual_product_name');
         $virtual_product_nb_days = Tools::getValue('virtual_product_nb_days');
         $virtual_product_nb_downloable = Tools::getValue('virtual_product_nb_downloable');
         $virtual_product_expiration_date = Tools::getValue('virtual_product_expiration_date');
         $download = new ProductDownload((int) $id_product_download);
         $download->id_product = (int) $product->id;
         $download->display_filename = $virtual_product_name;
         $download->filename = $virtual_product_filename;
         $download->date_add = date('Y-m-d H:i:s');
         $download->date_expiration = $virtual_product_expiration_date ? $virtual_product_expiration_date . ' 23:59:59' : '';
         $download->nb_days_accessible = (int) $virtual_product_nb_days;
         $download->nb_downloadable = (int) $virtual_product_nb_downloable;
         $download->active = 1;
         $download->is_shareable = (int) $is_shareable;
         if ($download->save()) {
             return true;
         }
     } else {
         /* unactive download product if checkbox not checked */
         if ($edit == 1) {
             $id_product_download = (int) ProductDownload::getIdFromIdProduct((int) $product->id);
             if (!$id_product_download) {
                 $id_product_download = (int) Tools::getValue('virtual_product_id');
             }
         } else {
             $id_product_download = ProductDownload::getIdFromIdProduct($product->id);
         }
         if (!empty($id_product_download)) {
             $product_download = new ProductDownload((int) $id_product_download);
             $product_download->date_expiration = date('Y-m-d H:i:s', time() - 1);
             $product_download->active = 0;
             return $product_download->save();
         }
     }
     return false;
 }
Example #21
0
 /**
  * Manage page processing
  *
  * @global string $currentIndex Current URL in order to keep current Tab
  */
 public function postProcess()
 {
     global $currentIndex, $cookie;
     if (!isset($this->table)) {
         return false;
     }
     // set token
     $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
     // Sub included tab postProcessing
     $this->includeSubTab('postProcess', array('status', 'submitAdd1', 'submitDel', 'delete', 'submitFilter', 'submitReset'));
     /* Delete object image */
     if (isset($_GET['deleteImage'])) {
         if (Validate::isLoadedObject($object = $this->loadObject())) {
             if ($object->deleteImage()) {
                 Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&' . $this->identifier . '=' . Tools::getValue($this->identifier) . '&conf=7&token=' . $token);
             }
         }
         $this->_errors[] = Tools::displayError('An error occurred during image deletion (cannot load object).');
     } elseif (isset($_GET['delete' . $this->table])) {
         if ($this->tabAccess['delete'] === '1') {
             if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) {
                 // check if request at least one object with noZeroObject
                 if (isset($object->noZeroObject) and sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1) {
                     $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                 } else {
                     if ($this->deleted) {
                         $object->deleteImage();
                         $object->deleted = 1;
                         if ($object->update()) {
                             Tools::redirectAdmin($currentIndex . '&conf=1&token=' . $token);
                         }
                     } elseif ($object->delete()) {
                         Tools::redirectAdmin($currentIndex . '&conf=1&token=' . $token);
                     }
                     $this->_errors[] = Tools::displayError('An error occurred during deletion.');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif ((isset($_GET['status' . $this->table]) or isset($_GET['status'])) and Tools::getValue($this->identifier)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Validate::isLoadedObject($object = $this->loadObject())) {
                 if ($object->toggleStatus()) {
                     Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = (int) Tools::getValue('id_category') and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token);
                 } else {
                     $this->_errors[] = Tools::displayError('An error occurred while updating status.');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         }
     } elseif (isset($_GET['position'])) {
         if ($this->tabAccess['edit'] !== '1') {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         } elseif (!Validate::isLoadedObject($object = $this->loadObject())) {
             $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
         } elseif (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) {
             $this->_errors[] = Tools::displayError('Failed to update the position.');
         } else {
             Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = (int) Tools::getValue($this->identifier)) ? '&' . $this->identifier . '=' . $id_category : '') . '&token=' . $token);
         }
         Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = (int) Tools::getValue('id_category') and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token);
     } elseif (Tools::getValue('submitDel' . $this->table)) {
         if ($this->tabAccess['delete'] === '1') {
             if (isset($_POST[$this->table . 'Box'])) {
                 $object = new $this->className();
                 if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) {
                     $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                 } else {
                     $result = true;
                     if ($this->deleted) {
                         foreach (Tools::getValue($this->table . 'Box') as $id) {
                             $toDelete = new $this->className($id);
                             $toDelete->deleted = 1;
                             $result = $result and $toDelete->update();
                         }
                     } else {
                         $result = $object->deleteSelection(Tools::getValue($this->table . 'Box'));
                     }
                     if ($result) {
                         Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token);
                     }
                     $this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('You must select at least one element to delete.');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif (Tools::getValue('submitAdd' . $this->table)) {
         /* Checking fields validity */
         $this->validateRules();
         if (!sizeof($this->_errors)) {
             $id = (int) Tools::getValue($this->identifier);
             /* Object update */
             if (isset($id) and !empty($id)) {
                 if ($this->tabAccess['edit'] === '1' or $this->table == 'employee' and $cookie->id_employee == Tools::getValue('id_employee') and Tools::isSubmit('updateemployee')) {
                     $object = new $this->className($id);
                     if (Validate::isLoadedObject($object)) {
                         /* Specific to objects which must not be deleted */
                         if ($this->deleted and $this->beforeDelete($object)) {
                             // Create new one with old objet values
                             $objectNew = new $this->className($object->id);
                             $objectNew->id = NULL;
                             $objectNew->date_add = '';
                             $objectNew->date_upd = '';
                             // Update old object to deleted
                             $object->deleted = 1;
                             $object->update();
                             // Update new object with post values
                             $this->copyFromPost($objectNew, $this->table);
                             $result = $objectNew->add();
                             if (Validate::isLoadedObject($objectNew)) {
                                 $this->afterDelete($objectNew, $object->id);
                             }
                         } else {
                             $this->copyFromPost($object, $this->table);
                             $result = $object->update();
                             $this->afterUpdate($object);
                         }
                         if (!$result) {
                             $this->_errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')';
                         } elseif ($this->postImage($object->id) and !sizeof($this->_errors)) {
                             $parent_id = (int) Tools::getValue('id_parent', 1);
                             // Specific back redirect
                             if ($back = Tools::getValue('back')) {
                                 Tools::redirectAdmin(urldecode($back) . '&conf=4');
                             }
                             // Specific scene feature
                             if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1') {
                                 Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=4&updatescene&token=' . $token);
                             }
                             // Save and stay on same form
                             if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                                 Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=4&update' . $this->table . '&token=' . $token);
                             }
                             // Save and back to parent
                             if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
                                 Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=4&token=' . $token);
                             }
                             // Default behavior (save and back)
                             Tools::redirectAdmin($currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=4&token=' . $token);
                         }
                     } else {
                         $this->_errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                     }
                 } else {
                     $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
                 }
             } else {
                 if ($this->tabAccess['add'] === '1') {
                     $object = new $this->className();
                     $this->copyFromPost($object, $this->table);
                     if (!$object->add()) {
                         $this->_errors[] = Tools::displayError('An error occurred while creating object.') . ' <b>' . $this->table . ' (' . mysql_error() . ')</b>';
                     } elseif ($_POST[$this->identifier] = $object->id and $this->postImage($object->id) and !sizeof($this->_errors) and $this->_redirect) {
                         $parent_id = (int) Tools::getValue('id_parent', 1);
                         $this->afterAdd($object);
                         // Save and stay on same form
                         if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                             Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=3&update' . $this->table . '&token=' . $token);
                         }
                         // Save and back to parent
                         if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
                             Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=3&token=' . $token);
                         }
                         // Default behavior (save and back)
                         Tools::redirectAdmin($currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=3&token=' . $token);
                     }
                 } else {
                     $this->_errors[] = Tools::displayError('You do not have permission to add here.');
                 }
             }
         }
         $this->_errors = array_unique($this->_errors);
     } elseif (isset($_POST['submitReset' . $this->table])) {
         $filters = $cookie->getFamily($this->table . 'Filter_');
         foreach ($filters as $cookieKey => $filter) {
             if (strncmp($cookieKey, $this->table . 'Filter_', 7 + Tools::strlen($this->table)) == 0) {
                 $key = substr($cookieKey, 7 + Tools::strlen($this->table));
                 /* Table alias could be specified using a ! eg. alias!field */
                 $tmpTab = explode('!', $key);
                 $key = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0];
                 if (array_key_exists($key, $this->fieldsDisplay)) {
                     unset($cookie->{$cookieKey});
                 }
             }
         }
         if (isset($cookie->{'submitFilter' . $this->table})) {
             unset($cookie->{'submitFilter' . $this->table});
         }
         if (isset($cookie->{$this->table . 'Orderby'})) {
             unset($cookie->{$this->table . 'Orderby'});
         }
         if (isset($cookie->{$this->table . 'Orderway'})) {
             unset($cookie->{$this->table . 'Orderway'});
         }
         unset($_POST);
     } elseif (Tools::getValue('submitOptions' . $this->table)) {
         $this->updateOptions($token);
     } elseif (Tools::isSubmit('submitFilter' . $this->table) or $cookie->{'submitFilter' . $this->table} !== false) {
         $_POST = array_merge($cookie->getFamily($this->table . 'Filter_'), isset($_POST) ? $_POST : array());
         foreach ($_POST as $key => $value) {
             /* Extracting filters from $_POST on key filter_ */
             if ($value != NULL and !strncmp($key, $this->table . 'Filter_', 7 + Tools::strlen($this->table))) {
                 $key = Tools::substr($key, 7 + Tools::strlen($this->table));
                 /* Table alias could be specified using a ! eg. alias!field */
                 $tmpTab = explode('!', $key);
                 $filter = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0];
                 if ($field = $this->filterToField($key, $filter)) {
                     $type = array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false);
                     if (($type == 'date' or $type == 'datetime') and is_string($value)) {
                         $value = unserialize($value);
                     }
                     $key = isset($tmpTab[1]) ? $tmpTab[0] . '.`' . $tmpTab[1] . '`' : '`' . $tmpTab[0] . '`';
                     if (array_key_exists('tmpTableFilter', $field)) {
                         $sqlFilter =& $this->_tmpTableFilter;
                     } elseif (array_key_exists('havingFilter', $field)) {
                         $sqlFilter =& $this->_filterHaving;
                     } else {
                         $sqlFilter =& $this->_filter;
                     }
                     /* Only for date filtering (from, to) */
                     if (is_array($value)) {
                         if (isset($value[0]) and !empty($value[0])) {
                             if (!Validate::isDate($value[0])) {
                                 $this->_errors[] = Tools::displayError('\'from:\' date format is invalid (YYYY-MM-DD)');
                             } else {
                                 $sqlFilter .= ' AND ' . pSQL($key) . ' >= \'' . pSQL(Tools::dateFrom($value[0])) . '\'';
                             }
                         }
                         if (isset($value[1]) and !empty($value[1])) {
                             if (!Validate::isDate($value[1])) {
                                 $this->_errors[] = Tools::displayError('\'to:\' date format is invalid (YYYY-MM-DD)');
                             } else {
                                 $sqlFilter .= ' AND ' . pSQL($key) . ' <= \'' . pSQL(Tools::dateTo($value[1])) . '\'';
                             }
                         }
                     } else {
                         $sqlFilter .= ' AND ';
                         if ($type == 'int' or $type == 'bool') {
                             $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`' or $key == '`active`') ? 'a.' : '') . pSQL($key) . ' = ' . (int) $value . ' ';
                         } elseif ($type == 'decimal') {
                             $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`') ? 'a.' : '') . pSQL($key) . ' = ' . (double) $value . ' ';
                         } elseif ($type == 'select') {
                             $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`') ? 'a.' : '') . pSQL($key) . ' = \'' . pSQL($value) . '\' ';
                         } else {
                             $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`') ? 'a.' : '') . pSQL($key) . ' LIKE \'%' . pSQL($value) . '%\' ';
                         }
                     }
                 }
             }
         }
     } elseif (Tools::isSubmit('submitFields') and $this->requiredDatabase and $this->tabAccess['add'] === '1' and $this->tabAccess['delete'] === '1') {
         if (!is_array($fields = Tools::getValue('fieldsBox'))) {
             $fields = array();
         }
         $object = new $this->className();
         if (!$object->addFieldsRequiredDatabase($fields)) {
             $this->_errors[] = Tools::displayError('Error in updating required fields');
         } else {
             Tools::redirectAdmin($currentIndex . '&conf=4&token=' . $token);
         }
     }
 }
Example #22
0
 public static function displayDate($date, $id_lang = null, $full = false, $separator = null)
 {
     if ($id_lang !== null) {
         Tools::displayParameterAsDeprecated('id_lang');
     }
     if ($separator !== null) {
         Tools::displayParameterAsDeprecated('separator');
     }
     if (!$date || !($time = strtotime($date))) {
         return $date;
     }
     if ($date == '0000-00-00 00:00:00' || $date == '0000-00-00') {
         return '';
     }
     if (!Validate::isDate($date) || !Validate::isBool($full)) {
         throw new PrestaShopException('Invalid date');
     }
     $date_format = $full ? Configuration::get('smartdataformat') : Configuration::get('smartdataformat');
     return date($date_format, $time);
 }
Example #23
0
 /**
  * Display date regarding to language preferences
  *
  * @param string $date Date to display format UNIX
  * @param integer $id_lang Language id DEPRECATED
  * @param boolean $full With time or not (optional)
  * @param string $separator DEPRECATED
  *
  * @return string Date
  */
 public static function displayDate($date, $id_lang = null, $full = false, $separator = null)
 {
     if ($id_lang !== null) {
         Tools::displayParameterAsDeprecated('id_lang');
     }
     if ($separator !== null) {
         Tools::displayParameterAsDeprecated('separator');
     }
     if (!$date || !($time = strtotime($date))) {
         return $date;
     }
     if ($date == '0000-00-00 00:00:00' || $date == '0000-00-00') {
         return '';
     }
     if (!Validate::isDate($date) || !Validate::isBool($full)) {
         throw new PrestaShopException('Invalid date');
     }
     $context = Context::getContext();
     $date_format = $full ? $context->language->date_format_full : $context->language->date_format_lite;
     return date($date_format, $time);
 }
Example #24
0
 /**
  * @param $id_carrier
  * @param bool $product_oos
  * @param null $date
  *
  * @return array|bool returns the min & max delivery date
  */
 private function _getDatesOfDelivery($id_carrier, $product_oos = false, $date = null)
 {
     if (!(int) $id_carrier) {
         return false;
     }
     $carrier_rule = $this->_getCarrierRuleWithIdCarrier((int) $id_carrier);
     if (empty($carrier_rule)) {
         return false;
     }
     if ($date != null and Validate::isDate($date)) {
         $date_now = strtotime($date);
     } else {
         $date_now = time();
     }
     // Date on timestamp format
     if ($product_oos) {
         $date_now += Configuration::get('DOD_EXTRA_TIME_PRODUCT_OOS') * 24 * 3600;
     }
     if (!Configuration::get('DOD_PREPARATION_SATURDAY') and date('l', $date_now) == 'Saturday') {
         $date_now += 24 * 3600;
     }
     if (!Configuration::get('DOD_PREPARATION_SUNDAY') and date('l', $date_now) == 'Sunday') {
         $date_now += 24 * 3600;
     }
     $date_minimal_time = $date_now + $carrier_rule['minimal_time'] * 24 * 3600 + Configuration::get('DOD_EXTRA_TIME_PREPARATION') * 24 * 3600;
     $date_maximal_time = $date_now + $carrier_rule['maximal_time'] * 24 * 3600 + Configuration::get('DOD_EXTRA_TIME_PREPARATION') * 24 * 3600;
     if (!$carrier_rule['delivery_saturday'] and date('l', $date_minimal_time) == 'Saturday') {
         $date_minimal_time += 24 * 3600;
         $date_maximal_time += 24 * 3600;
     }
     if (!$carrier_rule['delivery_saturday'] and date('l', $date_maximal_time) == 'Saturday') {
         $date_maximal_time += 24 * 3600;
     }
     if (!$carrier_rule['delivery_sunday'] and date('l', $date_minimal_time) == 'Sunday') {
         $date_minimal_time += 24 * 3600;
         $date_maximal_time += 24 * 3600;
     }
     if (!$carrier_rule['delivery_sunday'] and date('l', $date_maximal_time) == 'Sunday') {
         $date_maximal_time += 24 * 3600;
     }
     /*
     
     // Do not remove this commentary, it's usefull to allow translations of months and days in the translator tool
     
     $this->l('Sunday');
     $this->l('Monday');
     $this->l('Tuesday');
     $this->l('Wednesday');
     $this->l('Thursday');
     $this->l('Friday');
     $this->l('Saturday');
     
     $this->l('January');
     $this->l('February');
     $this->l('March');
     $this->l('April');
     $this->l('May');
     $this->l('June');
     $this->l('July');
     $this->l('August');
     $this->l('September');
     $this->l('October');
     $this->l('November');
     $this->l('December');
     */
     $date_minimal_string = '';
     $date_maximal_string = '';
     $date_format = preg_split('/([a-z])/Ui', Configuration::get('DOD_DATE_FORMAT'), NULL, PREG_SPLIT_DELIM_CAPTURE);
     foreach ($date_format as $elmt) {
         if ($elmt == 'l' or $elmt == 'F') {
             $date_minimal_string .= $this->l(date($elmt, $date_minimal_time));
             $date_maximal_string .= $this->l(date($elmt, $date_maximal_time));
         } elseif (preg_match('/[a-z]/Ui', $elmt)) {
             $date_minimal_string .= date($elmt, $date_minimal_time);
             $date_maximal_string .= date($elmt, $date_maximal_time);
         } else {
             $date_minimal_string .= $elmt;
             $date_maximal_string .= $elmt;
         }
     }
     return array(array($date_minimal_string, $date_minimal_time), array($date_maximal_string, $date_maximal_time));
 }
Example #25
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();
 }
 public static function ensure_date_custom_field()
 {
     $kkxeclu = "conf";
     ${"GLOBALS"}["kiynxrt"] = "idx";
     ${$kkxeclu} = Configuration::getMultiple(array("AGILE_MS_SELLER_DATE1", "AGILE_MS_SELLER_DATE2", "AGILE_MS_SELLER_DATE3", "AGILE_MS_SELLER_DATE4", "AGILE_MS_SELLER_DATE5"));
     for (${${"GLOBALS"}["kiynxrt"]} = 1; ${${"GLOBALS"}["mqkxjudxxy"]} <= 5; ${${"GLOBALS"}["mqkxjudxxy"]}++) {
         ${"GLOBALS"}["xfqhmhyn"] = "conf";
         $irrdgsew = "idx";
         $wwectyjfh = "idx";
         if (!${${"GLOBALS"}["xfqhmhyn"]}["AGILE_MS_SELLER_DATE" . ${${"GLOBALS"}["mqkxjudxxy"]}] or !isset($_POST["ams_custom_date" . ${$irrdgsew}]) or !Validate::isDate($_POST["ams_custom_date" . ${$wwectyjfh}])) {
             $_POST["ams_custom_date" . ${${"GLOBALS"}["mqkxjudxxy"]}] = "1900-01-01";
         }
     }
 }
 /**
  * Update product download
  *
  * @param object $product Product
  */
 public function updateDownloadProduct($product)
 {
     /* add or update a virtual product */
     if (Tools::getValue('is_virtual_good') == 'true') {
         if (!Tools::getValue('virtual_product_name')) {
             $this->_errors[] = $this->l('the field') . ' <b>' . $this->l('display filename') . '</b> ' . $this->l('is required');
             return false;
         }
         if (!Tools::getValue('virtual_product_nb_days')) {
             $this->_errors[] = $this->l('the field') . ' <b>' . $this->l('number of days') . '</b> ' . $this->l('is required');
             return false;
         }
         if (Tools::getValue('virtual_product_expiration_date') and !Validate::isDate(Tools::getValue('virtual_product_expiration_date'))) {
             $this->_errors[] = $this->l('the field') . ' <b>' . $this->l('expiration date') . '</b> ' . $this->l('is not valid');
             return false;
         }
         // The oos behavior MUST be "Deny orders" for virtual products
         if (Tools::getValue('out_of_stock') != 0) {
             $this->_errors[] = $this->l('The "when out of stock" behavior selection must be "deny order" for virtual products');
             return false;
         }
         $download = new ProductDownload(Tools::getValue('virtual_product_id'));
         $download->id_product = $product->id;
         $download->display_filename = Tools::getValue('virtual_product_name');
         $download->physically_filename = Tools::getValue('virtual_product_filename') ? Tools::getValue('virtual_product_filename') : $download->getNewFilename();
         $download->date_deposit = date('Y-m-d H:i:s');
         $download->date_expiration = Tools::getValue('virtual_product_expiration_date') ? Tools::getValue('virtual_product_expiration_date') . ' 23:59:59' : '';
         $download->nb_days_accessible = Tools::getValue('virtual_product_nb_days');
         $download->nb_downloadable = Tools::getValue('virtual_product_nb_downloable');
         $download->active = 1;
         if ($download->save()) {
             return true;
         }
     } else {
         /* unactive download product if checkbox not checked */
         if ($id_product_download = ProductDownload::getIdFromIdProduct($product->id)) {
             $productDownload = new ProductDownload($id_product_download);
             $productDownload->date_expiration = date('Y-m-d H:i:s', time() - 1);
             $productDownload->active = 0;
             return $productDownload->save();
         }
     }
     return false;
 }
 /**
  * Update product download
  *
  * @param object $product Product
  * @return bool
  */
 public function updateDownloadProduct($product, $edit = 0)
 {
     $is_virtual_file = (int) Tools::getValue('is_virtual_file');
     // add or update a virtual product
     if (Tools::getValue('is_virtual_good') == 'true') {
         $product->setDefaultAttribute(0);
         //reset cache_default_attribute
         if (Tools::getValue('virtual_product_expiration_date') && !Validate::isDate(Tools::getValue('virtual_product_expiration_date') && !empty($is_virtual_file))) {
             if (!Tools::getValue('virtual_product_expiration_date')) {
                 $this->errors[] = Tools::displayError('The expiration-date attribute is required.');
                 return false;
             }
         }
         // Trick's
         if ($edit == 1) {
             $id_product_download = (int) ProductDownload::getIdFromIdProduct((int) $product->id);
             if (!$id_product_download) {
                 $id_product_download = (int) Tools::getValue('virtual_product_id');
             }
         } else {
             $id_product_download = Tools::getValue('virtual_product_id');
         }
         $is_shareable = Tools::getValue('virtual_product_is_shareable');
         $virtual_product_name = Tools::getValue('virtual_product_name');
         $virtual_product_filename = Tools::getValue('virtual_product_filename');
         $virtual_product_nb_days = Tools::getValue('virtual_product_nb_days');
         $virtual_product_nb_downloable = Tools::getValue('virtual_product_nb_downloable');
         $virtual_product_expiration_date = Tools::getValue('virtual_product_expiration_date');
         if ($virtual_product_filename) {
             $filename = $virtual_product_filename;
         } else {
             $filename = ProductDownload::getNewFilename();
         }
         $download = new ProductDownload((int) $id_product_download);
         $download->id_product = (int) $product->id;
         $download->display_filename = $virtual_product_name;
         $download->filename = $filename;
         $download->date_add = date('Y-m-d H:i:s');
         $download->date_expiration = $virtual_product_expiration_date ? $virtual_product_expiration_date . ' 23:59:59' : '';
         $download->nb_days_accessible = (int) $virtual_product_nb_days;
         $download->nb_downloadable = (int) $virtual_product_nb_downloable;
         $download->active = 1;
         $download->is_shareable = (int) $is_shareable;
         if ($download->save()) {
             return true;
         }
     } else {
         /* unactive download product if checkbox not checked */
         if ($edit == 1) {
             $id_product_download = (int) ProductDownload::getIdFromIdProduct((int) $product->id);
             if (!$id_product_download) {
                 $id_product_download = (int) Tools::getValue('virtual_product_id');
             }
         } else {
             $id_product_download = ProductDownload::getIdFromIdProduct($product->id);
         }
         if (!empty($id_product_download)) {
             $product_download = new ProductDownload((int) $id_product_download);
             $product_download->date_expiration = date('Y-m-d H:i:s', time() - 1);
             $product_download->active = 0;
             return $product_download->save();
         }
     }
     return false;
 }
Example #29
0
    public static function setPageTime($id_connections, $id_page, $time_start, $time)
    {
        if (!Validate::isUnsignedId($id_connections) or !Validate::isUnsignedId($id_page) or !Validate::isDate($time_start)) {
            return;
        }
        // Limited to 5 minutes because more than 5 minutes is considered as an error
        if ($time > 300000) {
            $time = 300000;
        }
        Db::getInstance()->Execute('
		UPDATE `' . _DB_PREFIX_ . 'connections_page`
		SET `time_end` = `time_start` + INTERVAL ' . (int) ($time / 1000) . ' SECOND
		WHERE `id_connections` = ' . (int) $id_connections . '
		AND `id_page` = ' . (int) $id_page . '
		AND `time_start` = \'' . pSQL($time_start) . '\'');
    }
 public function postProcess()
 {
     if (Tools::isSubmit('submitDateRealTime')) {
         if ($use_realtime = (int) Tools::getValue('submitDateRealTime')) {
             $this->context->employee->stats_date_from = date('Y-m-d');
             $this->context->employee->stats_date_to = date('Y-m-d');
             $this->context->employee->stats_compare_option = HelperCalendar::DEFAULT_COMPARE_OPTION;
             $this->context->employee->stats_compare_from = null;
             $this->context->employee->stats_compare_to = null;
             $this->context->employee->update();
         }
         Configuration::updateValue('PS_DASHBOARD_USE_PUSH', $use_realtime);
     }
     if (Tools::isSubmit('submitDateRange')) {
         if (!Validate::isDate(Tools::getValue('date_from')) || !Validate::isDate(Tools::getValue('date_to'))) {
             $this->errors[] = Tools::displayError('The selected date range is not valid.');
         }
         if (Tools::getValue('datepicker_compare')) {
             if (!Validate::isDate(Tools::getValue('compare_date_from')) || !Validate::isDate(Tools::getValue('compare_date_to'))) {
                 $this->errors[] = Tools::displayError('The selected date range is not valid.');
             }
         }
         if (!count($this->errors)) {
             $this->context->employee->stats_date_from = Tools::getValue('date_from');
             $this->context->employee->stats_date_to = Tools::getValue('date_to');
             $this->context->employee->preselect_date_range = Tools::getValue('preselectDateRange');
             if (Tools::getValue('datepicker_compare')) {
                 $this->context->employee->stats_compare_from = Tools::getValue('compare_date_from');
                 $this->context->employee->stats_compare_to = Tools::getValue('compare_date_to');
                 $this->context->employee->stats_compare_option = Tools::getValue('compare_date_option');
             } else {
                 $this->context->employee->stats_compare_from = null;
                 $this->context->employee->stats_compare_to = null;
                 $this->context->employee->stats_compare_option = HelperCalendar::DEFAULT_COMPARE_OPTION;
             }
             $this->context->employee->update();
         }
     }
     parent::postProcess();
 }