/** * Render the payment gateway template. The module should provide the gateway URL and the form fields names and values. * * @param Order $order the order * @param string $gateway_url the payment gateway URL * @param array $form_data an associative array of form data, that will be rendered as hiddent fields * * @return Response the HTTP response. */ public function generateGatewayFormResponse($order, $gateway_url, $form_data) { /** @var ParserInterface $parser */ $parser = $this->getContainer()->get("thelia.parser"); $parser->setTemplateDefinition(${$parser}->getTemplateHelper()->getActiveFrontTemplate()); $renderedTemplate = $parser->render("order-payment-gateway.html", array("order_id" => $order->getId(), "cart_count" => $this->getRequest()->getSession()->getSessionCart($this->getDispatcher())->getCartItems()->count(), "gateway_url" => $gateway_url, "payment_form_data" => $form_data)); return Response::create($renderedTemplate); }
protected function displayAdminGeneralError(GetResponseForExceptionEvent $event) { // Define the template thant shoud be used $this->parser->setTemplateDefinition($this->parser->getTemplateHelper()->getActiveAdminTemplate()); $message = $event->getException()->getMessage(); $response = Response::create($this->parser->render('general_error.html', array("error_message" => $message)), 403); $event->setResponse($response); }
public function displayLogo($image) { if (file_exists(__DIR__ . DS . '..' . DS . 'logo' . DS . $image)) { $sourceImage = file_get_contents(__DIR__ . DS . '..' . DS . 'logo' . DS . $image); return Response::create($sourceImage, 200, ['Content-Type' => 'image/gif', 'Content-Length' => strlen($sourceImage)]); } else { throw new NotFoundHttpException(); } }
/** * @return Response */ public function generateAction() { /** @var Request $request */ $request = $this->getRequest(); // the locale : fr, en, $lang = $request->query->get("lang", ""); if ("" !== $lang) { if (!$this->checkLang($lang)) { $this->pageNotFound(); } } // specific content : product, category, cms $context = $request->query->get("context", ""); if (!in_array($context, array("", "catalog", "content"))) { $this->pageNotFound(); } $flush = $request->query->get("flush", ""); // check if sitemap already in cache $cacheContent = false; $cacheDir = $this->getCacheDir(); $cacheKey = self::SITEMAP_CACHE_KEY . $lang . $context; $cacheExpire = intval(ConfigQuery::read("sitemap_ttl", '7200')) ?: 7200; $cacheDriver = new FilesystemCache($cacheDir); if (!($this->checkAdmin() && "" !== $flush)) { $cacheContent = $cacheDriver->fetch($cacheKey); } else { $cacheDriver->delete($cacheKey); } // if not in cache if (false === $cacheContent) { // render the view $cacheContent = $this->renderRaw("sitemap", array("_lang_" => $lang, "_context_" => $context)); // save cache $cacheDriver->save($cacheKey, $cacheContent, $cacheExpire); } $response = new Response(); $response->setContent($cacheContent); $response->headers->set('Content-Type', 'application/xml'); return $response; }
public function set() { $form = new \Colissimo\Form\FreeShipping($this->getRequest()); $response = null; try { $vform = $this->validateForm($form); $data = $vform->get('freeshipping')->getData(); $save = new ColissimoFreeshipping(); $save->setActive(!empty($data))->save(); $response = Response::create(''); } catch (\Exception $e) { $response = JsonResponse::create(array("error" => $e->getMessage()), 500); } return $response; }
/** * Get the latest available Thelia version from the Thelia web site. * * @return Thelia\Core\HttpFoundation\Response the response */ public function getLatestTheliaVersion() { if (null !== ($response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::VIEW))) { return $response; } // get the latest version $version = @file_get_contents("http://thelia.net/version.php"); if ($version === false) { $version = $this->getTranslator()->trans("Not found"); } else { if (!preg_match("/^[0-9.]*\$/", $version)) { $version = $this->getTranslator()->trans("Unavailable"); } } return Response::create($version); }
protected function toggleSearchable($type) { try { $categoryId = $this->getRequest()->get('category_id'); $objectId = $this->getRequest()->get('object_id'); $searchable = $this->getRequest()->get('searchable') === "true" ? true : false; if ($type === 'feature') { $query = CriteriaSearchCategoryFeatureQuery::create()->filterByCategoryId($categoryId)->filterByFeatureId($objectId)->findOneOrCreate(); } elseif ($type === 'attribute') { $query = CriteriaSearchCategoryAttributeQuery::create()->filterByCategoryId($categoryId)->filterByAttributeId($objectId)->findOneOrCreate(); } $query->setSearchable($searchable)->save(); return Response::create(); } catch (\Exception $e) { return Response::create($e->getMessage(), 500); } }
/** * Constructor. * * @param array $data Array to be serialized * @param string $format serialization format, text, xml or json available * @param integer $status The response status code * @param array $headers An array of response headers * * @throws \InvalidArgumentException When the HTTP status code is not valid * * @api */ public function __construct($data = null, $format = 'json', $status = 200, $headers = array()) { parent::__construct('', $status, $headers); if ($format == 'text') { if (isset($data)) { $this->setContent($data); } $this->headers->set('Content-Type', 'text/plain'); } else { $this->format = $format; $serializer = $this->getSerializer(); if (isset($data)) { $this->setContent($serializer->serialize($data, $this->format)); } $this->headers->set('Content-Type', 'application/' . $this->format); } }
public function setFreeShipping() { if (null !== ($response = $this->checkAuth([AdminResources::MODULE], ['Predict'], AccessManager::UPDATE))) { return $response; } $form = new FreeShipping($this->getRequest()); $response = null; try { $vform = $this->validateForm($form); $data = $vform->get('freeshipping')->getData(); ConfigQuery::write("predict_freeshipping", $data); $response = Response::create(''); } catch (\Exception $e) { $response = JsonResponse::create(array("error" => $e->getMessage()), 500); } return $response; }
public function set() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('DpdPickup'), AccessManager::UPDATE))) { return $response; } $form = new \DpdPickup\Form\FreeShipping($this->getRequest()); $response = null; try { $vform = $this->validateForm($form); $data = $vform->get('freeshipping')->getData(); $save = new IcirelaisFreeshipping(); $save->setActive(!empty($data))->save(); $response = Response::create(''); } catch (\Exception $e) { $response = JsonResponse::create(array("error" => $e->getMessage()), 500); } return $response; }
public function toggleFreeShippingActivation() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('SoColissimo'), AccessManager::UPDATE))) { return $response; } $form = new \SoColissimo\Form\FreeShipping($this->getRequest()); $response = null; try { $vform = $this->validateForm($form); $freeshipping = $vform->get('freeshipping')->getData(); $deliveryModeId = $vform->get('delivery_mode')->getData(); $deliveryMode = SocolissimoDeliveryModeQuery::create()->findOneById($deliveryModeId); $deliveryMode->setFreeshippingActive($freeshipping)->save(); $response = Response::create(''); } catch (\Exception $e) { $response = JsonResponse::create(array("error" => $e->getMessage()), 500); } return $response; }
<?php /*************************************************************************************/ /* This file is part of the Thelia package. */ /* */ /* Copyright (c) OpenStudio */ /* email : dev@thelia.net */ /* web : http://www.thelia.net */ /* */ /* For the full copyright and license information, please view the LICENSE.txt */ /* file that was distributed with this source code. */ /*************************************************************************************/ use Thelia\Core\Thelia; use Thelia\Core\HttpFoundation\Response; use Thelia\Core\HttpFoundation\Request; use Thelia\Core\HttpKernel\HttpCache\HttpCache; //use Symfony\Component\DependencyInjection; $env = 'dev'; require __DIR__ . '/../core/vendor/autoload.php'; // List of allowed IP $trustedIp = array('::1', '127.0.0.1'); $request = Request::createFromGlobals(); $thelia = new Thelia("dev", true); if (false === in_array($request->getClientIp(), $trustedIp)) { $response = Response::create('Forbidden', 403)->send(); $thelia->terminate($request, $response); } else { $response = $thelia->handle($request)->prepare($request)->send(); $thelia->terminate($request, $response); }
/** * @return mixed */ public function pay(Order $order) { $c = Config::read(CmCIC::JSON_CONFIG_PATH); $currency = $order->getCurrency()->getCode(); $opts = ""; $cmCicRouter = $this->container->get('router.cmcic'); $mainRouter = $this->container->get('router.front'); $vars = array("url_bank" => sprintf(self::CMCIC_URLPAIEMENT, $c["CMCIC_SERVER"], $c["CMCIC_PAGE"]), "version" => $c["CMCIC_VERSION"], "TPE" => $c["CMCIC_TPE"], "date" => date("d/m/Y:H:i:s"), "montant" => (string) round($order->getTotalAmount(), 2) . $currency, "reference" => self::harmonise($order->getId(), 'numeric', 12), "url_retour" => URL::getInstance()->absoluteUrl($cmCicRouter->generate("cmcic.receive", array(), Router::ABSOLUTE_URL)) . "/" . (string) $order->getId(), "url_retour_ok" => URL::getInstance()->absoluteUrl($mainRouter->generate("order.placed", array("order_id" => (string) $order->getId()), Router::ABSOLUTE_URL)), "url_retour_err" => URL::getInstance()->absoluteUrl($cmCicRouter->generate("cmcic.payfail", array("order_id" => (string) $order->getId()), Router::ABSOLUTE_URL)), "lgue" => strtoupper($this->getRequest()->getSession()->getLang()->getCode()), "societe" => $c["CMCIC_CODESOCIETE"], "texte-libre" => "0", "mail" => $this->getRequest()->getSession()->getCustomerUser()->getEmail(), "nbrech" => "", "dateech1" => "", "montantech1" => "", "dateech2" => "", "montantech2" => "", "dateech3" => "", "montantech3" => "", "dateech4" => "", "montantech4" => ""); $hashable = sprintf(self::CMCIC_CGI1_FIELDS, $vars["TPE"], $vars["date"], $vars["montant"], $vars["reference"], $vars["texte-libre"], $vars["version"], $vars["lgue"], $vars["societe"], $vars["mail"], $vars["nbrech"], $vars["dateech1"], $vars["montantech1"], $vars["dateech2"], $vars["montantech2"], $vars["dateech3"], $vars["montantech3"], $vars["dateech4"], $vars["montantech4"], $opts); $mac = self::computeHmac($hashable, self::getUsableKey($c["CMCIC_KEY"])); $vars["MAC"] = $mac; $parser = $this->container->get("thelia.parser"); $parser->setTemplateDefinition(new TemplateDefinition('module_cmcic', TemplateDefinition::FRONT_OFFICE)); $render = $parser->render("gotobankservice.html", $vars); return Response::create($render); }
/** * @param Api $api * @return \Symfony\Component\HttpFoundation\Response */ private function retrieveSecureKey(Api $api) { $response = Response::create($api->getSecureKey()); $response->headers->add(['Content-Type' => 'application/octet-stream', 'Content-disposition' => sprintf('filename=%s.key', $api->getApiKey())]); return $response; }
/** * Render the given template, and returns the result as an Http Response. * * @param string $templateName the complete template name, with extension * @param array $args the template arguments * @param int $status http code status * @return \Thelia\Core\HttpFoundation\Response */ protected function render($templateName, $args = array(), $status = 200) { $response = $this->renderRaw($templateName, $args); if (!$response instanceof \Symfony\Component\HttpFoundation\Response) { $response = Response::create($response, $status); } return $response; }
public function deleteImageAction($entityId, $imageId) { $request = $this->getRequest(); $entity = $request->attributes->get('entity'); $this->checkAuth($this->getAdminResources()->getResource($entity), [], AccessManager::UPDATE); $this->checkEntityExists($entity, $entityId); $entityModel = $this->checkImage($entity, $imageId); if (null === $entityModel) { throw new HttpException(404, sprintf('{"error": "image with id %d not found"}', $imageId)); } try { $fileDeleteEvent = new FileDeleteEvent($entityModel); $this->dispatch(TheliaEvents::IMAGE_DELETE, $fileDeleteEvent); return Response::create('', 204); } catch (\Exception $e) { return JsonResponse::create(['error' => $e->getMessage()], 500); } }
/** * Process a Payzen platform request */ public function processPayzenRequest() { // The response code to the server $gateway_response_code = 'ko'; $payzenResponse = new PayzenResponse($_POST, PayzenConfigQuery::read('mode'), PayzenConfigQuery::read('test_certificate'), PayzenConfigQuery::read('production_certificate')); $request = $this->getRequest(); $order_id = intval($request->get('vads_order_id')); $this->getLog()->addInfo($this->getTranslator()->trans("Payzen platform request received for order ID %id.", array('%id' => $order_id), Payzen::MODULE_DOMAIN)); if (null !== ($order = $this->getOrder($order_id))) { // Check the authenticity of the request if ($payzenResponse->isAuthentified()) { // Check payment status if ($payzenResponse->isAcceptedPayment()) { // Payment was accepted. if ($order->isPaid()) { $this->getLog()->addInfo($this->getTranslator()->trans("Order ID %id is already paid.", array('%id' => $order_id), Payzen::MODULE_DOMAIN)); $gateway_response_code = 'payment_ok_already_done'; } else { $this->getLog()->addInfo($this->getTranslator()->trans("Order ID %id payment was successful.", array('%id' => $order_id), Payzen::MODULE_DOMAIN)); // Payment OK ! $this->confirmPayment($order_id); $gateway_response_code = 'payment_ok'; } } else { if ($payzenResponse->isCancelledPayment()) { // Payment was canceled. $this->cancelPayment($order_id); } else { // Payment was not accepted. $this->getLog()->addError($this->getTranslator()->trans("Order ID %id payment failed.", array('%id' => $order_id), Payzen::MODULE_DOMAIN)); if ($order->isPaid()) { $gateway_response_code = 'payment_ko_already_done'; } else { $gateway_response_code = 'payment_ko'; } } } } else { $this->getLog()->addError($this->getTranslator()->trans("Response could not be authentified.")); $gateway_response_code = 'auth_fail'; } } else { $gateway_response_code = 'order_not_found'; } $this->getLog()->info($this->getTranslator()->trans("Payzen platform request for order ID %id processing teminated.", array('%id' => $order_id), Payzen::MODULE_DOMAIN)); return Response::create($payzenResponse->getOutputForGateway($gateway_response_code)); }
/** * Render the given template, and returns the result as an Http Response. * * @param string $templateName the complete template name, with extension * @param array $args the template arguments * @param int $status http code status * @return \Thelia\Core\HttpFoundation\Response */ protected function render($templateName, $args = array(), $status = 200) { return Response::create($this->renderRaw($templateName, $args), $status); }
public function deleteAction($productId) { $this->checkAuth(AdminResources::PRODUCT, [], AccessManager::DELETE); $this->checkProductExists($productId); try { $event = new ProductDeleteEvent($productId); $this->dispatch(TheliaEvents::PRODUCT_DELETE, $event); return Response::create('', 204); } catch (\Exception $e) { return JsonResponse::create(['error' => $e->getMessage()], 500); } }
/** * render the RSS feed * * @param $context string The context of the feed : catalog, content. default: catalog * @param $lang string The lang of the feed : fr_FR, en_US, ... default: default language of the site * @param $id string The id of the parent element. The id of the main parent category for catalog context. * The id of the content folder for content context * @return Response * @throws \RuntimeException */ public function generateAction($context, $lang, $id) { /** @var Request $request */ $request = $this->getRequest(); // context if ("" === $context) { $context = "catalog"; } else { if (!in_array($context, array("catalog", "content", "brand"))) { $this->pageNotFound(); } } // the locale : fr_FR, en_US, if ("" !== $lang) { if (!$this->checkLang($lang)) { $this->pageNotFound(); } } else { try { $lang = Lang::getDefaultLanguage(); $lang = $lang->getLocale(); } catch (\RuntimeException $ex) { // @todo generate error page throw new \RuntimeException("No default language is defined. Please define one."); } } if (null === ($lang = LangQuery::create()->findOneByLocale($lang))) { $this->pageNotFound(); } $lang = $lang->getId(); // check if element exists and is visible if ("" !== $id) { if (false === $this->checkId($context, $id)) { $this->pageNotFound(); } } $flush = $request->query->get("flush", ""); // check if feed already in cache $cacheContent = false; $cacheDir = $this->getCacheDir(); $cacheKey = self::FEED_CACHE_KEY . $lang . $context . $id; $cacheExpire = intval(ConfigQuery::read("feed_ttl", '7200')) ?: 7200; $cacheDriver = new FilesystemCache($cacheDir); if (!($this->checkAdmin() && "" !== $flush)) { $cacheContent = $cacheDriver->fetch($cacheKey); } else { $cacheDriver->delete($cacheKey); } // if not in cache if (false === $cacheContent) { // render the view $cacheContent = $this->renderRaw("feed", array("_context_" => $context, "_lang_" => $lang, "_id_" => $id)); // save cache $cacheDriver->save($cacheKey, $cacheContent, $cacheExpire); } $response = new Response(); $response->setContent($cacheContent); $response->headers->set('Content-Type', 'application/rss+xml'); return $response; }
public function exportAction() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('Colissimo'), AccessManager::UPDATE))) { return $response; } $form = new FormExport($this->getRequest()); try { $exportForm = $this->validateForm($form); // Get new status $status_id = $exportForm->get('status_id')->getData(); $status = OrderStatusQuery::create()->filterByCode($status_id)->findOne(); // Get Colissimo orders $orders = ColissimoQuery::getOrders()->find(); $export = ""; $store_name = ConfigQuery::getStoreName(); /** @var $order \Thelia\Model\Order */ foreach ($orders as $order) { $value = $exportForm->get('order_' . $order->getId())->getData(); if ($value) { // Get order information $customer = $order->getCustomer(); $locale = $order->getLang()->getLocale(); $address = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); $country = CountryQuery::create()->findPk($address->getCountryId()); $country->setLocale($locale); $customerTitle = CustomerTitleQuery::create()->findPk($address->getCustomerTitleId()); $customerTitle->setLocale($locale); $weight = $exportForm->get('order_weight_' . $order->getId())->getData(); if ($weight == 0) { /** @var \Thelia\Model\OrderProduct $product */ foreach ($order->getOrderProducts() as $product) { $weight += (double) $product->getWeight(); } } /** * Get user's phone & cellphone * First get invoice address phone, * If empty, try to get default address' phone. * If still empty, set default value */ $phone = $address->getPhone(); if (empty($phone)) { $phone = $customer->getDefaultAddress()->getPhone(); if (empty($phone)) { $phone = self::DEFAULT_PHONE; } } // Cellphone $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = self::DEFAULT_CELLPHONE; } } $export .= "\"" . $order->getRef() . "\";\"" . $address->getLastname() . "\";\"" . $address->getFirstname() . "\";\"" . $address->getAddress1() . "\";\"" . $address->getAddress2() . "\";\"" . $address->getAddress3() . "\";\"" . $address->getZipcode() . "\";\"" . $address->getCity() . "\";\"" . $country->getIsoalpha2() . "\";\"" . $phone . "\";\"" . $cellphone . "\";\"" . $weight . "\";\"" . $customer->getEmail() . "\";\"\";\"" . $store_name . "\";\"DOM\";\r\n"; if ($status) { $event = new OrderEvent($order); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } } return Response::create(utf8_decode($export), 200, array("Content-Encoding" => "ISO-8889-1", "Content-Type" => "application/csv-tab-delimited-table", "Content-disposition" => "filename=export.csv")); } catch (FormValidationException $e) { $this->setupFormErrorContext(Translator::getInstance()->trans("colissimo expeditor export", [], Colissimo::DOMAIN_NAME), $e->getMessage(), $form, $e); return $this->render("module-configure", array("module_code" => "Colissimo")); } }
/** * Render the given template, and returns the result as an Http Response. * * @param mixed $content the response content * @param array $args the template arguments * @param int $status http code status * @param array $headers The HTTP headers of the response * @return \Thelia\Core\HttpFoundation\Response */ protected function render($content, $args = array(), $status = 200, $headers = array()) { return Response::create($this->renderRaw($content), $status, $headers); }
/** * @param $content * @return \Symfony\Component\HttpFoundation\Response */ public function createResponse($content) { return Response::create($content, 200, array('Content-Type' => 'application/csv-tab-delimited-table', 'Content-disposition' => 'filename=record.dat')); }
public function showLogAction() { $resp = new Response(); $resp->setContent(nl2br(file_get_contents($this->log_file))); return $resp; }
public function export() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('FreeShipping'), AccessManager::UPDATE))) { return $response; } $csv = new CSV(self::CSV_SEPARATOR); try { $form = new ExportOrder($this->getRequest()); $vform = $this->validateForm($form); // Check status_id $status_id = $vform->get("new_status_id")->getData(); if (!preg_match("#^nochange|processing|sent\$#", $status_id)) { throw new Exception("Bad value for new_status_id field"); } $status = OrderStatusQuery::create()->filterByCode(array(OrderStatus::CODE_PAID, OrderStatus::CODE_PROCESSING, OrderStatus::CODE_SENT), Criteria::IN)->find()->toArray("code"); $query = OrderQuery::create()->filterByDeliveryModuleId(FreeShipping::getModuleId())->filterByStatusId(array($status[OrderStatus::CODE_PAID]['Id'], $status[OrderStatus::CODE_PROCESSING]['Id']), Criteria::IN)->find(); // check form && exec csv /** @var \Thelia\Model\Order $order */ foreach ($query as $order) { $value = $vform->get('order_' . $order->getId())->getData(); // If checkbox is checked if ($value) { /** * Retrieve user with the order */ $customer = $order->getCustomer(); /** * Retrieve address with the order */ $address = OrderAddressQuery::create()->findPk($order->getDeliveryOrderAddressId()); if ($address === null) { throw new Exception("Could not find the order's invoice address"); } /** * Retrieve country with the address */ $country = CountryQuery::create()->findPk($address->getCountryId()); if ($country === null) { throw new Exception("Could not find the order's country"); } /** * Retrieve Title */ $title = CustomerTitleI18nQuery::create()->filterById($customer->getTitleId())->findOneByLocale($this->getSession()->getAdminEditionLang()->getLocale()); /** * Get user's phone & cellphone * First get invoice address phone, * If empty, try to get default address' phone. * If still empty, set default value */ $phone = $address->getPhone(); if (empty($phone)) { $phone = $customer->getDefaultAddress()->getPhone(); if (empty($phone)) { $phone = self::DEFAULT_PHONE; } } /** * Cellp */ $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = self::DEFAULT_CELLPHONE; } /** * Compute package weight */ $weight = 0; /** @var \Thelia\Model\OrderProduct $product */ foreach ($order->getOrderProducts() as $product) { $weight += (double) $product->getWeight(); } /** * Get store's name */ $store_name = ConfigQuery::read("store_name"); /** * Write CSV line */ $csv->addLine(CSVLine::create(array($address->getFirstname(), $address->getLastname(), $address->getCompany(), $address->getAddress1(), $address->getAddress2(), $address->getAddress3(), $address->getZipcode(), $address->getCity(), $country->getIsoalpha2(), $phone, $cellphone, $order->getRef(), $title->getShort(), $customer->getEmail(), $weight, $store_name))); /** * Then update order's status if necessary */ if ($status_id == "processing") { $event = new OrderEvent($order); $event->setStatus($status[OrderStatus::CODE_PROCESSING]['Id']); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } elseif ($status_id == "sent") { $event = new OrderEvent($order); $event->setStatus($status[OrderStatus::CODE_SENT]['Id']); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } } } catch (\Exception $e) { return Response::create($e->getMessage(), 500); } return Response::create(utf8_decode($csv->parse()), 200, array("Content-Encoding" => "ISO-8889-1", "Content-Type" => "application/csv-tab-delimited-table", "Content-disposition" => "filename=export.csv")); }
public function exportfile() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('DpdPickup'), AccessManager::UPDATE))) { return $response; } if (is_readable(ExportExaprint::getJSONpath())) { $admici = json_decode(file_get_contents(ExportExaprint::getJSONpath()), true); $keys = array("name", "addr", "zipcode", "city", "tel", "mobile", "mail", "expcode"); $valid = true; foreach ($keys as $key) { $valid &= isset($admici[$key]) && ($key === "assur" ? true : !empty($admici[$key])); } if (!$valid) { return Response::create(Translator::getInstance()->trans("The file DpdPickup/Config/exportdat.json is not valid. Please correct it.", [], DpdPickup::DOMAIN), 500); } } else { return Response::create(Translator::getInstance()->trans("Can't read DpdPickup/Config/exportdat.json. Did you save the export information ?", [], DpdPickup::DOMAIN), 500); } $exp_name = $admici['name']; $exp_address1 = $admici['addr']; $exp_address2 = isset($admici['addr2']) ? $admici['addr2'] : ""; $exp_zipcode = $admici['zipcode']; $exp_city = $admici['city']; $exp_phone = $admici['tel']; $exp_cellphone = $admici['mobile']; $exp_email = $admici['mail']; $exp_code = $admici['expcode']; $res = self::harmonise('$' . "VERSION=110", 'alphanumeric', 12) . "\r\n"; $orders = OrderQuery::create()->filterByDeliveryModuleId(DpdPickup::getModuleId())->find(); // FORM VALIDATION $form = new ExportExaprintSelection($this->getRequest()); $status_id = null; try { $vform = $this->validateForm($form); $status_id = $vform->get("new_status_id")->getData(); if (!preg_match("#^nochange|processing|sent\$#", $status_id)) { throw new \Exception("Invalid status ID. Expecting nochange or processing or sent"); } } catch (\Exception $e) { Tlog::getInstance()->error("Form dpdpickup.selection sent with bad infos. "); return Response::create(Translator::getInstance()->trans("Got invalid data : %err", ['%err' => $e->getMessage()], DpdPickup::DOMAIN), 500); } // For each selected order /** @var Order $order */ foreach ($orders as $order) { $orderRef = str_replace(".", "-", $order->getRef()); $collectionKey = array_search($orderRef, $vform->getData()['order_ref']); if (false !== $collectionKey && array_key_exists($collectionKey, $vform->getData()['order_ref_check']) && $vform->getData()['order_ref_check'][$collectionKey]) { // Get if the package is assured, how many packages there are & their weight $assur_package = array_key_exists($collectionKey, $vform->getData()['assur']) ? $vform->getData()['assur'][$collectionKey] : false; $pkgNumber = array_key_exists($collectionKey, $vform->getData()['pkgNumber']) ? $vform->getData()['pkgNumber'][$collectionKey] : null; $pkgWeight = array_key_exists($collectionKey, $vform->getData()['pkgWeight']) ? $vform->getData()['pkgWeight'][$collectionKey] : null; // Check if status has to be changed if ($status_id == "processing") { $event = new OrderEvent($order); $status = OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_PROCESSING); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } elseif ($status_id == "sent") { $event = new OrderEvent($order); $status = OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_SENT); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } //Get invoice address $address = OrderAddressQuery::create()->findPK($order->getInvoiceOrderAddressId()); //Get Customer object $customer = CustomerQuery::create()->findPK($order->getCustomerId()); //Get OrderAddressDpdPickup object $icirelais_code = OrderAddressIcirelaisQuery::create()->findPK($order->getDeliveryOrderAddressId()); if ($icirelais_code !== null) { // Get Customer's cellphone if (null == ($cellphone = $address->getCellphone())) { $address->getPhone(); } //Weight & price calc $price = 0; $price = $order->getTotalAmount($price, false); // tax = 0 && include postage = flase $pkgWeight = floor($pkgWeight * 100); $assur_price = $assur_package == 'true' ? $price : 0; $date_format = date("d/m/y", $order->getUpdatedAt()->getTimestamp()); $res .= self::harmonise($order->getRef(), 'alphanumeric', 35); // Order ref $res .= self::harmonise("", 'alphanumeric', 2); $res .= self::harmonise($pkgWeight, 'numeric', 8); // Package weight $res .= self::harmonise("", 'alphanumeric', 15); $res .= self::harmonise($address->getLastname(), 'alphanumeric', 35); // Charged customer $res .= self::harmonise($address->getFirstname(), 'alphanumeric', 35); $res .= self::harmonise($address->getAddress2(), 'alphanumeric', 35); // Invoice address info $res .= self::harmonise($address->getAddress3(), 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 35); $res .= self::harmonise($address->getZipcode(), 'alphanumeric', 10); // Invoice address $res .= self::harmonise($address->getCity(), 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise($address->getAddress1(), 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise("F", 'alphanumeric', 3); // Default invoice country code $res .= self::harmonise($address->getPhone(), 'alphanumeric', 30); // Invoice phone $res .= self::harmonise("", 'alphanumeric', 15); $res .= self::harmonise($exp_name, 'alphanumeric', 35); // Expeditor name $res .= self::harmonise($exp_address2, 'alphanumeric', 35); // Expeditor address $res .= self::harmonise("", 'alphanumeric', 140); $res .= self::harmonise($exp_zipcode, 'alphanumeric', 10); $res .= self::harmonise($exp_city, 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise($exp_address1, 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise("F", 'alphanumeric', 3); // Default expeditor country code $res .= self::harmonise($exp_phone, 'alphanumeric', 30); // Expeditor phone $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 1 $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 2 $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 3 $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 4 $res .= self::harmonise($date_format . ' ', 'alphanumeric', 10); // Date $res .= self::harmonise($exp_code, 'numeric', 8); // Expeditor DPD code $res .= self::harmonise("", 'alphanumeric', 35); // Bar code $res .= self::harmonise($customer->getRef(), 'alphanumeric', 35); // Customer ref $res .= self::harmonise("", 'alphanumeric', 29); $res .= self::harmonise($assur_price, 'float', 9); // Insured value $res .= self::harmonise("", 'alphanumeric', 8); $res .= self::harmonise($customer->getId(), 'alphanumeric', 35); // Customer ID $res .= self::harmonise("", 'alphanumeric', 46); $res .= self::harmonise($exp_email, 'alphanumeric', 80); // Expeditor email $res .= self::harmonise($exp_cellphone, 'alphanumeric', 35); // Expeditor cellphone $res .= self::harmonise($customer->getEmail(), 'alphanumeric', 80); // Customer email $res .= self::harmonise($cellphone, 'alphanumeric', 35); // Invoice cellphone $res .= self::harmonise("", 'alphanumeric', 96); $res .= self::harmonise($icirelais_code->getCode(), 'alphanumeric', 8); // DPD relay ID $res .= "\r\n"; } } } $response = new Response(utf8_decode(mb_strtoupper($res)), 200, array('Content-Type' => 'application/csv-tab-delimited-table;charset=iso-8859-1', 'Content-disposition' => 'filename=export.dat')); return $response; }
/** * Process a Paybox platform request */ public function processPayboxRequest() { // The response code to the server $request = $this->getRequest(); $this->getLog()->addInfo($this->getTranslator()->trans("Paybox platform request received.", [], Paybox::MODULE_DOMAIN)); $orderId = 0; $orderReference = $this->getTranslator()->trans('UNDEFINED', [], Paybox::MODULE_DOMAIN); $orderStatus = $this->getTranslator()->trans('UNKNOWN', [], Paybox::MODULE_DOMAIN); $payboxRequestValues = []; $variables = explode(';', Paybox::PARAMETRES_RETOUR); foreach ($variables as $variable) { list($nom, $dummy) = explode(':', $variable); $payboxRequestValues[$nom] = $request->get($nom); } // Vérification de la signature $stringParam = ''; foreach ($payboxRequestValues as $key => $value) { // Ignore sign parameter if ($key == 'sign') { continue; } $stringParam .= "&" . $key . '=' . $value; } $stringParam = ltrim($stringParam, '&'); $signature = base64_decode($request->get('sign')); // Charger le fichier qui contient la clef publique de Paybox $publicKeyFile = __DIR__ . DS . '..' . DS . 'Config' . DS . 'clef-publique-paybox.pem'; if (false !== ($publicKeyData = file_get_contents($publicKeyFile))) { $publicKey = openssl_pkey_get_public($publicKeyData); if (openssl_verify($stringParam, $signature, $publicKey)) { // L'ID de transaction passé est l'ID de la commande $orderId = intval($payboxRequestValues['ref']); $orderStatus = $this->getTranslator()->trans('NOT PAID', [], Paybox::MODULE_DOMAIN); if (null !== ($order = $this->getOrder($orderId))) { $orderReference = $order->getRef(); $codeRetour = $payboxRequestValues['erreur']; // Check payment status if ($codeRetour == '00000') { $orderStatus = $this->getTranslator()->trans('PAID', [], Paybox::MODULE_DOMAIN); if (!$order->isPaid()) { $this->confirmPayment($orderId); $message = $this->getTranslator()->trans("Order ID %id is confirmed.", ['%id' => $orderId], Paybox::MODULE_DOMAIN); } else { $message = $this->getTranslator()->trans("Order ID %id already paid, message ignored.", ['%id' => $orderId], Paybox::MODULE_DOMAIN); } } else { $message = $this->getTranslator()->trans("Order cannot be confirmed, Paybox returned error %num: %text", ['%num' => $codeRetour, '%text' => $this->getTextualMessage($codeRetour)], Paybox::MODULE_DOMAIN); } } else { $message = $this->getTranslator()->trans("Order ID %id was not found. Transaction reference is '%ref'.", ['%id' => $orderId, '%ref' => $payboxRequestValues['ref']], Paybox::MODULE_DOMAIN); } } else { $message = $this->getTranslator()->trans("Request parameters signature verification failed.", [], Paybox::MODULE_DOMAIN); } } else { $message = $this->getTranslator()->trans("Failed to open %file, please check Paybox configuration", ['%file' => $publicKeyFile], Paybox::MODULE_DOMAIN); } $this->getLog()->addInfo($message); $this->getLog()->info($this->getTranslator()->trans("Paybox platform request processing terminated.", [], Paybox::MODULE_DOMAIN)); $this->sendPaymentNotification($orderId, $orderReference, $orderStatus, $message); return Response::create(''); }
/** * * Method used by payment gateway. * * If this method return a \Thelia\Core\HttpFoundation\Response instance, this response is send to the * browser. * * In many cases, it's necessary to send a form to the payment gateway. * On your response you can return this form already completed, ready to be sent * * @param \Thelia\Model\Order $order processed order * @return null|\Thelia\Core\HttpFoundation\Response */ public function pay(Order $order) { $pathBin = self::getBinDirectory() . 'request'; $atosCurrency = AtosCurrencyQuery::create()->findPk($order->getCurrency()->getCode()); if (null == $atosCurrency) { throw new \InvalidArgumentException(sprintf("Atos does not supprot this currency : %s", $order->getCurrency()->getCode())); } $amount = $order->getTotalAmount(); $amount = number_format($amount, $atosCurrency->getDecimals(), '', ''); $transactionId = $this->generateTransactionID(); $order->setTransactionRef($transactionId)->save(); $router = $this->getContainer()->get('router.atos'); $this->addParam('pathfile', self::getPathfilePath())->addParam('merchant_id', self::getConfigValue('atos_merchantId'))->addParam('customer_email', $order->getCustomer()->getEmail())->addParam('currency_code', $atosCurrency->getAtosCode())->addParam('amount', $amount)->addParam('language', $order->getLang()->getCode())->addParam('transaction_id', $transactionId)->addParam('order_id', $order->getId())->addParam('automatic_response_url', URL::getInstance()->absoluteUrl($router->generate('atos.payment.confirmation')))->addParam('cancel_return_url', $this->getPaymentFailurePageUrl($order->getId(), Translator::getInstance()->trans('you cancel the payment', [], Atos::MODULE_DOMAIN)))->addParam('normal_return_url', $this->getPaymentSuccessPageUrl($order->getId())); $encrypt = exec(sprintf("%s %s", $pathBin, $this->getParameters())); if (!empty($encrypt)) { $datas = explode('!', $encrypt); if ($datas[1] == '' && $datas[2] == '') { throw new \RuntimeException(Translator::getInstance()->trans('Request binary not found in "%path"', ['%path' => $pathBin])); } elseif ($datas[1] != 0) { throw new \RuntimeException($datas[2]); } else { $parser = $this->getContainer()->get('thelia.parser'); $parser->setTemplateDefinition($parser->getTemplateHelper()->getActiveFrontTemplate()); $content = $parser->renderString(file_get_contents(__DIR__ . DS . 'templates' . DS . 'atos' . DS . 'payment.html'), ['site_name' => self::getConfigValue('store_name'), 'form' => $datas[3]]); return Response::create($content); } } else { throw new \RuntimeException(Translator::getInstance()->trans('Empty response recevied from Atos binary "%path". Please check path and permissions.', ['%path' => $pathBin], self::MODULE_DOMAIN)); // FIXME : show something to the customer } }
/** * @param $pdf * @param $fileName * @param $status * @return \Symfony\Component\HttpFoundation\Response */ protected function pdfResponse($pdf, $fileName, $status = 200) { return Response::create($pdf, $status, array('Content-type' => "application/pdf", 'Content-Disposition' => sprintf('Attachment;filename=%s.pdf', $fileName))); }
/** * @throws \Exception */ public function receiveResponse() { $request = $this->getRequest(); $order_id = $request->get('reference'); if (is_numeric($order_id)) { $order_id = (int) $order_id; } /* * Configure log output */ $log = Tlog::getInstance(); $log->setDestinations("\\Thelia\\Log\\Destination\\TlogDestinationFile"); $log->setConfig("\\Thelia\\Log\\Destination\\TlogDestinationFile", 0, THELIA_ROOT . "log" . DS . "log-cmcic.txt"); $log->info("accessed"); $order = OrderQuery::create()->findPk($order_id); /* * Retrieve HMac for CGI2 */ $config = Config::read(CmCIC::JSON_CONFIG_PATH); $hashable = sprintf(CmCIC::CMCIC_CGI2_FIELDS, $config['CMCIC_TPE'], $request->get('date'), $request->get('montant'), $request->get('reference'), $request->get('texte-libre'), $config['CMCIC_VERSION'], $request->get('code-retour'), $request->get('cvx'), $request->get('vld'), $request->get('brand'), $request->get('status3ds'), $request->get('numauto'), $request->get('motifrefus'), $request->get('originecb'), $request->get('bincb'), $request->get('hpancb'), $request->get('ipclient'), $request->get('originetr'), $request->get('veres'), $request->get('pares')); $mac = CmCIC::computeHmac($hashable, CmCIC::getUsableKey($config["CMCIC_KEY"])); $response = CmCIC::CMCIC_CGI2_MACNOTOK . $hashable; if ($mac === strtolower($request->get('MAC'))) { $code = $request->get("code-retour"); $msg = null; $status = OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_PAID); $event = new OrderEvent($order); $event->setStatus($status->getId()); switch ($code) { case "payetest": $msg = "The test payment of the order " . $order->getRef() . " has been successfully released. "; $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); break; case "paiement": $msg = "The payment of the order " . $order->getRef() . " has been successfully released. "; $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); break; case "Annulation": $msg = "Error during the paiement: " . $this->getRequest()->get("motifrefus"); break; default: $log->error("Error while receiving response from CMCIC: code-retour not valid"); throw new \Exception(Translator::getInstance()->trans("An error occured, no valid code-retour")); } if (!empty($msg)) { $log->info($msg); } $response = CmCIC::CMCIC_CGI2_MACOK; } /* * Get log back to previous state */ $log->setDestinations("\\Thelia\\Log\\Destination\\TlogDestinationRotatingFile"); return Response::create(sprintf(CmCIC::CMCIC_CGI2_RECEIPT, $response), 200, array("Content-type" => "text/plain", "Pragma" => "nocache")); }