Inital commit

This commit is contained in:
2020-11-19 15:36:28 +01:00
parent 71f32f83d3
commit 66ce4ee218
18077 changed files with 2166122 additions and 35184 deletions

View File

@@ -12,31 +12,30 @@
namespace Thelia\Controller;
use Thelia\Core\Event\PdfEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Router;
use Thelia\Core\Template\TemplateHelper;
use Thelia\Core\Translation\Translator;
use Thelia\Form\FirewallForm;
use Thelia\Model\OrderQuery;
use Thelia\Tools\Redirect;
use Thelia\Core\Template\ParserContext;
use Thelia\Core\Event\ActionEvent;
use Thelia\Core\Event\DefaultActionEvent;
use Thelia\Core\Event\PdfEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Template\ParserContext;
use Thelia\Core\Translation\Translator;
use Thelia\Exception\TheliaProcessException;
use Thelia\Form\BaseForm;
use Thelia\Form\Exception\FormValidationException;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\DefaultActionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Thelia\Log\Tlog;
use Thelia\Mailer\MailerFactory;
use Thelia\Model\OrderQuery;
use Thelia\Tools\URL;
/**
*
@@ -44,11 +43,28 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* user is not yet logged in, or back-office home page if the user is logged in.
*
* @author Franck Allimant <franck@cqfdev.fr>
* @author Manuel Raynaud <mraynaud@openstudio.fr>
* @author Manuel Raynaud <manu@raynaud.io>
* @author Benjamin Perche <bperche@openstudio.fr>
*/
abstract class BaseController extends ContainerAware
abstract class BaseController
{
use ContainerAwareTrait;
const EMPTY_FORM_NAME = "thelia.empty";
protected $tokenProvider;
protected $currentRouter;
protected $translator;
protected $templateHelper;
protected $adminResources;
/** @var bool Fallback on default template when setting the templateDefinition */
protected $useFallbackTemplate = true;
/**
* Return an empty response (after an ajax request, for example)
@@ -61,37 +77,45 @@ abstract class BaseController extends ContainerAware
}
/**
* Return a JSON response
* @param $jsonData
* @param int $status
* @return Response Return a JSON response
*/
protected function jsonResponse($json_data, $status = 200)
protected function jsonResponse($jsonData, $status = 200)
{
return new Response($json_data, $status, array('content-type' => 'application/json'));
return new Response($jsonData, $status, array('content-type' => 'application/json'));
}
/**
* @param $pdf
* @param $fileName
* @param $status
* @param int $status
* @param bool $browser
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function pdfResponse($pdf, $fileName, $status = 200)
protected function pdfResponse($pdf, $fileName, $status = 200, $browser = false)
{
return Response::create($pdf, $status,
return Response::create(
$pdf,
$status,
array(
'Content-type' => "application/pdf",
'Content-Disposition' => sprintf('Attachment;filename=%s.pdf', $fileName),
));
'Content-Disposition' => $browser === false ? sprintf('Attachment;filename=%s.pdf', $fileName) : '',
)
);
}
/**
* Dispatch a Thelia event
*
* @param string $eventName a TheliaEvent name, as defined in TheliaEvents class
* @param Event $event the action event, or null (a DefaultActionEvent will be dispatched)
* @param ActionEvent $event the action event, or null (a DefaultActionEvent will be dispatched)
*/
protected function dispatch($eventName, ActionEvent $event = null)
{
if ($event == null) $event = new DefaultActionEvent();
if ($event == null) {
$event = new DefaultActionEvent();
}
$this->getDispatcher()->dispatch($eventName, $event);
}
@@ -107,14 +131,16 @@ abstract class BaseController extends ContainerAware
}
/**
*
* return the Translator
*
* @return Translator
*/
public function getTranslator()
{
return $this->container->get('thelia.translator');
if (null === $this->translator) {
$this->translator = $this->container->get('thelia.translator');
}
return $this->translator;
}
/**
@@ -142,7 +168,7 @@ abstract class BaseController extends ContainerAware
*/
protected function getRequest()
{
return $this->container->get('request');
return $this->container->get('request_stack')->getCurrentRequest();
}
/**
@@ -152,36 +178,55 @@ abstract class BaseController extends ContainerAware
*/
protected function getSession()
{
$request = $this->getRequest();
return $request->getSession();
return $this->container->get('request_stack')->getCurrentRequest()->getSession();
}
/**
* Get all errors that occured in a form
* @return \Thelia\Tools\TokenProvider
*/
protected function getTokenProvider()
{
if (null === $this->tokenProvider) {
$this->tokenProvider = $this->container->get("thelia.token_provider");
}
return $this->tokenProvider;
}
/**
* @return \Thelia\Core\Template\TemplateHelperInterface
*/
protected function getTemplateHelper()
{
if (null === $this->templateHelper) {
$this->templateHelper = $this->container->get("thelia.template_helper");
}
return $this->templateHelper;
}
/**
* @since 2.3
* @return \Thelia\Core\Security\Resource\AdminResources
*/
protected function getAdminResources()
{
if (null === $this->adminResources) {
$this->adminResources = $this->container->get("thelia.admin.resources");
}
return $this->adminResources;
}
/**
* Get all errors that occurred in a form
*
* @param \Symfony\Component\Form\Form $form
* @return string the error string
*/
private function getErrorMessages(\Symfony\Component\Form\Form $form)
protected function getErrorMessages(Form $form)
{
$errors = '';
foreach ($form->getErrors() as $key => $error) {
$errors .= $error->getMessage() . ', ';
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$fieldName = $child->getConfig()->getOption('label', $child->getName());
$errors .= sprintf("[%s] %s, ", $fieldName, $this->getErrorMessages($child));
}
}
return rtrim($errors, ', ');
return $this->getTheliaFormValidator()->getErrorMessages($form);
}
/**
@@ -194,97 +239,225 @@ abstract class BaseController extends ContainerAware
*/
protected function validateForm(BaseForm $aBaseForm, $expectedMethod = null)
{
$form = $aBaseForm->getForm();
$form = $this->getTheliaFormValidator()->validateForm($aBaseForm, $expectedMethod);
if ($expectedMethod == null || $aBaseForm->getRequest()->isMethod($expectedMethod)) {
// At this point, the form is valid (no exception was thrown). Remove it from the error context.
$this->getParserContext()->clearForm($aBaseForm);
$form->bind($aBaseForm->getRequest());
if ($form->isValid()) {
$env = $this->container->getParameter("kernel.environment");
if ($aBaseForm instanceof FirewallForm && !$aBaseForm->isFirewallOk($env)) {
throw new FormValidationException(
$this->getTranslator()->trans(
"You've submitted this form too many times. Further submissions will be ignored during %time",
[
"%time" => $aBaseForm->getWaitingTime(),
]
)
);
}
return $form;
} else {
$errorMessage = null;
if ($form->get("error_message")->getData() != null) {
$errorMessage = $form->get("error_message")->getData();
} else {
$errorMessage = sprintf($this->getTranslator()->trans("Missing or invalid data: %s"), $this->getErrorMessages($form));
}
throw new FormValidationException($errorMessage);
}
} else {
throw new FormValidationException(sprintf($this->getTranslator()->trans("Wrong form method, %s expected."), $expectedMethod));
}
return $form;
}
protected function generateOrderPdf($order_id, $fileName)
/**
* @return \Thelia\Core\Form\TheliaFormValidatorInterface
*/
protected function getTheliaFormValidator()
{
return $this->container->get("thelia.form_validator");
}
/**
* @param int $order_id
* @param string $fileName
* @param bool $checkOrderStatus
* @param bool $checkAdminUser
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function generateOrderPdf($order_id, $fileName, $checkOrderStatus = true, $checkAdminUser = true, $browser = false)
{
$order = OrderQuery::create()->findPk($order_id);
// check if the order has the paid status
if ($checkAdminUser && !$this->getSecurityContext()->hasAdminUser()) {
if ($checkOrderStatus && !$order->isPaid(false)) {
throw new NotFoundHttpException();
}
}
$html = $this->renderRaw(
$fileName,
array(
'order_id' => $order_id
),
TemplateHelper::getInstance()->getActivePdfTemplate()
$this->getTemplateHelper()->getActivePdfTemplate()
);
$order = OrderQuery::create()->findPk($order_id);
try {
$pdfEvent = new PdfEvent($html);
$this->dispatch(TheliaEvents::GENERATE_PDF, $pdfEvent);
if ($pdfEvent->hasPdf()) {
return $this->pdfResponse($pdfEvent->getPdf(), $order->getRef());
return $this->pdfResponse($pdfEvent->getPdf(), $order->getRef(), 200, $browser);
}
} catch (\Exception $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf('error during generating invoice pdf for order id : %d with message "%s"', $order_id, $e->getMessage()));
Tlog::getInstance()->error(
sprintf(
'error during generating invoice pdf for order id : %d with message "%s"',
$order_id,
$e->getMessage()
)
);
}
throw new TheliaProcessException(
$this->getTranslator()->trans(
"We're sorry, this PDF invoice is not available at the moment."
)
);
}
/**
* Search success url in a form if present, in the query string otherwise
*
* redirect request to the specified url
*
* @param string $url
* @param int $status http status. Must be a 30x status
* @param array $cookies
* @param BaseForm $form
* @return mixed|null|string
*/
public function redirect($url, $status = 302, $cookies = array())
protected function retrieveSuccessUrl(BaseForm $form = null)
{
Redirect::exec($url, $status, $cookies);
return $this->retrieveFormBasedUrl('success_url', $form);
}
/**
* If success_url param is present in request or in the provided form, redirect to this URL.
* Search error url in a form if present, in the query string otherwise
*
* @param BaseForm $form a base form, which may contains the success URL
* @param BaseForm $form
* @return mixed|null|string
*/
protected function redirectSuccess(BaseForm $form = null)
protected function retrieveErrorUrl(BaseForm $form = null)
{
return $this->retrieveFormBasedUrl('error_url', $form);
}
/**
* Search url in a form parameter, or in a request parameter.
*
* @param string $parameterName the form parameter name, or request parameter name.
* @param BaseForm $form the form
* @return mixed|null|string
*/
protected function retrieveFormBasedUrl($parameterName, BaseForm $form = null)
{
$url = null;
if ($form != null) {
$url = $form->getSuccessUrl();
$url = $form->getFormDefinedUrl($parameterName);
} else {
$url = $this->getRequest()->get("success_url");
$url = $this->container->get('request_stack')->getCurrentRequest()->get($parameterName);
}
if (null !== $url) $this->redirect($url);
return $url;
}
/**
* @param $routeId
* @param array $urlParameters
* @param array $routeParameters
* @param int $referenceType
* @return string
*/
protected function retrieveUrlFromRouteId(
$routeId,
array $urlParameters = [],
array $routeParameters = [],
$referenceType = Router::ABSOLUTE_PATH
) {
return URL::getInstance()->absoluteUrl(
$this->getRoute(
$routeId,
$routeParameters,
$referenceType
),
$urlParameters
);
}
/**
*
* create an instance of RedirectResponse
*
* @param $url
* @param int $status
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function generateRedirect($url, $status = 302)
{
return RedirectResponse::create($url, $status);
}
/**
* create an instance of RedirectReponse if a success url is present, return null otherwise
*
* @param BaseForm $form
* @return null|\Symfony\Component\HttpFoundation\Response
*/
protected function generateSuccessRedirect(BaseForm $form = null)
{
if (null !== $url = $this->retrieveSuccessUrl($form)) {
return $this->generateRedirect($url);
}
return null;
}
/**
* create an instance of RedirectReponse if a success url is present, return null otherwise
*
* @param BaseForm $form
* @return null|\Symfony\Component\HttpFoundation\Response
*/
protected function generateErrorRedirect(BaseForm $form = null)
{
if (null !== $url = $this->retrieveErrorUrl($form)) {
return $this->generateRedirect($url);
}
return null;
}
/**
*
* create an instance of RedriectResponse for a given route id.
*
* @param $routeId
* @param array $urlParameters
* @param array $routeParameters
* @param int $referenceType
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function generateRedirectFromRoute(
$routeId,
array $urlParameters = [],
array $routeParameters = [],
$referenceType = Router::ABSOLUTE_PATH
) {
return $this->generateRedirect(
$this->retrieveUrlFromRouteId($routeId, $urlParameters, $routeParameters, $referenceType)
);
}
/**
* Return the route path defined for the givent route ID
*
* @param string $routeId a route ID, as defines in Config/Resources/routing/admin.xml
* @param mixed $parameters An array of parameters
* @param int $referenceType The type of reference to be generated (one of the constants)
*
* @throws RouteNotFoundException If the named route doesn't exist
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
* @throws InvalidParameterException When a parameter value for a placeholder is not correct because
* it does not match the requirement
* @throws \InvalidArgumentException When the router doesn't exist
* @return string The generated URL
*
* @see \Thelia\Controller\BaseController::getRouteFromRouter()
*/
protected function getRoute($routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_URL)
{
return $this->getRouteFromRouter(
$this->getCurrentRouter(),
$routeId,
$parameters,
$referenceType
);
}
/**
@@ -293,7 +466,7 @@ abstract class BaseController extends ContainerAware
* @param string $routerName Router name
* @param string $routeId The name of the route
* @param mixed $parameters An array of parameters
* @param Boolean|string $referenceType The type of reference to be generated (one of the constants)
* @param int $referenceType The type of reference to be generated (one of the constants)
*
* @throws RouteNotFoundException If the named route doesn't exist
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
@@ -302,8 +475,12 @@ abstract class BaseController extends ContainerAware
* @throws \InvalidArgumentException When the router doesn't exist
* @return string The generated URL
*/
protected function getRouteFromRouter($routerName, $routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_URL)
{
protected function getRouteFromRouter(
$routerName,
$routeId,
$parameters = array(),
$referenceType = Router::ABSOLUTE_URL
) {
/** @var Router $router */
$router = $this->getRouter($routerName);
@@ -354,7 +531,7 @@ abstract class BaseController extends ContainerAware
*/
protected function checkXmlHttpRequest()
{
if (false === $this->getRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
if (false === $this->container->get('request_stack')->getCurrentRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
$this->accessDenied();
}
}
@@ -363,24 +540,74 @@ abstract class BaseController extends ContainerAware
*
* return an instance of \Swift_Mailer with good Transporter configured.
*
* @return \Swift_Mailer
* @return MailerFactory
*/
public function getMailer()
{
$mailer = $this->container->get('mailer');
return $this->container->get('mailer');
}
return $mailer->getSwiftMailer();
protected function getCurrentRouter()
{
return $this->currentRouter;
}
protected function setCurrentRouter($routerId)
{
$this->currentRouter = $routerId;
}
/**
* @return a ParserInterface instance parser
* @param $name
* @param $type
* @param array $data
* @param array $options
* @return BaseForm
*
* This method builds a thelia form with its name
*/
public function createForm($name, $type = "form", array $data = array(), array $options = array())
{
if (empty($name)) {
$name = static::EMPTY_FORM_NAME;
}
return $this->getTheliaFormFactory()->createForm($name, $type, $data, $options);
}
/**
* @return \Thelia\Core\Form\TheliaFormFactoryInterface
*/
protected function getTheliaFormFactory()
{
return $this->container->get("thelia.form_factory");
}
/**
* @return \Symfony\Component\DependencyInjection\ContainerInterface
*/
public function getContainer()
{
return $this->container;
}
/**
* Return controller type
*
* @return string
*/
abstract public function getControllerType();
/**
* @param null|mixed $template
* @return \Thelia\Core\Template\ParserInterface instance parser
*/
abstract protected function getParser($template = null);
/**
* Render the given template, and returns the result as an Http Response.
*
* @param $templateName the complete template name, with extension
* @param string $templateName the complete template name, with extension
* @param array $args the template arguments
* @param int $status http code status
* @return \Thelia\Core\HttpFoundation\Response
@@ -390,7 +617,7 @@ abstract class BaseController extends ContainerAware
/**
* Render the given template, and returns the result as a string.
*
* @param $templateName the complete template name, with extension
* @param string $templateName the complete template name, with extension
* @param array $args the template arguments
* @param null $templateDir
*