示例#1
0
 /**
  * @param $areaId
  * @param $weight
  *
  * @return mixed
  * @throws DeliveryException
  */
 public static function getPostageAmount($areaId, $weight)
 {
     $freeshipping = @(bool) ConfigQuery::read("predict_freeshipping");
     $postage = 0;
     if (!$freeshipping) {
         $prices = static::getPrices();
         /* check if Predict delivers the asked area */
         if (!isset($prices[$areaId]) || !isset($prices[$areaId]["slices"])) {
             throw new DeliveryException("Predict delivery unavailable for the chosen delivery country");
         }
         $areaPrices = $prices[$areaId]["slices"];
         ksort($areaPrices);
         /* check this weight is not too much */
         end($areaPrices);
         $maxWeight = key($areaPrices);
         if ($weight > $maxWeight) {
             throw new DeliveryException(sprintf("Predict delivery unavailable for this cart weight (%s kg)", $weight));
         }
         $postage = current($areaPrices);
         while (prev($areaPrices)) {
             if ($weight > key($areaPrices)) {
                 break;
             }
             $postage = current($areaPrices);
         }
     }
     return $postage;
 }
示例#2
0
 /**
  * this method returns an array ***Thanks cap'tain obvious \(^.^)/***
  *->
  * @return array
  */
 public function buildArray()
 {
     // Find the address ... To find ! \m/
     $zipcode = $this->getZipcode();
     $city = $this->getCity();
     $address = $this->getAddress();
     $address = array("zipcode" => $zipcode, "city" => $city, "address" => "", "countrycode" => "FR");
     if (empty($zipcode) || empty($city)) {
         $search = AddressQuery::create();
         $customer = $this->securityContext->getCustomerUser();
         if ($customer !== null) {
             $search->filterByCustomerId($customer->getId());
             $search->filterByIsDefault("1");
         } else {
             throw new \ErrorException("Customer not connected.");
         }
         $search = $search->findOne();
         $address["zipcode"] = $search->getZipcode();
         $address["city"] = $search->getCity();
         $address["address"] = $search->getAddress1();
         $address["countrycode"] = $search->getCountry()->getIsoalpha2();
     }
     // Then ask the Web Service
     $request = new FindByAddress();
     $request->setAddress($address["address"])->setZipCode($address["zipcode"])->setCity($address["city"])->setCountryCode($address["countrycode"])->setFilterRelay("1")->setRequestId(md5(microtime()))->setLang("FR")->setOptionInter("1")->setShippingDate(date("d/m/Y"))->setAccountNumber(ConfigQuery::read('socolissimo_login'))->setPassword(ConfigQuery::read('socolissimo_pwd'));
     try {
         $response = $request->exec();
     } catch (InvalidArgumentException $e) {
         $response = array();
     } catch (\SoapFault $e) {
         $response = array();
     }
     return $response;
 }
示例#3
0
 /**
  * @param  int                                       $titleId          customer title id (from customer_title table)
  * @param  string                                    $firstname        customer first name
  * @param  string                                    $lastname         customer last name
  * @param  string                                    $address1         customer address
  * @param  string                                    $address2         customer adress complement 1
  * @param  string                                    $address3         customer adress complement 2
  * @param  string                                    $phone            customer phone number
  * @param  string                                    $cellphone        customer cellphone number
  * @param  string                                    $zipcode          customer zipcode
  * @param  string                                    $city
  * @param  int                                       $countryId        customer country id (from Country table)
  * @param  string                                    $email            customer email, must be unique
  * @param  string                                    $plainPassword    customer plain password, hash is made calling setPassword method. Not mandatory parameter but an exception is thrown if customer is new without password
  * @param  string                                    $lang
  * @param  int                                       $reseller
  * @param  null                                      $sponsor
  * @param  int                                       $discount
  * @param  null                                      $company
  * @param  null                                      $ref
  * @param  bool                                      $forceEmailUpdate true if the email address could be updated.
  * @param  int                                       $stateId          customer state id (from State table)
  * @throws \Exception
  * @throws \Propel\Runtime\Exception\PropelException
  */
 public function createOrUpdate($titleId, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $countryId, $email = null, $plainPassword = null, $lang = null, $reseller = 0, $sponsor = null, $discount = 0, $company = null, $ref = null, $forceEmailUpdate = false, $stateId = null)
 {
     $this->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setEmail($email, $forceEmailUpdate)->setPassword($plainPassword)->setReseller($reseller)->setSponsor($sponsor)->setDiscount($discount)->setRef($ref);
     if (!is_null($lang)) {
         $this->setLangId($lang);
     }
     $con = Propel::getWriteConnection(CustomerTableMap::DATABASE_NAME);
     $con->beginTransaction();
     try {
         if ($this->isNew()) {
             $address = new Address();
             $address->setLabel(Translator::getInstance()->trans("Main address"))->setCompany($company)->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setAddress1($address1)->setAddress2($address2)->setAddress3($address3)->setPhone($phone)->setCellphone($cellphone)->setZipcode($zipcode)->setCity($city)->setCountryId($countryId)->setStateId($stateId)->setIsDefault(1);
             $this->addAddress($address);
             if (ConfigQuery::isCustomerEmailConfirmationEnable()) {
                 $this->setConfirmationToken(bin2hex(random_bytes(32)));
             }
         } else {
             $address = $this->getDefaultAddress();
             $address->setCompany($company)->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setAddress1($address1)->setAddress2($address2)->setAddress3($address3)->setPhone($phone)->setCellphone($cellphone)->setZipcode($zipcode)->setCity($city)->setCountryId($countryId)->setStateId($stateId)->save($con);
         }
         $this->save($con);
         $con->commit();
     } catch (PropelException $e) {
         $con->rollBack();
         throw $e;
     }
 }
 /**
  * @see \Thelia\Core\Security\Authentication\AuthenticatorInterface::getAuthentifiedUser()
  */
 public function getAuthentifiedUser()
 {
     if ($this->request->isMethod($this->options['required_method'])) {
         if (!$this->loginForm->isValid()) {
             throw new ValidatorException("Form is not valid.");
         }
         // Retreive user
         $username = $this->getUsername();
         $password = $this->loginForm->get($this->options['password_field_name'])->getData();
         $user = $this->userProvider->getUser($username);
         if ($user === null) {
             throw new UsernameNotFoundException(sprintf("Username '%s' was not found.", $username));
         }
         // Check user password
         $authOk = $user->checkPassword($password) === true;
         if ($authOk !== true) {
             throw new WrongPasswordException(sprintf("Wrong password for user '%s'.", $username));
         }
         if (ConfigQuery::isCustomerEmailConfirmationEnable() && $user instanceof Customer) {
             // Customer (confirmation_token & enable) introduces since Thelia 2.4
             // this test prevent backward compatibility and if option is enable when customer has been created
             if ($user->getConfirmationToken() !== null && !$user->getEnable()) {
                 throw (new CustomerNotConfirmedException())->setUser($user);
             }
         }
         return $user;
     }
     throw new \RuntimeException("Invalid method.");
 }
示例#5
0
 public function update_status(OrderEvent $event)
 {
     if ($event->getOrder()->getDeliveryModuleId() === DpdClassic::getModuleId()) {
         if ($event->getOrder()->getStatusId() === DpdClassic::STATUS_SENT) {
             $contact_email = ConfigQuery::read('store_email');
             if ($contact_email) {
                 $message = MessageQuery::create()->filterByName('order_confirmation_dpdclassic')->findOne();
                 if (false === $message) {
                     throw new \Exception("Failed to load message 'order_confirmation_dpdclassic'.");
                 }
                 $order = $event->getOrder();
                 $customer = $order->getCustomer();
                 $this->parser->assign('order_id', $order->getId());
                 $this->parser->assign('order_ref', $order->getRef());
                 $this->parser->assign('order_date', $order->getCreatedAt());
                 $this->parser->assign('update_date', $order->getUpdatedAt());
                 $this->parser->assign('package', $order->getDeliveryRef());
                 $message->setLocale($order->getLang()->getLocale());
                 $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name'));
                 // Build subject and body
                 $message->buildMessage($this->parser, $instance);
                 $this->getMailer()->send($instance);
             }
         }
     }
 }
 /**
  * Fill the form with the configuration data
  */
 public function saveAction()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::MODULE, [OpenGraph::DOMAIN_NAME], AccessManager::UPDATE))) {
         return $response;
     }
     // Create the form from the request
     $form = $this->createForm('open.graph.configuration.form');
     // Initialize the potential error
     $error_message = null;
     try {
         // Check the form against constraints violations
         $validateForm = $this->validateForm($form);
         // Get the form field values
         $data = $validateForm->getData();
         OpenGraph::setConfigValue(OpenGraphConfigValue::ENABLE_SHARING_BUTTONS, is_bool($data["enable_sharing_buttons"]) ? (int) $data["enable_sharing_buttons"] : $data["enable_sharing_buttons"]);
         foreach ($data as $name => $value) {
             ConfigQuery::write("opengraph_" . $name, $value, false, true);
         }
         // Redirect to the configuration page if everything is OK
         return $this->redirectToConfigurationPage();
     } catch (FormValidationException $e) {
         // Form cannot be validated. Create the error message using
         // the BaseAdminController helper method.
         $error_message = $this->createStandardFormValidationErrorMessage($e);
     }
     if (null !== $error_message) {
         $this->setupFormErrorContext('configuration', $error_message, $form);
         $response = $this->render("module-configure", ['module_code' => 'OpenGraph']);
     }
     return $response;
 }
示例#7
0
 public function update_status(OrderEvent $event)
 {
     if ($event->getOrder()->getDeliveryModuleId() === LocalPickup::getModCode()) {
         if ($event->getOrder()->isSent()) {
             $contact_email = ConfigQuery::read('store_email');
             if ($contact_email) {
                 $message = MessageQuery::create()->filterByName('order_confirmation_localpickup')->findOne();
                 if (false === $message) {
                     throw new \Exception("Failed to load message 'order_confirmation_localpickup'.");
                 }
                 $order = $event->getOrder();
                 $customer = $order->getCustomer();
                 $store = ConfigQuery::create();
                 $country = CountryQuery::create()->findPk($store->read("store_country"));
                 $country = CountryI18nQuery::create()->filterById($country->getId())->findOneByLocale($order->getLang()->getLocale())->getTitle();
                 $this->parser->assign('order_id', $order->getId());
                 $this->parser->assign('order_ref', $order->getRef());
                 $this->parser->assign('store_name', $store->read("store_name"));
                 $this->parser->assign('store_address1', $store->read("store_address1"));
                 $this->parser->assign('store_address2', $store->read("store_address2"));
                 $this->parser->assign('store_address3', $store->read("store_address3"));
                 $this->parser->assign('store_zipcode', $store->read("store_zipcode"));
                 $this->parser->assign('store_city', $store->read("store_city"));
                 $this->parser->assign('store_country', $country);
                 $message->setLocale($order->getLang()->getLocale());
                 $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name'));
                 // Build subject and body
                 $message->buildMessage($this->parser, $instance);
                 $this->getMailer()->send($instance);
             }
         }
     }
 }
 public function __construct()
 {
     $this->url = ConfigQuery::read('hookpiwikanalytics_url', false);
     $this->website_id = ConfigQuery::read('hookpiwikanalytics_website_id', false);
     \PiwikTracker::$URL = $this->url;
     $this->tracker = new \PiwikTracker($this->website_id);
 }
示例#9
0
 public function onMainHeadBottom(HookRenderEvent $event)
 {
     $value = trim(ConfigQuery::read("hookanalytics_trackingcode", ""));
     if ("" != $value) {
         $event->add($value);
     }
 }
示例#10
0
 public function postActivation(ConnectionInterface $con = null)
 {
     $languages = LangQuery::create()->find();
     ConfigQuery::write(self::CONFIG_ENABLED, self::DEFAULT_ENABLED);
     ConfigQuery::write(self::CONFIG_THRESHOLD, self::DEFAULT_THRESHOLD);
     ConfigQuery::write(self::CONFIG_EMAILS, self::DEFAULT_EMAILS);
     // create new message
     if (null === MessageQuery::create()->findOneByName('stockalert_customer')) {
         $message = new Message();
         $message->setName('stockalert_customer')->setHtmlTemplateFileName('alert-customer.html')->setHtmlLayoutFileName('')->setTextTemplateFileName('alert-customer.txt')->setTextLayoutFileName('')->setSecured(0);
         foreach ($languages as $language) {
             $locale = $language->getLocale();
             $message->setLocale($locale);
             $message->setTitle($this->trans('Stock Alert - Customer', [], $locale));
             $message->setSubject($this->trans('Product {$product_title} is available again', [], $locale));
         }
         $message->save();
         $message = new Message();
         $message->setName('stockalert_administrator')->setHtmlTemplateFileName('alert-administrator.html')->setHtmlLayoutFileName('')->setTextTemplateFileName('alert-administrator.txt')->setTextLayoutFileName('')->setSecured(0);
         foreach ($languages as $language) {
             $locale = $language->getLocale();
             $message->setLocale($locale);
             $message->setTitle($this->trans('Stock Alert - Administrator', [], $locale));
             $message->setSubject($this->trans('Product {$product_title} is (nearly) out of stock', [], $locale));
         }
         $message->save();
     }
     try {
         RestockingAlertQuery::create()->findOne();
     } catch (\Exception $e) {
         $database = new Database($con);
         $database->insertSql(null, [__DIR__ . '/Config/thelia.sql']);
     }
 }
示例#11
0
 /**
  * Save the previous URL in session which is based on the referer header or the request, or
  * the _previous_url request attribute, if defined.
  *
  * If the value of _previous_url is "dont-save", the current referrer is not saved.
  *
  * @param FilterResponseEvent $event
  */
 public function registerPreviousUrl(PostResponseEvent $event)
 {
     $request = $event->getRequest();
     $referrer = $request->attributes->get('_previous_url', null);
     if (null !== $referrer) {
         // A previous URL (or the keyword 'dont-save') has been specified.
         if ('dont-save' == $referrer) {
             // We should not save the current URL as the previous URL
             $referrer = null;
         }
     } else {
         // The current URL will become the previous URL
         $referrer = $request->getUri();
     }
     // Set previous URL, if defined
     if (null !== $referrer) {
         $session = $request->getSession();
         if (ConfigQuery::read("one_domain_foreach_lang", false) == 1) {
             $components = parse_url($referrer);
             $lang = LangQuery::create()->filterByUrl(sprintf("%s://%s", $components["scheme"], $components["host"]), ModelCriteria::LIKE)->findOne();
             if (null !== $lang) {
                 $session->setReturnToUrl($referrer);
             }
         } else {
             if (false !== strpos($referrer, $request->getSchemeAndHttpHost())) {
                 $session->setReturnToUrl($referrer);
             }
         }
     }
 }
 public function exapaqConfigure()
 {
     if (null !== ($response = $this->checkAuth([AdminResources::MODULE], ['Predict'], AccessManager::UPDATE))) {
         return $response;
     }
     $error_msg = false;
     $save_mode = "stay";
     $form = new ConfigureForm($this->getRequest());
     try {
         $vform = $this->validateForm($form);
         $save_mode = $this->getRequest()->request->get("save_mode");
         ConfigQuery::write("store_exapaq_account", $vform->get("account_number")->getData());
         ConfigQuery::write("store_cellphone", $vform->get("store_cellphone")->getData());
         ConfigQuery::write("store_predict_option", $vform->get("predict_option")->getData() ? "1" : "");
     } catch (FormValidationException $ex) {
         // Form cannot be validated
         $error_msg = $this->createStandardFormValidationErrorMessage($ex);
     } catch (\Exception $ex) {
         // Any other error
         $error_msg = $ex->getMessage();
     }
     if (false !== $error_msg) {
         $form->setErrorMessage($error_msg);
         $this->getParserContext()->addForm($form)->setGeneralError($error_msg);
     }
     if ($save_mode !== "stay") {
         return $this->generateRedirectFromRoute("admin.module", [], ['_controller' => 'Thelia\\Controller\\Admin\\ModuleController::indexAction']);
     }
     return $this->render("module-configure", ["module_code" => "Predict", "tab" => "configure"]);
 }
示例#13
0
 public function loadStatsAjaxAction()
 {
     if (null !== ($response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::VIEW))) {
         return $response;
     }
     $cacheExpire = ConfigQuery::getAdminCacheHomeStatsTTL();
     /** @var AdapterInterface $cacheAdapter */
     $cacheAdapter = $this->container->get('thelia.cache');
     $month = (int) $this->getRequest()->query->get('month', date('m'));
     $year = (int) $this->getRequest()->query->get('year', date('Y'));
     $cacheKey = self::STATS_CACHE_KEY . "_" . $month . "_" . $year;
     $cacheItem = $cacheAdapter->getItem($cacheKey);
     // force flush
     if ($this->getRequest()->query->get('flush', "0")) {
         $cacheAdapter->deleteItem($cacheItem);
     }
     if (!$cacheItem->isHit()) {
         $data = $this->getStatus($month, $year);
         $cacheItem->set(json_encode($data));
         $cacheItem->expiresAfter($cacheExpire);
         if ($cacheExpire) {
             $cacheAdapter->save($cacheItem);
         }
     }
     return $this->jsonResponse($cacheItem->get());
 }
示例#14
0
 /**
  * @inheritdoc
  */
 public function postActivation(ConnectionInterface $con = null)
 {
     $fileSystem = new Filesystem();
     //Check for environment
     if ($env = $this->getContainer()->getParameter('kernel.environment')) {
         //Check for backward compatibility
         if ($env !== "prod" && $env !== "dev") {
             //Remove separtion between dev and prod in particular environment
             $env = str_replace('_dev', '', $env);
             $this->webMediaEnvPath = $this->webMediaPath . DS . $env;
         }
     }
     // Create symbolic links or hard copy in the web directory
     // (according to \Thelia\Action\Document::CONFIG_DELIVERY_MODE),
     // to make the TinyMCE code available.
     if (false === $fileSystem->exists($this->webJsPath)) {
         if (ConfigQuery::read(Document::CONFIG_DELIVERY_MODE) === 'symlink') {
             $fileSystem->symlink($this->jsPath, $this->webJsPath);
         } else {
             $fileSystem->mirror($this->jsPath, $this->webJsPath);
         }
     }
     // Create the media directory in the web root , if required
     if (null !== $this->webMediaEnvPath) {
         if (false === $fileSystem->exists($this->webMediaEnvPath)) {
             $fileSystem->mkdir($this->webMediaEnvPath . DS . 'upload');
             $fileSystem->mkdir($this->webMediaEnvPath . DS . 'thumbs');
         }
     } else {
         if (false === $fileSystem->exists($this->webMediaPath)) {
             $fileSystem->mkdir($this->webMediaPath . DS . 'upload');
             $fileSystem->mkdir($this->webMediaPath . DS . 'thumbs');
         }
     }
 }
示例#15
0
 /**
  * Shuts the kernel down if it was used in the test.
  */
 protected function tearDown()
 {
     ConfigQuery::write('one_domain_foreach_lang', $this->isMultiDomainActivated);
     if (null !== static::$kernel) {
         static::$kernel->shutdown();
     }
 }
示例#16
0
 /**
  *
  * set the default value for thelia
  *
  * In this case there is no action so we have to verify if some needed params are not missing
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  */
 public function noAction(Request $request)
 {
     $view = null;
     if (!($view = $request->query->get('view'))) {
         if ($request->request->has('view')) {
             $view = $request->request->get('view');
         }
     }
     if (null !== $view) {
         $request->attributes->set('_view', $view);
     }
     if (null === $view && null === $request->attributes->get("_view")) {
         $request->attributes->set("_view", "index");
     }
     if (ConfigQuery::isRewritingEnable()) {
         if ($request->attributes->get('_rewritten', false) === false) {
             /* Does the query GET parameters match a rewritten URL ? */
             $rewrittenUrl = URL::getInstance()->retrieveCurrent($request);
             if ($rewrittenUrl->rewrittenUrl !== null) {
                 /* 301 redirection to rewritten URL */
                 return $this->generateRedirect($rewrittenUrl, 301);
             }
         }
     }
 }
示例#17
0
 public function saveAction()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::STORE, array(), AccessManager::UPDATE))) {
         return $response;
     }
     $error_msg = false;
     $response = null;
     $configStoreForm = new ConfigStoreForm($this->getRequest());
     try {
         $form = $this->validateForm($configStoreForm);
         $data = $form->getData();
         // Update store
         foreach ($data as $name => $value) {
             if (!in_array($name, array('success_url', 'error_message'))) {
                 ConfigQuery::write($name, $value, false);
             }
         }
         $this->adminLogAppend(AdminResources::STORE, AccessManager::UPDATE, "Store configuration changed");
         if ($this->getRequest()->get('save_mode') == 'stay') {
             $response = $this->generateRedirectFromRoute('admin.configuration.store.default');
         } else {
             $response = $this->generateSuccessRedirect($configStoreForm);
         }
     } catch (\Exception $ex) {
         $error_msg = $ex->getMessage();
     }
     if (false !== $error_msg) {
         $this->setupFormErrorContext($this->getTranslator()->trans("Store configuration failed."), $error_msg, $configStoreForm, $ex);
         $response = $this->renderTemplate();
     }
     return $response;
 }
示例#18
0
文件: Cart.php 项目: alex63530/thelia
 public function parseResults(LoopResult $loopResult)
 {
     $taxCountry = $this->container->get('thelia.taxEngine')->getDeliveryCountry();
     $locale = $this->request->getSession()->getLang()->getLocale();
     $checkAvailability = ConfigQuery::checkAvailableStock();
     $defaultAvailability = intval(ConfigQuery::read('default-available-stock', 100));
     foreach ($loopResult->getResultDataCollection() as $cartItem) {
         $product = $cartItem->getProduct(null, $locale);
         $productSaleElement = $cartItem->getProductSaleElements();
         $loopResultRow = new LoopResultRow();
         $loopResultRow->set("ITEM_ID", $cartItem->getId());
         $loopResultRow->set("TITLE", $product->getTitle());
         $loopResultRow->set("REF", $product->getRef());
         $loopResultRow->set("QUANTITY", $cartItem->getQuantity());
         $loopResultRow->set("PRODUCT_ID", $product->getId());
         $loopResultRow->set("PRODUCT_URL", $product->getUrl($this->request->getSession()->getLang()->getLocale()));
         if (!$checkAvailability || $product->getVirtual() === 1) {
             $loopResultRow->set("STOCK", $defaultAvailability);
         } else {
             $loopResultRow->set("STOCK", $productSaleElement->getQuantity());
         }
         $loopResultRow->set("PRICE", $cartItem->getPrice())->set("PROMO_PRICE", $cartItem->getPromoPrice())->set("TAXED_PRICE", $cartItem->getTaxedPrice($taxCountry))->set("PROMO_TAXED_PRICE", $cartItem->getTaxedPromoPrice($taxCountry))->set("IS_PROMO", $cartItem->getPromo() === 1 ? 1 : 0);
         $loopResultRow->set("PRODUCT_SALE_ELEMENTS_ID", $productSaleElement->getId());
         $loopResultRow->set("PRODUCT_SALE_ELEMENTS_REF", $productSaleElement->getRef());
         $loopResult->addRow($loopResultRow);
     }
     return $loopResult;
 }
示例#19
0
 public function updateStatus(OrderEvent $event)
 {
     $order = $event->getOrder();
     $Predict = new Predict();
     if ($order->isSent() && $order->getDeliveryModuleId() == $Predict->getModuleModel()->getId()) {
         $contact_email = ConfigQuery::read('store_email');
         if ($contact_email) {
             $message = MessageQuery::create()->filterByName('mail_predict')->findOne();
             if (false === $message) {
                 throw new \Exception(Translator::getInstance()->trans("Failed to load message '%mail_tpl_name'.", ["%mail_tpl_name" => "mail_predict"], Predict::MESSAGE_DOMAIN));
             }
             $order = $event->getOrder();
             $customer = $order->getCustomer();
             $this->parser->assign('customer_id', $customer->getId());
             $this->parser->assign('order_ref', $order->getRef());
             $this->parser->assign('order_date', $order->getCreatedAt());
             $this->parser->assign('order_id', $order->getId());
             $this->parser->assign('update_date', $order->getUpdatedAt());
             $this->parser->assign('package', $order->getDeliveryRef());
             $message->setLocale($order->getLang()->getLocale());
             $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name'));
             // Build subject and body
             $message->buildMessage($this->parser, $instance);
             $this->mailer->send($instance);
             Tlog::getInstance()->debug("Predict shipping message sent to customer " . $customer->getEmail());
         } else {
             $customer = $order->getCustomer();
             Tlog::getInstance()->debug("Predict shipping message no contact email customer_id", $customer->getId());
         }
     }
 }
示例#20
0
 public function checkDuplicateName($value, ExecutionContextInterface $context)
 {
     $config = ConfigQuery::create()->findOneByName($value);
     if ($config) {
         $context->addViolation(Translator::getInstance()->trans('A variable with name "%name" already exists.', array('%name' => $value)));
     }
 }
示例#21
0
 public function doRequest(GetResponseEvent $event)
 {
     if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
         return;
     }
     $prefix = ConfigQuery::read("back_office_path");
     $defaultEnabled = intval(ConfigQuery::read("back_office_path_default_enabled", "1"));
     $pathInfo = $event->getRequest()->getPathInfo();
     $url = $event->getRequest()->server->get('REQUEST_URI');
     // Discard the default /admin URL
     $isValid = 1 !== $defaultEnabled && strpos($pathInfo, '/' . BackOfficePath::DEFAULT_THELIA_PREFIX) === 0 && $prefix !== null && $prefix !== "";
     if ($isValid) {
         /** @var \Symfony\Component\Routing\RequestContext $context */
         $context = $event->getKernel()->getContainer()->get('request.context');
         $context->fromRequest($event->getRequest());
         throw new NotFoundHttpException();
     }
     // Check if the URL is an backOffice URL
     $isValid = strpos($pathInfo, '/' . $prefix) === 0 && $prefix !== null && $prefix !== "";
     if ($isValid) {
         $newUrl = $this->replaceUrl($url, $prefix, BackOfficePath::DEFAULT_THELIA_PREFIX);
         $event->getRequest()->server->set('REQUEST_URI', $newUrl);
         $event->getRequest()->initialize($event->getRequest()->query->all(), $event->getRequest()->request->all(), $event->getRequest()->attributes->all(), $event->getRequest()->cookies->all(), $event->getRequest()->files->all(), $event->getRequest()->server->all(), $event->getRequest()->getContent());
     }
 }
示例#22
0
 protected function display404(GetResponseForExceptionEvent $event)
 {
     // Define the template thant shoud be used
     $this->parser->setTemplateDefinition($this->parser->getTemplateHelper()->getActiveFrontTemplate());
     $response = new Response($this->parser->render(ConfigQuery::getPageNotFoundView()), 404);
     $event->setResponse($response);
 }
示例#23
0
 public function updateStatus(OrderEvent $event)
 {
     $order = $event->getOrder();
     $colissimo = new Colissimo();
     if ($order->isSent() && $order->getDeliveryModuleId() == $colissimo->getModuleModel()->getId()) {
         $contact_email = ConfigQuery::getStoreEmail();
         if ($contact_email) {
             $message = MessageQuery::create()->filterByName('mail_colissimo')->findOne();
             if (false === $message) {
                 throw new \Exception("Failed to load message 'order_confirmation'.");
             }
             $order = $event->getOrder();
             $customer = $order->getCustomer();
             $this->parser->assign('customer_id', $customer->getId());
             $this->parser->assign('order_ref', $order->getRef());
             $this->parser->assign('order_date', $order->getCreatedAt());
             $this->parser->assign('update_date', $order->getUpdatedAt());
             $this->parser->assign('package', $order->getDeliveryRef());
             $message->setLocale($order->getLang()->getLocale());
             $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::getStoreName());
             // Build subject and body
             $message->buildMessage($this->parser, $instance);
             $this->mailer->send($instance);
             Tlog::getInstance()->debug("Colissimo shipping message sent to customer " . $customer->getEmail());
         } else {
             $customer = $order->getCustomer();
             Tlog::getInstance()->debug("Colissimo shipping message no contact email customer_id", $customer->getId());
         }
     }
 }
示例#24
0
 /**
  * Process document and write the result in the document cache.
  *
  * When the original document is required, create either a symbolic link with the
  * original document in the cache dir, or copy it in the cache dir if it's not already done.
  *
  * This method updates the cache_file_path and file_url attributes of the event
  *
  * @param DocumentEvent $event Event
  *
  * @throws \Thelia\Exception\DocumentException
  * @throws \InvalidArgumentException           , DocumentException
  */
 public function processDocument(DocumentEvent $event)
 {
     $subdir = $event->getCacheSubdirectory();
     $sourceFile = $event->getSourceFilepath();
     if (null == $subdir || null == $sourceFile) {
         throw new \InvalidArgumentException("Cache sub-directory and source file path cannot be null");
     }
     $originalDocumentPathInCache = $this->getCacheFilePath($subdir, $sourceFile, true);
     if (!file_exists($originalDocumentPathInCache)) {
         if (!file_exists($sourceFile)) {
             throw new DocumentException(sprintf("Source document file %s does not exists.", $sourceFile));
         }
         $mode = ConfigQuery::read('original_document_delivery_mode', 'symlink');
         if ($mode == 'symlink') {
             if (false == symlink($sourceFile, $originalDocumentPathInCache)) {
                 throw new DocumentException(sprintf("Failed to create symbolic link for %s in %s document cache directory", basename($sourceFile), $subdir));
             }
         } else {
             // mode = 'copy'
             if (false == @copy($sourceFile, $originalDocumentPathInCache)) {
                 throw new DocumentException(sprintf("Failed to copy %s in %s document cache directory", basename($sourceFile), $subdir));
             }
         }
     }
     // Compute the document URL
     $documentUrl = $this->getCacheFileURL($subdir, basename($originalDocumentPathInCache));
     // Update the event with file path and file URL
     $event->setDocumentPath($documentUrl);
     $event->setDocumentUrl(URL::getInstance()->absoluteUrl($documentUrl, null, URL::PATH_TO_FILE));
 }
示例#25
0
 /**
  * Checks if we are the payment module for the order, and if the order is paid,
  * then send a confirmation email to the customer.
  *
  * @params OrderEvent $order
  */
 public function update_status(OrderEvent $event)
 {
     $payzen = new Payzen();
     if ($event->getOrder()->isPaid() && $payzen->isPaymentModuleFor($event->getOrder())) {
         $contact_email = ConfigQuery::read('store_email', false);
         Tlog::getInstance()->debug("Sending confirmation email from store contact e-mail {$contact_email}");
         if ($contact_email) {
             $message = MessageQuery::create()->filterByName(Payzen::CONFIRMATION_MESSAGE_NAME)->findOne();
             if (false === $message) {
                 throw new \Exception(sprintf("Failed to load message '%s'.", Payzen::CONFIRMATION_MESSAGE_NAME));
             }
             $order = $event->getOrder();
             $customer = $order->getCustomer();
             $this->parser->assign('order_id', $order->getId());
             $this->parser->assign('order_ref', $order->getRef());
             $message->setLocale($order->getLang()->getLocale());
             $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name'));
             // Build subject and body
             $message->buildMessage($this->parser, $instance);
             $this->getMailer()->send($instance);
             Tlog::getInstance()->debug("Confirmation email sent to customer " . $customer->getEmail());
         }
     } else {
         Tlog::getInstance()->debug("No confirmation email sent (order not paid, or not the proper payement module.");
     }
 }
 public function testAction()
 {
     // Check current user authorization
     if (null !== ($response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::UPDATE))) {
         return $response;
     }
     $contactEmail = ConfigQuery::read('store_email');
     $storeName = ConfigQuery::read('store_name', 'Thelia');
     $json_data = array("success" => false, "message" => "");
     if ($contactEmail) {
         $emailTest = $this->getRequest()->get("email", $contactEmail);
         $message = $this->getTranslator()->trans("Email test from : %store%", array("%store%" => $storeName));
         $htmlMessage = "<p>{$message}</p>";
         $instance = \Swift_Message::newInstance()->addTo($emailTest, $storeName)->addFrom($contactEmail, $storeName)->setSubject($message)->setBody($message, 'text/plain')->setBody($htmlMessage, 'text/html');
         try {
             $this->getMailer()->send($instance);
             $json_data["success"] = true;
             $json_data["message"] = $this->getTranslator()->trans("Your configuration seems to be ok. Checked out your mailbox : %email%", array("%email%" => $emailTest));
         } catch (\Exception $ex) {
             $json_data["message"] = $ex->getMessage();
         }
     } else {
         $json_data["message"] = $this->getTranslator()->trans("You have to configure your store email first !");
     }
     $response = JsonResponse::create($json_data);
     return $response;
 }
示例#27
0
 public function updateStatus(OrderEvent $event)
 {
     $order = $event->getOrder();
     $paidStatusId = OrderStatusQuery::create()->filterByCode(OrderStatus::CODE_PAID)->select('Id')->findOne();
     if ($order->hasVirtualProduct() && $event->getStatus() == $paidStatusId) {
         $contact_email = ConfigQuery::read('store_email');
         if ($contact_email) {
             $message = MessageQuery::create()->filterByName('mail_virtualproduct')->findOne();
             if (false === $message) {
                 throw new \Exception("Failed to load message 'mail_virtualproduct'.");
             }
             $order = $event->getOrder();
             $customer = $order->getCustomer();
             $this->parser->assign('customer_id', $customer->getId());
             $this->parser->assign('order_id', $order->getId());
             $this->parser->assign('order_ref', $order->getRef());
             $this->parser->assign('order_date', $order->getCreatedAt());
             $this->parser->assign('update_date', $order->getUpdatedAt());
             $message->setLocale($order->getLang()->getLocale());
             $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name'));
             // Build subject and body
             $message->buildMessage($this->parser, $instance);
             $this->mailer->send($instance);
             Tlog::getInstance()->debug("Virtual product download message sent to customer " . $customer->getEmail());
         } else {
             $customer = $order->getCustomer();
             Tlog::getInstance()->debug("Virtual product download message no contact email customer_id", $customer->getId());
         }
     }
 }
示例#28
0
 protected function getExistingObject()
 {
     $config = ConfigQuery::create()->findOneById($this->getRequest()->get('variable_id'));
     if (null !== $config) {
         $config->setLocale($this->getCurrentEditionLocale());
     }
     return $config;
 }
 public function getPointInfo($point_id)
 {
     $req = new FindById();
     $req->setId($point_id)->setLangue("FR")->setDate(date("d/m/Y"))->setAccountNumber(ConfigQuery::read('socolissimo_login'))->setPassword(ConfigQuery::read('socolissimo_pwd'));
     $response = $req->exec();
     $response = new JsonResponse($response);
     return $response;
 }
示例#30
0
 public function postActivation(ConnectionInterface $con = null)
 {
     if (null === ConfigQuery::read(static::RESOURCE_PATH_CONFIG_NAME)) {
         $config = new Config();
         $config->setHidden(0)->setSecured(0)->setName(static::RESOURCE_PATH_CONFIG_NAME)->setValue(__DIR__ . DS . "Resources")->getTranslation("fr_FR")->setTitle("Chemin de templates pour Thelia studio")->getConfig()->getTranslation("en_US")->setTitle("Templates path for Thelia studio");
         $config->save();
     }
 }