作者:marger
项目:theli
/**
* 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;
}
作者:Alban-i
项目:Paylin
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']);
}
作者:marger
项目:theli
public function indexAction()
{
if (!$this->getSecurityContext()->hasAdminUser()) {
return new RedirectResponse(URL::getInstance()->absoluteUrl($this->getRoute("admin.login")));
}
return $this->render("home");
}
作者:NandoKstroNe
项目:theli
/**
*
* 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);
}
}
}
}
作者:thelia-module
项目:DealerTea
/**
* @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]));
}
作者:Asena
项目:thelia-Paypa
/**
* @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]);
}
作者:Mertiozy
项目:GoogleShoppin
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;
}
作者:zorn-
项目:theli
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'));
}
作者:nicolasleo
项目:Twitte
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;
}
作者:marger
项目:theli
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);
}
作者:Asena
项目:thelia-Paypa
/**
* @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;
}
作者:marger
项目:theli
/**
* 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;
}
作者:NandoKstroNe
项目:theli
/**
* @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;
}
作者:roadster3
项目:Payze
/**
* @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'));
}
作者:egrue
项目:jus-de-corosso
/**
* @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);
}
作者:alex6353
项目:theli
/**
* @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();
}
}
作者:Mertiozy
项目:GoogleShoppin
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);
}
}
作者:Boyquote
项目:Mailje
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"));
}
}
作者:alex6353
项目:theli
/**
* @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);
}
作者:thelia-module
项目:ForcePhon
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'));
}
}