function processOrderStep($params) { global $cart, $smarty, $errors; if (!isset($_POST['id_address_delivery']) or !Address::isCountryActiveById(intval($_POST['id_address_delivery']))) { $errors[] = 'this address is not in a valid area'; } else { $cart->id_address_delivery = intval($_POST['id_address_delivery']); $cart->id_address_invoice = isset($_POST['same']) ? intval($_POST['id_address_delivery']) : intval($_POST['id_address_invoice']); if (!$cart->update()) { $errors[] = Tools::displayError('an error occured while updating your cart'); } Module::hookExec('orderAddressVerification', array()); if (isset($_POST['message']) and !empty($_POST['message'])) { if (!Validate::isMessage($_POST['message'])) { $errors[] = Tools::displayError('invalid message'); } elseif ($oldMessage = Message::getMessageByCartId(intval($cart->id))) { $message = new Message(intval($oldMessage['id_message'])); $message->message = htmlentities($_POST['message'], ENT_COMPAT, 'UTF-8'); $message->update(); } else { $message = new Message(); $message->message = htmlentities($_POST['message'], ENT_COMPAT, 'UTF-8'); $message->id_cart = intval($cart->id); $message->id_customer = intval($cart->id_customer); $message->add(); } } } }
public static function addMessageToOrder($id_order, $message) { $msg = new Message(); $msg->message = $message; $msg->id_order = (int) $id_order; $msg->private = 1; $msg->add(); }
public function preUpdate($eventArgs) { global $_CONFIG, $_ARRAYLANG; try { $objSetting = $eventArgs->getEntity(); $value = $objSetting->getValue(); switch ($objSetting->getName()) { case 'timezone': if (!in_array($value, timezone_identifiers_list())) { \Message::add($_ARRAYLANG['TXT_CORE_TIMEZONE_INVALID'], \Message::CLASS_ERROR); throw new YamlSettingEventListenerException($_ARRAYLANG['TXT_CORE_TIMEZONE_INVALID']); } break; case 'domainUrl': $arrMatch = array(); if (preg_match('#^https?://(.*)$#', $value, $arrMatch)) { $value = $arrMatch[1]; } $value = htmlspecialchars($value, ENT_QUOTES, CONTREXX_CHARSET); $objSetting->setValue($value); break; case 'forceProtocolFrontend': if ($_CONFIG['forceProtocolFrontend'] != $value) { if (!\Cx\Core\Config\Controller\Config::checkAccessibility($value)) { $value = 'none'; } $objSetting->setValue($value); } break; case 'forceProtocolBackend': if ($_CONFIG['forceProtocolBackend'] != $value) { if (!\Cx\Core\Config\Controller\Config::checkAccessibility($value)) { $value = 'none'; } $objSetting->setValue($value); } break; case 'forceDomainUrl': $useHttps = $_CONFIG['forceProtocolBackend'] == 'https'; $protocol = 'http'; if ($useHttps == 'https') { $protocol = 'https'; } $value = \Cx\Core\Config\Controller\Config::checkAccessibility($protocol) ? $value : 'off'; $objSetting->setValue($value); break; } } catch (YamlSettingEventListenerException $e) { \DBG::msg($e->getMessage()); } }
public function ajouter($nom) { $nom = trim($nom); if (empty($nom)) { throw new TheliaAdminException("Empty message name", TheliaAdminException::MESSAGE_NAME_EMPTY); } if (Message::exist_nom($nom)) { throw new TheliaAdminException("Message already exists", TheliaAdminException::MESSAGE_ALREADY_EXISTS); } $message = new Message(); $message->nom = $nom; $message->id = $message->add(); redirige("message_modifier.php?id=" . $message->id); }
/** * write SystemMessageHook if update necessary */ public function syncSwatchbookColors() { // Count DataSet $sql = \Database::getInstance()->prepare("SELECT id FROM tl_swatchbookColors")->execute(); // Load File $file = new \File('src/CtEye/swatchbook-bundle/src/Resources/public/css/divElements.css'); /** * Dataset rows are not equal File rows * @return SystemMessage => Sync */ if ($sql->numRows !== count($file->getContentAsArray())) { \Message::add($GLOBALS['TL_LANG']['swatchbook']['syncSystemMessage'], 'TL_ERROR'); $this->isUpdate = true; } return ''; }
/** * Assign summary template */ public function webhook() { $stripe = new StripeJs(); if ($stripe->active) { if (Tools::getIsset('token') && Configuration::get('STRIPE_WEBHOOK_TOKEN') == Tools::getValue('token')) { include $this->module->getLocalPath() . 'lib/Stripe.php'; Stripe::setApiKey(Configuration::get('STRIPE_MODE') ? Configuration::get('STRIPE_PRIVATE_KEY_LIVE') : Configuration::get('STRIPE_PRIVATE_KEY_TEST')); $event_json = Tools::jsonDecode(@Tools::file_get_contents('php://input')); if (isset($event_json->id)) { /* In case there is an issue with the event, Stripe throw an exception, just ignore it. */ try { /* To double-check and for more security, we retrieve the original event directly from Stripe */ $event = Stripe_Event::retrieve($event_json->id); /* We are only handling chargebacks, other events are ignored */ if ($event->type == 'charge.dispute.created') { $id_order = (int) Db::getInstance()->getValue('SELECT id_order FROM ' . _DB_PREFIX_ . 'stripe_transaction WHERE id_stripe_transaction = \'' . pSQL($event->id) . '\' AND `charge_back` = 0'); if ($id_order) { $order = new Order((int) $id_order); if (Validate::isLoadedObject($order)) { if (Configuration::get('STRIPE_CHARGEBACKS_ORDER_STATUS') != -1) { if ($order->getCurrentState() != Configuration::get('STRIPE_CHARGEBACKS_ORDER_STATUS')) { $order->changeIdOrderState((int) Configuration::get('STRIPE_CHARGEBACKS_ORDER_STATUS'), (int) $id_order); Db::getInstance()->getValue('UPDATE `' . _DB_PREFIX_ . 'stipe_transaction` SET `charge_back` = 1 WHERE `id_stripe_transaction` = \'' . pSQL($event->id) . '\' AND `charge_back` = 0'); } } $message = new Message(); $message->message = $stripe->l('A chargeback occured on this order and was reported by Stripe on') . ' ' . date('Y-m-d H:i:s'); $message->id_order = (int) $order->id; $message->id_employee = 1; $message->private = 1; $message->date_add = date('Y-m-d H:i:s'); $message->add(); } } } } catch (Exception $e) { header('HTTP/1.1 200 OK'); exit; } header('HTTP/1.1 200 OK'); exit; } } } header('HTTP/1.1 200 OK'); exit; }
public function action_add_gift() { $view = View::factory('bookmarklet/add_gift'); $view->url = @$_GET['u']; $view->categories = ORM::factory('category')->order_by('name', 'asc')->find_all()->as_array('id', 'name'); $view->lists = $this->me('owner')->lists->order_by('updated', 'desc')->find_all()->as_array('id', 'name'); $view->errors = array(); if ($_POST) { if (!arr::get($_POST, 'list_id')) { $view->errors = 'Please select a list'; } else { $list = new Model_List((int) arr::get($_POST, 'list_id')); if ($list->owner->id != $this->me()->id) { Request::current()->redirect('user/noaccess'); } if (arr::get($_POST, 'name') && arr::get($_POST, 'category_id')) { $gift = new Model_Gift(); $gift->list_id = $list->id; $gift->name = arr::get($_POST, 'name'); $gift->price = arr::get($_POST, 'price'); $gift->url = arr::get($_POST, 'url'); $gift->category_id = arr::get($_POST, 'category_id'); $gift->details = arr::get($_POST, 'details'); $gift->save(); Message::add('success', 'Your gift has been added'); Request::current()->redirect('bookmarklet/added/' . $gift->id); } if (!arr::get($_POST, 'name')) { $view->errors['name'] = Kohana::message('gift', 'title-required'); } if (!arr::get($_POST, 'category_id')) { $view->errors['cat'] = 'Please select a category'; } } } $this->template->content = $view; }
/** * Add order private message. * * @param $text * @return bool */ public function addMessage($text) { $message = new Message(); $text = strip_tags($text, '<br>'); if (!Validate::isCleanHtml($text)) { $text = 'Invalid payment message.'; } $message->message = $text; $message->id_order = (int) $this->getOrderId(); $message->private = 1; return $message->add(); }
/** * This function checks if a form is valid * * @access protected * @global array $_ARRAYLANG array containing the language variables * @return boolean true if form is valid */ protected function validateForm() { global $_ARRAYLANG; if ($this->formGenerator === false) { // cannot save, no such entry \Message::add($_ARRAYLANG['TXT_CORE_RECORD_NO_SUCH_ENTRY'], \Message::CLASS_ERROR); return false; } else { if (!$this->formGenerator->isValid() || isset($this->options['validate']) && !$this->options['validate']($this->formGenerator)) { // data validation failed \Message::add($_ARRAYLANG['TXT_CORE_RECORD_VALIDATION_FAILED'], \Message::CLASS_ERROR); return false; } } return true; }
protected function _updateMessage($messageContent) { if ($messageContent) { if (!Validate::isMessage($messageContent)) { $this->errors[] = Tools::displayError('Invalid message'); } else { if ($oldMessage = Message::getMessageByCartId((int) $this->context->cart->id)) { $message = new Message((int) $oldMessage['id_message']); $message->message = $messageContent; $message->update(); } else { $message = new Message(); $message->message = $messageContent; $message->id_cart = (int) $this->context->cart->id; $message->id_customer = (int) $this->context->cart->id_customer; $message->add(); } } } else { if ($oldMessage = Message::getMessageByCartId($this->context->cart->id)) { $message = new Message($oldMessage['id_message']); $message->delete(); } } return true; }
/** * Add a message * * @param string $strMessage The message * @param string $strType The message type * * @deprecated Use Message::add() instead */ protected function addMessage($strMessage, $strType) { \Message::add($strMessage, $strType); }
/** * Check statut of last applications * saved with TSBuyerProtection::_requestForProtectionV2() * * Negative value means an error occurred. * Error code are managed in TSBPException. * @see (exception) TSBPException::_getFrontEndMessage() method * * Trusted Shops recommends that the request * should be automated by a cronjob with an interval of 10 minutes. * @see /../cron_garantee.php * * A message is added to the sheet order in Back-office, * @see Message class * * @uses TSBuyerProtection::_getRequestState() * @uses Message class * @return void */ public function cronTask() { // get the last 20min to get the api number (to be sure) $mktime = mktime(date('H'), date('i') - 20, date('s'), date('m'), date('d'), date('Y')); $date = date('Y-m-d H:i:s', $mktime); $db_name = _DB_PREFIX_ . TSBuyerProtection::DB_APPLI; $sql = ' SELECT * FROM `' . $db_name . '` WHERE `last_update` >= "' . $date . '" OR `statut_number` <= 0 '; $to_check = Db::getInstance()->ExecuteS($sql); foreach ($to_check as $application) { $code = $this->_getRequestState(array('tsID' => $application['ts_id'], 'applicationID' => $application['id_application'])); if (!empty($this->errors)) { $return_message = '<p style="color:red;">' . $this->l('Trusted Shops API returns an error concerning the application #') . $application['id_application'] . ': <br />' . implode(', <br />', $this->errors) . '</p>'; $this->errors = array(); } elseif ($code > 0) { $return_message = sprintf($this->l('Trusted Shops application number %1$d was successfully processed. The guarantee number is: %2$d'), $application['id_application'], $code); } $sql = ' UPDATE `' . $db_name . '` SET `statut_number` = "' . $code . '" WHERE `id_application` >= "' . $application['id_application'] . '" '; Db::getInstance()->Execute($sql); $msg = new Message(); $msg->message = $return_message; $msg->id_order = (int) $application['id_order']; $msg->private = 1; $msg->add(); } }
/** * Adds a new private message for the Admin */ public function addNewPrivateMessage($order_id, $message) { if (!(bool) $order_id) { return false; } $new_message = new Message(); $message = strip_tags($message, '<br>'); if (!Validate::isCleanHtml($message)) { $message = $this->l('Payment message is not valid, please check your module.'); } $new_message->message = $message; $new_message->id_order = $order_id; $new_message->private = 1; return $new_message->add(); }
$order_state_name = 'PS_OS_ERROR'; $message = $module->l('Unknown transaction status notification.'); break; } if ($order_state_name == 'PS_OS_PAYMENT' && $api->paymentType == 'rechnungskauf') { $order_state_name = 'MASTERPAYMENT_INVOICE_APPROVED'; } //Get order state id $id_order_state = Configuration::get($order_state_name); //Update order state if ($order && $order->getCurrentState() != $id_order_state) { $order->setCurrentState($id_order_state); } //Creates new order if (!$order && in_array($status, array('SUCCESS', 'SCHEDULED', 'PENDING', 'FAILED', 'UNKNOWN'))) { $paymentMethods = $module->getPaymentMethods(); $paymentName = isset($paymentMethods[$api->paymentType]) ? $paymentMethods[$api->paymentType] : $paymentMethods['none']; $module->registerPaymentInfo($cart->id, $api->paymentType); //create order $module->validateOrder($cart->id, $id_order_state, $totalAmount, $paymentName, $message, array(), $currency->id, false, $cart->secure_key); } //Add message to order if ($order && $message) { $msg = new Message(); $msg->message = $message; $msg->id_order = $order->id; $msg->id_customer = $cart->id_customer; $msg->private = true; $msg->add(); } exit;
<?php Database::update(array('table' => 'bad_player', 'row' => array('id' => intval($_POST['id']), 'first_name' => "'" . Database::escape($_POST['first_name']) . "'", 'last_name' => "'" . Database::escape($_POST['last_name']) . "'"))); Message::add(array('type' => 'success', 'text' => 'Joueur modifié avec succès.')); Routing::redirect(array('module' => $g_current_module, 'action' => 'list'));
public function preProcess() { parent::preProcess(); if (Tools::isSubmit('submitMessage')) { $idOrder = (int) Tools::getValue('id_order'); $msgText = htmlentities(Tools::getValue('msgText'), ENT_COMPAT, 'UTF-8'); if (!$idOrder or !Validate::isUnsignedId($idOrder)) { $this->errors[] = Tools::displayError('Order is no longer valid'); } elseif (empty($msgText)) { $this->errors[] = Tools::displayError('Message cannot be blank'); } elseif (!Validate::isMessage($msgText)) { $this->errors[] = Tools::displayError('Message is invalid (HTML is not allowed)'); } if (!sizeof($this->errors)) { $order = new Order((int) $idOrder); if (Validate::isLoadedObject($order) and $order->id_customer == self::$cookie->id_customer) { $message = new Message(); $message->id_customer = (int) self::$cookie->id_customer; $message->message = $msgText; $message->id_order = (int) $idOrder; $message->private = false; $message->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 = new Customer((int) self::$cookie->id_customer); if (Validate::isLoadedObject($customer)) { Mail::Send((int) self::$cookie->id_lang, 'order_customer_comment', Mail::l('Message from a customer', (int) self::$cookie->id_lang), array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{email}' => $customer->email, '{id_order}' => (int) $message->id_order, '{order_name}' => sprintf("#%06d", (int) $message->id_order), '{message}' => $message->message), $to, $toName, $customer->email, $customer->firstname . ' ' . $customer->lastname); } if (Tools::getValue('ajax') != 'true') { Tools::redirect('order-detail.php?id_order=' . (int) $idOrder); } } else { $this->errors[] = Tools::displayError('Order not found'); } } } if (!($id_order = (int) Tools::getValue('id_order')) or !Validate::isUnsignedId($id_order)) { $this->errors[] = Tools::displayError('Order ID required'); } else { $order = new Order($id_order); if (Validate::isLoadedObject($order) and $order->id_customer == self::$cookie->id_customer) { $id_order_state = (int) $order->getCurrentState(); $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang); $addressInvoice = new Address((int) $order->id_address_invoice); $addressDelivery = new Address((int) $order->id_address_delivery); // $stateInvoiceAddress = new State((int)$addressInvoice->id_state); $inv_adr_fields = AddressFormat::getOrderedAddressFields($addressInvoice->id_country); $dlv_adr_fields = AddressFormat::getOrderedAddressFields($addressDelivery->id_country); $invoiceAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($addressInvoice, $inv_adr_fields); $deliveryAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($addressDelivery, $dlv_adr_fields); if ($order->total_discounts > 0) { self::$smarty->assign('total_old', (double) ($order->total_paid - $order->total_discounts)); } $products = $order->getProducts(); $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $customer = new Customer($order->id_customer); self::$smarty->assign(array('shop_name' => strval(Configuration::get('PS_SHOP_NAME')), 'order' => $order, 'return_allowed' => (int) $order->isReturnable(), 'currency' => new Currency($order->id_currency), 'order_state' => (int) $id_order_state, 'invoiceAllowed' => (int) Configuration::get('PS_INVOICE'), 'invoice' => OrderState::invoiceAvailable((int) $id_order_state) and $order->invoice_number, 'order_history' => $order->getHistory((int) self::$cookie->id_lang, false, true), 'products' => $products, 'discounts' => $order->getDiscounts(), 'carrier' => $carrier, 'address_invoice' => $addressInvoice, 'invoiceState' => (Validate::isLoadedObject($addressInvoice) and $addressInvoice->id_state) ? new State((int) $addressInvoice->id_state) : false, 'address_delivery' => $addressDelivery, 'inv_adr_fields' => $inv_adr_fields, 'dlv_adr_fields' => $dlv_adr_fields, 'invoiceAddressFormatedValues' => $invoiceAddressFormatedValues, 'deliveryAddressFormatedValues' => $deliveryAddressFormatedValues, 'deliveryState' => (Validate::isLoadedObject($addressDelivery) and $addressDelivery->id_state) ? new State((int) $addressDelivery->id_state) : false, 'is_guest' => false, 'messages' => Message::getMessagesByOrderId((int) $order->id), 'CUSTOMIZE_FILE' => _CUSTOMIZE_FILE_, 'CUSTOMIZE_TEXTFIELD' => _CUSTOMIZE_TEXTFIELD_, 'isRecyclable' => Configuration::get('PS_RECYCLABLE_PACK'), 'use_tax' => Configuration::get('PS_TAX'), 'group_use_tax' => Group::getPriceDisplayMethod($customer->id_default_group) == PS_TAX_INC, 'customizedDatas' => $customizedDatas)); if ($carrier->url and $order->shipping_number) { self::$smarty->assign('followup', str_replace('@', $order->shipping_number, $carrier->url)); } self::$smarty->assign('HOOK_ORDERDETAILDISPLAYED', Module::hookExec('orderDetailDisplayed', array('order' => $order))); Module::hookExec('OrderDetail', array('carrier' => $carrier, 'order' => $order)); unset($carrier); unset($addressInvoice); unset($addressDelivery); } else { $this->errors[] = Tools::displayError('Cannot find this order'); } unset($order); } }
private function _addNewPrivateMessage($id_order, $message) { if (!$id_order) { return false; } $msg = new Message(); $message = strip_tags($message, '<br>'); if (!Validate::isCleanHtml($message)) { $message = $this->l('Payment message is not valid, please check your module.'); } $msg->message = $message; $msg->id_order = (int) $id_order; $msg->private = 1; return $msg->add(); }
<?php Message::add(array("name" => "名前", "created" => "作成日時", "category" => "カテゴリ", "subject" => "タイトル", "description" => "概要", "close" => "完了", "priority" => "優先度", "blocker" => "最高", "critical" => "高い", "major" => "普通", "minor" => "低い", "trivial" => "最低", "updated" => "更新日時", "Add new todo" => "新しい TODO を作成する", "action" => "操作", "todo manager" => "TODO 管理", "list" => "リスト"));
} if (Configuration::get('QUI_CARRIER')) { $cart->id_carrier = Configuration::get('QUI_CARRIER'); } if (Configuration::get('QUI_PAYMENT')) { $payment = Module::getInstanceById(Configuration::get('QUI_PAYMENT')); } $cart->id_customer = (int) $customer->id; $cookie->id_customer = (int) $customer->id; $cookie->update(); if (Tools::getValue('comment')) { $message = new Message(); $message->id_cart = $cart->id; $message->message = 'Комментарий:' . ' ' . Tools::getValue('comment'); $message->private = true; $message->add(); } $cart->update(); $total = $cart->getOrderTotal(true, Cart::BOTH); $order = new QuickOrderCreate(); if (Configuration::get('QUI_PAYMENT')) { $order->name = $payment->name; } $order->validateOrder((int) $cart->id, Configuration::get('PS_OS_PREPARATION'), $total, $payment->displayName, null, array(), null, false, $cart->secure_key ? $cart->secure_key : false); die(true); } else { $products_list = ''; foreach ($cart->getProducts() 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;
public function hookUpdateOrderStatus($params) { $id_order = $params['id_order']; $orderState = $params['newOrderStatus']; $shopgateOrder = PSShopgateOrder::instanceByOrderId($id_order); $shopgateConfig = new ShopgateConfigPresta(); $shopgateBuilder = new ShopgateBuilder($shopgateConfig); $shopgateMerchantApi = $shopgateBuilder->buildMerchantApi(); if (!Validate::isLoadedObject($shopgateOrder)) { return; } try { switch ($orderState->id) { case _PS_OS_DELIVERED_: $shopgateMerchantApi->setOrderShippingCompleted($shopgateOrder->order_number); break; case _PS_OS_SHIPPING_: $shopgateMerchantApi->addOrderDeliveryNote($shopgateOrder->order_number, $shopgateOrder->shipping_service, $shopgateOrder->tracking_number, true, false); break; default: break; } } catch (ShopgateMerchantApiException $e) { $msg = new Message(); $msg->message = $this->l('On order state') . ': ' . $orderState->name . ' - ' . $this->l('Shopgate status was not updated because of following error') . ': ' . $e->getMessage(); $msg->id_order = $id_order; $msg->id_employee = isset($params['cookie']->id_employee) ? $params['cookie']->id_employee : 0; $msg->private = true; $msg->add(); } }
public function _releasePayment($order, $disposition) { if (!$disposition) { die(Tools::displayError()); } list($resultcode, $errorcode, $errormessage) = $this->executeDebit($disposition['id_cart'], 0, 1); $param = ''; if ($resultcode != 0) { $message = $this->getL('release_error') . ' ' . $errormessage; $isCorrect = false; } else { $message = $this->getL('payment_released'); } $msg = new Message(); $msg->message = $message; $msg->id_order = (int) $order->id; $msg->private = 1; $msg->add(); return $errorcode; }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit cart') * @param string $message Message to attach to order */ function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false) { global $cart; $cart = new Cart(intval($id_cart)); // Does order already exists ? if (Validate::isLoadedObject($cart) and $cart->OrderExists() === 0) { // Copying data from cart $order = new Order(); $order->id_carrier = intval($cart->id_carrier); $order->id_customer = intval($cart->id_customer); $order->id_address_invoice = intval($cart->id_address_invoice); $order->id_address_delivery = intval($cart->id_address_delivery); $vat_address = new Address(intval($order->id_address_delivery)); $id_zone = Address::getZoneById(intval($vat_address->id)); $order->id_currency = $currency_special ? intval($currency_special) : intval($cart->id_currency); $order->id_lang = intval($cart->id_lang); $order->id_cart = intval($cart->id); $customer = new Customer(intval($order->id_customer)); $order->secure_key = pSQL($customer->secure_key); $order->payment = Tools::substr($paymentMethod, 0, 32); if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = intval($cart->gift); $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $amountPaid = !$dont_touch_amount ? Tools::ps_round(floatval($amountPaid), 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = floatval($cart->getOrderTotal(false, 1)); $order->total_products_wt = floatval($cart->getOrderTotal(true, 1)); $order->total_discounts = floatval(abs($cart->getOrderTotal(true, 2))); $order->total_shipping = floatval($cart->getOrderShippingCost()); $order->total_wrapping = floatval(abs($cart->getOrderTotal(true, 6))); $order->total_paid = floatval(Tools::ps_round(floatval($cart->getOrderTotal(true, 3)), 2)); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Amount paid by customer is not the right one -> Status = payment error if ($order->total_paid != $order->total_paid_real) { $id_order_state = _PS_OS_ERROR_; } // Creating order if ($cart->OrderExists() === 0) { $result = $order->add(); } else { die(Tools::displayError('An order has already been placed using this cart')); } // Next ! if ($result and isset($order->id)) { // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (!Validate::isCleanHtml($message)) { $message = $this->l('Payment message is not valid, please check your module!'); } $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `product_quantity_discount`, `product_ean13`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `discount_quantity_applied`, `download_deadline`, `download_hash`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas(intval($order->id_cart)); Product::addCustomizationPrice($products, $customizedDatas); foreach ($products as $key => $product) { $outOfStock = false; $productQuantity = intval(Product::getQuantity(intval($product['id_product']), $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL)); $quantityInStock = $productQuantity - intval($product['cart_quantity']) < 0 ? $productQuantity : intval($product['cart_quantity']); if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) { if (($updateResult = Product::updateQuantity($product)) === false or $updateResult === -1) { $outOfStock = true; } if (!$outOfStock) { $product['stock_quantity'] -= $product['cart_quantity']; } Hook::updateQuantity($product, $order); } $price = Product::getPriceStatic(intval($product['id_product']), false, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 6, NULL, false, true, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery)); $price_wt = Product::getPriceStatic(intval($product['id_product']), true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery)); // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = NULL; if ($id_product_download = ProductDownload::getIdFromIdProduct(intval($product['id_product']))) { $productDownload = new ProductDownload(intval($id_product_download)); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (Tax::excludeTaxeOption()) { $product['tax'] = 0; $product['rate'] = 0; $tax = 0; } else { $tax = Tax::getApplicableTax(intval($product['id_tax']), floatval($product['rate']), intval($order->id_address_delivery)); } $currentDate = date('Y-m-d H:m:i'); if ($product['reduction_from'] != $product['reduction_to'] and ($currentDate > $product['reduction_to'] or $currentDate < $product['reduction_from'])) { $reduction_percent = 0.0; $reduction_amount = 0.0; } else { $reduction_percent = floatval($product['reduction_percent']); $reduction_amount = Tools::ps_round(floatval($product['reduction_price']) / (1 + floatval($tax) / 100), 6); } // Quantity discount $reduc = 0.0; if ($product['cart_quantity'] > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($product['id_product'], $product['cart_quantity'])) { $reduc = QuantityDiscount::getValue($price_wt, $qtyD->id_discount_type, $qtyD->value, new Currency(intval($order->id_currency))); } $query .= '(' . intval($order->id) . ', ' . intval($product['id_product']) . ', ' . (isset($product['id_product_attribute']) ? intval($product['id_product_attribute']) : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . intval($product['cart_quantity']) . ', ' . $quantityInStock . ', ' . floatval(Product::getPriceStatic(intval($product['id_product']), false, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, Product::getTaxCalculationMethod(intval($order->id_customer)) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery))) . ', ' . floatval($reduction_percent) . ', ' . floatval($reduction_amount) . ', ' . floatval($reduc) . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . floatval($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (!$tax ? '' : pSQL($product['tax'])) . '\', ' . floatval($tax) . ', ' . floatval($product['ecotax']) . ', ' . (int) QuantityDiscount::getDiscountFromQuantity(intval($product['id_product']), intval($product['cart_quantity'])) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\'),'; $priceWithTax = number_format($price * (($tax + 100) / 100), 2, '.', ''); $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { $customizationText .= $text['name'] . $this->l(':') . ' ' . $text['value'] . ', '; } } } $customizationText = rtrim($customizationText, ', '); $customizationQuantity = intval($product['customizationQuantityTotal']); $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false, false) . '</td> </tr>'; } if (!$customizationQuantity or intval($product['cart_quantity']) > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . (intval($product['cart_quantity']) - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice((intval($product['cart_quantity']) - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false, false) . '</td> </tr>'; } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; foreach ($discounts as $discount) { $objDiscount = new Discount(intval($discount['id_discount'])); $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, 1), $order->total_shipping, $cart->id); $order->addDiscount($objDiscount->id, $objDiscount->name, $value); if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">-' . Tools::displayPrice($value, $currency, false, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId(intval($cart->id)); if ($oldMessage) { $message = new Message(intval($oldMessage['id_message'])); $message->id_order = intval($order->id); $message->update(); } // Hook new order $orderStatus = new OrderState(intval($id_order_state)); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale(intval($product['id_product']), intval($product['cart_quantity'])); } } } if (isset($outOfStock) and $outOfStock) { $history = new OrderHistory(); $history->id_order = intval($order->id); $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, intval($order->id)); $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 = intval($order->id); $new_history->changeIdOrderState(intval($id_order_state), intval($order->id)); $new_history->addWithemail(true, $extraVars); // Send an e-mail to customer if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id) { $invoice = new Address(intval($order->id_address_invoice)); $delivery = new Address(intval($order->id_address_delivery)); $carrier = new Carrier(intval($order->id_carrier)); $delivery_state = $delivery->id_state ? new State(intval($delivery->id_state)) : false; $invoice_state = $invoice->id_state ? new State(intval($invoice->id_state)) : false; $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{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_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{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_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", intval($order->id)), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), intval($order->id_lang), 1), '{carrier}' => strval($carrier->name) != '0' ? $carrier->name : Configuration::get('PS_SHOP_NAME'), '{payment}' => $order->payment, '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if (intval(Configuration::get('PS_INVOICE')) and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', intval($order->id_lang)) . sprintf('%06d', $order->invoice_number) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = NULL; } if ($orderStatus->send_email and Validate::isEmail($customer->email)) { Mail::Send(intval($order->id_lang), 'order_conf', 'Order confirmation', $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } $this->currentOrder = intval($order->id); return true; } $this->currentOrder = intval($order->id); return true; } else { die(Tools::displayError('Order creation failed')); } } else { die(Tools::displayError('An order has already been placed using this cart')); } }
/** * Allow the user to login and register using a 3rd party provider. */ function action_provider_return() { $provider_name = $this->request->param('provider'); $provider = Provider::factory($provider_name); if (!is_object($provider)) { Message::add('error', 'Provider is not enabled; please select another provider or log in normally.'); $this->redirect('user/login'); return; } // verify the request if ($provider->verify()) { // check for previously connected user $uid = $provider->user_id(); $user_identity = ORM::factory('User_Identity')->where('provider', '=', $provider_name)->and_where('identity', '=', $uid)->find(); if ($user_identity->loaded()) { $user = $user_identity->user; if ($user->loaded() && $user->id == $user_identity->user_id && is_numeric($user->id)) { // found, log user in Auth::instance()->force_login($user); // redirect to the user account $this->redirect('user/profile'); return; } } // create new account if (!Auth::instance()->logged_in()) { // Instantiate a new user $user = ORM::factory('User'); // fill in values // generate long random password (maximum that passes validation is 42 characters) $password = $user->generate_password(42); $values = array('username' => $user->generate_username(str_replace(' ', '.', $provider->name())), 'password' => $password, 'password_confirm' => $password); if (Valid::email($provider->email(), TRUE)) { $values['email'] = $provider->email(); } try { // If the post data validates using the rules setup in the user model $user->create_user($values, array('username', 'password', 'email')); // Add the login role to the user (add a row to the db) $login_role = new Model_Role(array('name' => 'login')); $user->add('roles', $login_role); // create user identity after we have the user id $user_identity = ORM::factory('User_Identity'); $user_identity->user_id = $user->id; $user_identity->provider = $provider_name; $user_identity->identity = $provider->user_id(); $user_identity->save(); // sign the user in Auth::instance()->login($values['username'], $password); // redirect to the user account $this->redirect('user/profile'); } catch (ORM_Validation_Exception $e) { if ($provider_name == 'twitter') { Message::add('error', 'The Twitter API does not support retrieving your email address; you will have to enter it manually.'); } else { Message::add('error', 'We have successfully retrieved some of the data from your other account, but we were unable to get all the required fields. Please complete form below to register an account.'); } // in case the data for some reason fails, the user will still see something sensible: // the normal registration form. $view = View::factory('user/register'); $errors = $e->errors('register'); // Move external errors to main array, for post helper compatibility $errors = array_merge($errors, isset($errors['_external']) ? $errors['_external'] : array()); $view->set('errors', $errors); // Pass on the old form values $values['password'] = $values['password_confirm'] = ''; $view->set('defaults', $values); if (Kohana::$config->load('useradmin')->captcha) { // FIXME: Is this the best place to include and use recaptcha? include Kohana::find_file('vendor', 'recaptcha/recaptchalib'); $recaptcha_config = Kohana::$config->load('recaptcha'); $recaptcha_error = null; $view->set('captcha_enabled', true); $view->set('recaptcha_html', recaptcha_get_html($recaptcha_config['publickey'], $recaptcha_error)); } $this->template->content = $view; } } else { Message::add('error', 'You are logged in, but the email received from the provider does not match the email associated with your account.'); $this->redirect('user/profile'); } } else { Message::add('error', 'Retrieving information from the provider failed. Please register below.'); $this->redirect('user/register'); } }
public function verifyUserAccount($email, $key) { global $_CORELANG; // TODO: add verificationTimeout as configuration option $verificationExpired = time() - 30 * 86400; $userFilter = array('restore_key' => $key, 'regdate' => array(array('>' => $verificationExpired), '=' => $verificationExpired), 'active' => 1, 'email' => $email); $objUser = $this->objUser->getUsers($userFilter, null, null, null, 1); if ($objUser) { if ($objUser->setVerification(true) && $objUser->releaseRestoreKey() && $objUser->store()) { // TODO: destroy session and create new one \FWUser::loginUser($objUser); // TODO: add language variable \Message::add('Sie haben Ihr Konto erfolgreich bestätigt.', \Message::CLASS_OK); return true; } $this->arrStatusMsg['error'] = array_merge($this->arrStatusMsg['error'], $objUser->getErrorMsg()); } else { $this->arrStatusMsg['error'][] = $_CORELANG['TXT_INVALID_USER_ACCOUNT']; } return false; }
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); } }
protected function _updateMessage($messageContent) { if ($messageContent) { if (!Validate::isMessage($messageContent)) { $this->errors[] = Tools::displayError('Invalid message'); } elseif ($oldMessage = Message::getMessageByCartId((int) self::$cart->id)) { $message = new Message((int) $oldMessage['id_message']); $message->message = htmlentities($messageContent, ENT_COMPAT, 'UTF-8'); $message->update(); } else { $message = new Message(); $message->message = htmlentities($messageContent, ENT_COMPAT, 'UTF-8'); $message->id_cart = (int) self::$cart->id; $message->id_customer = (int) self::$cart->id_customer; $message->add(); } } else { if ($oldMessage = Message::getMessageByCartId((int) self::$cart->id)) { $message = new Message((int) $oldMessage['id_message']); $message->delete(); } } return true; }
<?php Database::insert(array('table' => 'bad_player', 'row' => array('first_name' => "'" . Database::escape($_POST['first_name']) . "'", 'last_name' => "'" . Database::escape($_POST['last_name']) . "'"))); Message::add(array('type' => 'success', 'text' => 'Joueur ajouté avec succès.')); Routing::redirect(array('module' => $g_current_module, 'action' => $g_current_action));
public function __construct(&$language, $mode, &$arguments) { $this->template = new \Cx\Core\Html\Sigma(ASCMS_CORE_MODULE_PATH . '/Workbench/View/Template/Backend'); switch ($mode) { case 'yaml': \JS::activate('ace'); \Message::add('YAML toolbox is currently not working.', \Message::CLASS_WARN); \Message::add('Implement in ' . __METHOD__ . ' (' . __FILE__ . ')', \Message::CLASS_WARN); $this->template->loadTemplateFile('Yaml.html'); $res = \Env::get('db')->Execute('SHOW TABLES'); while (!$res->EOF) { $this->template->setVariable('TABLE', current($res->fields)); $this->template->parse('table_option'); $res->MoveNext(); } //if (mode = table) { $result = $this->loadSql($arguments['table']); //} else { //$result = sql //} //$result = $this->sql2Yaml($result); $this->template->setVariable(array('TXT_WORKBENCH_TOOLBOX_YAML_FROM_TABLE' => $language['TXT_WORKBENCH_TOOLBOX_YAML_FROM_TABLE'], 'TXT_WORKBENCH_TOOLBOX_YAML_FROM_SQL' => $language['TXT_WORKBENCH_TOOLBOX_YAML_FROM_SQL'], 'TXT_WORKBENCH_TOOLBOX_SUBMIT' => $language['TXT_WORKBENCH_TOOLBOX_SUBMIT'], 'RESULT' => $result)); break; case 'components': $this->template->loadTemplateFile('Components.html'); $query = ' SELECT `id`, `name`, `is_required`, `is_core` FROM `' . DBPREFIX . 'modules` ORDER BY `name` ASC '; $res = \Env::get('db')->Execute($query); $modules = array(); while (!$res->EOF) { $fsExists = $this->componentExistsInFileSystem($res->fields['is_core'], $res->fields['name']); $modules[$res->fields['name']] = array('id' => $res->fields['id'], 'name' => $res->fields['name'], 'type' => $res->fields['is_core'], 'exists_db' => 'true', 'exists_filesystem' => $fsExists, 'skeleton_version' => $this->getComponentStyle($res->fields['is_core'], $res->fields['name'])); $res->MoveNext(); } foreach (\Env::get('em')->getRepository('Cx\\Core\\Core\\Model\\Entity\\SystemComponent')->findAll() as $component) { if (isset($modules[$component->getName()])) { continue; } $name = $component->getName(); $type = $component->getType(); $modules[$component->getName()] = array('id' => $component->getId(), 'name' => $component->getName(), 'type' => $component->getType(), 'exists_db' => '<span style="color:red;">false</span>', 'exists_filesystem' => $this->componentExistsInFileSystem($type, $name), 'skeleton_version' => '3.1.0'); } foreach (array(ASCMS_CORE_FOLDER, ASCMS_CORE_MODULE_FOLDER, ASCMS_MODULE_FOLDER) as $basedir) { $dh = opendir(ASCMS_DOCUMENT_ROOT . $basedir); while ($file = readdir($dh)) { if (substr($file, 0, 1) == '.') { continue; } if (!is_dir(ASCMS_DOCUMENT_ROOT . $basedir . '/' . $file)) { continue; } if (isset($modules[$file])) { continue; } $modules[$file] = array('id' => '<span style="color:red;">(none)</span>', 'name' => $file, 'type' => preg_replace('/s/', '', substr(strtolower($basedir), 1)), 'exists_db' => '<span style="color:red;">false</span>', 'exists_filesystem' => '.' . $basedir . '/' . $file, 'skeleton_version' => '<span style="color:red;"><= 2.2.6</span>'); } closedir($dh); } // add all not-yet-listed components existing in filesystem $tableDefinition = array('fields' => array('id' => array('table' => array('parse' => function ($value) { return $value; })), 'exists_db' => array('table' => array('parse' => function ($value) { return $value; })), 'skeleton_version' => array('table' => array('parse' => function ($value) { return $value; })))); $table = new \BackendTable(new \Cx\Core_Modules\Listing\Model\Entity\DataSet($modules), $tableDefinition); $this->template->setVariable(array('RECORD_COUNT' => count($modules), 'RESULT' => $table->toHtml())); break; } }
/** * Writes the component.yml file with the data defined in component data array * * @param \Cx\Core\View\Model\Entity\Theme $theme the theme object */ public function saveComponentData(\Cx\Core\View\Model\Entity\Theme $theme) { global $_ARRAYLANG; if (!file_exists(\Env::get('cx')->getWebsiteThemesPath() . '/' . $theme->getFoldername())) { if (!\Cx\Lib\FileSystem\FileSystem::make_folder(\Env::get('cx')->getWebsiteThemesPath() . '/' . $theme->getFoldername())) { \Message::add($theme->getFoldername() . " : " . $_ARRAYLANG['TXT_THEME_UNABLE_TO_CREATE']); } } $filePath = \Env::get('cx')->getWebsiteThemesPath() . '/' . $theme->getFoldername() . '/component.yml'; try { $file = new \Cx\Lib\FileSystem\File($filePath); $file->touch(); $yaml = new \Symfony\Component\Yaml\Yaml(); $file->write($yaml->dump(array('DlcInfo' => $theme->getComponentData()))); } catch (\Exception $e) { \DBG::log($e->getMessage()); throw new $e(); } }
/** * Write all settings to the config file * */ public static function updatePhpCache() { global $_ARRAYLANG, $_CONFIG; if (!\Cx\Lib\FileSystem\FileSystem::makeWritable(self::getSettingsFile())) { \Message::add(self::getSettingsFile() . ' ' . $_ARRAYLANG['TXT_SETTINGS_ERROR_WRITABLE'], \Message::CLASS_ERROR); return false; } //get values from ymlsetting \Cx\Core\Setting\Controller\Setting::init('Config', NULL, 'Yaml'); $ymlArray = \Cx\Core\Setting\Controller\Setting::getArray('Config', null); $intMaxLen = 0; $ymlArrayValues = array(); foreach ($ymlArray as $key => $ymlValue) { $_CONFIG[$key] = $ymlValue['value']; $ymlArrayValues[$ymlValue['group']][$key] = $ymlValue['value']; // special case to add legacy domainUrl configuration option if ($key == 'mainDomainId') { $domainRepository = new \Cx\Core\Net\Model\Repository\DomainRepository(); $objMainDomain = $domainRepository->findOneBy(array('id' => $ymlArray[$key]['value'])); if ($objMainDomain) { $domainUrl = $objMainDomain->getName(); } else { $domainUrl = $_SERVER['SERVER_NAME']; } $ymlArrayValues[$ymlValue['group']]['domainUrl'] = $domainUrl; if ($_CONFIG['xmlSitemapStatus'] == 'on') { \Cx\Core\PageTree\XmlSitemapPageTree::write(); } } $intMaxLen = strlen($key) > $intMaxLen ? strlen($key) : $intMaxLen; } $intMaxLen += strlen('$_CONFIG[\'\']') + 1; //needed for formatted output // update environment \Env::set('config', $_CONFIG); $strHeader = "<?php\n"; $strHeader .= "/**\n"; $strHeader .= "* This file is generated by the \"settings\"-menu in your CMS.\n"; $strHeader .= "* Do not try to edit it manually!\n"; $strHeader .= "*/\n\n"; $strFooter = "?>"; //Write values $data = $strHeader; $strBody = ''; foreach ($ymlArrayValues as $group => $sectionValues) { $strBody .= "/**\n"; $strBody .= "* -------------------------------------------------------------------------\n"; $strBody .= "* " . ucfirst($group) . "\n"; $strBody .= "* -------------------------------------------------------------------------\n"; $strBody .= "*/\n"; foreach ($sectionValues as $sectionName => $sectionNameValue) { $strBody .= sprintf("%-" . $intMaxLen . "s", '$_CONFIG[\'' . $sectionName . '\']'); $strBody .= "= "; $strBody .= (self::isANumber($sectionNameValue) ? $sectionNameValue : '"' . str_replace('"', '\\"', $sectionNameValue) . '"') . ";\n"; } $strBody .= "\n"; } $data .= $strBody; $data .= $strFooter; try { $objFile = new \Cx\Lib\FileSystem\File(self::getSettingsFile()); $objFile->write($data); return true; } catch (\Cx\Lib\FileSystem\FileSystemException $e) { \DBG::msg($e->getMessage()); } return false; }