Пример #1
0
 /**
  * Start forms process
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     if (Tools::isSubmit('submitMessage')) {
         $idOrder = (int) Tools::getValue('id_order');
         $msgText = Tools::getValue('msgText');
         if (!$idOrder || !Validate::isUnsignedId($idOrder)) {
             $this->errors[] = Tools::displayError('The order is no longer valid.');
         } elseif (empty($msgText)) {
             $this->errors[] = Tools::displayError('The message cannot be blank.');
         } elseif (!Validate::isMessage($msgText)) {
             $this->errors[] = Tools::displayError('This message is invalid (HTML is not allowed).');
         }
         if (!count($this->errors)) {
             $order = new Order($idOrder);
             if (Validate::isLoadedObject($order) && $order->id_customer == $this->context->customer->id) {
                 //check if a thread already exist
                 $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($this->context->customer->email, $order->id);
                 $cm = new CustomerMessage();
                 if (!$id_customer_thread) {
                     $ct = new CustomerThread();
                     $ct->id_contact = 0;
                     $ct->id_customer = (int) $order->id_customer;
                     $ct->id_shop = (int) $this->context->shop->id;
                     if (($id_product = (int) Tools::getValue('id_product')) && $order->orderContainProduct((int) $id_product)) {
                         $ct->id_product = $id_product;
                     }
                     $ct->id_order = (int) $order->id;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $this->context->customer->email;
                     $ct->status = 'open';
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 } else {
                     $ct = new CustomerThread((int) $id_customer_thread);
                 }
                 $cm->id_customer_thread = $ct->id;
                 $cm->message = $msgText;
                 $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                 $cm->add();
                 if (!Configuration::get('PS_MAIL_EMAIL_MESSAGE')) {
                     $to = strval(Configuration::get('PS_SHOP_EMAIL'));
                 } else {
                     $to = new Contact((int) Configuration::get('PS_MAIL_EMAIL_MESSAGE'));
                     $to = strval($to->email);
                 }
                 $toName = strval(Configuration::get('PS_SHOP_NAME'));
                 $customer = $this->context->customer;
                 if (Validate::isLoadedObject($customer)) {
                     Mail::Send($this->context->language->id, 'order_customer_comment', Mail::l('Message from a customer'), array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{email}' => $customer->email, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => Tools::nl2br($msgText)), $to, $toName, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 }
                 if (Tools::getValue('ajax') != 'true') {
                     Tools::redirect('index.php?controller=order-detail&id_order=' . (int) $idOrder);
                 }
                 $this->context->smarty->assign('message_confirmation', true);
             } else {
                 $this->errors[] = Tools::displayError('Order not found');
             }
         }
     }
 }
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $order_details = AphOrderDetail::getList($order->id);
     foreach ($order_details as &$order_detail) {
         $products[$order_detail['id_order_detail']]['delivery_date'] = $order_detail['delivery_date'];
         $products[$order_detail['id_order_detail']]['delivery_time_from'] = $order_detail['delivery_time_from'];
         $products[$order_detail['id_order_detail']]['delivery_time_to'] = $order_detail['delivery_time_to'];
     }
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         // Get total customized quantity for current product
         $customized_product_quantity = 0;
         if (is_array($product['customizedDatas'])) {
             foreach ($product['customizedDatas'] as $customizationPerAddress) {
                 foreach ($customizationPerAddress as $customizationId => $customization) {
                     $customized_product_quantity += (int) $customization['quantity'];
                 }
             }
         }
         $product['customized_product_quantity'] = $customized_product_quantity;
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
         $product['amount_refundable_tax_incl'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] <= 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->l('This product is out of stock: ') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
             $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
             if (!empty($warehouse_location)) {
                 $product['warehouse_location'] = $warehouse_location;
             } else {
                 $product['warehouse_location'] = false;
             }
         } else {
             $product['warehouse_name'] = '--';
             $product['warehouse_location'] = false;
         }
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $order, 'products' => $products, 'customer' => $customer)));
     $options_time = array();
     $time_slice = Configuration::get('APH_CALENDAR_TIME_SLICE');
     for ($hours = 0; $hours < 24; $hours++) {
         // the interval for hours is '1'
         for ($mins = 0; $mins < 60; $mins += $time_slice) {
             // the interval for mins is 'APH_CALENDAR_TIME_SLICE'
             $options_time[str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($mins, 2, '0', STR_PAD_LEFT)] = str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($mins, 2, '0', STR_PAD_LEFT);
         }
     }
     $this->tpl_view_vars['options_time'] = $options_time;
     $employees = array();
     $e = AphEmployeeProduct::getEmployeesByShop((int) Context::getContext()->shop->id);
     foreach ($e as $employee) {
         $employees[$employee['id_employee']] = $employee['fullName'];
     }
     $this->tpl_view_vars['employees'] = $employees;
     $helper = new HelperView($this);
     $this->setHelperDisplay($helper);
     $helper->tpl_vars = $this->getTemplateViewVars();
     $helper->base_folder = $this->getTemplatePath() . 'aph_orders/helpers/';
     $helper->base_tpl = 'view/view.tpl';
     $view = $helper->generateView();
     return $view;
 }
    public function preProcess()
    {
        parent::preProcess();
        if (self::$cookie->isLogged()) {
            self::$smarty->assign('isLogged', 1);
            $customer = new Customer((int) self::$cookie->id_customer);
            if (!Validate::isLoadedObject($customer)) {
                die(Tools::displayError('Customer not found'));
            }
            $products = array();
            $orders = array();
            $getOrders = Db::getInstance()->ExecuteS('
				SELECT id_order
				FROM ' . _DB_PREFIX_ . 'orders
				WHERE id_customer = ' . (int) $customer->id . ' ORDER BY date_add');
            foreach ($getOrders as $row) {
                $order = new Order($row['id_order']);
                $date = explode(' ', $order->date_add);
                $orders[$row['id_order']] = Tools::displayDate($date[0], self::$cookie->id_lang);
                $tmp = $order->getProducts();
                foreach ($tmp as $key => $val) {
                    $products[$val['product_id']] = $val['product_name'];
                }
            }
            $orderList = '';
            foreach ($orders as $key => $val) {
                $orderList .= '<option value="' . $key . '" ' . ((int) Tools::getValue('id_order') == $key ? 'selected' : '') . ' >' . $key . ' -- ' . $val . '</option>';
            }
            $orderedProductList = '';
            foreach ($products as $key => $val) {
                $orderedProductList .= '<option value="' . $key . '" ' . ((int) Tools::getValue('id_product') == $key ? 'selected' : '') . ' >' . $val . '</option>';
            }
            self::$smarty->assign('orderList', $orderList);
            self::$smarty->assign('orderedProductList', $orderedProductList);
        }
        if (Tools::isSubmit('submitMessage')) {
            $fileAttachment = NULL;
            if (isset($_FILES['fileUpload']['name']) and !empty($_FILES['fileUpload']['name']) and !empty($_FILES['fileUpload']['tmp_name'])) {
                $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
                $filename = uniqid() . substr($_FILES['fileUpload']['name'], -5);
                $fileAttachment['content'] = file_get_contents($_FILES['fileUpload']['tmp_name']);
                $fileAttachment['name'] = $_FILES['fileUpload']['name'];
                $fileAttachment['mime'] = $_FILES['fileUpload']['type'];
            }
            $message = Tools::htmlentitiesUTF8(Tools::getValue('message'));
            if (!($from = trim(Tools::getValue('from'))) or !Validate::isEmail($from)) {
                $this->errors[] = Tools::displayError('Invalid e-mail address');
            } elseif (!($message = nl2br2($message))) {
                $this->errors[] = Tools::displayError('Message cannot be blank');
            } elseif (!Validate::isCleanHtml($message)) {
                $this->errors[] = Tools::displayError('Invalid message');
            } elseif (!($id_contact = (int) Tools::getValue('id_contact')) or !Validate::isLoadedObject($contact = new Contact((int) $id_contact, (int) self::$cookie->id_lang))) {
                $this->errors[] = Tools::displayError('Please select a subject on the list.');
            } elseif (!empty($_FILES['fileUpload']['name']) and $_FILES['fileUpload']['error'] != 0) {
                $this->errors[] = Tools::displayError('An error occurred during the file upload');
            } elseif (!empty($_FILES['fileUpload']['name']) and !in_array(substr($_FILES['fileUpload']['name'], -4), $extension) and !in_array(substr($_FILES['fileUpload']['name'], -5), $extension)) {
                $this->errors[] = Tools::displayError('Bad file extension');
            } else {
                if ((int) self::$cookie->id_customer) {
                    $customer = new Customer((int) self::$cookie->id_customer);
                } else {
                    $customer = new Customer();
                    $customer->getByEmail($from);
                }
                $contact = new Contact($id_contact, self::$cookie->id_lang);
                if (!($id_customer_thread = (int) Tools::getValue('id_customer_thread') and (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') or $id_customer_thread = (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.email = \'' . pSQL($from) . '\' AND cm.id_order = ' . (int) Tools::getValue('id_order') . ''))) {
                    $fields = Db::getInstance()->ExecuteS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) Tools::getValue('id_order') . ')');
                    $score = 0;
                    foreach ($fields as $key => $row) {
                        $tmp = 0;
                        if ((int) $row['id_customer'] and $row['id_customer'] != $customer->id and $row['email'] != $from) {
                            continue;
                        }
                        if ($row['id_order'] != 0 and Tools::getValue('id_order') != $row['id_order']) {
                            continue;
                        }
                        if ($row['email'] == $from) {
                            $tmp += 4;
                        }
                        if ($row['id_contact'] == $id_contact) {
                            $tmp++;
                        }
                        if (Tools::getValue('id_product') != 0 and $row['id_product'] == Tools::getValue('id_product')) {
                            $tmp += 2;
                        }
                        if ($tmp >= 5 and $tmp >= $score) {
                            $score = $tmp;
                            $id_customer_thread = $row['id_customer_thread'];
                        }
                    }
                }
                $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . '
					ORDER BY date_add DESC');
                if ($old_message == htmlentities($message, ENT_COMPAT, 'UTF-8')) {
                    self::$smarty->assign('alreadySent', 1);
                    $contact->email = '';
                    $contact->customer_service = 0;
                }
                if (!empty($contact->email)) {
                    if (Mail::Send((int) self::$cookie->id_lang, 'contact', Mail::l('Message from contact form'), array('{email}' => $from, '{message}' => stripslashes($message)), $contact->email, $contact->name, $from, (int) self::$cookie->id_customer ? $customer->firstname . ' ' . $customer->lastname : '', $fileAttachment) and Mail::Send((int) self::$cookie->id_lang, 'contact_form', Mail::l('Your message has been correctly sent'), array('{message}' => stripslashes($message)), $from)) {
                        self::$smarty->assign('confirmation', 1);
                    } else {
                        $this->errors[] = Tools::displayError('An error occurred while sending message.');
                    }
                }
                if ($contact->customer_service) {
                    if ((int) $id_customer_thread) {
                        $ct = new CustomerThread($id_customer_thread);
                        $ct->status = 'open';
                        $ct->id_lang = (int) self::$cookie->id_lang;
                        $ct->id_contact = (int) $id_contact;
                        if ($id_order = (int) Tools::getValue('id_order')) {
                            $ct->id_order = $id_order;
                        }
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->update();
                    } else {
                        $ct = new CustomerThread();
                        if (isset($customer->id)) {
                            $ct->id_customer = (int) $customer->id;
                        }
                        if ($id_order = (int) Tools::getValue('id_order')) {
                            $ct->id_order = $id_order;
                        }
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->id_contact = (int) $id_contact;
                        $ct->id_lang = (int) self::$cookie->id_lang;
                        $ct->email = $from;
                        $ct->status = 'open';
                        $ct->token = Tools::passwdGen(12);
                        $ct->add();
                    }
                    if ($ct->id) {
                        $cm = new CustomerMessage();
                        $cm->id_customer_thread = $ct->id;
                        $cm->message = htmlentities($message, ENT_COMPAT, 'UTF-8');
                        if (isset($filename) and rename($_FILES['fileUpload']['tmp_name'], _PS_MODULE_DIR_ . '../upload/' . $filename)) {
                            $cm->file_name = $filename;
                        }
                        $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                        $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                        if ($cm->add()) {
                            if (empty($contact->email)) {
                                Mail::Send((int) self::$cookie->id_lang, 'contact_form', Mail::l('Your message has been correctly sent'), array('{message}' => stripslashes($message)), $from);
                            }
                            self::$smarty->assign('confirmation', 1);
                        } else {
                            $this->errors[] = Tools::displayError('An error occurred while sending message.');
                        }
                    } else {
                        $this->errors[] = Tools::displayError('An error occurred while sending message.');
                    }
                }
                if (count($this->errors) > 1) {
                    array_unique($this->errors);
                }
            }
        }
    }
Пример #4
0
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = $this->trans('The order cannot be found within your database.', array(), 'Admin.OrdersCustomers.Notification');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = $this->trans('Order #%id% (%ref%) - %firstname% %lastname%', array('%id%' => $order->id, '%ref%' => $order->reference, '%firstname%' => $customer->firstname, '%lastname%' => $customer->lastname), 'Admin.OrdersCustomers.Feature');
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->trans('Shop: %s', array(), 'Admin.OrdersCustomers.Feature'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         // Get total customized quantity for current product
         $customized_product_quantity = 0;
         if (is_array($product['customizedDatas'])) {
             foreach ($product['customizedDatas'] as $customizationPerAddress) {
                 foreach ($customizationPerAddress as $customizationId => $customization) {
                     $customized_product_quantity += (int) $customization['quantity'];
                 }
             }
         }
         $product['customized_product_quantity'] = $customized_product_quantity;
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
         $product['amount_refundable_tax_incl'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] <= 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->trans('This product is out of stock: ', array(), 'Admin.OrdersCustomers.Notification') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
             $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
             if (!empty($warehouse_location)) {
                 $product['warehouse_location'] = $warehouse_location;
             } else {
                 $product['warehouse_location'] = false;
             }
         } else {
             $product['warehouse_name'] = '--';
             $product['warehouse_location'] = false;
         }
     }
     // Package management for order
     foreach ($products as &$product) {
         $pack_items = $product['cache_is_pack'] ? Pack::getItemTable($product['id_product'], $this->context->language->id, true) : array();
         foreach ($pack_items as &$pack_item) {
             $pack_item['current_stock'] = StockAvailable::getQuantityAvailableByProduct($pack_item['id_product'], $pack_item['id_product_attribute'], $pack_item['id_shop']);
             // if the current stock requires a warning
             if ($product['current_stock'] <= 0 && $display_out_of_stock_warning) {
                 $this->displayWarning($this->trans('This product, included in package (' . $product['product_name'] . ') is out of stock: ', array(), 'Admin.OrdersCustomers.Notification') . ' ' . $pack_item['product_name']);
             }
             $this->setProductImageInformations($pack_item);
             if ($pack_item['image'] != null) {
                 $name = 'product_mini_' . (int) $pack_item['id_product'] . (isset($pack_item['id_product_attribute']) ? '_' . (int) $pack_item['id_product_attribute'] : '') . '.jpg';
                 // generate image cache, only for back office
                 $pack_item['image_tag'] = ImageManager::thumbnail(_PS_IMG_DIR_ . 'p/' . $pack_item['image']->getExistingImgPath() . '.jpg', $name, 45, 'jpg');
                 if (file_exists(_PS_TMP_IMG_DIR_ . $name)) {
                     $pack_item['image_size'] = getimagesize(_PS_TMP_IMG_DIR_ . $name);
                 } else {
                     $pack_item['image_size'] = false;
                 }
             }
         }
         $product['pack_items'] = $pack_items;
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->access('edit'), 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'carrier_list' => $this->getCarrierList($order), 'recalculate_shipping_cost' => (int) Configuration::get('PS_ORDER_RECALCULATE_SHIPPING'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $order, 'products' => $products, 'customer' => $customer)));
     return parent::renderView();
 }
Пример #5
0
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] == 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->l('This product is out of stock: ') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
         } else {
             $product['warehouse_name'] = '--';
         }
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'));
     return parent::renderView();
 }
Пример #6
0
    /**
     * Start forms process
     * @see FrontController::postProcess()
     */
    public function postProcess()
    {
        if (Tools::isSubmit('submitMessage')) {
            $fileAttachment = null;
            if (isset($_FILES['fileUpload']['name']) && !empty($_FILES['fileUpload']['name']) && !empty($_FILES['fileUpload']['tmp_name'])) {
                $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
                $filename = uniqid() . substr($_FILES['fileUpload']['name'], -5);
                $fileAttachment['content'] = file_get_contents($_FILES['fileUpload']['tmp_name']);
                $fileAttachment['name'] = $_FILES['fileUpload']['name'];
                $fileAttachment['mime'] = $_FILES['fileUpload']['type'];
            }
            $message = Tools::getValue('message');
            // Html entities is not usefull, iscleanHtml check there is no bad html tags.
            if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
                $this->errors[] = Tools::displayError('Invalid e-mail address');
            } else {
                if (!$message) {
                    $this->errors[] = Tools::displayError('Message cannot be blank');
                } else {
                    if (!Validate::isCleanHtml($message)) {
                        $this->errors[] = Tools::displayError('Invalid message');
                    } else {
                        if (!($id_contact = (int) Tools::getValue('id_contact')) || !Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))) {
                            $this->errors[] = Tools::displayError('Please select a subject from the list.');
                        } else {
                            if (!empty($_FILES['fileUpload']['name']) && $_FILES['fileUpload']['error'] != 0) {
                                $this->errors[] = Tools::displayError('An error occurred during the file upload');
                            } else {
                                if (!empty($_FILES['fileUpload']['name']) && !in_array(substr($_FILES['fileUpload']['name'], -4), $extension) && !in_array(substr($_FILES['fileUpload']['name'], -5), $extension)) {
                                    $this->errors[] = Tools::displayError('Bad file extension');
                                } else {
                                    $customer = $this->context->customer;
                                    if (!$customer->id) {
                                        $customer->getByEmail($from);
                                    }
                                    $contact = new Contact($id_contact, $this->context->language->id);
                                    if (!(($id_customer_thread = (int) Tools::getValue('id_customer_thread')) && (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') || ($id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, (int) Tools::getValue('id_order'))))) {
                                        $fields = Db::getInstance()->executeS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) Tools::getValue('id_order') . ')');
                                        $score = 0;
                                        foreach ($fields as $key => $row) {
                                            $tmp = 0;
                                            if ((int) $row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from) {
                                                continue;
                                            }
                                            if ($row['id_order'] != 0 && Tools::getValue('id_order') != $row['id_order']) {
                                                continue;
                                            }
                                            if ($row['email'] == $from) {
                                                $tmp += 4;
                                            }
                                            if ($row['id_contact'] == $id_contact) {
                                                $tmp++;
                                            }
                                            if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product')) {
                                                $tmp += 2;
                                            }
                                            if ($tmp >= 5 && $tmp >= $score) {
                                                $score = $tmp;
                                                $id_customer_thread = $row['id_customer_thread'];
                                            }
                                        }
                                    }
                                    $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread)
					WHERE cc.id_customer_thread = ' . (int) $id_customer_thread . ' AND cc.id_shop = ' . (int) $this->context->shop->id . '
					ORDER BY cm.date_add DESC');
                                    if ($old_message == $message) {
                                        $this->context->smarty->assign('alreadySent', 1);
                                        $contact->email = '';
                                        $contact->customer_service = 0;
                                    }
                                    if (!empty($contact->email)) {
                                        $id_order = (int) Tools::getValue('id_order', 0);
                                        $order = new Order($id_order);
                                        $mail_var_list = array('{email}' => $from, '{message}' => Tools::nl2br(stripslashes($message)), '{id_order}' => $id_order, '{order_name}' => $order->getUniqReference(), '{attached_file}' => isset($_FILES['fileUpload'], $_FILES['fileUpload']['name']) ? $_FILES['fileUpload']['name'] : '');
                                        if (Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form'), $mail_var_list, $contact->email, $contact->name, $from, $customer->id ? $customer->firstname . ' ' . $customer->lastname : '', $fileAttachment) && Mail::Send($this->context->language->id, 'contact_form', Mail::l('Your message has been correctly sent'), $mail_var_list, $from)) {
                                            $this->context->smarty->assign('confirmation', 1);
                                        } else {
                                            $this->errors[] = Tools::displayError('An error occurred while sending message.');
                                        }
                                    }
                                    if ($contact->customer_service) {
                                        if ((int) $id_customer_thread) {
                                            $ct = new CustomerThread($id_customer_thread);
                                            $ct->status = 'open';
                                            $ct->id_lang = (int) $this->context->language->id;
                                            $ct->id_contact = (int) $id_contact;
                                            if ($id_order = (int) Tools::getValue('id_order')) {
                                                $ct->id_order = $id_order;
                                            }
                                            if ($id_product = (int) Tools::getValue('id_product')) {
                                                $ct->id_product = $id_product;
                                            }
                                            $ct->update();
                                        } else {
                                            $ct = new CustomerThread();
                                            if (isset($customer->id)) {
                                                $ct->id_customer = (int) $customer->id;
                                            }
                                            $ct->id_shop = (int) $this->context->shop->id;
                                            if ($id_order = (int) Tools::getValue('id_order')) {
                                                $ct->id_order = $id_order;
                                            }
                                            if ($id_product = (int) Tools::getValue('id_product')) {
                                                $ct->id_product = $id_product;
                                            }
                                            $ct->id_contact = (int) $id_contact;
                                            $ct->id_lang = (int) $this->context->language->id;
                                            $ct->email = $from;
                                            $ct->status = 'open';
                                            $ct->token = Tools::passwdGen(12);
                                            $ct->add();
                                        }
                                        if ($ct->id) {
                                            $cm = new CustomerMessage();
                                            $cm->id_customer_thread = $ct->id;
                                            $cm->message = Tools::htmlentitiesUTF8($message);
                                            if (isset($filename) && rename($_FILES['fileUpload']['tmp_name'], _PS_MODULE_DIR_ . '../upload/' . $filename)) {
                                                $cm->file_name = $filename;
                                            }
                                            $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                                            $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                                            if ($cm->add()) {
                                                if (empty($contact->email)) {
                                                    $var_list = array('{order_name}' => '-', '{attached_file}' => '-', '{message}' => stripslashes($message));
                                                    if ($ct->id_order) {
                                                        $order = new Order($ct->id_order);
                                                        $var_list['{order_name}'] = $order->reference;
                                                    }
                                                    if (isset($filename)) {
                                                        $var_list['{attached_file}'] = $_FILES['fileUpload']['name'];
                                                    }
                                                    Mail::Send($this->context->language->id, 'contact_form', Mail::l('Your message has been correctly sent'), $var_list, $from);
                                                }
                                                $this->context->smarty->assign('confirmation', 1);
                                            } else {
                                                $this->errors[] = Tools::displayError('An error occurred while sending message.');
                                            }
                                        } else {
                                            $this->errors[] = Tools::displayError('An error occurred while sending message.');
                                        }
                                    }
                                    if (count($this->errors) > 1) {
                                        array_unique($this->errors);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
Пример #7
0
 public function postProcess()
 {
     if (Tools::isSubmit('submitMessage')) {
         $idOrder = (int) Tools::getValue('id_order');
         $msgText = Tools::getValue('msgText');
         if (!$idOrder || !Validate::isUnsignedId($idOrder)) {
             $this->errors[] = Tools::displayError('The order is no longer valid.');
         } elseif (empty($msgText)) {
             $this->errors[] = Tools::displayError('The message cannot be blank.');
         } elseif (!Validate::isMessage($msgText)) {
             $this->errors[] = Tools::displayError('This message is invalid (HTML is not allowed).');
         }
         if (!count($this->errors)) {
             $order = new Order($idOrder);
             if (Validate::isLoadedObject($order) && $order->id_customer == $this->context->customer->id) {
                 //check if a thread already exist
                 $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($this->context->customer->email, $order->id);
                 $id_product = (int) Tools::getValue('id_product');
                 $cm = new CustomerMessage();
                 if (!$id_customer_thread) {
                     $ct = new CustomerThread();
                     $ct->id_contact = 0;
                     $ct->id_customer = (int) $order->id_customer;
                     $ct->id_shop = (int) $this->context->shop->id;
                     if ($id_product && $order->orderContainProduct((int) $id_product)) {
                         $ct->id_product = $id_product;
                     }
                     $ct->id_order = (int) $order->id;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $this->context->customer->email;
                     $ct->status = 'open';
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 } else {
                     $ct = new CustomerThread((int) $id_customer_thread);
                 }
                 $cm->id_customer_thread = $ct->id;
                 if ($id_product && $order->orderContainProduct((int) $id_product)) {
                     $cm->id_product = $id_product;
                 }
                 $cm->message = $msgText;
                 $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                 $cm->add();
                 if (!Configuration::get('PS_MAIL_EMAIL_MESSAGE')) {
                     $to = strval(Configuration::get('PS_SHOP_EMAIL'));
                 } else {
                     $to = new Contact((int) Configuration::get('PS_MAIL_EMAIL_MESSAGE'));
                     $to = strval($to->email);
                 }
                 $toName = strval(Configuration::get('PS_SHOP_NAME'));
                 $customer = $this->context->customer;
                 $product = new Product($id_product);
                 $product_name = '';
                 if (Validate::isLoadedObject($product) && isset($product->name[(int) $this->context->language->id])) {
                     $product_name = $product->name[(int) $this->context->language->id];
                 }
                 if (Validate::isLoadedObject($customer)) {
                     Mail::Send($this->context->language->id, 'order_customer_comment', Mail::l('Message from a customer'), array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{email}' => $customer->email, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => Tools::nl2br($msgText), '{product_name}' => $product_name), $to, $toName, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 }
                 if (Tools::getValue('ajax') != 'true') {
                     Tools::redirect('index.php?controller=order-detail&id_order=' . (int) $idOrder);
                 }
                 $this->context->smarty->assign('message_confirmation', true);
             } else {
                 $this->errors[] = Tools::displayError('Order not found');
             }
         }
     }
     if (Tools::isSubmit('markAsReceived')) {
         $idOrder = (int) Tools::getValue('id_order');
         $order = new Order($idOrder);
         if (Validate::isLoadedObject($order)) {
             if ($order->getCurrentState() == 15) {
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState(3, $order);
                 // 16: Ready for Production
                 //var_dump($order,$new_history);
                 $myfile = fopen(PS_PRODUCT_IMG_PATH . "/orders/" . $order->reference . ".txt", "w") or die("Unable to open file!");
                 $txt = "Order Confirmed\n Order Reference: " . $order->reference;
                 fwrite($myfile, $txt);
                 fclose($myfile);
                 $new_history->addWithemail(true);
             }
             $this->context->smarty->assign('receipt_confirmation', true);
         } else {
             $this->_errors[] = Tools::displayError('Error: Invalid order number');
         }
     }
 }
 public static function getPendingMessages()
 {
     return CustomerThread::getTotalCustomerThreads('status LIKE "%pending%" OR status = "open"' . Shop::addSqlRestriction());
 }
Пример #9
0
    public function saveContact()
    {
        $message = Tools::getValue('message');
        // Html entities is not usefull, iscleanHtml check there is no bad html tags.
        if (!($from = trim(Tools::getValue('email'))) || !Validate::isEmail($from)) {
            $this->errors[] = Tools::displayError('Invalid email address.');
        } elseif (!$message) {
            $this->errors[] = Tools::displayError('The message cannot be blank.');
        } elseif (!Validate::isCleanHtml($message)) {
            $this->errors[] = Tools::displayError('Invalid message');
        } elseif (!($id_contact = (int) Tools::getValue('id_contact')) || !Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))) {
            $this->errors[] = Tools::displayError('Please select a subject from the list provided. ');
        } else {
            $customer = $this->context->customer;
            if (!$customer->id) {
                $customer->getByEmail($from);
            }
            $id_order = (int) $this->getOrder();
            if (!(($id_customer_thread = (int) Tools::getValue('id_customer_thread')) && (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') || ($id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, $id_order)))) {
                $fields = Db::getInstance()->executeS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) $id_order . ')');
                $score = 0;
                foreach ($fields as $key => $row) {
                    $tmp = 0;
                    if ((int) $row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from) {
                        continue;
                    }
                    if ($row['id_order'] != 0 && $id_order != $row['id_order']) {
                        continue;
                    }
                    if ($row['email'] == $from) {
                        $tmp += 4;
                    }
                    if ($row['id_contact'] == $id_contact) {
                        $tmp++;
                    }
                    if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product')) {
                        $tmp += 2;
                    }
                    if ($tmp >= 5 && $tmp >= $score) {
                        $score = $tmp;
                        $id_customer_thread = $row['id_customer_thread'];
                    }
                }
            }
            $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread)
					WHERE cc.id_customer_thread = ' . (int) $id_customer_thread . ' AND cc.id_shop = ' . (int) $this->context->shop->id . '
					ORDER BY cm.date_add DESC');
            if ($old_message == $message) {
                $this->context->smarty->assign('alreadySent', 1);
                $contact->email = '';
                $contact->customer_service = 0;
            }
            if ($contact->customer_service) {
                if ((int) $id_customer_thread) {
                    $ct = new CustomerThread($id_customer_thread);
                    $ct->status = 'open';
                    $ct->id_lang = (int) $this->context->language->id;
                    $ct->id_contact = (int) $id_contact;
                    $ct->id_order = (int) $id_order;
                    if ($id_product = (int) Tools::getValue('id_product')) {
                        $ct->id_product = $id_product;
                    }
                    $ct->update();
                } else {
                    $ct = new CustomerThread();
                    if (isset($customer->id)) {
                        $ct->id_customer = (int) $customer->id;
                    }
                    $ct->id_shop = (int) $this->context->shop->id;
                    $ct->id_order = (int) $id_order;
                    if ($id_product = (int) Tools::getValue('id_product')) {
                        $ct->id_product = $id_product;
                    }
                    $ct->id_contact = (int) $id_contact;
                    $ct->id_lang = (int) $this->context->language->id;
                    $ct->email = $from;
                    $ct->status = 'open';
                    $ct->token = Tools::passwdGen(12);
                    $ct->add();
                }
                if ($ct->id) {
                    $cm = new CustomerMessage();
                    $cm->id_customer_thread = $ct->id;
                    $cm->message = $message;
                    $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                    $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                    if (!$cm->add()) {
                        $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                    }
                } else {
                    $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                }
            }
            if (!count($this->errors)) {
                $var_list = array('{order_name}' => '-', '{attached_file}' => '-', '{message}' => Tools::nl2br(stripslashes($message)), '{email}' => $from, '{product_name}' => '');
                if (isset($file_attachment['name'])) {
                    $var_list['{attached_file}'] = $file_attachment['name'];
                }
                $id_product = (int) Tools::getValue('id_product');
                if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order) {
                    $order = new Order((int) $ct->id_order);
                    $var_list['{order_name}'] = $order->getUniqReference();
                    $var_list['{id_order}'] = (int) $order->id;
                }
                if ($id_product) {
                    $product = new Product((int) $id_product);
                    if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id])) {
                        $var_list['{product_name}'] = $product->name[Context::getContext()->language->id];
                    }
                }
                if (empty($contact->email)) {
                    Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, null, null);
                } else {
                    if (!Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form') . ' [no_sync]', $var_list, $contact->email, $contact->name, $from, $customer->id ? $customer->firstname . ' ' . $customer->lastname : '') || !Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, $contact->email, $contact->name)) {
                        $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                    }
                }
            }
            $response = new stdClass();
            if ($this->errors) {
                $response->status = '0';
                $response->msg = implode('<br />', $this->errors);
            } else {
                $response->status = 1;
                $response->msg = "Send message success!";
            }
            die(Tools::jsonEncode($response));
            /*
            if (count($this->errors) > 1)
            	array_unique($this->errors);
            elseif (!count($this->errors))
            	$this->context->smarty->assign('confirmation', 1);
            * 
            */
        }
    }
Пример #10
0
 public function postProcess()
 {
     ${${"GLOBALS"}["thtbvco"]} = new Order((int) Tools::getValue("id_order"));
     $difdqhzqxl = "id_order_seller";
     if (!Validate::isLoadedObject(${${"GLOBALS"}["thtbvco"]})) {
         $this->errors[] = Tools::displayError("Order not found or you do not have permission to view this order.");
         return;
     }
     ${"GLOBALS"}["fqitvbmdfl"] = "order";
     ${${"GLOBALS"}["gfrblyem"]} = AgileSellerManager::getObjectOwnerID("order", $order->id);
     ${"GLOBALS"}["bsmpehdujqe"] = "id_customer_seller";
     ${${"GLOBALS"}["taultlaseq"]} = AgileSellerManager::getLinkedSellerID($this->context->customer->id);
     $qjwuyezbnwd = "order";
     if (${$difdqhzqxl} != ${${"GLOBALS"}["taultlaseq"]} || ${${"GLOBALS"}["gfrblyem"]} <= 0 || ${${"GLOBALS"}["bsmpehdujqe"]} <= 0) {
         $this->errors[] = Tools::displayError("You do not have permission to view this order.");
         return;
     }
     if (Tools::isSubmit("submitShippingNumber") && isset(${${"GLOBALS"}["fqitvbmdfl"]})) {
         ${"GLOBALS"}["mllzihk"] = "order_carrier";
         $fdknpwcl = "order_carrier";
         ${$fdknpwcl} = new OrderCarrier(Tools::getValue("id_order_carrier"));
         if (!Validate::isLoadedObject(${${"GLOBALS"}["mllzihk"]})) {
             $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 {
             $order->shipping_number = Tools::getValue("tracking_number");
             $order->update();
             $order_carrier->tracking_number = pSQL(Tools::getValue("tracking_number"));
             if ($order_carrier->update()) {
                 $qvvnrvmsp = "templateVars";
                 ${${"GLOBALS"}["cdmray"]} = new Customer((int) $order->id_customer);
                 $ijyvqhqokid = "carrier";
                 ${"GLOBALS"}["mhbtmrqg"] = "templateVars";
                 ${$ijyvqhqokid} = new Carrier((int) $order_carrier->id_carrier, $order->id_lang);
                 if (!Validate::isLoadedObject(${${"GLOBALS"}["cdmray"]})) {
                     throw new PrestaShopException("Can't load Customer object");
                 }
                 if (!Validate::isLoadedObject(${${"GLOBALS"}["tvqrewgc"]})) {
                     throw new PrestaShopException("Can't load Carrier object");
                 }
                 ${${"GLOBALS"}["mhbtmrqg"]} = array("{followup}" => str_replace("@", $order_carrier->tracking_number, $carrier->url), "{firstname}" => $customer->firstname, "{lastname}" => $customer->lastname, "{id_order}" => $order->id, "{shipping_number}" => $order_carrier->tracking_number, "{order_name}" => $order->getUniqReference());
                 if (@Mail::Send((int) $order->id_lang, "in_transit", Mail::l('Package in transit', (int) $order->id_lang), ${$qvvnrvmsp}, $customer->email, $customer->firstname . " " . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                     ${"GLOBALS"}["rwzquyb"] = "order";
                     Hook::exec("actionAdminOrdersTrackingNumberUpdate", array("order" => ${${"GLOBALS"}["rwzquyb"]}, "customer" => ${${"GLOBALS"}["cdmray"]}, "carrier" => ${${"GLOBALS"}["tvqrewgc"]}), null, false, true, false, $order->id_shop);
                 } 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.");
             }
         }
     } elseif (Tools::isSubmit("submitState") && isset(${$qjwuyezbnwd})) {
         ${${"GLOBALS"}["bfrxhizen"]} = new OrderState(Tools::getValue("id_order_state"));
         if (!Validate::isLoadedObject(${${"GLOBALS"}["bfrxhizen"]})) {
             $this->errors[] = Tools::displayError("Invalid new order status");
         } else {
             ${${"GLOBALS"}["rxsllerec"]} = $order->getCurrentOrderState();
             if ($current_order_state->id != $order_state->id) {
                 $heccerkhiwt = "history";
                 ${$heccerkhiwt} = new OrderHistory();
                 ${"GLOBALS"}["uynetoegv"] = "templateVars";
                 $vriwvgqg = "templateVars";
                 $history->id_order = $order->id;
                 $history->id_employee = 1;
                 $history->changeIdOrderState($order_state->id, $order->id);
                 ${${"GLOBALS"}["tvqrewgc"]} = new Carrier($order->id_carrier, $order->id_lang);
                 ${$vriwvgqg} = array();
                 if ($history->id_order_state == Configuration::get("PS_OS_SHIPPING") && $order->shipping_number) {
                     ${${"GLOBALS"}["nkwobosfw"]} = array("{followup}" => str_replace("@", $order->shipping_number, $carrier->url));
                 } elseif ($history->id_order_state == Configuration::get("PS_OS_CHEQUE")) {
                     ${${"GLOBALS"}["nkwobosfw"]} = array("{cheque_name}" => Configuration::get("CHEQUE_NAME") ? Configuration::get("CHEQUE_NAME") : "", "{cheque_address_html}" => Configuration::get("CHEQUE_ADDRESS") ? nl2br(Configuration::get("CHEQUE_ADDRESS")) : "");
                 } elseif ($history->id_order_state == Configuration::get("PS_OS_BANKWIRE")) {
                     ${${"GLOBALS"}["nkwobosfw"]} = array("{bankwire_owner}" => Configuration::get("BANK_WIRE_OWNER") ? Configuration::get("BANK_WIRE_OWNER") : "", "{bankwire_details}" => Configuration::get("BANK_WIRE_DETAILS") ? nl2br(Configuration::get("BANK_WIRE_DETAILS")) : "", "{bankwire_address}" => Configuration::get("BANK_WIRE_ADDRESS") ? nl2br(Configuration::get("BANK_WIRE_ADDRESS")) : "");
                 }
                 if (!$history->addWithemail(true, ${${"GLOBALS"}["uynetoegv"]})) {
                     $this->errors[] = Tools::displayError("An error occurred while changing the status or was unable to send e-mail to the customer.");
                 }
             } else {
                 $this->errors[] = Tools::displayError("This order is already assigned this status");
             }
         }
         if (empty($this->errors)) {
             self::$smarty->assign("cfmmsg_flag", 1);
         }
     }
     if (Tools::isSubmit("submitMessage")) {
         $ipovlstkh = "idOrder";
         ${${"GLOBALS"}["pfwbejwlah"]} = (int) Tools::getValue("id_order");
         ${${"GLOBALS"}["nioumgdgj"]} = Tools::getValue("msgText");
         ${"GLOBALS"}["tumvnnp"] = "msgText";
         if (!${${"GLOBALS"}["pfwbejwlah"]} || !Validate::isUnsignedId(${$ipovlstkh})) {
             $this->errors[] = Tools::displayError("Order is no longer valid");
         } else {
             if (empty(${${"GLOBALS"}["nioumgdgj"]})) {
                 $this->errors[] = Tools::displayError("Message cannot be blank");
             } else {
                 if (!Validate::isMessage(${${"GLOBALS"}["tumvnnp"]})) {
                     $this->errors[] = Tools::displayError("Message is invalid (HTML is not allowed)");
                 }
             }
         }
         if (!count($this->errors)) {
             $svycwjflohh = "idOrder";
             ${${"GLOBALS"}["thtbvco"]} = new Order(${$svycwjflohh});
             if (Validate::isLoadedObject(${${"GLOBALS"}["thtbvco"]})) {
                 ${"GLOBALS"}["pcdbkuo"] = "cm";
                 ${"GLOBALS"}["qejrcjwlidu"] = "to";
                 ${${"GLOBALS"}["nbpumdloal"]} = new Employee();
                 $iilmenu = "seller";
                 ${$iilmenu} = $emp->getbyEmail($this->context->customer->email);
                 $ucwaikq = "customer";
                 ${$ucwaikq} = new Customer($order->id_customer);
                 ${${"GLOBALS"}["ryhapbx"]} = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                 ${"GLOBALS"}["pnxcso"] = "id_customer_thread";
                 ${${"GLOBALS"}["pcdbkuo"]} = new CustomerMessage();
                 ${"GLOBALS"}["csptele"] = "ct";
                 $pykymotfmtq = "fromName";
                 if (!${${"GLOBALS"}["pnxcso"]}) {
                     ${"GLOBALS"}["azdvluwhw"] = "id_product";
                     ${"GLOBALS"}["fpmtmpmcoy"] = "id_product";
                     $vckfnym = "id_product";
                     ${${"GLOBALS"}["docrub"]} = new CustomerThread();
                     $ct->id_contact = 2;
                     $ct->id_customer = (int) $order->id_customer;
                     $ct->id_shop = (int) $this->context->shop->id;
                     ${$vckfnym} = (int) Tools::getValue("id_product");
                     if (${${"GLOBALS"}["fxogbxc"]} && $order->orderContainProduct(${${"GLOBALS"}["azdvluwhw"]})) {
                         $ct->id_product = ${${"GLOBALS"}["fpmtmpmcoy"]};
                     }
                     $ct->id_order = (int) $order->id;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $customer->email;
                     $ct->status = "open";
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 } else {
                     ${${"GLOBALS"}["csptele"]} = new CustomerThread((int) ${${"GLOBALS"}["ryhapbx"]});
                 }
                 $qlkkcochivs = "msgText";
                 $cm->id_customer_thread = $ct->id;
                 $cm->message = ${${"GLOBALS"}["nioumgdgj"]};
                 $cm->ip_address = ip2long($_SERVER["REMOTE_ADDR"]);
                 $cm->id_employee = $seller->id;
                 $cm->add();
                 $mwsicth = "fromName";
                 ${"GLOBALS"}["lhbflpuhi"] = "customer";
                 ${${"GLOBALS"}["oatuem"]} = $customer->email;
                 ${${"GLOBALS"}["xtxkthxeqll"]} = $customer->firstname . " " . $customer->lastname;
                 ${${"GLOBALS"}["sormbzxw"]} = $seller->email;
                 ${$mwsicth} = $seller->firstname . " " . $seller->lastname;
                 if (Validate::isLoadedObject(${${"GLOBALS"}["lhbflpuhi"]})) {
                     Mail::Send($this->context->language->id, "order_merchant_comment", Mail::l('Message from a seller'), array("{lastname}" => $customer->lastname, "{firstname}" => $customer->firstname, "{email}" => $customer->email, "{id_order}" => (int) $order->id, "{order_name}" => $order->getUniqReference(), "{message}" => Tools::nl2br(${$qlkkcochivs})), ${${"GLOBALS"}["qejrcjwlidu"]}, ${${"GLOBALS"}["xtxkthxeqll"]}, ${${"GLOBALS"}["sormbzxw"]}, ${$pykymotfmtq});
                 }
             } else {
                 $this->errors[] = Tools::displayError("Order not found");
             }
         }
     }
 }
Пример #11
0
 public function sendMessage()
 {
     $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
     $file_attachment = Tools::fileAttachment('fileUpload');
     $message = Tools::getValue('message');
     if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
         $this->context->controller->errors[] = $this->l('Invalid email address.');
     } elseif (!$message) {
         $this->context->controller->errors[] = $this->l('The message cannot be blank.');
     } elseif (!Validate::isCleanHtml($message)) {
         $this->context->controller->errors[] = $this->l('Invalid message');
     } elseif (!($id_contact = (int) Tools::getValue('id_contact')) || !Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))) {
         $this->context->controller->errors[] = $this->l('Please select a subject from the list provided. ');
     } elseif (!empty($file_attachment['name']) && $file_attachment['error'] != 0) {
         $this->context->controller->errors[] = $this->l('An error occurred during the file-upload process.');
     } elseif (!empty($file_attachment['name']) && !in_array(Tools::strtolower(substr($file_attachment['name'], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment['name'], -5)), $extension)) {
         $this->context->controller->errors[] = $this->l('Bad file extension');
     } else {
         $customer = $this->context->customer;
         if (!$customer->id) {
             $customer->getByEmail($from);
         }
         $id_order = (int) Tools::getValue('id_order');
         $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, $id_order);
         if ($contact->customer_service) {
             if ((int) $id_customer_thread) {
                 $ct = new CustomerThread($id_customer_thread);
                 $ct->status = 'open';
                 $ct->id_lang = (int) $this->context->language->id;
                 $ct->id_contact = (int) $id_contact;
                 $ct->id_order = (int) $id_order;
                 if ($id_product = (int) Tools::getValue('id_product')) {
                     $ct->id_product = $id_product;
                 }
                 $ct->update();
             } else {
                 $ct = new CustomerThread();
                 if (isset($customer->id)) {
                     $ct->id_customer = (int) $customer->id;
                 }
                 $ct->id_shop = (int) $this->context->shop->id;
                 $ct->id_order = (int) $id_order;
                 if ($id_product = (int) Tools::getValue('id_product')) {
                     $ct->id_product = $id_product;
                 }
                 $ct->id_contact = (int) $id_contact;
                 $ct->id_lang = (int) $this->context->language->id;
                 $ct->email = $from;
                 $ct->status = 'open';
                 $ct->token = Tools::passwdGen(12);
                 $ct->add();
             }
             if ($ct->id) {
                 $lastMessage = CustomerMessage::getLastMessageForCustomerThread($ct->id);
                 $testFileUpload = isset($file_attachment['rename']) && !empty($file_attachment['rename']);
                 // if last message is the same as new message (and no file upload), do not consider this contact
                 if ($lastMessage != $message || $testFileUpload) {
                     $cm = new CustomerMessage();
                     $cm->id_customer_thread = $ct->id;
                     $cm->message = $message;
                     if ($testFileUpload && rename($file_attachment['tmp_name'], _PS_UPLOAD_DIR_ . basename($file_attachment['rename']))) {
                         $cm->file_name = $file_attachment['rename'];
                         @chmod(_PS_UPLOAD_DIR_ . basename($file_attachment['rename']), 0664);
                     }
                     $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                     $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                     if (!$cm->add()) {
                         $this->context->controller->errors[] = $this->l('An error occurred while sending the message.');
                     }
                 } else {
                     $mailAlreadySend = true;
                 }
             } else {
                 $this->context->controller->errors[] = $this->l('An error occurred while sending the message.');
             }
         }
         if (!count($this->context->controller->errors) && empty($mailAlreadySend)) {
             $var_list = ['{order_name}' => '-', '{attached_file}' => '-', '{message}' => Tools::nl2br(stripslashes($message)), '{email}' => $from, '{product_name}' => ''];
             if (isset($file_attachment['name'])) {
                 $var_list['{attached_file}'] = $file_attachment['name'];
             }
             $id_product = (int) Tools::getValue('id_product');
             if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order) {
                 $order = new Order((int) $ct->id_order);
                 $var_list['{order_name}'] = $order->getUniqReference();
                 $var_list['{id_order}'] = (int) $order->id;
             }
             if ($id_product) {
                 $product = new Product((int) $id_product);
                 if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id])) {
                     $var_list['{product_name}'] = $product->name[Context::getContext()->language->id];
                 }
             }
             if (empty($contact->email)) {
                 Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? $this->trans('Your message has been correctly sent #ct%thread_id% #tc%thread_token%', array('%thread_id%' => $ct->id, '%thread_token%' => $ct->token), 'Emails.Subject') : $this->trans('Your message has been correctly sent', array(), 'Emails.Subject'), $var_list, $from, null, null, null, $file_attachment);
             } else {
                 if (!Mail::Send($this->context->language->id, 'contact', $this->trans('Message from contact form', array(), 'Emails.Subject') . ' [no_sync]', $var_list, $contact->email, $contact->name, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $from) || !Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? $this->trans('Your message has been correctly sent #ct%thread_id% #tc%thread_token%', array('%thread_id%' => $ct->id, '%thread_token%' => $ct->token), 'Emails.Subject') : $this->trans('Your message has been correctly sent', array(), 'Emails.Subject'), $var_list, $from, null, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $contact->email)) {
                     $this->context->controller->errors[] = $this->l('An error occurred while sending the message.');
                 }
             }
         }
         if (!count($this->context->controller->errors)) {
             $this->context->controller->success[] = $this->l('Your message has been successfully sent to our team.');
         }
     }
 }
    /**
     * Imap synchronization method.
     *
     * @return array Errors list.
     */
    public function syncImap()
    {
        if (!($url = Configuration::get('PS_SAV_IMAP_URL')) || !($port = Configuration::get('PS_SAV_IMAP_PORT')) || !($user = Configuration::get('PS_SAV_IMAP_USER')) || !($password = Configuration::get('PS_SAV_IMAP_PWD'))) {
            return array('hasError' => true, 'errors' => array('IMAP configuration is not correct'));
        }
        $conf = Configuration::getMultiple(array('PS_SAV_IMAP_OPT_POP3', 'PS_SAV_IMAP_OPT_NORSH', 'PS_SAV_IMAP_OPT_SSL', 'PS_SAV_IMAP_OPT_VALIDATE-CERT', 'PS_SAV_IMAP_OPT_NOVALIDATE-CERT', 'PS_SAV_IMAP_OPT_TLS', 'PS_SAV_IMAP_OPT_NOTLS'));
        $conf_str = '';
        if ($conf['PS_SAV_IMAP_OPT_POP3']) {
            $conf_str .= '/pop3';
        }
        if ($conf['PS_SAV_IMAP_OPT_NORSH']) {
            $conf_str .= '/norsh';
        }
        if ($conf['PS_SAV_IMAP_OPT_SSL']) {
            $conf_str .= '/ssl';
        }
        if ($conf['PS_SAV_IMAP_OPT_VALIDATE-CERT']) {
            $conf_str .= '/validate-cert';
        }
        if ($conf['PS_SAV_IMAP_OPT_NOVALIDATE-CERT']) {
            $conf_str .= '/novalidate-cert';
        }
        if ($conf['PS_SAV_IMAP_OPT_TLS']) {
            $conf_str .= '/tls';
        }
        if ($conf['PS_SAV_IMAP_OPT_NOTLS']) {
            $conf_str .= '/notls';
        }
        if (!function_exists('imap_open')) {
            return array('hasError' => true, 'errors' => array('imap is not installed on this server'));
        }
        $mbox = @imap_open('{' . $url . ':' . $port . $conf_str . '}', $user, $password);
        //checks if there is no error when connecting imap server
        $errors = imap_errors();
        if (is_array($errors)) {
            $errors = array_unique($errors);
        }
        $str_errors = '';
        $str_error_delete = '';
        if (count($errors) && is_array($errors)) {
            $str_errors = '';
            foreach ($errors as $error) {
                $str_errors .= $error . ', ';
            }
            $str_errors = rtrim(trim($str_errors), ',');
        }
        //checks if imap connexion is active
        if (!$mbox) {
            return array('hasError' => true, 'errors' => array('Cannot connect to the mailbox :<br />' . $str_errors));
        }
        //Returns information about the current mailbox. Returns FALSE on failure.
        $check = imap_check($mbox);
        if (!$check) {
            return array('hasError' => true, 'errors' => array('Fail to get information about the current mailbox'));
        }
        if ($check->Nmsgs == 0) {
            return array('hasError' => true, 'errors' => array('NO message to sync'));
        }
        $result = imap_fetch_overview($mbox, "1:{$check->Nmsgs}", 0);
        $message_errors = array();
        foreach ($result as $overview) {
            //check if message exist in database
            if (isset($overview->subject)) {
                $subject = $overview->subject;
            } else {
                $subject = '';
            }
            //Creating an md5 to check if message has been allready processed
            $md5 = md5($overview->date . $overview->from . $subject . $overview->msgno);
            $exist = Db::getInstance()->getValue('SELECT `md5_header`
						 FROM `' . _DB_PREFIX_ . 'customer_message_sync_imap`
						 WHERE `md5_header` = \'' . pSQL($md5) . '\'');
            if ($exist) {
                if (Configuration::get('PS_SAV_IMAP_DELETE_MSG')) {
                    if (!imap_delete($mbox, $overview->msgno)) {
                        $str_error_delete = ', Fail to delete message';
                    }
                }
            } else {
                //check if subject has id_order
                preg_match('/\\#ct([0-9]*)/', $subject, $matches1);
                preg_match('/\\#tc([0-9-a-z-A-Z]*)/', $subject, $matches2);
                $match_found = false;
                if (isset($matches1[1]) && isset($matches2[1])) {
                    $match_found = true;
                }
                $new_ct = Configuration::get('PS_SAV_IMAP_CREATE_THREADS') && !$match_found && strpos($subject, '[no_sync]') == false;
                $fetch_succeed = true;
                if ($match_found || $new_ct) {
                    if ($new_ct) {
                        // parse from attribute and fix it if needed
                        $from_parsed = array();
                        if (!isset($overview->from) || !preg_match('/<(' . Tools::cleanNonUnicodeSupport('[a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z\\p{L}0-9]+[._a-z\\p{L}0-9-]*\\.[a-z0-9]+') . ')>/', $overview->from, $from_parsed) && !Validate::isEmail($overview->from)) {
                            $message_errors[] = $this->trans('Cannot create message in a new thread.', array(), 'Admin.OrdersCustomers.Notification');
                            continue;
                        }
                        // fix email format: from "Mr Sanders <*****@*****.**>" to "*****@*****.**"
                        $from = $overview->from;
                        if (isset($from_parsed[1])) {
                            $from = $from_parsed[1];
                        }
                        // we want to assign unrecognized mails to the right contact category
                        $contacts = Contact::getContacts($this->context->language->id);
                        if (!$contacts) {
                            continue;
                        }
                        foreach ($contacts as $contact) {
                            if (isset($overview->to) && strpos($overview->to, $contact['email']) !== false) {
                                $id_contact = $contact['id_contact'];
                            }
                        }
                        if (!isset($id_contact)) {
                            // if not use the default contact category
                            $id_contact = $contacts[0]['id_contact'];
                        }
                        $customer = new Customer();
                        $client = $customer->getByEmail($from);
                        //check if we already have a customer with this email
                        $ct = new CustomerThread();
                        if (isset($client->id)) {
                            //if mail is owned by a customer assign to him
                            $ct->id_customer = $client->id;
                        }
                        $ct->email = $from;
                        $ct->id_contact = $id_contact;
                        $ct->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                        $ct->id_shop = $this->context->shop->id;
                        //new customer threads for unrecognized mails are not shown without shop id
                        $ct->status = 'open';
                        $ct->token = Tools::passwdGen(12);
                        $ct->add();
                    } else {
                        $ct = new CustomerThread((int) $matches1[1]);
                    }
                    //check if order exist in database
                    if (Validate::isLoadedObject($ct) && (isset($matches2[1]) && $ct->token == $matches2[1] || $new_ct)) {
                        $structure = imap_bodystruct($mbox, $overview->msgno, '1');
                        if ($structure->type == 0) {
                            $message = imap_fetchbody($mbox, $overview->msgno, '1');
                        } elseif ($structure->type == 1) {
                            $structure = imap_bodystruct($mbox, $overview->msgno, '1.1');
                            $message = imap_fetchbody($mbox, $overview->msgno, '1.1');
                        } else {
                            continue;
                        }
                        switch ($structure->encoding) {
                            case 3:
                                $message = imap_base64($message);
                                break;
                            case 4:
                                $message = imap_qprint($message);
                                break;
                        }
                        $message = iconv($this->getEncoding($structure), 'utf-8', $message);
                        $message = nl2br($message);
                        if (!$message || strlen($message) == 0) {
                            $message_errors[] = $this->trans('The message body is empty, cannot import it.', array(), 'Admin.OrdersCustomers.Notification');
                            $fetch_succeed = false;
                            continue;
                        }
                        $cm = new CustomerMessage();
                        $cm->id_customer_thread = $ct->id;
                        if (empty($message) || !Validate::isCleanHtml($message)) {
                            $str_errors .= Tools::displayError(sprintf('Invalid Message Content for subject: %1s', $subject));
                        } else {
                            try {
                                $cm->message = $message;
                                $cm->add();
                            } catch (PrestaShopException $pse) {
                                $message_errors[] = $this->trans('The message content is not valid, cannot import it.', array(), 'Admin.OrdersCustomers.Notification');
                                $fetch_succeed = false;
                                continue;
                            }
                        }
                    }
                }
                if ($fetch_succeed) {
                    Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customer_message_sync_imap` (`md5_header`) VALUES (\'' . pSQL($md5) . '\')');
                }
            }
        }
        imap_expunge($mbox);
        imap_close($mbox);
        if (sizeof($message_errors) > 0) {
            if (($more_error = $str_errors . $str_error_delete) && strlen($more_error) > 0) {
                $message_errors = array_merge(array($more_error), $message_errors);
            }
            return array('hasError' => true, 'errors' => $message_errors);
        }
        if ($str_errors . $str_error_delete) {
            return array('hasError' => true, 'errors' => array($str_errors . $str_error_delete));
        } else {
            return array('hasError' => false, 'errors' => '');
        }
    }
 public function renderView()
 {
     $neoExchange = new NeoExchanges(Tools::getValue('id_neo_exchange'));
     $order = new Order(Tools::getValue('id_neo_exchange'));
     if (!Validate::isLoadedObject($neoExchange)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($neoExchange->id_customer);
     //$carrier = new Carrier($neoExchange->id_carrier);
     $currency = new Currency((int) $neoExchange->id_currency);
     $buys = new NeoItemsBuyCore(Tools::getValue('id_neo_exchange'));
     $sales = new NeoItemsSalesCore(Tools::getValue('id_neo_exchange'));
     $products = $this->getProducts($buys);
     $products2 = $this->getProducts($sales);
     //$products = $this->getProducts($neoExchange);
     // Carrier module call
     /*$carrier_module_call = null;
             if ($carrier->is_module)
             {
                 $module = Module::getInstanceByName($carrier->external_module_name);
                 if (method_exists($module, 'displayInfoByCart'))
                     $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $neoExchange->id_cart);
             }
     
             // Retrieve addresses information
             $addressInvoice = new Address($neoExchange->id_address_invoice, $this->context->language->id);
             if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state)
                 $invoiceState = new State((int)$addressInvoice->id_state);
     
             if ($neoExchange->id_address_invoice == $neoExchange->id_address_delivery)
             {
                 $addressDelivery = $addressInvoice;
                 if (isset($invoiceState))
                     $deliveryState = $invoiceState;
             }
             else
             {
                 $addressDelivery = new Address($neoExchange->id_address_delivery, $this->context->language->id);
                 if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state)
                     $deliveryState = new State((int)($addressDelivery->id_state));
             }*/
     $this->toolbar_title = sprintf($this->l('Intercambio #%1$d (%2$s) - %3$s %4$s'), $neoExchange->id, $neoExchange->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $neoExchange->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $neoExchange->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     $total_buy = 0;
     $total_sale = 0;
     $products_buy = count($products);
     $products_sale = count($products2);
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         $total_buy += $product['price'];
     }
     foreach ($products2 as &$product) {
         $total_sale += $product['price'];
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $neoExchange->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $neoExchange, 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'customerStats' => $customer->getStats(), 'products' => $products, 'products2' => $products2, 'total_buy' => $total_buy, 'total_sale' => $total_sale, 'products_buy' => $products_buy, 'products_sale' => $products_sale, 'neo_order_shipping_price' => 0, 'orders_total_paid_tax_incl' => $neoExchange->getOrdersTotalPaid(), 'total_paid' => $neoExchange->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($neoExchange->id_customer, $neoExchange->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($neoExchange->id_customer), 'orderMessages' => OrderMessage::getOrderMessages($neoExchange->id_lang), 'messages' => Message::getMessagesByOrderId($neoExchange->id, true), 'history' => $history, 'neoStatus' => NeoStatusCore::getNeoStatus(), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($neoExchange->id), 'currentState' => $neoExchange->getCurrentOrderState(), 'currency' => new Currency($neoExchange->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($neoExchange->id_shop), 'previousOrder' => $neoExchange->getPreviousOrderId(), 'nextOrder' => $neoExchange->getNextOrderId(), 'current_index' => self::$currentIndex, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $neoExchange->getInvoicesCollection(), 'not_paid_invoices_collection' => $neoExchange->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $neoExchange->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)));
     return parent::renderView();
 }
Пример #14
0
    /**
     * Start forms process
     * @see FrontController::postProcess()
     */
    public function postProcess()
    {
        if (Tools::isSubmit('submitMessage')) {
            $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
            $file_attachment = Tools::fileAttachment('fileUpload');
            $message = Tools::getValue('message');
            // Html entities is not usefull, iscleanHtml check there is no bad html tags.
            if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
                $this->errors[] = Tools::displayError('Invalid email address.');
            } elseif (!$message) {
                $this->errors[] = Tools::displayError('The message cannot be blank.');
            } elseif (!Validate::isCleanHtml($message)) {
                $this->errors[] = Tools::displayError('Invalid message');
            } elseif (!($id_contact = (int) Tools::getValue('id_contact')) || !Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))) {
                $this->errors[] = Tools::displayError('Please select a subject from the list provided. ');
            } elseif (!empty($file_attachment['name']) && $file_attachment['error'] != 0) {
                $this->errors[] = Tools::displayError('An error occurred during the file-upload process.');
            } elseif (!empty($file_attachment['name']) && !in_array(Tools::strtolower(substr($file_attachment['name'], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment['name'], -5)), $extension)) {
                $this->errors[] = Tools::displayError('Bad file extension');
            } else {
                $customer = $this->context->customer;
                if (!$customer->id) {
                    $customer->getByEmail($from);
                }
                $id_order = (int) $this->getOrder();
                if (!(($id_customer_thread = (int) Tools::getValue('id_customer_thread')) && (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') || ($id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, $id_order)))) {
                    $fields = Db::getInstance()->executeS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) $id_order . ')');
                    $score = 0;
                    foreach ($fields as $key => $row) {
                        $tmp = 0;
                        if ((int) $row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from) {
                            continue;
                        }
                        if ($row['id_order'] != 0 && $id_order != $row['id_order']) {
                            continue;
                        }
                        if ($row['email'] == $from) {
                            $tmp += 4;
                        }
                        if ($row['id_contact'] == $id_contact) {
                            $tmp++;
                        }
                        if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product')) {
                            $tmp += 2;
                        }
                        if ($tmp >= 5 && $tmp >= $score) {
                            $score = $tmp;
                            $id_customer_thread = $row['id_customer_thread'];
                        }
                    }
                }
                $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread)
					WHERE cc.id_customer_thread = ' . (int) $id_customer_thread . ' AND cc.id_shop = ' . (int) $this->context->shop->id . '
					ORDER BY cm.date_add DESC');
                if ($old_message == $message) {
                    $this->context->smarty->assign('alreadySent', 1);
                    $contact->email = '';
                    $contact->customer_service = 0;
                }
                if ($contact->customer_service) {
                    if ((int) $id_customer_thread) {
                        $ct = new CustomerThread($id_customer_thread);
                        $ct->status = 'open';
                        $ct->id_lang = (int) $this->context->language->id;
                        $ct->id_contact = (int) $id_contact;
                        $ct->id_order = (int) $id_order;
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->update();
                    } else {
                        $ct = new CustomerThread();
                        if (isset($customer->id)) {
                            $ct->id_customer = (int) $customer->id;
                        }
                        $ct->id_shop = (int) $this->context->shop->id;
                        $ct->id_order = (int) $id_order;
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->id_contact = (int) $id_contact;
                        $ct->id_lang = (int) $this->context->language->id;
                        $ct->email = $from;
                        $ct->status = 'open';
                        $ct->token = Tools::passwdGen(12);
                        $ct->add();
                    }
                    if ($ct->id) {
                        $cm = new CustomerMessage();
                        $cm->id_customer_thread = $ct->id;
                        $cm->message = $message;
                        if (isset($file_attachment['rename']) && !empty($file_attachment['rename']) && rename($file_attachment['tmp_name'], _PS_UPLOAD_DIR_ . basename($file_attachment['rename']))) {
                            $cm->file_name = $file_attachment['rename'];
                            @chmod(_PS_UPLOAD_DIR_ . basename($file_attachment['rename']), 0664);
                        }
                        $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                        $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                        if (!$cm->add()) {
                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                        }
                    } else {
                        $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                    }
                }
                if (!count($this->errors)) {
                    $var_list = array('{order_name}' => '-', '{attached_file}' => '-', '{message}' => Tools::nl2br(stripslashes($message)), '{email}' => $from, '{product_name}' => '');
                    if (isset($file_attachment['name'])) {
                        $var_list['{attached_file}'] = $file_attachment['name'];
                    }
                    $id_product = (int) Tools::getValue('id_product');
                    if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order) {
                        $order = new Order((int) $ct->id_order);
                        $var_list['{order_name}'] = $order->getUniqReference();
                        $var_list['{id_order}'] = (int) $order->id;
                    }
                    if ($id_product) {
                        $product = new Product((int) $id_product);
                        if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id])) {
                            $var_list['{product_name}'] = $product->name[Context::getContext()->language->id];
                        }
                    }
                    if (empty($contact->email)) {
                        Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, null, null, $file_attachment);
                    } else {
                        if (!Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form') . ' [no_sync]', $var_list, $contact->email, $contact->name, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $from) || !Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $contact->email)) {
                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                        }
                    }
                }
                if (count($this->errors) > 1) {
                    array_unique($this->errors);
                } elseif (!count($this->errors)) {
                    $this->context->smarty->assign('confirmation', 1);
                }
            }
        }
    }
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         // Get total customized quantity for current product
         $customized_product_quantity = 0;
         if (is_array($product['customizedDatas'])) {
             foreach ($product['customizedDatas'] as $customizationPerAddress) {
                 foreach ($customizationPerAddress as $customizationId => $customization) {
                     $customized_product_quantity += (int) $customization['quantity'];
                 }
             }
         }
         $product['customized_product_quantity'] = $customized_product_quantity;
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
         $product['amount_refundable_tax_incl'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] == 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->l('This product is out of stock: ') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
             $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
             if (!empty($warehouse_location)) {
                 $product['warehouse_location'] = $warehouse_location;
             } else {
                 $product['warehouse_location'] = false;
             }
         } else {
             $product['warehouse_name'] = '--';
             $product['warehouse_location'] = false;
         }
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     //by webkul to get data to show hotel rooms order data on order detail page
     $cart_id = Cart::getCartIdByOrderId(Tools::getValue('id_order'));
     $cart_detail_data = array();
     $cart_detail_data_obj = new HotelCartBookingData();
     $cart_detail_data = $cart_detail_data_obj->getCartCurrentDataByCartId((int) $cart_id);
     if ($cart_detail_data) {
         foreach ($cart_detail_data as $key => $value) {
             $product_image_id = Product::getCover($value['id_product']);
             $link_rewrite = (new Product((int) $value['id_product'], Configuration::get('PS_LANG_DEFAULT')))->link_rewrite[Configuration::get('PS_LANG_DEFAULT')];
             if ($product_image_id) {
                 $cart_detail_data[$key]['image_link'] = $this->context->link->getImageLink($link_rewrite, $product_image_id['id_image'], 'small_default');
             } else {
                 $cart_detail_data[$key]['image_link'] = $this->context->link->getImageLink($link_rewrite, $this->context->language->iso_code . "-default", 'small_default');
             }
             $cart_detail_data[$key]['room_type'] = (new Product((int) $value['id_product']))->name[Configuration::get('PS_LANG_DEFAULT')];
             $cart_detail_data[$key]['room_num'] = (new HotelRoomInformation((int) $value['id_room']))->room_num;
             $cart_detail_data[$key]['date_from'] = (new DateTime($value['date_from']))->format('d-M Y');
             $cart_detail_data[$key]['date_to'] = (new DateTime($value['date_to']))->format('d-M Y');
             $cust_obj = new Customer($value['id_customer']);
             $cart_detail_data[$key]['alloted_cust_name'] = $cust_obj->firstname . ' ' . $cust_obj->lastname;
             $cart_detail_data[$key]['alloted_cust_email'] = $cust_obj->email;
             $cart_detail_data[$key]['avail_rooms_to_swap'] = (new HotelBookingDetail())->getAvailableRoomsForSwaping($value['date_from'], $value['date_to'], $value['id_product'], $value['id_hotel']);
             $obj_booking_dtl = new HotelBookingDetail();
             $num_days = $obj_booking_dtl->getNumberOfDays($cart_detail_data[$key]['date_from'], $cart_detail_data[$key]['date_to']);
             //quantity of product
             $cart_detail_data[$key]['amt_with_qty'] = $value['amount'] * $num_days;
         }
     }
     //end
     //by webkul to send order status on order detail page
     $obj_bookin_detail = new HotelBookingDetail();
     $htl_booking_data_order_id = $obj_bookin_detail->getBookingDataByOrderId(Tools::getValue('id_order'));
     if ($htl_booking_data_order_id) {
         foreach ($htl_booking_data_order_id as $key => $value) {
             $htl_booking_data_order_id[$key]['room_num'] = (new HotelRoomInformation())->getHotelRoomInfoById($value['id_room']);
             $htl_booking_data_order_id[$key]['order_status'] = $value['id_status'];
             $htl_booking_data_order_id[$key]['date_from'] = (new DateTime($value['date_from']))->format('d-M Y');
             $htl_booking_data_order_id[$key]['date_to'] = (new DateTime($value['date_to']))->format('d-M Y');
         }
     }
     $htl_order_status = HotelOrderStatus::getAllHotelOrderStatus();
     //end
     // Smarty assign
     $this->tpl_view_vars = array('htl_booking_order_data' => $htl_booking_data_order_id, 'hotel_order_status' => $htl_order_status, 'cart_detail_data' => $cart_detail_data, 'order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $order, 'products' => $products, 'customer' => $customer)));
     return parent::renderView();
 }
    public function renderView()
    {
        /** @var Customer $customer */
        if (!($customer = $this->loadObject())) {
            return;
        }
        $this->context->customer = $customer;
        $gender = new Gender($customer->id_gender, $this->context->language->id);
        $gender_image = $gender->getImage();
        $customer_stats = $customer->getStats();
        $sql = 'SELECT SUM(total_paid_real) FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = %d AND valid = 1';
        if ($total_customer = Db::getInstance()->getValue(sprintf($sql, $customer->id))) {
            $sql = 'SELECT SQL_CALC_FOUND_ROWS COUNT(*) FROM ' . _DB_PREFIX_ . 'orders WHERE valid = 1 AND id_customer != ' . (int) $customer->id . ' GROUP BY id_customer HAVING SUM(total_paid_real) > %d';
            Db::getInstance()->getValue(sprintf($sql, (int) $total_customer));
            $count_better_customers = (int) Db::getInstance()->getValue('SELECT FOUND_ROWS()') + 1;
        } else {
            $count_better_customers = '-';
        }
        $orders = Order::getCustomerOrders($customer->id, true);
        $total_orders = count($orders);
        for ($i = 0; $i < $total_orders; $i++) {
            $orders[$i]['total_paid_real_not_formated'] = $orders[$i]['total_paid_real'];
            $orders[$i]['total_paid_real'] = Tools::displayPrice($orders[$i]['total_paid_real'], new Currency((int) $orders[$i]['id_currency']));
        }
        $messages = CustomerThread::getCustomerMessages((int) $customer->id);
        $total_messages = count($messages);
        for ($i = 0; $i < $total_messages; $i++) {
            $messages[$i]['message'] = substr(strip_tags(html_entity_decode($messages[$i]['message'], ENT_NOQUOTES, 'UTF-8')), 0, 75);
            $messages[$i]['date_add'] = Tools::displayDate($messages[$i]['date_add'], null, true);
            if (isset(self::$meaning_status[$messages[$i]['status']])) {
                $messages[$i]['status'] = self::$meaning_status[$messages[$i]['status']];
            }
        }
        $groups = $customer->getGroups();
        $total_groups = count($groups);
        for ($i = 0; $i < $total_groups; $i++) {
            $group = new Group($groups[$i]);
            $groups[$i] = array();
            $groups[$i]['id_group'] = $group->id;
            $groups[$i]['name'] = $group->name[$this->default_form_language];
        }
        $total_ok = 0;
        $orders_ok = array();
        $orders_ko = array();
        foreach ($orders as $order) {
            if (!isset($order['order_state'])) {
                $order['order_state'] = $this->l('There is no status defined for this order.');
            }
            if ($order['valid']) {
                $orders_ok[] = $order;
                $total_ok += $order['total_paid_real_not_formated'];
            } else {
                $orders_ko[] = $order;
            }
        }
        $products = $customer->getBoughtProducts();
        $carts = Cart::getCustomerCarts($customer->id);
        $total_carts = count($carts);
        for ($i = 0; $i < $total_carts; $i++) {
            $cart = new Cart((int) $carts[$i]['id_cart']);
            $this->context->cart = $cart;
            $summary = $cart->getSummaryDetails();
            $currency = new Currency((int) $carts[$i]['id_currency']);
            $carrier = new Carrier((int) $carts[$i]['id_carrier']);
            $carts[$i]['id_cart'] = sprintf('%06d', $carts[$i]['id_cart']);
            $carts[$i]['date_add'] = Tools::displayDate($carts[$i]['date_add'], null, true);
            $carts[$i]['total_price'] = Tools::displayPrice($summary['total_price'], $currency);
            $carts[$i]['name'] = $carrier->name;
        }
        $sql = 'SELECT DISTINCT cp.id_product, c.id_cart, c.id_shop, cp.id_shop AS cp_id_shop
				FROM ' . _DB_PREFIX_ . 'cart_product cp
				JOIN ' . _DB_PREFIX_ . 'cart c ON (c.id_cart = cp.id_cart)
				JOIN ' . _DB_PREFIX_ . 'product p ON (cp.id_product = p.id_product)
				WHERE c.id_customer = ' . (int) $customer->id . '
					AND NOT EXISTS (
							SELECT 1
							FROM ' . _DB_PREFIX_ . 'orders o
							JOIN ' . _DB_PREFIX_ . 'order_detail od ON (o.id_order = od.id_order)
							WHERE product_id = cp.id_product AND o.valid = 1 AND o.id_customer = ' . (int) $customer->id . '
						)';
        $interested = Db::getInstance()->executeS($sql);
        $total_interested = count($interested);
        for ($i = 0; $i < $total_interested; $i++) {
            $product = new Product($interested[$i]['id_product'], false, $this->default_form_language, $interested[$i]['id_shop']);
            if (!Validate::isLoadedObject($product)) {
                continue;
            }
            $interested[$i]['url'] = $this->context->link->getProductLink($product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, $this->default_form_language), null, null, $interested[$i]['cp_id_shop']);
            $interested[$i]['id'] = (int) $product->id;
            $interested[$i]['name'] = Tools::htmlentitiesUTF8($product->name);
        }
        $emails = $customer->getLastEmails();
        $connections = $customer->getLastConnections();
        if (!is_array($connections)) {
            $connections = array();
        }
        $total_connections = count($connections);
        for ($i = 0; $i < $total_connections; $i++) {
            $connections[$i]['http_referer'] = $connections[$i]['http_referer'] ? preg_replace('/^www./', '', parse_url($connections[$i]['http_referer'], PHP_URL_HOST)) : $this->l('Direct link');
        }
        $referrers = Referrer::getReferrers($customer->id);
        $total_referrers = count($referrers);
        for ($i = 0; $i < $total_referrers; $i++) {
            $referrers[$i]['date_add'] = Tools::displayDate($referrers[$i]['date_add'], null, true);
        }
        $customerLanguage = new Language($customer->id_lang);
        $shop = new Shop($customer->id_shop);
        $this->tpl_view_vars = array('customer' => $customer, 'gender' => $gender, 'gender_image' => $gender_image, 'registration_date' => Tools::displayDate($customer->date_add, null, true), 'customer_stats' => $customer_stats, 'last_visit' => Tools::displayDate($customer_stats['last_visit'], null, true), 'count_better_customers' => $count_better_customers, 'shop_is_feature_active' => Shop::isFeatureActive(), 'name_shop' => $shop->name, 'customer_birthday' => Tools::displayDate($customer->birthday), 'last_update' => Tools::displayDate($customer->date_upd, null, true), 'customer_exists' => Customer::customerExists($customer->email), 'id_lang' => $customer->id_lang, 'customerLanguage' => $customerLanguage, 'customer_note' => Tools::htmlentitiesUTF8($customer->note), 'messages' => $messages, 'groups' => $groups, 'orders' => $orders, 'orders_ok' => $orders_ok, 'orders_ko' => $orders_ko, 'total_ok' => Tools::displayPrice($total_ok, $this->context->currency->id), 'products' => $products, 'addresses' => $customer->getAddresses($this->default_form_language), 'discounts' => CartRule::getCustomerCartRules($this->default_form_language, $customer->id, false, false), 'carts' => $carts, 'interested' => $interested, 'emails' => $emails, 'connections' => $connections, 'referrers' => $referrers, 'show_toolbar' => true);
        return parent::renderView();
    }
Пример #17
0
    public function postProcess()
    {
        global $currentIndex, $cookie, $link;
        if ($id_customer_thread = (int) Tools::getValue('id_customer_thread')) {
            if ($id_contact = (int) Tools::getValue('id_contact')) {
                Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'customer_thread SET id_contact = ' . (int) $id_contact . ' WHERE id_customer_thread = ' . (int) $id_customer_thread);
            }
            if ($id_status = (int) Tools::getValue('setstatus')) {
                $statusArray = array(1 => 'open', 2 => 'closed', 3 => 'pending1', 4 => 'pending2');
                Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'customer_thread SET status = "' . $statusArray[$id_status] . '" WHERE id_customer_thread = ' . (int) $id_customer_thread . ' LIMIT 1');
            }
            if (isset($_POST['id_employee_forward'])) {
                // Todo: need to avoid doubles
                $messages = Db::getInstance()->ExecuteS('
				SELECT ct.*, cm.*, cl.name subject, CONCAT(e.firstname, \' \', e.lastname) employee_name, CONCAT(c.firstname, \' \', c.lastname) customer_name, c.firstname
				FROM ' . _DB_PREFIX_ . 'customer_thread ct
				LEFT JOIN ' . _DB_PREFIX_ . 'customer_message cm ON (ct.id_customer_thread = cm.id_customer_thread)
				LEFT JOIN ' . _DB_PREFIX_ . 'contact_lang cl ON (cl.id_contact = ct.id_contact AND cl.id_lang = ' . (int) $cookie->id_lang . ')
				LEFT OUTER JOIN ' . _DB_PREFIX_ . 'employee e ON e.id_employee = cm.id_employee
				LEFT OUTER JOIN ' . _DB_PREFIX_ . 'customer c ON (c.email = ct.email)
				WHERE ct.id_customer_thread = ' . (int) Tools::getValue('id_customer_thread') . '
				ORDER BY cm.date_add DESC');
                $output = '';
                foreach ($messages as $message) {
                    $output .= $this->displayMsg($message, true, (int) Tools::getValue('id_employee_forward'));
                }
                $cm = new CustomerMessage();
                $cm->id_employee = (int) $cookie->id_employee;
                $cm->id_customer_thread = (int) Tools::getValue('id_customer_thread');
                $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                $currentEmployee = new Employee($cookie->id_employee);
                if ($id_employee = (int) Tools::getValue('id_employee_forward') and $employee = new Employee($id_employee) and Validate::isLoadedObject($employee)) {
                    $params = array('{messages}' => $output, '{employee}' => $currentEmployee->firstname . ' ' . $currentEmployee->lastname, '{comment}' => stripslashes($_POST['message_forward']));
                    if (Mail::Send((int) $cookie->id_lang, 'forward_msg', Mail::l('Fwd: Customer message', (int) $cookie->id_lang), $params, $employee->email, $employee->firstname . ' ' . $employee->lastname, $currentEmployee->email, $currentEmployee->firstname . ' ' . $currentEmployee->lastname, NULL, NULL, _PS_MAIL_DIR_, true)) {
                        $cm->message = $this->l('Message forwarded to') . ' ' . $employee->firstname . ' ' . $employee->lastname . "\n" . $this->l('Comment:') . ' ' . $_POST['message_forward'];
                        $cm->add();
                    }
                } elseif ($email = Tools::getValue('email') and Validate::isEmail($email)) {
                    $params = array('{messages}' => $output, '{employee}' => $currentEmployee->firstname . ' ' . $currentEmployee->lastname, '{comment}' => stripslashes($_POST['message_forward']));
                    if (Mail::Send((int) $cookie->id_lang, 'forward_msg', Mail::l('Fwd: Customer message', (int) $cookie->id_lang), $params, $email, NULL, $currentEmployee->email, $currentEmployee->firstname . ' ' . $currentEmployee->lastname, NULL, NULL, _PS_MAIL_DIR_, true)) {
                        $cm->message = $this->l('Message forwarded to') . ' ' . $email . "\n" . $this->l('Comment:') . ' ' . $_POST['message_forward'];
                        $cm->add();
                    }
                } else {
                    echo '<div class="alert error">' . Tools::displayError('Email invalid.') . '</div>';
                }
            }
            if (Tools::isSubmit('submitReply')) {
                $ct = new CustomerThread($id_customer_thread);
                $cm = new CustomerMessage();
                $cm->id_employee = (int) $cookie->id_employee;
                $cm->id_customer_thread = $ct->id;
                $cm->message = Tools::htmlentitiesutf8(nl2br2(Tools::getValue('reply_message')));
                $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                if (isset($_FILES) and !empty($_FILES['joinFile']['name']) and $_FILES['joinFile']['error'] != 0) {
                    $this->_errors[] = Tools::displayError('An error occurred with the file upload.');
                } elseif ($cm->add()) {
                    $fileAttachment = NULL;
                    if (!empty($_FILES['joinFile']['name'])) {
                        $fileAttachment['content'] = file_get_contents($_FILES['joinFile']['tmp_name']);
                        $fileAttachment['name'] = $_FILES['joinFile']['name'];
                        $fileAttachment['mime'] = $_FILES['joinFile']['type'];
                    }
                    $params = array('{reply}' => nl2br2(Tools::getValue('reply_message')), '{link}' => $link->getPageLink('contact-form.php', true) . '?id_customer_thread=' . (int) $ct->id . '&token=' . $ct->token);
                    if (Mail::Send((int) $ct->id_lang, 'reply_msg', Mail::l('An answer to your message is available', (int) $ct->id_lang), $params, Tools::getValue('msg_email'), NULL, NULL, NULL, $fileAttachment, NULL, _PS_MAIL_DIR_, true)) {
                        $ct->status = 'closed';
                        $ct->update();
                    }
                    Tools::redirectAdmin($currentIndex . '&id_customer_thread=' . (int) $id_customer_thread . '&viewcustomer_thread&token=' . Tools::getValue('token'));
                } else {
                    $this->_errors[] = Tools::displayError('An error occurred, your message was not sent. Please contact your system administrator.');
                }
            }
        }
        return parent::postProcess();
    }
Пример #18
0
    public function viewcustomer()
    {
        global $currentIndex, $cookie, $link;
        $irow = 0;
        $configurations = Configuration::getMultiple(array('PS_LANG_DEFAULT', 'PS_CURRENCY_DEFAULT'));
        $defaultLanguage = (int) $configurations['PS_LANG_DEFAULT'];
        $defaultCurrency = (int) $configurations['PS_CURRENCY_DEFAULT'];
        if (!($customer = $this->loadObject())) {
            return;
        }
        $customerStats = $customer->getStats();
        $addresses = $customer->getAddresses($defaultLanguage);
        $products = $customer->getBoughtProducts();
        $discounts = Discount::getCustomerDiscounts($defaultLanguage, (int) $customer->id, false, false);
        $orders = Order::getCustomerOrders((int) $customer->id, true);
        $carts = Cart::getCustomerCarts((int) $customer->id);
        $groups = $customer->getGroups();
        $messages = CustomerThread::getCustomerMessages((int) $customer->id);
        $referrers = Referrer::getReferrers((int) $customer->id);
        if ($totalCustomer = Db::getInstance()->getValue('SELECT SUM(total_paid_real) FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = ' . $customer->id . ' AND valid = 1')) {
            Db::getInstance()->getValue('SELECT SQL_CALC_FOUND_ROWS COUNT(*) FROM ' . _DB_PREFIX_ . 'orders WHERE valid = 1 GROUP BY id_customer HAVING SUM(total_paid_real) > ' . $totalCustomer);
            $countBetterCustomers = (int) Db::getInstance()->getValue('SELECT FOUND_ROWS()') + 1;
        } else {
            $countBetterCustomers = '-';
        }
        echo '
		<fieldset style="width:400px;float: left"><div style="float: right"><a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a></div>
			<span style="font-weight: bold; font-size: 14px;">' . $customer->firstname . ' ' . $customer->lastname . '</span>
			<img src="../img/admin/' . ($customer->id_gender == 2 ? 'female' : ($customer->id_gender == 1 ? 'male' : 'unknown')) . '.gif" style="margin-bottom: 5px" /><br />
			<a href="mailto:' . $customer->email . '" style="text-decoration: underline; color: blue">' . $customer->email . '</a><br /><br />
			' . $this->l('ID:') . ' ' . sprintf('%06d', $customer->id) . '<br />
			' . $this->l('Registration date:') . ' ' . Tools::displayDate($customer->date_add, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Last visit:') . ' ' . ($customerStats['last_visit'] ? Tools::displayDate($customerStats['last_visit'], (int) $cookie->id_lang, true) : $this->l('never')) . '<br />
			' . ($countBetterCustomers != '-' ? $this->l('Rank: #') . ' ' . (int) $countBetterCustomers . '<br />' : '') . '
		</fieldset>
		<fieldset style="width:300px;float:left;margin-left:50px">
			<div style="float: right">
				<a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a>
			</div>
			' . $this->l('Newsletter:') . ' ' . ($customer->newsletter ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Opt-in:') . ' ' . ($customer->optin ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Age:') . ' ' . $customerStats['age'] . ' ' . (!empty($customer->birthday['age']) ? '(' . Tools::displayDate($customer->birthday, (int) $cookie->id_lang) . ')' : $this->l('unknown')) . '<br /><br />
			' . $this->l('Last update:') . ' ' . Tools::displayDate($customer->date_upd, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Status:') . ' ' . ($customer->active ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />');
        if ($customer->isGuest()) {
            echo '
			<div>
			' . $this->l('This customer is registered as') . ' <b>' . $this->l('guest') . '</b>';
            if (!Customer::customerExists($customer->email)) {
                echo '
					<form method="POST" action="index.php?tab=AdminCustomers&id_customer=' . (int) $customer->id . '&token=' . Tools::getAdminTokenLite('AdminCustomers') . '">
						<input type="hidden" name="id_lang" value="' . (int) (sizeof($orders) ? $orders[0]['id_lang'] : Configuration::get('PS_LANG_DEFAULT')) . '" />
						<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="' . $this->l('Transform to customer') . '" /></p>
						' . $this->l('This feature generates a random password and sends an e-mail to the customer') . '</form>';
            } else {
                echo '</div><div><b style="color:red;">' . $this->l('A registered customer account exists with the same email address') . '</b>';
            }
            echo '
			</div>
			';
        }
        echo '
		</fieldset>
		<div class="clear">&nbsp;</div>';
        echo '<fieldset style="height:190px"><legend><img src="../img/admin/cms.gif" /> ' . $this->l('Add a private note') . '</legend>
			<p>' . $this->l('This note will be displayed to all the employees but not to the customer.') . '</p>
			<form action="ajax.php" method="post" onsubmit="saveCustomerNote();return false;" id="customer_note">
				<textarea name="note" id="noteContent" style="width:600px;height:100px" onkeydown="$(\'#submitCustomerNote\').removeAttr(\'disabled\');">' . Tools::htmlentitiesUTF8($customer->note) . '</textarea><br />
				<input type="submit" id="submitCustomerNote" class="button" value="' . $this->l('   Save   ') . '" style="float:left;margin-top:5px" disabled="disabled" />
				<span id="note_feedback" style="float:left;margin:10px 0 0 10px"></span>
			</form>
		</fieldset>
		<div class="clear">&nbsp;</div>
		<script type="text/javascript">
			function saveCustomerNote()
			{
				$("#note_feedback").html("<img src=\\"../img/loader.gif\\" />").show();
				var noteContent = $("#noteContent").val();
				$.post("ajax.php", {submitCustomerNote:1,id_customer:' . (int) $customer->id . ',note:noteContent}, function (r) {
					$("#note_feedback").html("").hide();
					if (r == "ok")
					{
						$("#note_feedback").html("<b style=\\"color:green\\">' . addslashes($this->l('Your note has been saved')) . '</b>").fadeIn(400);
						$("#submitCustomerNote").attr("disabled", "disabled");
					}
					else if (r == "error:validation")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: your note is not valid')) . '</b>").fadeIn(400);
					else if (r == "error:update")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: cannot save your note')) . '</b>").fadeIn(400);
					$("#note_feedback").fadeOut(3000);
				});
			}
		</script>';
        echo '<h2>' . $this->l('Messages') . ' (' . sizeof($messages) . ')</h2>';
        if (sizeof($messages)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Status') . '</th>
					<th class="center">' . $this->l('Message') . '</th>
					<th class="center">' . $this->l('Sent on') . '</th>
				</tr>';
            foreach ($messages as $message) {
                echo '<tr>
					<td>' . $message['status'] . '</td>
					<td><a href="index.php?tab=AdminCustomerThreads&id_customer_thread=' . (int) $message['id_customer_thread'] . '&viewcustomer_thread&token=' . Tools::getAdminTokenLite('AdminCustomerThreads') . '">' . substr(strip_tags(html_entity_decode($message['message'], ENT_NOQUOTES, 'UTF-8')), 0, 75) . '...</a></td>
					<td>' . Tools::displayDate($message['date_add'], (int) $cookie->id_lang, true) . '</td>
				</tr>';
            }
            echo '</table>
			<div class="clear">&nbsp;</div>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has never contacted you.');
        }
        // display hook specified to this page : AdminCustomers
        if (($hook = Module::hookExec('adminCustomers', array('id_customer' => $customer->id))) !== false) {
            echo '<div>' . $hook . '</div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Groups') . ' (' . sizeof($groups) . ')</h2>';
        if ($groups and sizeof($groups)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenGroups = Tools::getAdminToken('AdminGroups' . (int) Tab::getIdFromClassName('AdminGroups') . (int) $cookie->id_employee);
            foreach ($groups as $group) {
                $objGroup = new Group($group);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '\'">
					<td class="center">' . $objGroup->id . '</td>
					<td>' . $objGroup->name[$defaultLanguage] . '</td>
					<td align="center"><a href="?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Orders') . ' (' . sizeof($orders) . ')</h2>';
        if ($orders and sizeof($orders)) {
            $totalOK = 0;
            $ordersOK = array();
            $ordersKO = array();
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($orders as $order) {
                if ($order['valid']) {
                    $ordersOK[] = $order;
                    $totalOK += $order['total_paid_real'];
                } else {
                    $ordersKO[] = $order;
                }
            }
            $orderHead = '
			<table cellspacing="0" cellpadding="0" class="table float">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Products') . '</th>
					<th class="center">' . $this->l('Total paid') . '</th>
					<th class="center">' . $this->l('Payment') . '</th>
					<th class="center">' . $this->l('State') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $orderFoot = '</table>';
            if ($countOK = sizeof($ordersOK)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:green;font-weight:700">' . $this->l('Valid orders:') . ' ' . $countOK . ' ' . $this->l('for') . ' ' . Tools::displayPrice($totalOK, new Currency($defaultCurrency)) . '</h3>' . $orderHead;
                foreach ($ordersOK as $order) {
                    echo '<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
						<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div>';
            }
            if ($countKO = sizeof($ordersKO)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:red;font-weight:700">' . $this->l('Invalid orders:') . ' ' . $countKO . '</h3>' . $orderHead;
                foreach ($ordersKO as $order) {
                    echo '
						<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
							<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div><div class="clear">&nbsp;</div>';
            }
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not placed any orders yet');
        }
        if ($products and sizeof($products)) {
            echo '<div class="clear">&nbsp;</div>
			<h2>' . $this->l('Products') . ' (' . sizeof($products) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Quantity') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($products as $product) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
					<td>' . Tools::displayDate($product['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td>' . $product['product_name'] . '</td>
					<td align="right">' . $product['product_quantity'] . '</td>
					<td align="center"><a href="?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Addresses') . ' (' . sizeof($addresses) . ')</h2>';
        if (sizeof($addresses)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('Company') . '</th>
					<th>' . $this->l('Name') . '</th>
					<th>' . $this->l('Address') . '</th>
					<th>' . $this->l('Country') . '</th>
					<th>' . $this->l('Phone number(s)') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenAddresses = Tools::getAdminToken('AdminAddresses' . (int) Tab::getIdFromClassName('AdminAddresses') . (int) $cookie->id_employee);
            foreach ($addresses as $address) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td>' . ($address['company'] ? $address['company'] : '--') . '</td>
					<td>' . $address['firstname'] . ' ' . $address['lastname'] . '</td>
					<td>' . $address['address1'] . ($address['address2'] ? ' ' . $address['address2'] : '') . ' ' . $address['postcode'] . ' ' . $address['city'] . '</td>
					<td>' . $address['country'] . '</td>
					<td>' . ($address['phone'] ? $address['phone'] . ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '') : ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '--')) . '</td>
					<td align="center">
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&addaddress&token=' . $tokenAddresses . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&deleteaddress&token=' . $tokenAddresses . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not registered any addresses yet') . '.';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Discounts') . ' (' . sizeof($discounts) . ')</h2>';
        if (sizeof($discounts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('ID') . '</th>
					<th>' . $this->l('Code') . '</th>
					<th>' . $this->l('Type') . '</th>
					<th>' . $this->l('Value') . '</th>
					<th>' . $this->l('Qty available') . '</th>
					<th>' . $this->l('Status') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenDiscounts = Tools::getAdminToken('AdminDiscounts' . (int) Tab::getIdFromClassName('AdminDiscounts') . (int) $cookie->id_employee);
            foreach ($discounts as $discount) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td align="center">' . $discount['id_discount'] . '</td>
					<td>' . $discount['name'] . '</td>
					<td>' . $discount['type'] . '</td>
					<td align="right">' . $discount['value'] . '</td>
					<td align="center">' . $discount['quantity_for_user'] . '</td>
					<td align="center"><img src="../img/admin/' . ($discount['active'] ? 'enabled.gif' : 'disabled.gif') . '" alt="' . $this->l('Status') . '" title="' . $this->l('Status') . '" /></td>
					<td align="center">
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&adddiscount&token=' . $tokenDiscounts . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&deletediscount&token=' . $tokenDiscounts . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has no discount vouchers') . '.';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<div style="float:left">
		<h2>' . $this->l('Carts') . ' (' . sizeof($carts) . ')</h2>';
        if ($carts and sizeof($carts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Total') . '</th>
					<th class="center">' . $this->l('Carrier') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenCarts = Tools::getAdminToken('AdminCarts' . (int) Tab::getIdFromClassName('AdminCarts') . (int) $cookie->id_employee);
            foreach ($carts as $cart) {
                $cartI = new Cart((int) $cart['id_cart']);
                $summary = $cartI->getSummaryDetails();
                $currency = new Currency((int) $cart['id_currency']);
                $carrier = new Carrier((int) $cart['id_carrier']);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '\'">
					<td class="center">' . sprintf('%06d', $cart['id_cart']) . '</td>
					<td>' . Tools::displayDate($cart['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td align="right">' . Tools::displayPrice($summary['total_price'], $currency) . '</td>
					<td>' . $carrier->name . '</td>
					<td align="center"><a href="index.php?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $this->l('No cart available') . '.';
        }
        echo '</div>';
        $interested = Db::getInstance()->ExecuteS('SELECT DISTINCT id_product FROM ' . _DB_PREFIX_ . 'cart_product cp INNER JOIN ' . _DB_PREFIX_ . 'cart c on c.id_cart = cp.id_cart WHERE c.id_customer = ' . (int) $customer->id . ' AND cp.id_product NOT IN (
		SELECT product_id FROM ' . _DB_PREFIX_ . 'orders o inner join ' . _DB_PREFIX_ . 'order_detail od ON o.id_order = od.id_order WHERE o.valid = 1 AND o.id_customer = ' . (int) $customer->id . ')');
        if (count($interested)) {
            echo '<div style="float:left;margin-left:20px">
			<h2>' . $this->l('Products') . ' (' . count($interested) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">';
            foreach ($interested as $p) {
                $product = new Product((int) $p['id_product'], false, $cookie->id_lang);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '\'">
					<td>' . (int) $product->id . '</td>
					<td>' . Tools::htmlentitiesUTF8($product->name) . '</td>
					<td align="center"><a href="' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '</table></div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        /* Last connections */
        $connections = $customer->getLastConnections();
        if (sizeof($connections)) {
            echo '<h2>' . $this->l('Last connections') . '</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th style="width: 200px">' . $this->l('Date') . '</th>
					<th style="width: 100px">' . $this->l('Pages viewed') . '</th>
					<th style="width: 100px">' . $this->l('Total time') . '</th>
					<th style="width: 100px">' . $this->l('Origin') . '</th>
					<th style="width: 100px">' . $this->l('IP Address') . '</th>
				</tr>';
            foreach ($connections as $connection) {
                echo '<tr>
						<td>' . Tools::displayDate($connection['date_add'], (int) $cookie->id_lang, true) . '</td>
						<td>' . (int) $connection['pages'] . '</td>
						<td>' . $connection['time'] . '</td>
						<td>' . ($connection['http_referer'] ? preg_replace('/^www./', '', parse_url($connection['http_referer'], PHP_URL_HOST)) : $this->l('Direct link')) . '</td>
						<td>' . $connection['ipaddress'] . '</td>
					</tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        if (sizeof($referrers)) {
            echo '<h2>' . $this->l('Referrers') . '</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th style="width: 200px">' . $this->l('Date') . '</th>
					<th style="width: 200px">' . $this->l('Name') . '</th>
				</tr>';
            foreach ($referrers as $referrer) {
                echo '<tr>
						<td>' . Tools::displayDate($referrer['date_add'], (int) $cookie->id_lang, true) . '</td>
						<td>' . $referrer['name'] . '</td>
					</tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        echo '<a href="' . $currentIndex . '&token=' . $this->token . '"><img src="../img/admin/arrow2.gif" /> ' . $this->l('Back to customer list') . '</a><br />';
    }
Пример #19
0
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amount_paid Amount really paid by customer (in the default currency)
     * @param string $payment_method Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
    {
        $this->context->cart = new Cart($id_cart);
        $this->context->customer = new Customer($this->context->cart->id_customer);
        $this->context->language = new Language($this->context->cart->id_lang);
        $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop);
        $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
        $this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
        if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
            $context_country = $this->context->country;
        }
        $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
        if (!Validate::isLoadedObject($order_status)) {
            throw new PrestaShopException('Can\'t load Order state status');
        }
        if (!$this->active) {
            die(Tools::displayError());
        }
        // Does order already exists ?
        if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
            if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
                die(Tools::displayError());
            }
            // For each package, generate an order
            $delivery_option_list = $this->context->cart->getDeliveryOptionList();
            $package_list = $this->context->cart->getPackageList();
            $cart_delivery_option = $this->context->cart->getDeliveryOption();
            // If some delivery options are not defined, or not valid, use the first valid option
            foreach ($delivery_option_list as $id_address => $package) {
                if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
                    foreach ($package as $key => $val) {
                        $cart_delivery_option[$id_address] = $key;
                        break;
                    }
                }
            }
            $order_list = array();
            $order_detail_list = array();
            $reference = Order::generateReference();
            $this->currentOrderReference = $reference;
            $order_creation_failed = false;
            $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
            foreach ($cart_delivery_option as $id_address => $key_carriers) {
                foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
                    foreach ($data['package_list'] as $id_package) {
                        // Rewrite the id_warehouse
                        $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier);
                        $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
                    }
                }
            }
            // Make sure CarRule caches are empty
            CartRule::cleanCache();
            foreach ($package_list as $id_address => $packageByAddress) {
                foreach ($packageByAddress as $id_package => $package) {
                    $order = new Order();
                    $order->product_list = $package['product_list'];
                    if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
                        $address = new Address($id_address);
                        $this->context->country = new Country($address->id_country, $this->context->cart->id_lang);
                    }
                    $carrier = null;
                    if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
                        $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang);
                        $order->id_carrier = (int) $carrier->id;
                        $id_carrier = (int) $carrier->id;
                    } else {
                        $order->id_carrier = 0;
                        $id_carrier = 0;
                    }
                    $order->id_customer = (int) $this->context->cart->id_customer;
                    $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
                    $order->id_address_delivery = (int) $id_address;
                    $order->id_currency = $this->context->currency->id;
                    $order->id_lang = (int) $this->context->cart->id_lang;
                    $order->id_cart = (int) $this->context->cart->id;
                    $order->reference = $reference;
                    $order->id_shop = (int) $this->context->shop->id;
                    $order->id_shop_group = (int) $this->context->shop->id_shop_group;
                    $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key);
                    $order->payment = $payment_method;
                    if (isset($this->name)) {
                        $order->module = $this->name;
                    }
                    $order->recyclable = $this->context->cart->recyclable;
                    $order->gift = (int) $this->context->cart->gift;
                    $order->gift_message = $this->context->cart->gift_message;
                    $order->mobile_theme = $this->context->cart->mobile_theme;
                    $order->conversion_rate = $this->context->currency->conversion_rate;
                    $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid;
                    $order->total_paid_real = 0;
                    $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                    $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                    $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                    $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                    $order->total_discounts = $order->total_discounts_tax_incl;
                    $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list);
                    $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list);
                    $order->total_shipping = $order->total_shipping_tax_incl;
                    if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
                        $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
                    }
                    $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                    $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                    $order->total_wrapping = $order->total_wrapping_tax_incl;
                    $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), 2);
                    $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), 2);
                    $order->total_paid = $order->total_paid_tax_incl;
                    $order->invoice_date = '0000-00-00 00:00:00';
                    $order->delivery_date = '0000-00-00 00:00:00';
                    // Creating order
                    $result = $order->add();
                    if (!$result) {
                        throw new PrestaShopException('Can\'t save Order');
                    }
                    // Amount paid by customer is not the right one -> Status = payment error
                    // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
                    // if ($order->total_paid != $order->total_paid_real)
                    // We use number_format in order to compare two string
                    if ($order_status->logable && number_format($cart_total_paid, 2) != number_format($amount_paid, 2)) {
                        $id_order_state = Configuration::get('PS_OS_ERROR');
                    }
                    $order_list[] = $order;
                    // Insert new Order detail list using cart for the current order
                    $order_detail = new OrderDetail(null, null, $this->context);
                    $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
                    $order_detail_list[] = $order_detail;
                    // Adding an entry in order_carrier table
                    if (!is_null($carrier)) {
                        $order_carrier = new OrderCarrier();
                        $order_carrier->id_order = (int) $order->id;
                        $order_carrier->id_carrier = (int) $id_carrier;
                        $order_carrier->weight = (double) $order->getTotalWeight();
                        $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl;
                        $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl;
                        $order_carrier->add();
                    }
                }
            }
            // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
                $this->context->country = $context_country;
            }
            // Register Payment only if the order status validate the order
            if ($order_status->logable) {
                // $order is the last order loop in the foreach
                // The method addOrderPayment of the class Order make a create a paymentOrder
                //     linked to the order reference and not to the order id
                if (isset($extra_vars['transaction_id'])) {
                    $transaction_id = $extra_vars['transaction_id'];
                } else {
                    $transaction_id = null;
                }
                if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
                    throw new PrestaShopException('Can\'t save Order Payment');
                }
            }
            // Next !
            $only_one_gift = false;
            $cart_rule_used = array();
            $products = $this->context->cart->getProducts();
            $cart_rules = $this->context->cart->getCartRules();
            // Make sure CarRule caches are empty
            CartRule::cleanCache();
            foreach ($order_detail_list as $key => $order_detail) {
                $order = $order_list[$key];
                if (!$order_creation_failed && isset($order->id)) {
                    if (!$secure_key) {
                        $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
                    }
                    // Optional message to attach to this order
                    if (isset($message) & !empty($message)) {
                        $msg = new Message();
                        $message = strip_tags($message, '<br>');
                        if (Validate::isCleanHtml($message)) {
                            $msg->message = $message;
                            $msg->id_order = intval($order->id);
                            $msg->private = 1;
                            $msg->add();
                        }
                    }
                    // Insert new Order detail list using cart for the current order
                    //$orderDetail = new OrderDetail(null, null, $this->context);
                    //$orderDetail->createList($order, $this->context->cart, $id_order_state);
                    // Construct order detail table for the email
                    $products_list = '';
                    $virtual_product = true;
                    foreach ($products as $key => $product) {
                        $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                        $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                        $customization_quantity = 0;
                        $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart);
                        if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                            $customization_text = '';
                            foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
                                if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                    foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                        $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
                                    }
                                }
                                if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                    $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />';
                                }
                                $customization_text .= '---<br />';
                            }
                            $customization_text = rtrim($customization_text, '---<br />');
                            $customization_quantity = (int) $product['customization_quantity'];
                            $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
								<td style="padding: 0.6em 0.4em;width: 15%;">' . $product['reference'] . '</td>
								<td style="padding: 0.6em 0.4em;width: 30%;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . Tools::displayError('Customized') . (!empty($customization_text) ? ' - ' . $customization_text : '') . '</strong></td>
								<td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false) . '</td>
								<td style="padding: 0.6em 0.4em; width: 15%;">' . $customization_quantity . '</td>
								<td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice($customization_quantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false) . '</td>
							</tr>';
                        }
                        if (!$customization_quantity || (int) $product['cart_quantity'] > $customization_quantity) {
                            $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
								<td style="padding: 0.6em 0.4em;width: 15%;">' . $product['reference'] . '</td>
								<td style="padding: 0.6em 0.4em;width: 30%;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td>
								<td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false) . '</td>
								<td style="padding: 0.6em 0.4em; width: 15%;">' . ((int) $product['cart_quantity'] - $customization_quantity) . '</td>
								<td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customization_quantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false) . '</td>
							</tr>';
                        }
                        // Check if is not a virutal product for the displaying of shipping
                        if (!$product['is_virtual']) {
                            $virtual_product &= false;
                        }
                    }
                    // end foreach ($products)
                    $cart_rules_list = '';
                    foreach ($cart_rules as $cart_rule) {
                        $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
                        $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package));
                        // If the reduction is not applicable to this order, then continue with the next one
                        if (!$values['tax_excl']) {
                            continue;
                        }
                        /* IF
                         ** - This is not multi-shipping
                         ** - The value of the voucher is greater than the total of the order
                         ** - Partial use is allowed
                         ** - This is an "amount" reduction, not a reduction in % or a gift
                         ** THEN
                         ** The voucher is cloned with a new value corresponding to the remainder
                         */
                        if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
                            // Create a new voucher from the original
                            $voucher = new CartRule($cart_rule['obj']->id);
                            // We need to instantiate the CartRule without lang parameter to allow saving it
                            unset($voucher->id);
                            // Set a new voucher code
                            $voucher->code = empty($voucher->code) ? substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
                            if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
                                $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (intval($matches[1]) + 1), $voucher->code);
                            }
                            // Set the new voucher value
                            if ($voucher->reduction_tax) {
                                $voucher->reduction_amount = $values['tax_incl'] - $order->total_products_wt;
                            } else {
                                $voucher->reduction_amount = $values['tax_excl'] - $order->total_products;
                            }
                            $voucher->id_customer = $order->id_customer;
                            $voucher->quantity = 1;
                            if ($voucher->add()) {
                                // If the voucher has conditions, they are now copied to the new voucher
                                CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
                                $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference());
                                Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                            }
                            $values['tax_incl'] -= $values['tax_incl'] - $order->total_products_wt;
                            $values['tax_excl'] -= $values['tax_excl'] - $order->total_products;
                        }
                        $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
                        if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
                            $cart_rule_used[] = $cart_rule['obj']->id;
                            // Create a new instance of Cart Rule without id_lang, in order to update its quantity
                            $cart_rule_to_update = new CartRule($cart_rule['obj']->id);
                            $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
                            $cart_rule_to_update->update();
                        }
                        $cart_rules_list .= '
						<tr>
							<td colspan="4" style="padding:0.6em 0.4em;text-align:right">' . Tools::displayError('Voucher name:') . ' ' . $cart_rule['obj']->name . '</td>
							<td style="padding:0.6em 0.4em;text-align:right">' . ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false) . '</td>
						</tr>';
                    }
                    // Specify order id for message
                    $old_message = Message::getMessageByCartId((int) $this->context->cart->id);
                    if ($old_message) {
                        $update_message = new Message((int) $old_message['id_message']);
                        $update_message->id_order = (int) $order->id;
                        $update_message->update();
                        // Add this message in the customer thread
                        $customer_thread = new CustomerThread();
                        $customer_thread->id_contact = 0;
                        $customer_thread->id_customer = (int) $order->id_customer;
                        $customer_thread->id_shop = (int) $this->context->shop->id;
                        $customer_thread->id_order = (int) $order->id;
                        $customer_thread->id_lang = (int) $this->context->language->id;
                        $customer_thread->email = $this->context->customer->email;
                        $customer_thread->status = 'open';
                        $customer_thread->token = Tools::passwdGen(12);
                        $customer_thread->add();
                        $customer_message = new CustomerMessage();
                        $customer_message->id_customer_thread = $customer_thread->id;
                        $customer_message->id_employee = 0;
                        $customer_message->message = $update_message->message;
                        $customer_message->private = 0;
                        if (!$customer_message->add()) {
                            $this->errors[] = Tools::displayError('An error occurred while saving message');
                        }
                    }
                    // Hook validate order
                    Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status));
                    foreach ($this->context->cart->getProducts() as $product) {
                        if ($order_status->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                    if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
                        $history = new OrderHistory();
                        $history->id_order = (int) $order->id;
                        $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), $order, true);
                        $history->addWithemail();
                    }
                    // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                    // So you migth have two order states
                    $new_history = new OrderHistory();
                    $new_history->id_order = (int) $order->id;
                    $new_history->changeIdOrderState((int) $id_order_state, $order, true);
                    $new_history->addWithemail(true, $extra_vars);
                    unset($order_detail);
                    // Order is reloaded because the status just changed
                    $order = new Order($order->id);
                    // Send an e-mail to customer (one order = one email)
                    if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
                        $invoice = new Address($order->id_address_invoice);
                        $delivery = new Address($order->id_address_delivery);
                        $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
                        $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
                        $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $virtual_product ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $this->formatProductAndVoucherForEmail($products_list), '{discounts}' => $this->formatProductAndVoucherForEmail($cart_rules_list), '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false));
                        if (is_array($extra_vars)) {
                            $data = array_merge($data, $extra_vars);
                        }
                        // Join PDF invoice
                        if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
                            $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
                            $file_attachement['content'] = $pdf->render(false);
                            $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                            $file_attachement['mime'] = 'application/pdf';
                        } else {
                            $file_attachement = null;
                        }
                        if (Validate::isEmail($this->context->customer->email)) {
                            Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                        }
                    }
                    // updates stock in shops
                    if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $product_list = $order->getProducts();
                        foreach ($product_list as $product) {
                            // if the available quantities depends on the physical stock
                            if (StockAvailable::dependsOnStock($product['product_id'])) {
                                // synchronizes
                                StockAvailable::synchronize($product['product_id'], $order->id_shop);
                            }
                        }
                    }
                } else {
                    $error = Tools::displayError('Order creation failed');
                    Logger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart));
                    die($error);
                }
            }
            // End foreach $order_detail_list
            // Use the last order as currentOrder
            $this->currentOrder = (int) $order->id;
            return true;
        } else {
            $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
            Logger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id));
            die($error);
        }
    }
Пример #20
0
 public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
 {
     if (self::DEBUG_MODE) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true);
     }
     if (!isset($this->context)) {
         $this->context = Context::getContext();
     }
     $this->context->cart = new Cart($id_cart);
     $this->context->customer = new Customer($this->context->cart->id_customer);
     // The tax cart is loaded before the customer so re-cache the tax calculation method
     $this->context->cart->setTaxCalculationMethod();
     $this->context->language = new Language($this->context->cart->id_lang);
     $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop);
     ShopUrl::resetMainDomainCache();
     $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
     $this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
         $context_country = $this->context->country;
     }
     $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
     if (!Validate::isLoadedObject($order_status)) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true);
         throw new PrestaShopException('Can\'t load Order status');
     }
     if (!$this->active) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true);
         die(Tools::displayError());
     }
     // Does order already exists ?
     if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
         if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true);
             die(Tools::displayError());
         }
         // For each package, generate an order
         $delivery_option_list = $this->context->cart->getDeliveryOptionList();
         $package_list = $this->context->cart->getPackageList();
         $cart_delivery_option = $this->context->cart->getDeliveryOption();
         // If some delivery options are not defined, or not valid, use the first valid option
         foreach ($delivery_option_list as $id_address => $package) {
             if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
                 foreach ($package as $key => $val) {
                     $cart_delivery_option[$id_address] = $key;
                     break;
                 }
             }
         }
         $order_list = array();
         $order_detail_list = array();
         do {
             $reference = Order::generateReference();
         } while (Order::getByReference($reference)->count());
         $this->currentOrderReference = $reference;
         $order_creation_failed = false;
         $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
         foreach ($cart_delivery_option as $id_address => $key_carriers) {
             foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
                 foreach ($data['package_list'] as $id_package) {
                     // Rewrite the id_warehouse
                     $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier);
                     $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
                 }
             }
         }
         // Make sure CartRule caches are empty
         CartRule::cleanCache();
         $cart_rules = $this->context->cart->getCartRules();
         foreach ($cart_rules as $cart_rule) {
             if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) {
                 if ($error = $rule->checkValidity($this->context, true, true)) {
                     $this->context->cart->removeCartRule((int) $rule->id);
                     if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) {
                         if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                             Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
                         }
                         Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
                     } else {
                         $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code;
                         $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name));
                         PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id);
                     }
                 }
             }
         }
         foreach ($package_list as $id_address => $packageByAddress) {
             foreach ($packageByAddress as $id_package => $package) {
                 $order = new Order();
                 $order->product_list = $package['product_list'];
                 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
                     $address = new Address($id_address);
                     $this->context->country = new Country($address->id_country, $this->context->cart->id_lang);
                     if (!$this->context->country->active) {
                         throw new PrestaShopException('The delivery address country is not active.');
                     }
                 }
                 $carrier = null;
                 if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
                     $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang);
                     $order->id_carrier = (int) $carrier->id;
                     $id_carrier = (int) $carrier->id;
                 } else {
                     $order->id_carrier = 0;
                     $id_carrier = 0;
                 }
                 $order->id_customer = (int) $this->context->cart->id_customer;
                 $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
                 $order->id_address_delivery = (int) $id_address;
                 $order->id_currency = $this->context->currency->id;
                 $order->id_lang = (int) $this->context->cart->id_lang;
                 $order->id_cart = (int) $this->context->cart->id;
                 $order->reference = $reference;
                 $order->id_shop = (int) $this->context->shop->id;
                 $order->id_shop_group = (int) $this->context->shop->id_shop_group;
                 $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key);
                 $order->payment = $payment_method;
                 if (isset($this->name)) {
                     $order->module = $this->name;
                 }
                 $order->recyclable = $this->context->cart->recyclable;
                 $order->gift = (int) $this->context->cart->gift;
                 $order->gift_message = $this->context->cart->gift_message;
                 $order->mobile_theme = $this->context->cart->mobile_theme;
                 $order->conversion_rate = $this->context->currency->conversion_rate;
                 $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid;
                 $order->total_paid_real = 0;
                 $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts = $order->total_discounts_tax_incl;
                 $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list);
                 $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list);
                 $order->total_shipping = $order->total_shipping_tax_incl;
                 if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
                     $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
                 }
                 $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping = $order->total_wrapping_tax_incl;
                 $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
                 $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
                 $order->total_paid = $order->total_paid_tax_incl;
                 $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
                 $order->invoice_date = '0000-00-00 00:00:00';
                 $order->delivery_date = '0000-00-00 00:00:00';
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Creating order
                 $result = $order->add();
                 if (!$result) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true);
                     throw new PrestaShopException('Can\'t save Order');
                 }
                 // Amount paid by customer is not the right one -> Status = payment error
                 // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
                 // if ($order->total_paid != $order->total_paid_real)
                 // We use number_format in order to compare two string
                 if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
                     $id_order_state = Configuration::get('PS_OS_ERROR');
                 }
                 $order_list[] = $order;
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Insert new Order detail list using cart for the current order
                 $order_detail = new OrderDetail(null, null, $this->context);
                 $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
                 $order_detail_list[] = $order_detail;
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Adding an entry in order_carrier table
                 if (!is_null($carrier)) {
                     $order_carrier = new OrderCarrier();
                     $order_carrier->id_order = (int) $order->id;
                     $order_carrier->id_carrier = (int) $id_carrier;
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl;
                     $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl;
                     $order_carrier->add();
                 }
             }
         }
         // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
             $this->context->country = $context_country;
         }
         if (!$this->context->country->active) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true);
             throw new PrestaShopException('The order address country is not active.');
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true);
         }
         // Register Payment only if the order status validate the order
         if ($order_status->logable) {
             // $order is the last order loop in the foreach
             // The method addOrderPayment of the class Order make a create a paymentOrder
             //     linked to the order reference and not to the order id
             if (isset($extra_vars['transaction_id'])) {
                 $transaction_id = $extra_vars['transaction_id'];
             } else {
                 $transaction_id = null;
             }
             if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
                 PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true);
                 throw new PrestaShopException('Can\'t save Order Payment');
             }
         }
         // Next !
         $only_one_gift = false;
         $cart_rule_used = array();
         $products = $this->context->cart->getProducts();
         // Make sure CarRule caches are empty
         CartRule::cleanCache();
         foreach ($order_detail_list as $key => $order_detail) {
             $order = $order_list[$key];
             if (!$order_creation_failed && isset($order->id)) {
                 if (!$secure_key) {
                     $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
                 }
                 // Optional message to attach to this order
                 if (isset($message) & !empty($message)) {
                     $msg = new Message();
                     $message = strip_tags($message, '<br>');
                     if (Validate::isCleanHtml($message)) {
                         if (self::DEBUG_MODE) {
                             PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                         }
                         $msg->message = $message;
                         $msg->id_order = (int) $order->id;
                         $msg->private = 1;
                         $msg->add();
                     }
                 }
                 // Insert new Order detail list using cart for the current order
                 //$orderDetail = new OrderDetail(null, null, $this->context);
                 //$orderDetail->createList($order, $this->context->cart, $id_order_state);
                 // Construct order detail table for the email
                 $products_list = '';
                 $virtual_product = true;
                 $ppropertiessmartprice_hook1 = null;
                 $product_var_tpl_list = array();
                 foreach ($order->product_list as $product) {
                     PP::smartyPPAssign(array('cart' => $product, 'currency' => $this->context->currency));
                     $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $ppropertiessmartprice_hook2 = '';
                     $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . PP::smartyDisplayProductName(array('name' => '')) . $ppropertiessmartprice_hook2, 'unit_price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt)), 'price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total'] : $product['total_wt'], 'quantity' => (int) $product['cart_quantity'], 'm' => 'total')), 'quantity' => PP::smartyDisplayQty(array('quantity' => (int) $product['cart_quantity'])), 'customization' => array());
                     $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart);
                     $productHasCustomizedDatas = Product::hasCustomizedDatas($product, $customized_datas);
                     if ($productHasCustomizedDatas && isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                         $product_var_tpl['customization'] = array();
                         foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
                             if ($product['id_cart_product'] == $customization['id_cart_product']) {
                                 $customization_text = '';
                                 if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                     foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                         $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
                                     }
                                 }
                                 if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                     $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />';
                                 }
                                 $customization_quantity = (int) $product['customization_quantity'];
                                 $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => PP::smartyDisplayQty(array('quantity' => $customization_quantity)), 'quantity' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total_customization'] : $product['total_customization_wt'], 'm' => 'total')));
                             }
                         }
                     }
                     $product_var_tpl_list[] = $product_var_tpl;
                     // Check if is not a virutal product for the displaying of shipping
                     if (!$product['is_virtual']) {
                         $virtual_product &= false;
                     }
                 }
                 // end foreach ($products)
                 PP::smartyPPAssign();
                 $product_list_txt = '';
                 $product_list_html = '';
                 if (count($product_var_tpl_list) > 0) {
                     $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
                     $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
                 }
                 $cart_rules_list = array();
                 $total_reduction_value_ti = 0;
                 $total_reduction_value_tex = 0;
                 foreach ($cart_rules as $cart_rule) {
                     $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
                     $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package));
                     // If the reduction is not applicable to this order, then continue with the next one
                     if (!$values['tax_excl']) {
                         continue;
                     }
                     // IF
                     //     This is not multi-shipping
                     //     The value of the voucher is greater than the total of the order
                     //     Partial use is allowed
                     //     This is an "amount" reduction, not a reduction in % or a gift
                     // THEN
                     //     The voucher is cloned with a new value corresponding to the remainder
                     if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
                         // Create a new voucher from the original
                         $voucher = new CartRule($cart_rule['obj']->id);
                         // We need to instantiate the CartRule without lang parameter to allow saving it
                         unset($voucher->id);
                         // Set a new voucher code
                         $voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
                         if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
                             $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (int) ($matches[1] + 1), $voucher->code);
                         }
                         // Set the new voucher value
                         if ($voucher->reduction_tax) {
                             $voucher->reduction_amount = $total_reduction_value_ti + $values['tax_incl'] - $order->total_products_wt;
                             // Add total shipping amout only if reduction amount > total shipping
                             if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) {
                                 $voucher->reduction_amount -= $order->total_shipping_tax_incl;
                             }
                         } else {
                             $voucher->reduction_amount = $total_reduction_value_tex + $values['tax_excl'] - $order->total_products;
                             // Add total shipping amout only if reduction amount > total shipping
                             if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) {
                                 $voucher->reduction_amount -= $order->total_shipping_tax_excl;
                             }
                         }
                         if ($voucher->reduction_amount <= 0) {
                             continue;
                         }
                         $voucher->id_customer = $order->id_customer;
                         $voucher->quantity = 1;
                         $voucher->quantity_per_user = 1;
                         $voucher->free_shipping = 0;
                         if ($voucher->add()) {
                             // If the voucher has conditions, they are now copied to the new voucher
                             CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
                             $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference());
                             Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                         }
                         $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti;
                         $values['tax_excl'] = $order->total_products - $total_reduction_value_tex;
                     }
                     $total_reduction_value_ti += $values['tax_incl'];
                     $total_reduction_value_tex += $values['tax_excl'];
                     $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
                     if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
                         $cart_rule_used[] = $cart_rule['obj']->id;
                         // Create a new instance of Cart Rule without id_lang, in order to update its quantity
                         $cart_rule_to_update = new CartRule($cart_rule['obj']->id);
                         $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
                         $cart_rule_to_update->update();
                     }
                     $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false));
                 }
                 $cart_rules_list_txt = '';
                 $cart_rules_list_html = '';
                 if (count($cart_rules_list) > 0) {
                     $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
                     $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
                 }
                 // Specify order id for message
                 $old_message = Message::getMessageByCartId((int) $this->context->cart->id);
                 if ($old_message) {
                     $update_message = new Message((int) $old_message['id_message']);
                     $update_message->id_order = (int) $order->id;
                     $update_message->update();
                     // Add this message in the customer thread
                     $customer_thread = new CustomerThread();
                     $customer_thread->id_contact = 0;
                     $customer_thread->id_customer = (int) $order->id_customer;
                     $customer_thread->id_shop = (int) $this->context->shop->id;
                     $customer_thread->id_order = (int) $order->id;
                     $customer_thread->id_lang = (int) $this->context->language->id;
                     $customer_thread->email = $this->context->customer->email;
                     $customer_thread->status = 'open';
                     $customer_thread->token = Tools::passwdGen(12);
                     $customer_thread->add();
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = 0;
                     $customer_message->message = $update_message->message;
                     $customer_message->private = 0;
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving message');
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Hook validate order
                 Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status));
                 foreach ($this->context->cart->getProducts() as $product) {
                     if ($order_status->logable) {
                         ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Set the order status
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState((int) $id_order_state, $order, true);
                 $new_history->addWithemail(true, $extra_vars);
                 // Switch to back order if needed
                 if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
                     $history = new OrderHistory();
                     $history->id_order = (int) $order->id;
                     $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
                     $history->addWithemail();
                 }
                 unset($order_detail);
                 // Order is reloaded because the status just changed
                 $order = new Order($order->id);
                 // Send an e-mail to customer (one order = one email)
                 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
                     $invoice = new Address($order->id_address_invoice);
                     $delivery = new Address($order->id_address_delivery);
                     $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
                     $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
                     $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false));
                     if (is_array($extra_vars)) {
                         $data = array_merge($data, $extra_vars);
                     }
                     // Join PDF invoice
                     if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
                         $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
                         $file_attachement = array();
                         $file_attachement['content'] = $pdf->render(false);
                         $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                         $file_attachement['mime'] = 'application/pdf';
                     } else {
                         $file_attachement = null;
                     }
                     if (self::DEBUG_MODE) {
                         PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true);
                     }
                     if (Validate::isEmail($this->context->customer->email)) {
                         Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                     }
                 }
                 // updates stock in shops
                 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                     $product_list = $order->getProducts();
                     foreach ($product_list as $product) {
                         // if the available quantities depends on the physical stock
                         if (StockAvailable::dependsOnStock($product['product_id'])) {
                             // synchronizes
                             StockAvailable::synchronize($product['product_id'], $order->id_shop);
                         }
                     }
                 }
             } else {
                 $error = Tools::displayError('Order creation failed');
                 PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart);
                 die($error);
             }
         }
         // End foreach $order_detail_list
         // Update Order Details Tax in case cart rules have free shipping
         foreach ($order->getOrderDetailList() as $detail) {
             $order_detail = new OrderDetail($detail['id_order_detail']);
             $order_detail->updateTaxAmount($order);
         }
         // Use the last order as currentOrder
         if (isset($order) && $order->id) {
             $this->currentOrder = (int) $order->id;
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true);
         }
         return true;
     } else {
         $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
         PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id);
         die($error);
     }
 }
 public function ajaxProcessMarkAsRead()
 {
     $id_thread = Tools::getValue('id_thread');
     $messages = CustomerThread::getMessageCustomerThreads($id_thread);
     if (count($messages)) {
         Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'customer_message set `read` = 1');
     }
 }
Пример #22
0
 public static function getPendingMessages()
 {
     return CustomerThread::getTotalCustomerThreads('status LIKE "%pending%" OR status = "open"');
 }
    public function ajaxProcessSyncImap()
    {
        if ($this->tabAccess['edit'] != '1') {
            throw new PrestaShopException(Tools::displayError('You do not have permission to edit this.'));
        }
        if (Tools::isSubmit('syncImapMail')) {
            if (!($url = Configuration::get('PS_SAV_IMAP_URL')) || !($port = Configuration::get('PS_SAV_IMAP_PORT')) || !($user = Configuration::get('PS_SAV_IMAP_USER')) || !($password = Configuration::get('PS_SAV_IMAP_PWD'))) {
                die('{"hasError" : true, "errors" : ["Configuration is not correct"]}');
            }
            $conf = Configuration::getMultiple(array('PS_SAV_IMAP_OPT_NORSH', 'PS_SAV_IMAP_OPT_SSL', 'PS_SAV_IMAP_OPT_VALIDATE-CERT', 'PS_SAV_IMAP_OPT_NOVALIDATE-CERT', 'PS_SAV_IMAP_OPT_TLS', 'PS_SAV_IMAP_OPT_NOTLS'));
            $conf_str = '';
            if ($conf['PS_SAV_IMAP_OPT_NORSH']) {
                $conf_str .= '/norsh';
            }
            if ($conf['PS_SAV_IMAP_OPT_SSL']) {
                $conf_str .= '/ssl';
            }
            if ($conf['PS_SAV_IMAP_OPT_VALIDATE-CERT']) {
                $conf_str .= '/validate-cert';
            }
            if ($conf['PS_SAV_IMAP_OPT_NOVALIDATE-CERT']) {
                $conf_str .= '/novalidate-cert';
            }
            if ($conf['PS_SAV_IMAP_OPT_TLS']) {
                $conf_str .= '/tls';
            }
            if ($conf['PS_SAV_IMAP_OPT_NOTLS']) {
                $conf_str .= '/notls';
            }
            if (!function_exists('imap_open')) {
                die('{"hasError" : true, "errors" : ["imap is not installed on this server"]}');
            }
            $mbox = @imap_open('{' . $url . ':' . $port . $conf_str . '}', $user, $password);
            //checks if there is no error when connecting imap server
            $errors = imap_errors();
            $str_errors = '';
            $str_error_delete = '';
            if (sizeof($errors) && is_array($errors)) {
                $str_errors = '';
                foreach ($errors as $error) {
                    $str_errors .= '"' . $error . '",';
                }
                $str_errors = rtrim($str_errors, ',') . '';
            }
            //checks if imap connexion is active
            if (!$mbox) {
                die('{"hasError" : true, "errors" : ["Cannot connect to the mailbox:.<br />' . addslashes($str_errors) . '"]}');
            }
            //Returns information about the current mailbox. Returns FALSE on failure.
            $check = imap_check($mbox);
            if (!$check) {
                die('{"hasError" : true, "errors" : ["Fail to get information about the current mailbox"]}');
            }
            if ($check->Nmsgs == 0) {
                die('{"hasError" : true, "errors" : ["NO message to sync"]}');
            }
            $result = imap_fetch_overview($mbox, "1:{$check->Nmsgs}", 0);
            foreach ($result as $overview) {
                //check if message exist in database
                if (isset($overview->subject)) {
                    $subject = $overview->subject;
                } else {
                    $subject = '';
                }
                //Creating an md5 to check if message has been allready processed
                $md5 = md5($overview->date . $overview->from . $subject . $overview->msgno);
                $exist = Db::getInstance()->getValue('SELECT `md5_header`
						 FROM `' . _DB_PREFIX_ . 'customer_message_sync_imap`
						 WHERE `md5_header` = \'' . pSQL($md5) . '\'');
                if ($exist) {
                    if (Configuration::get('PS_SAV_IMAP_DELETE_MSG')) {
                        if (!imap_delete($mbox, $overview->msgno)) {
                            $str_error_delete = ', "Fail to delete message"';
                        }
                    }
                } else {
                    //check if subject has id_order
                    preg_match('/\\#ct([0-9]*)/', $subject, $matches1);
                    preg_match('/\\#tc([0-9-a-z-A-Z]*)/', $subject, $matches2);
                    $new_ct = Configuration::get('PS_SAV_IMAP_CREATE_THREADS') && !isset($matches1[1]) && !isset($matches2[1]) && !preg_match('/[no_sync]/', $subject);
                    if (isset($matches1[1]) && isset($matches2[1]) || $new_ct) {
                        if ($new_ct) {
                            if (!preg_match('/<(' . Tools::cleanNonUnicodeSupport('[a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z\\p{L}0-9]+[._a-z\\p{L}0-9-]*\\.[a-z0-9]+') . ')>/', $overview->from, $result) || !Validate::isEmail($from = $result[1])) {
                                continue;
                            }
                            $contacts = Contact::getCategoriesContacts();
                            if (!$contacts) {
                                continue;
                            }
                            $id_contact = $contacts[0]['id_contact'];
                            $ct = new CustomerThread();
                            $ct->email = $from;
                            $ct->id_contact = $id_contact;
                            $ct->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                            $ct->status = 'open';
                            $ct->token = Tools::passwdGen(12);
                            $ct->add();
                        } else {
                            $ct = new CustomerThread((int) $matches1[1]);
                        }
                        //check if order exist in database
                        if (Validate::isLoadedObject($ct) && (isset($matches2[1]) && $ct->token == $matches2[1] || $new_ct)) {
                            $cm = new CustomerMessage();
                            $cm->id_customer_thread = $ct->id;
                            $cm->message = imap_fetchbody($mbox, $overview->msgno, 1);
                            $cm->add();
                        }
                    }
                    Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customer_message_sync_imap` (`md5_header`) VALUES (\'' . pSQL($md5) . '\')');
                }
            }
            imap_expunge($mbox);
            imap_close($mbox);
            die('{"hasError" : false, "errors" : ["' . $str_errors . $str_error_delete . '"]}');
        }
    }
    public function ajaxProcessSyncImap()
    {
        if ($this->tabAccess['edit'] != '1') {
            throw new PrestaShopException(Tools::displayError('You do not have permission to edit this.'));
        }
        if (Tools::isSubmit('syncImapMail')) {
            if (!($url = Configuration::get('PS_SAV_IMAP_URL')) || !($port = Configuration::get('PS_SAV_IMAP_PORT')) || !($user = Configuration::get('PS_SAV_IMAP_USER')) || !($password = Configuration::get('PS_SAV_IMAP_PWD'))) {
                die('{"hasError" : true, "errors" : ["Configuration is not correct"]}');
            }
            $conf = Configuration::getMultiple(array('PS_SAV_IMAP_OPT_NORSH', 'PS_SAV_IMAP_OPT_SSL', 'PS_SAV_IMAP_OPT_VALIDATE-CERT', 'PS_SAV_IMAP_OPT_NOVALIDATE-CERT', 'PS_SAV_IMAP_OPT_TLS', 'PS_SAV_IMAP_OPT_NOTLS'));
            $conf_str = '';
            if ($conf['PS_SAV_IMAP_OPT_NORSH']) {
                $conf_str .= '/norsh';
            }
            if ($conf['PS_SAV_IMAP_OPT_SSL']) {
                $conf_str .= '/ssl';
            }
            if ($conf['PS_SAV_IMAP_OPT_VALIDATE-CERT']) {
                $conf_str .= '/validate-cert';
            }
            if ($conf['PS_SAV_IMAP_OPT_NOVALIDATE-CERT']) {
                $conf_str .= '/novalidate-cert';
            }
            if ($conf['PS_SAV_IMAP_OPT_TLS']) {
                $conf_str .= '/tls';
            }
            if ($conf['PS_SAV_IMAP_OPT_NOTLS']) {
                $conf_str .= '/notls';
            }
            if (!function_exists('imap_open')) {
                die('{"hasError" : true, "errors" : ["imap is not installed on this server"]}');
            }
            $mbox = @imap_open('{' . $url . ':' . $port . $conf_str . '}', $user, $password);
            //checks if there is no error when connecting imap server
            $errors = array_unique(imap_errors());
            $str_errors = '';
            $str_error_delete = '';
            if (sizeof($errors) && is_array($errors)) {
                $str_errors = '';
                foreach ($errors as $error) {
                    $str_errors .= $error . ', ';
                }
                $str_errors = rtrim(trim($str_errors), ',');
            }
            //checks if imap connexion is active
            if (!$mbox) {
                $array = array('hasError' => true, 'errors' => array('Cannot connect to the mailbox :<br />' . $str_errors));
                die(Tools::jsonEncode($array));
            }
            //Returns information about the current mailbox. Returns FALSE on failure.
            $check = imap_check($mbox);
            if (!$check) {
                die('{"hasError" : true, "errors" : ["Fail to get information about the current mailbox"]}');
            }
            if ($check->Nmsgs == 0) {
                die('{"hasError" : true, "errors" : ["NO message to sync"]}');
            }
            $result = imap_fetch_overview($mbox, "1:{$check->Nmsgs}", 0);
            foreach ($result as $overview) {
                //check if message exist in database
                if (isset($overview->subject)) {
                    $subject = $overview->subject;
                } else {
                    $subject = '';
                }
                //Creating an md5 to check if message has been allready processed
                $md5 = md5($overview->date . $overview->from . $subject . $overview->msgno);
                $exist = Db::getInstance()->getValue('SELECT `md5_header`
						 FROM `' . _DB_PREFIX_ . 'customer_message_sync_imap`
						 WHERE `md5_header` = \'' . pSQL($md5) . '\'');
                if ($exist) {
                    if (Configuration::get('PS_SAV_IMAP_DELETE_MSG')) {
                        if (!imap_delete($mbox, $overview->msgno)) {
                            $str_error_delete = ', Fail to delete message';
                        }
                    }
                } else {
                    //check if subject has id_order
                    preg_match('/\\#ct([0-9]*)/', $subject, $matches1);
                    preg_match('/\\#tc([0-9-a-z-A-Z]*)/', $subject, $matches2);
                    $matchFound = false;
                    if (isset($matches1[1]) && isset($matches2[1])) {
                        $matchFound = true;
                    }
                    $new_ct = Configuration::get('PS_SAV_IMAP_CREATE_THREADS') && !$matchFound && strpos($subject, '[no_sync]') == false;
                    if ($matchFound || $new_ct) {
                        if ($new_ct) {
                            if (!preg_match('/<(' . Tools::cleanNonUnicodeSupport('[a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z\\p{L}0-9]+[._a-z\\p{L}0-9-]*\\.[a-z0-9]+') . ')>/', $overview->from, $result) || !Validate::isEmail($from = $result[1])) {
                                continue;
                            }
                            // we want to assign unrecognized mails to the right contact category
                            $contacts = Contact::getContacts($this->context->language->id);
                            if (!$contacts) {
                                continue;
                            }
                            foreach ($contacts as $contact) {
                                if (strpos($overview->to, $contact['email']) !== false) {
                                    $id_contact = $contact['id_contact'];
                                }
                            }
                            if (!isset($id_contact)) {
                                // if not use the default contact category
                                $id_contact = $contacts[0]['id_contact'];
                            }
                            $customer = new Customer();
                            $client = $customer->getByEmail($from);
                            //check if we already have a customer with this email
                            $ct = new CustomerThread();
                            if (isset($client->id)) {
                                //if mail is owned by a customer assign to him
                                $ct->id_customer = $client->id;
                            }
                            $ct->email = $from;
                            $ct->id_contact = $id_contact;
                            $ct->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                            $ct->id_shop = $this->context->shop->id;
                            //new customer threads for unrecognized mails are not shown without shop id
                            $ct->status = 'open';
                            $ct->token = Tools::passwdGen(12);
                            $ct->add();
                        } else {
                            $ct = new CustomerThread((int) $matches1[1]);
                        }
                        //check if order exist in database
                        if (Validate::isLoadedObject($ct) && (isset($matches2[1]) && $ct->token == $matches2[1] || $new_ct)) {
                            $message = imap_fetchbody($mbox, $overview->msgno, 1);
                            $message = quoted_printable_decode($message);
                            $message = utf8_encode($message);
                            $message = quoted_printable_decode($message);
                            $message = nl2br($message);
                            $cm = new CustomerMessage();
                            $cm->id_customer_thread = $ct->id;
                            $cm->message = $message;
                            $cm->add();
                        }
                    }
                    Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customer_message_sync_imap` (`md5_header`) VALUES (\'' . pSQL($md5) . '\')');
                }
            }
            imap_expunge($mbox);
            imap_close($mbox);
            $array = array('hasError' => false, 'errors' => array($str_errors . $str_error_delete));
            die(Tools::jsonEncode($array));
        }
    }
Пример #25
0
 /**
  * Start forms process
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     if (Tools::isSubmit('submitMessage')) {
         $message = Tools::getValue('message');
         // Html entities is not usefull, iscleanHtml check there is no bad html tags.
         if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
             $this->errors[] = Tools::displayError('Invalid email address.');
         } elseif (!$message) {
             $this->errors[] = Tools::displayError('The message cannot be blank.');
         } elseif (!Validate::isCleanHtml($message)) {
             $this->errors[] = Tools::displayError('Invalid message');
         } elseif (!empty($file_attachment['name']) && $file_attachment['error'] != 0) {
             $this->errors[] = Tools::displayError('An error occurred during the file-upload process.');
         } elseif (!empty($file_attachment['name']) && !in_array(Tools::strtolower(substr($file_attachment['name'], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment['name'], -5)), $extension)) {
             $this->errors[] = Tools::displayError('Bad file extension');
         } else {
             $customer = $this->context->customer;
             if (!$customer->id) {
                 $customer->getByEmail($from);
             }
             $id_contact = (int) Configuration::get('ASKFORPRICE_CONTACT');
             $contact = new Contact($id_contact);
             if ($contact->customer_service) {
                 if ((int) $id_customer_thread) {
                     $ct = new CustomerThread($id_customer_thread);
                     $ct->status = 'open';
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->id_contact = (int) $id_contact;
                     $ct->id_order = (int) $id_order;
                     if ($id_product = (int) Tools::getValue('id_product')) {
                         $ct->id_product = $id_product;
                     }
                     $ct->update();
                 } else {
                     $ct = new CustomerThread();
                     if (isset($customer->id)) {
                         $ct->id_customer = (int) $customer->id;
                     }
                     $ct->id_shop = (int) $this->context->shop->id;
                     $ct->id_order = (int) $id_order;
                     if ($id_product = (int) Tools::getValue('id_product')) {
                         $ct->id_product = $id_product;
                     }
                     $ct->id_contact = (int) $id_contact;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $from;
                     $ct->status = 'open';
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 }
                 if ($ct->id) {
                     $cm = new CustomerMessage();
                     $cm->id_customer_thread = $ct->id;
                     $cm->message = $message;
                     if (isset($file_attachment['rename']) && !empty($file_attachment['rename']) && rename($file_attachment['tmp_name'], _PS_UPLOAD_DIR_ . basename($file_attachment['rename']))) {
                         $cm->file_name = $file_attachment['rename'];
                         @chmod(_PS_UPLOAD_DIR_ . basename($file_attachment['rename']), 0664);
                     }
                     $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                     $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                     if (!$cm->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                 }
             }
             if (!count($this->errors)) {
                 $mailpaht = _PS_MODULE_DIR_ . 'askforprice/mails/';
                 $message = Tools::nl2br(stripslashes($message));
                 $var_list = array('{message}' => $message, '{email}' => $from, '{id_product}' => (int) Tools::getValue('id_product'), '{product_name}' => '', '{product_qty}' => (int) Tools::getValue('qty'), '{suggested_price}' => (double) Tools::getValue('price'));
                 $id_product = (int) Tools::getValue('id_product');
                 if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order) {
                     $order = new Order((int) $ct->id_order);
                     $var_list['{order_name}'] = $order->getUniqReference();
                     $var_list['{id_order}'] = (int) $order->id;
                 }
                 if ($id_product) {
                     $product = new Product((int) $id_product);
                     if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id])) {
                         $var_list['{product_name}'] = $product->name[Context::getContext()->language->id];
                     }
                 }
                 if (empty($contact->email)) {
                     Mail::Send($this->context->language->id, 'askforprice_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, null, null, $mailpaht);
                 } else {
                     if (!Mail::Send($this->context->language->id, 'askforprice', Mail::l('Message from contact form') . ' [no_sync]', $var_list, $contact->email, $contact->name, $from, $customer->id ? $customer->firstname . ' ' . $customer->lastname : '', null, null, $mailpaht) || !Mail::Send($this->context->language->id, 'askforprice_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, $contact->email, $contact->name, null, null, $mailpaht)) {
                         $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                     }
                 }
             }
             if (count($this->errors) > 1) {
                 array_unique($this->errors);
             } elseif (!count($this->errors)) {
                 $this->context->smarty->assign('confirmation', 1);
             }
         }
     }
 }