Exemplo n.º 1
1
 public function postAction(Request $request)
 {
     $form = new ConfigurationForm($request);
     try {
         $configForm = $this->validateForm($form);
         $data = $configForm->getData();
         $paylineConfig = new PaylineConfig();
         $paylineConfig->merge($data);
         // Redirect to the success URL,
         if ($this->getRequest()->get('save_mode') == 'stay') {
             // If we have to stay on the same page, redisplay the configuration page/
             $route = '/admin/module/Payline';
         } else {
             // If we have to close the page, go back to the module back-office page.
             $route = '/admin/modules';
         }
         return RedirectResponse::create(URL::getInstance()->absoluteUrl($route));
     } catch (FormValidationException $e) {
         $error = $this->createStandardFormValidationErrorMessage($e);
     } catch (\Exception $e) {
         $error = $e->getMessage();
     }
     $this->setupFormErrorContext('Payline Configuration', $error, $form, $e);
     return $this->render('module-configure', ['module_code' => 'Payline']);
 }
Exemplo n.º 2
0
 public function checkRedirectException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     if ($exception instanceof ExceptionRedirectException) {
         $response = RedirectResponse::create($exception->getUrl(), $exception->getStatusCode());
         $event->setResponse($response);
     } elseif ($exception instanceof AuthenticationException) {
         // Redirect to the login template
         $response = RedirectResponse::create($this->urlManager->viewUrl($exception->getLoginTemplate()));
         $event->setResponse($response);
     }
 }
Exemplo n.º 3
0
 /**
  * Generate a rewritten URL from the object title, and store it in the rewriting table
  *
  * @param string $locale a valid locale (e.g. en_US)
  */
 public function generateRewrittenUrl($locale)
 {
     if ($this->isNew()) {
         throw new \RuntimeException(sprintf('Object %s must be saved before generating url', $this->getRewrittenUrlViewName()));
     }
     // Borrowed from http://stackoverflow.com/questions/2668854/sanitizing-strings-to-make-them-url-and-filename-safe
     $this->setLocale($locale);
     $generateEvent = new GenerateRewrittenUrlEvent($this, $locale);
     $this->dispatchEvent(TheliaEvents::GENERATE_REWRITTENURL, $generateEvent);
     if ($generateEvent->isRewritten()) {
         return $generateEvent->getUrl();
     }
     $title = $this->getTitle();
     if (null == $title) {
         throw new \RuntimeException('Impossible to create an url if title is null');
     }
     // Replace all weird characters with dashes
     $string = preg_replace('/[^\\w\\-~_\\.]+/u', '-', $title);
     // Only allow one dash separator at a time (and make string lowercase)
     $cleanString = mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8');
     $urlFilePart = rtrim($cleanString, '.-~_') . ".html";
     try {
         $i = 0;
         while (URL::getInstance()->resolve($urlFilePart)) {
             $i++;
             $urlFilePart = sprintf("%s-%d.html", $cleanString, $i);
         }
     } catch (UrlRewritingException $e) {
         $rewritingUrl = new RewritingUrl();
         $rewritingUrl->setUrl($urlFilePart)->setView($this->getRewrittenUrlViewName())->setViewId($this->getId())->setViewLocale($locale)->save();
     }
     return $urlFilePart;
 }
Exemplo n.º 4
0
 public function indexAction()
 {
     if (!$this->getSecurityContext()->hasAdminUser()) {
         return new RedirectResponse(URL::getInstance()->absoluteUrl($this->getRoute("admin.login")));
     }
     return $this->render("home");
 }
Exemplo n.º 5
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);
             }
         }
     }
 }
 /**
  * @inheritDoc
  */
 protected function redirectToListTemplate()
 {
     $id = $this->getRequest()->query->get("dealer_id");
     if (null === $id) {
         $id = $this->getRequest()->request->get("dealer_id");
     }
     return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/module/Dealer/dealer/edit#dealerteam", ["dealer_id" => $id]));
 }
Exemplo n.º 7
0
 /**
  * @param $order_id
  * @return \Thelia\Core\HttpFoundation\Response
  */
 public function ok($order_id)
 {
     /*
      * Check if token&order are valid
      */
     $token = null;
     $order = $this->checkorder($order_id, $token);
     /*
      * $payerid string value returned by paypal
      * $logger PaypalApiLogManager used to log transctions with paypal
      */
     $payerid = $this->getRequest()->get('PayerID');
     $logger = new PaypalApiLogManager();
     if (!empty($payerid)) {
         /*
          * $config ConfigInterface Object that contains configuration
          * $api PaypalApiCredentials Class used by the library to store and use 3T login(username, password, signature)
          * $sandbox bool true if sandbox is enabled
          */
         $config = new PaypalConfig();
         $config->pushValues();
         $api = new PaypalApiCredentials($config);
         $sandbox = $api->getConfig()->getSandbox();
         /*
          * Send getExpressCheckout & doExpressCheckout
          * empty cart
          */
         $getExpressCheckout = new PaypalNvpOperationsGetExpressCheckoutDetails($api, $token);
         $request = new PaypalNvpMessageSender($getExpressCheckout, $sandbox);
         $response = $request->send();
         $logger->logTransaction($response);
         $response = PaypalApiManager::nvpToArray($response);
         if (isset($response['ACK']) && $response['ACK'] === 'Success' && isset($response['PAYERID']) && $response['PAYERID'] === $payerid && isset($response['TOKEN']) && $response['TOKEN'] === $token) {
             $doExpressCheckout = new PaypalNvpOperationsDoExpressCheckoutPayment($api, round($order->getTotalAmount(), 2), $order->getCurrency()->getCode(), $payerid, PaypalApiManager::PAYMENT_TYPE_SALE, $token, URL::getInstance()->absoluteUrl("/module/paypal/listen"));
             $request = new PaypalNvpMessageSender($doExpressCheckout, $token);
             $response = $request->send();
             $logger->logTransaction($response);
             $response = PaypalApiManager::nvpToArray($response);
             /*
              * In case of success, go to success page
              * In case of error, show it
              */
             if (isset($response['ACK']) && $response['ACK'] === "Success" && isset($response['PAYMENTINFO_0_PAYMENTSTATUS']) && $response['PAYMENTINFO_0_PAYMENTSTATUS'] === "Completed" && isset($response['TOKEN']) && $response['TOKEN'] === $token) {
                 /*
                  * Set order status as paid
                  */
                 $event = new OrderEvent($order);
                 $event->setStatus(OrderStatusQuery::getPaidStatus()->getId());
                 $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
                 $this->redirectToSuccessPage($order_id);
             }
         }
     }
     /*
      * If no redirection done ( === error ): Empty cart
      */
     return $this->render("order-failed", ["failed_order_id" => $order_id]);
 }
 public function createGoogleClient()
 {
     $client = new \Google_Client();
     $client->setApplicationName(GoogleShopping::getConfigValue('application_name'));
     $client->setClientId(GoogleShopping::getConfigValue('client_id'));
     $client->setClientSecret(GoogleShopping::getConfigValue('client_secret'));
     $client->setRedirectUri(URL::getInstance()->absoluteUrl('/googleshopping/oauth2callback'));
     $client->setScopes('https://www.googleapis.com/auth/content');
     $client->setAccessToken(GoogleShopping::getConfigValue('oauth_access_token'));
     return $client;
 }
Exemplo n.º 9
0
 public function configure()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::MODULE, 'Tinymce', AccessManager::UPDATE))) {
         return $response;
     }
     // Initialize the potential exception
     $ex = null;
     // Create the Form from the request
     $configurationForm = new ConfigurationForm($this->getRequest());
     try {
         // Check the form against constraints violations
         $form = $this->validateForm($configurationForm, "POST");
         // Get the form field values
         $data = $form->getData();
         Tinymce::setConfigValue('product_summary', $data['product_summary']);
         Tinymce::setConfigValue('product_conclusion', $data['product_conclusion']);
         Tinymce::setConfigValue('content_summary', $data['content_summary']);
         Tinymce::setConfigValue('content_conclusion', $data['content_conclusion']);
         Tinymce::setConfigValue('category_summary', $data['category_summary']);
         Tinymce::setConfigValue('category_conclusion', $data['category_conclusion']);
         Tinymce::setConfigValue('folder_summary', $data['folder_summary']);
         Tinymce::setConfigValue('folder_conclusion', $data['folder_conclusion']);
         Tinymce::setConfigValue('brand_summary', $data['brand_summary']);
         Tinymce::setConfigValue('brand_conclusion', $data['brand_conclusion']);
         Tinymce::setConfigValue('show_menu_bar', $data['show_menu_bar']);
         Tinymce::setConfigValue('force_pasting_as_text', $data['force_pasting_as_text']);
         Tinymce::setConfigValue('editor_height', $data['editor_height']);
         Tinymce::setConfigValue('custom_css', $data['custom_css']);
         // Save Custom CSS in default assets
         $customCss = __DIR__ . DS . '..' . DS . 'templates' . DS . 'backOffice' . DS . 'default' . DS . 'assets' . DS . 'css' . DS . 'custom-css.less';
         if (1 || false === file_put_contents($customCss, $data['custom_css'])) {
             throw new TheliaProcessException($this->getTranslator()->trans("Failed to update custom CSS file \"%file\". Please check this file or parent folder write permissions.", ['%file' => $customCss]));
         }
         // Log configuration modification
         $this->adminLogAppend("tinymce.configuration.message", AccessManager::UPDATE, sprintf("Tinymce configuration updated"));
         // Everything is OK.
         return new RedirectResponse(URL::getInstance()->absoluteUrl('/admin/module/Tinymce'));
     } catch (FormValidationException $ex) {
         // Form cannot be validated. Create the error message using
         // the BaseAdminController helper method.
         $error_msg = $this->createStandardFormValidationErrorMessage($ex);
     } catch (\Exception $ex) {
         // Any other error
         $error_msg = $ex->getMessage();
     }
     // At this point, the form has errors, and should be redisplayed. We don not redirect,
     // just redisplay the same template.
     // Setup the Form error context, to make error information available in the template.
     $this->setupFormErrorContext($this->getTranslator()->trans("Tinymce configuration", [], Tinymce::MODULE_DOMAIN), $error_msg, $configurationForm, $ex);
     // Do not redirect at this point, or the error context will be lost.
     // Just redisplay the current template.
     return $this->render('module-configure', array('module_code' => 'Tinymce'));
 }
Exemplo n.º 10
0
 public function saveAction()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::MODULE, ['Twitter'], AccessManager::UPDATE))) {
         return $response;
     }
     $form = new ConfigurationForm($this->getRequest());
     $configurationForm = $this->validateForm($form);
     $consumer_key = $configurationForm->get('consumer_key')->getData();
     $consumer_secret = $configurationForm->get('consumer_secret')->getData();
     $screen_name = $configurationForm->get('screen_name')->getData();
     $count = $configurationForm->get('count')->getData();
     $cache_lifetime = $configurationForm->get('cache_lifetime')->getData();
     // $debug_mode     = $configurationForm->get('debug_mode')->getData();
     $errorMessage = null;
     $response = null;
     // Save config values
     ConfigQuery::write('twitter_consumer_key', $consumer_key, 1, 1);
     ConfigQuery::write('twitter_consumer_secret', $consumer_secret, 1, 1);
     ConfigQuery::write('twitter_screen_name', $screen_name, 1, 1);
     ConfigQuery::write('twitter_count', $count, 1, 1);
     ConfigQuery::write('twitter_cache_lifetime', $cache_lifetime * 60, 1, 1);
     // Minutes
     ConfigQuery::write('twitter_last_updated', 0, 1, 1);
     if ($screen_name && $consumer_key && $consumer_secret) {
         if (!extension_loaded('openssl')) {
             $sslError = $this->getTranslator()->trans("This module requires the PHP extension open_ssl to work.", [], Twitter::DOMAIN_NAME);
         } else {
             $config = array('consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, 'output_format' => 'array');
             try {
                 $connection = new TwitterOAuth($config);
                 $bearer_token = $connection->getBearerToken();
             } catch (\Exception $e) {
                 $errorMessage = $e->getMessage();
             }
             try {
                 $params = array('screen_name' => $screen_name, 'count' => 1, 'exclude_replies' => true);
                 $response = $connection->get('statuses/user_timeline', $params);
                 if ($response['error']) {
                     throw new TwitterException($response['error']);
                 }
             } catch (\Exception $e) {
                 $erroMessage = $this->getTranslator()->trans("Unrecognized screen name", [], Twitter::DOMAIN_NAME);
             }
         }
     }
     $response = RedirectResponse::create(URL::getInstance()->absoluteUrl('/admin/module/Twitter'));
     if (null !== $errorMessage) {
         $this->setupFormErrorContext($this->getTranslator()->trans("Twitter configuration failed.", [], Twitter::DOMAIN_NAME), $errorMessage, $form);
         $response = $this->render("module-configure", ['module_code' => 'Twitter']);
     }
     return $response;
 }
Exemplo n.º 11
0
 public function testLoadSpecificUrl()
 {
     $searchResult = new RewritingUrl();
     $searchResult->setUrl('foo.html');
     $retrieverQuery = $this->getMock('\\Thelia\\Model\\RewritingUrlQuery', array('getSpecificUrlQuery'));
     $retrieverQuery->expects($this->any())->method('getSpecificUrlQuery')->with('view', 'fr_FR', 1, array('foo0' => 'bar0', 'foo1' => 'bar1'))->will($this->returnValue($searchResult));
     $retriever = new RewritingRetriever();
     $rewritingUrlQuery = $this->getProperty('rewritingUrlQuery');
     $rewritingUrlQuery->setValue($retriever, $retrieverQuery);
     $retriever->loadSpecificUrl('view', 'fr_FR', 1, array('foo0' => 'bar0', 'foo1' => 'bar1'));
     $this->assertEquals('foo.html', $retriever->rewrittenUrl);
     $this->assertEquals(URL::getInstance()->viewUrl('view', array('foo0' => 'bar0', 'foo1' => 'bar1', 'lang' => 'fr_FR', 'view_id' => 1)), $retriever->url);
 }
Exemplo n.º 12
0
 /**
  * @param  string $type
  * @return string
  */
 public static function getPaypalURL($type, $order_id)
 {
     $ret = "";
     switch ($type) {
         case 'cancel':
             $ret = URL::getInstance()->absoluteUrl("/module/paypal/cancel/" . $order_id);
             break;
         case 'paiement':
             $ret = URL::getInstance()->absoluteUrl("/module/paypal/ok/" . $order_id);
             break;
     }
     return $ret;
 }
Exemplo n.º 13
0
 /**
  * Generate an asset URL
  *
  * @param string $source a module code, or SmartyParser::TEMPLATE_ASSETS_KEY
  * @param string $file the file path, relative to a template base directory (e.g. assets/css/style.css)
  * @param string $type the asset type, either 'css' or '
  * @param ParserInterface $parserInterface the current template parser
  * @param array $filters the filters to pass to the asset manager
  * @param bool $debug the debug mode
  * @param string $declaredAssetsDirectory if not null, this is the assets directory declared in the {declare_assets} function of a template.
  * @param mixed $sourceTemplateName A template name, of false. If provided, the assets will be searched in this template directory instead of the current one.
  * @return mixed
  */
 public function resolveAssetURL($source, $file, $type, ParserInterface $parserInterface, $filters = [], $debug = false, $declaredAssetsDirectory = null, $sourceTemplateName = false)
 {
     $url = "";
     // Normalize path separator
     $file = $this->fixPathSeparator($file);
     $fileRoot = $this->resolveAssetSourcePath($source, $sourceTemplateName, $file, $parserInterface);
     if (null !== $fileRoot) {
         $templateDefinition = $parserInterface->getTemplateDefinition($sourceTemplateName);
         $url = $this->assetsManager->processAsset($fileRoot . DS . $file, $fileRoot, THELIA_WEB_DIR . $this->path_relative_to_web_root, $templateDefinition->getPath(), $source, URL::getInstance()->absoluteUrl($this->path_relative_to_web_root, null, URL::PATH_TO_FILE), $type, $filters, $debug);
     } else {
         Tlog::getInstance()->addError("Asset {$file} (type {$type}) was not found.");
     }
     return $url;
 }
Exemplo n.º 14
0
 /**
  * @param LoopResult $loopResult
  *
  * @return LoopResult
  */
 public function parseResults(LoopResult $loopResult)
 {
     foreach ($loopResult->getResultDataCollection() as $type) {
         $loopResultRow = new LoopResultRow($type);
         $url = URL::getInstance()->absoluteUrl($this->getBaseUrl() . "/" . $type->getId());
         try {
             $loopResultRow->set("HANDLE_CLASS", $type->getHandleClass())->set("ID", $type->getId())->set("TITLE", $type->getVirtualColumn("i18n_TITLE"))->set("DESCRIPTION", $type->getVirtualColumn("i18n_DESCRIPTION"))->set("URL", $url)->set("POSITION", $type->getPosition())->set("CATEGORY_ID", $type->getByName($this->getCategoryName()));
         } catch (ClassNotFoundException $e) {
         } catch (\ErrorException $e) {
         }
         $loopResult->addRow($loopResultRow);
     }
     return $loopResult;
 }
Exemplo n.º 15
0
 /**
  * @return mixed an HTTP response, or
  */
 public function configure()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::MODULE, 'Payzen', AccessManager::UPDATE))) {
         return $response;
     }
     // Initialize the potential error message, and the potential exception
     $error_msg = $ex = null;
     // Create the Form from the request
     $configurationForm = new ConfigurationForm($this->getRequest());
     try {
         // Check the form against constraints violations
         $form = $this->validateForm($configurationForm, "POST");
         // Get the form field values
         $data = $form->getData();
         foreach ($data as $name => $value) {
             if (is_array($value)) {
                 $value = implode(';', $value);
             }
             PayzenConfigQuery::set($name, $value);
         }
         // Log configuration modification
         $this->adminLogAppend("payzen.configuration.message", AccessManager::UPDATE, sprintf("Payzen configuration updated"));
         // Redirect to the success URL,
         if ($this->getRequest()->get('save_mode') == 'stay') {
             // If we have to stay on the same page, redisplay the configuration page/
             $route = '/admin/module/Payzen';
         } else {
             // If we have to close the page, go back to the module back-office page.
             $route = '/admin/modules';
         }
         $this->redirect(URL::getInstance()->absoluteUrl($route));
         // An exit is performed after redirect.+
     } catch (FormValidationException $ex) {
         // Form cannot be validated. Create the error message using
         // the BaseAdminController helper method.
         $error_msg = $this->createStandardFormValidationErrorMessage($ex);
     } catch (\Exception $ex) {
         // Any other error
         $error_msg = $ex->getMessage();
     }
     // At this point, the form has errors, and should be redisplayed. We don not redirect,
     // just redisplay the same template.
     // Setup the Form error context, to make error information available in the template.
     $this->setupFormErrorContext($this->getTranslator()->trans("Payzen configuration", [], Payzen::MODULE_DOMAIN), $error_msg, $configurationForm, $ex);
     // Do not redirect at this point, or the error context will be lost.
     // Just redisplay the current template.
     return $this->render('module-configure', array('module_code' => 'Payzen'));
 }
Exemplo n.º 16
0
 /**
  * @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);
 }
Exemplo n.º 17
0
 /**
  * @param       $view
  * @param       $viewLocale
  * @param null  $viewId
  * @param array $viewOtherParameters
  */
 public function loadSpecificUrl($view, $viewLocale, $viewId = null, $viewOtherParameters = array())
 {
     if (empty($viewOtherParameters)) {
         $this->loadViewUrl($view, $viewLocale, $viewId);
         return;
     }
     $this->search = $this->rewritingUrlQuery->getSpecificUrlQuery($view, $viewLocale, $viewId, $viewOtherParameters);
     $allParametersWithoutView = $viewOtherParameters;
     $allParametersWithoutView['locale'] = $viewLocale;
     if (null !== $viewId) {
         $allParametersWithoutView[$view . '_id'] = $viewId;
     }
     $this->rewrittenUrl = null;
     $this->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView);
     if ($this->search !== null) {
         $this->rewrittenUrl = $this->search->getUrl();
     }
 }
Exemplo n.º 18
0
 public function oAuthCheckToken($params, $smarty)
 {
     $token = GoogleShopping::getConfigValue('oauth_access_token');
     if (!$token) {
         $smarty->assign('tokenExist', 'none');
         return;
     }
     $client = new \Google_Client();
     $client->setApplicationName(GoogleShopping::getConfigValue('application_name'));
     $client->setClientId(GoogleShopping::getConfigValue('client_id'));
     $client->setClientSecret(GoogleShopping::getConfigValue('client_secret'));
     $client->setRedirectUri(URL::getInstance()->absoluteUrl('/googleshopping/oauth2callback'));
     $client->setScopes('https://www.googleapis.com/auth/content');
     $client->setAccessToken($token);
     if (true === $client->isAccessTokenExpired()) {
         $smarty->assign('tokenExpired', true);
     }
 }
Exemplo n.º 19
0
 public function saveAction()
 {
     $baseForm = new MailjetConfigurationForm($this->getRequest());
     try {
         $form = $this->validateForm($baseForm);
         $data = $form->getData();
         ConfigQuery::write(Mailjet::CONFIG_API_KEY, $data["api_key"]);
         ConfigQuery::write(Mailjet::CONFIG_API_SECRET, $data["api_secret"]);
         ConfigQuery::write(Mailjet::CONFIG_API_WS_ADDRESS, $data["ws_address"]);
         ConfigQuery::write(Mailjet::CONFIG_NEWSLETTER_LIST, $data["newsletter_list"]);
         $this->getParserContext()->set("success", true);
     } catch (\Exception $e) {
         $this->getParserContext()->setGeneralError($e->getMessage())->addForm($baseForm);
     }
     if ("close" === $this->getRequest()->request->get("save_mode")) {
         return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/modules"));
     }
 }
Exemplo n.º 20
0
 /**
  * @param  string                                  $url
  * @param  string                                  $pathToStore
  * @throws \Thelia\Exception\FileNotFoundException
  * @throws \ErrorException
  * @throws \HttpUrlException
  *
  * Downloads the file $url in $pathToStore
  */
 public function download($url, $pathToStore)
 {
     if (!URL::checkUrl($url)) {
         /**
          * The URL is not valid
          */
         throw new HttpUrlException($this->translator->trans("Tried to download a file, but the URL was not valid: %url", ["%url" => $url]));
     }
     /**
      * Try to get the file if it is online
      */
     $con = curl_init($url);
     curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
     $response = curl_exec($con);
     $errno = curl_errno($con);
     $curlErrorMessage = curl_error($con);
     $httpCode = curl_getinfo($con, CURLINFO_HTTP_CODE);
     curl_close($con);
     if (false === $response || $errno !== 0 || $httpCode != "200" && $httpCode != "204") {
         /**
          * The server is down ? The file doesn't exist ? Anything else ?
          */
         $errorMessage = $this->translator->trans("cURL errno %errno, http code %http_code on link \"%path\": %error", ["%errno" => $errno, "%path" => $url, "%error" => $curlErrorMessage, "%http_code" => $httpCode]);
         $this->logger->error($errorMessage);
         throw new FileNotFoundException($errorMessage);
     }
     /**
      * Inform that you've downloaded a file
      */
     $this->logger->info($this->translator->trans("The file %path has been successfully downloaded", ["%path" => $url]));
     /**
      * Then try to write it on the disk
      */
     $file = @fopen($pathToStore, "w");
     if ($file === false) {
         $translatedErrorMessage = $this->translator->trans("Failed to open a writing stream on the file: %file", ["%file" => $pathToStore]);
         $this->logger->error($translatedErrorMessage);
         throw new \ErrorException($translatedErrorMessage);
     }
     fputs($file, $response);
     fclose($file);
 }
 public function configure()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::MODULE, 'forcephone', AccessManager::UPDATE))) {
         return $response;
     }
     $configurationForm = $this->createForm('forcephone_configuration');
     $message = null;
     try {
         $form = $this->validateForm($configurationForm);
         // Get the form field values
         $data = $form->getData();
         foreach ($data as $name => $value) {
             if (is_array($value)) {
                 $value = implode(';', $value);
             }
             ForcePhone::setConfigValue($name, $value);
         }
         // Log configuration modification
         $this->adminLogAppend("forcephone.configuration.message", AccessManager::UPDATE, "ForcePhone configuration updated");
         // Redirect to the success URL,
         if ($this->getRequest()->get('save_mode') == 'stay') {
             // If we have to stay on the same page, redisplay the configuration page/
             $url = '/admin/module/ForcePhone';
         } else {
             // If we have to close the page, go back to the module back-office page.
             $url = '/admin/modules';
         }
         return $this->generateRedirect(URL::getInstance()->absoluteUrl($url));
     } catch (FormValidationException $ex) {
         $message = $this->createStandardFormValidationErrorMessage($ex);
     } catch (\Exception $ex) {
         $message = $ex->getMessage();
     }
     $this->setupFormErrorContext($this->getTranslator()->trans("ForcePhone configuration", [], ForcePhone::DOMAIN_NAME), $message, $configurationForm, $ex);
     // Before 2.2, the errored form is not stored in session
     if (Version::test(Thelia::THELIA_VERSION, '2.2', false, "<")) {
         return $this->render('module-configure', ['module_code' => 'ForcePhone']);
     } else {
         return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ForcePhone'));
     }
 }
Exemplo n.º 22
0
 public function importAction()
 {
     $i = 0;
     $con = Propel::getWriteConnection(OrderTableMap::DATABASE_NAME);
     $con->beginTransaction();
     $form = $this->createForm('socolissimo.import');
     try {
         $vForm = $this->validateForm($form);
         // Get file
         $importedFile = $vForm->getData()['import_file'];
         // Check extension
         if (strtolower($importedFile->getClientOriginalExtension()) != 'csv') {
             throw new FormValidationException(Translator::getInstance()->trans('Bad file format. CSV expected.', [], SoColissimo::DOMAIN));
         }
         $csvData = file_get_contents($importedFile);
         $lines = explode(PHP_EOL, $csvData);
         // For each line, parse columns
         foreach ($lines as $line) {
             $parsedLine = str_getcsv($line, ";");
             // Check if there are 2 columns : delivery ref & order ref
             if (count($parsedLine) == SoColissimo::IMPORT_NB_COLS) {
                 // Get delivery and order ref
                 $deliveryRef = $parsedLine[SoColissimo::IMPORT_DELIVERY_REF_COL];
                 $orderRef = $parsedLine[SoColissimo::IMPORT_ORDER_REF_COL];
                 // Save delivery ref if there is one
                 if (!empty($deliveryRef)) {
                     $this->importDeliveryRef($deliveryRef, $orderRef, $i);
                 }
             }
         }
         $con->commit();
         // Get number of affected rows to display
         $this->getSession()->getFlashBag()->add('import-result', Translator::getInstance()->trans('Operation successful. %i orders affected.', ['%i' => $i], SoColissimo::DOMAIN));
         // Redirect
         return $this->generateRedirect(URL::getInstance()->absoluteUrl($form->getSuccessUrl(), ['current_tab' => 'import']));
     } catch (FormValidationException $e) {
         $con->rollback();
         $this->setupFormErrorContext(null, $e->getMessage(), $form);
         return $this->render('module-configure', ['module_code' => SoColissimo::getModuleCode(), 'current_tab' => 'import']);
     }
 }
Exemplo n.º 23
0
 /**
  * Get products
  *
  * @param $sitemap
  * @param $locale
  * @throws \Propel\Runtime\Exception\PropelException
  */
 protected function setSitemapProducts(&$sitemap, $locale)
 {
     // Prepare query - get products URL
     $query = RewritingUrlQuery::create()->filterByView('product')->filterByRedirected(null)->filterByViewLocale($locale);
     // Join with visible products
     self::addJoinProduct($query);
     // Get products last update
     $query->withColumn(ProductTableMap::UPDATED_AT, 'PRODUCT_UPDATE_AT');
     // Execute query
     $results = $query->find();
     // For each result, hydrate XML file
     /** @var RewritingUrl $result */
     foreach ($results as $result) {
         // Open new sitemap line & set product URL & update date
         $sitemap[] = '
         <url>
             <loc>' . URL::getInstance()->absoluteUrl($result->getUrl()) . '</loc>
             <lastmod>' . date('c', strtotime($result->getVirtualColumn('PRODUCT_UPDATE_AT'))) . '</lastmod>
         </url>';
     }
 }
Exemplo n.º 24
0
 public function renderJs($params, \Smarty_Internal_Template $template)
 {
     $render = "";
     if ($this->debugMode) {
         $webFile = "cache/debugbar.js";
         $cacheFile = THELIA_WEB_DIR . "/" . $webFile;
         if (!file_exists($cacheFile)) {
             $javascriptRenderer = $this->debugBar->getJavascriptRenderer();
             $assetJs = $javascriptRenderer->getAsseticCollection("js");
             foreach ($assetJs->all() as $asset) {
                 if (strpos($asset->getSourcePath(), "jquery") !== false) {
                     $assetJs->removeLeaf($asset);
                 }
             }
             if (!file_exists(THELIA_WEB_DIR . "/cache")) {
                 @mkdir(THELIA_WEB_DIR . "/cache");
             }
             @file_put_contents($cacheFile, $assetJs->dump());
         }
         $render = sprintf('<script src="%s"></script>', URL::getInstance()->absoluteUrl($webFile, array(), URL::PATH_TO_FILE));
     }
     return $render;
 }
Exemplo n.º 25
0
 public function configure()
 {
     if (null !== ($response = $this->checkAuth(AdminResources::MODULE, 'Cheque', AccessManager::UPDATE))) {
         return $response;
     }
     // Initialize the potential exception
     $ex = null;
     // Create the Form from the request
     $configurationForm = new ConfigurationForm($this->getRequest());
     try {
         // Check the form against constraints violations
         $form = $this->validateForm($configurationForm, "POST");
         // Get the form field values
         $data = $form->getData();
         Cheque::setConfigValue('instructions', $data['instructions'], $this->getCurrentEditionLocale());
         Cheque::setConfigValue('payable_to', $data['payable_to']);
         // Log configuration modification
         $this->adminLogAppend("cheque.configuration.message", AccessManager::UPDATE, sprintf("Cheque instructions configuration updated"));
         // Everything is OK.
         return new RedirectResponse(URL::getInstance()->absoluteUrl('/admin/module/Cheque'));
     } catch (FormValidationException $ex) {
         // Form cannot be validated. Create the error message using
         // the BaseAdminController helper method.
         $error_msg = $this->createStandardFormValidationErrorMessage($ex);
     } catch (\Exception $ex) {
         // Any other error
         $error_msg = $ex->getMessage();
     }
     // At this point, the form has errors, and should be redisplayed. We don not redirect,
     // just redisplay the same template.
     // Setup the Form error context, to make error information available in the template.
     $this->setupFormErrorContext($this->getTranslator()->trans("Cheque instructions configuration", [], Cheque::MESSAGE_DOMAIN), $error_msg, $configurationForm, $ex);
     // Do not redirect at this point, or the error context will be lost.
     // Just redisplay the current template.
     return $this->render('module-configure', array('module_code' => 'Cheque'));
 }
Exemplo n.º 26
0
 public function saveAction()
 {
     $response = $this->checkAuth([AdminResources::MODULE], ['backofficepath'], AccessManager::UPDATE);
     if ($response !== null) {
         return $response;
     }
     $form = new \BackOfficePath\Form\Configuration($this->getRequest());
     $message = '';
     try {
         $vform = $this->validateForm($form);
         $data = $vform->getData();
         ConfigQuery::write('back_office_path', $data['back_office_path'], false, true);
         ConfigQuery::write('back_office_path_default_enabled', $data['back_office_path_default_enabled'] ? '1' : '0', false, true);
     } catch (\Exception $e) {
         $message = $e->getMessage();
     }
     if ($message) {
         $form->setErrorMessage($message);
         $this->getParserContext()->addForm($form);
         $this->getParserContext()->setGeneralError($message);
         return $this->render('module-configure', array('module_code' => BackOfficePath::getModuleCode()));
     }
     return RedirectResponse::create(URL::getInstance()->absoluteUrl('/admin/module/' . BackOfficePath::getModuleCode()));
 }
Exemplo n.º 27
0
 /**
  * Redirect to à route ID related URL
  *
  * @param string $routeId         the route ID, as found in Config/Resources/routing/admin.xml
  * @param array  $urlParameters   the URL parameters, as a var/value pair array
  * @param array  $routeParameters
  * @deprecated since 2.1 and will be removed in 2.3
  * @see generateRedirectFromRoute
  */
 public function redirectToRoute($routeId, array $urlParameters = array(), array $routeParameters = array())
 {
     $this->redirect(URL::getInstance()->absoluteUrl($this->getRoute($routeId, $routeParameters), $urlParameters));
 }
Exemplo n.º 28
0
 /**
  * Build an absolute URL using the value of a form parameter.
  *
  * @param string $parameterName the form parameter name
  * @param string $default a default value for the form parameter. If not defined, the configured base URL is used.
  * @return string an absolute URL
  */
 public function getFormDefinedUrl($parameterName, $default = null)
 {
     $formDefinedUrl = $this->form->get($parameterName)->getData();
     if (empty($formDefinedUrl)) {
         if ($default === null) {
             $default = ConfigQuery::read('base_url', '/');
         }
         $formDefinedUrl = $default;
     }
     return URL::getInstance()->absoluteUrl($formDefinedUrl);
 }
Exemplo n.º 29
0
 public function changeCountry()
 {
     $redirectUrl = URL::getInstance()->absoluteUrl("/cart");
     $deliveryId = $this->getRequest()->get("country");
     $cookieName = ConfigQuery::read('front_cart_country_cookie_name', 'fcccn');
     $cookieExpires = ConfigQuery::read('front_cart_country_cookie_expires', 2592000);
     $cookieExpires = intval($cookieExpires) ?: 2592000;
     $cookie = new Cookie($cookieName, $deliveryId, time() + $cookieExpires, '/');
     $response = $this->generateRedirect($redirectUrl);
     $response->headers->setCookie($cookie);
     return $response;
 }
 /**
  * redirect to OpenSearchServer admin home
  *
  * @return \Symfony\Component\HttpFoundation\Response|static
  */
 protected function redirectToHome()
 {
     return RedirectResponse::create(URL::getInstance()->absoluteUrl('/admin/module/OpenSearchServerSearch'));
 }