Merge branch 'master' into rewrite

This commit is contained in:
Etienne Roudeix
2013-09-03 10:10:32 +02:00
275 changed files with 7203 additions and 2657 deletions

View File

@@ -29,10 +29,4 @@ class AdminController extends BaseAdminController
{
return $this->render("home");
}
public function processAction()
{
echo "not yet coded !";
exit();
}
}

View File

@@ -32,6 +32,8 @@ use Thelia\Tools\URL;
use Thelia\Tools\Redirect;
use Thelia\Core\Security\SecurityContext;
use Thelia\Model\AdminLog;
use Thelia\Model\Lang;
use Thelia\Model\LangQuery;
class BaseAdminController extends BaseController
{
@@ -46,17 +48,25 @@ class BaseAdminController extends BaseController
AdminLog::append($message, $this->getRequest(), $this->getSecurityContext()->getAdminUser());
}
/**
* This method process the rendering of view called from an admin page
*
* @param unknown $template
* @return Response the reponse which contains the rendered view
*/
public function processTemplateAction($template)
{
try {
if (! empty($template)) {
// If we have a view in the URL, render this view
return $this->render($template);
} elseif (null != $view = $this->getRequest()->get('view')) {
}
elseif (null != $view = $this->getRequest()->get('view')) {
return $this->render($view);
}
} catch (\Exception $ex) {
// Nothing special
}
catch (\Exception $ex) {
return new Response($this->errorPage($ex->getMessage()));
}
return $this->pageNotFound();
@@ -87,19 +97,31 @@ class BaseAdminController extends BaseController
/**
* Check current admin user authorisations. An ADMIN role is assumed.
*
* @param unknown $permissions a single permission or an array of permissions.
* @param mixed $permissions a single permission or an array of permissions.
*
* @return mixed null if authorization is granted, or a Response object which contains the error page otherwise
*
* @throws AuthenticationException if permissions are not granted ti the current user.
*/
protected function checkAuth($permissions)
{
if (! $this->getSecurityContext()->isGranted(array("ADMIN"), is_array($permissions) ? $permissions : array($permissions))) {
throw new AuthorizationException("Sorry, you're not allowed to perform this action");
}
$permArr = is_array($permissions) ? $permissions : array($permissions);
if ($this->getSecurityContext()->isGranted(array("ADMIN"), $permArr)) {
// Okay !
return null;
}
// Log the problem
$this->adminLogAppend("User is not granted for permissions %s", implode(", ", $permArr));
// Generate the proper response
$response = new Response();
return $response->setContent($this->errorPage("Sorry, you're not allowed to perform this action"));
}
/**
* @return a ParserInterfac instance parser
* @return a ParserInterface instance parser
*/
protected function getParser()
{
@@ -128,6 +150,23 @@ class BaseAdminController extends BaseController
return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
/**
* Get the current edition lang ID, checking if a change was requested in the current request
*/
protected function getCurrentEditionLangId() {
return $this->getRequest()->get(
'edition_language',
$this->getSession()->getAdminEditionLangId()
);
}
/**
* A simple helper to get the current edition locale, from the session edition language ID
*/
protected function getCurrentEditionLocale() {
return LangQuery::create()->findOneById($this->getCurrentEditionLangId())->getLocale();
}
/**
* Render the given template, and returns the result as an Http Response.
*
@@ -151,26 +190,41 @@ class BaseAdminController extends BaseController
*/
protected function renderRaw($templateName, $args = array())
{
// Add the template standard extension
$templateName .= '.html';
$session = $this->getSession();
// Find the current edit language ID
$edition_language = $this->getCurrentEditionLangId();
// Prepare common template variables
$args = array_merge($args, array(
'locale' => $session->getLocale(),
'lang' => $session->getLang()
'locale' => $session->getLocale(),
'lang_code' => $session->getLang(),
'lang_id' => $session->getLangId(),
'edition_language' => $edition_language,
'current_url' => htmlspecialchars($this->getRequest()->getUri())
));
// Update the current edition language in session
$this->getSession()->setAdminEditionLangId($edition_language);
// Render the template.
try {
$data = $this->getParser()->render($templateName, $args);
return $data;
} catch (AuthenticationException $ex) {
}
catch (AuthenticationException $ex) {
// User is not authenticated, and templates requires authentication -> redirect to login page
// We user login_tpl as a path, not a template.
Redirect::exec(URL::absoluteUrl($ex->getLoginTemplate()));
}
catch (AuthorizationException $ex) {
// User is not allowed to perform the required action. Return the error page instead of the requested page.
return $this->errorPage("Sorry, you are not allowed to perform this action.");
}
}
}

View File

@@ -33,6 +33,7 @@ use Thelia\Core\Event\CategoryDeleteEvent;
use Thelia\Core\Event\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\CategoryChangePositionEvent;
use Thelia\Form\CategoryDeletionForm;
use Thelia\Model\Lang;
class CategoryController extends BaseAdminController
{
@@ -65,7 +66,7 @@ class CategoryController extends BaseAdminController
}
catch (FormValidationException $e) {
$categoryCreationForm->setErrorMessage($e->getMessage());
$this->getParserContext()->setErrorForm($categoryCreationForm);
$this->getParserContext()->addForm($categoryCreationForm);
}
catch (Exception $e) {
Tlog::getInstance()->error(sprintf("Failed to create category: %s", $e->getMessage()));
@@ -78,7 +79,7 @@ class CategoryController extends BaseAdminController
protected function editCategory($args)
{
$this->checkAuth("ADMIN", "admin.category.edit");
if (null !== $response = $this->checkAuth("admin.category.edit")) return $response;
return $this->render('edit_category', $args);
}
@@ -99,14 +100,14 @@ class CategoryController extends BaseAdminController
$this->adminLogAppend(sprintf("Category %s (ID %s) deleted", $category->getTitle(), $category->getId()));
// Substitute _ID_ in the URL with the ID of the created category
$successUrl = str_replace('_ID_', $categoryDeleteEvent->getDeletedCategory()->getId(), $categoryDeletionForm->getSuccessUrl());
$successUrl = str_replace('_ID_', $categoryDeleteEvent->getDeletedCategory()->getParent(), $categoryDeletionForm->getSuccessUrl());
// Redirect to the success URL
$this->redirect($successUrl);
}
catch (FormValidationException $e) {
$categoryDeletionForm->setErrorMessage($e->getMessage());
$this->getParserContext()->setErrorForm($categoryDeletionForm);
$this->getParserContext()->addForm($categoryDeletionForm);
}
catch (Exception $e) {
Tlog::getInstance()->error(sprintf("Failed to delete category: %s", $e->getMessage()));
@@ -119,7 +120,7 @@ class CategoryController extends BaseAdminController
protected function browseCategory($args)
{
$this->checkAuth("AMIN", "admin.catalog.view");
if (null !== $response = $this->checkAuth("admin.catalog.view")) return $response;
return $this->render('categories', $args);
}
@@ -185,11 +186,31 @@ class CategoryController extends BaseAdminController
// Get the category ID
$id = $this->getRequest()->get('id', 0);
// Find the current order
$category_order = $this->getRequest()->get(
'category_order',
$this->getSession()->get('admin.category_order', 'manual')
);
// Find the current edit language ID
$edition_language = $this->getRequest()->get(
'edition_language',
$this->getSession()->get('admin.edition_language', Lang::getDefaultLanguage()->getId())
);
$args = array(
'action' => $action,
'current_category_id' => $id
'current_category_id' => $id,
'category_order' => $category_order,
'edition_language' => $edition_language,
);
// Store the current sort order in session
$this->getSession()->set('admin.category_order', $category_order);
// Store the current edition language in session
$this->getSession()->set('admin.edition_language', $edition_language);
try {
switch ($action) {
case 'browse' : // Browse categories

View File

@@ -0,0 +1,299 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\ConfigDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Tools\URL;
use Thelia\Core\Event\ConfigChangeEvent;
use Thelia\Core\Event\ConfigCreateEvent;
use Thelia\Log\Tlog;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Security\Exception\AuthorizationException;
use Thelia\Model\ConfigQuery;
use Thelia\Form\ConfigModificationForm;
use Thelia\Form\ConfigCreationForm;
/**
* Manages Thelmia system variables, aka Config objects.
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class ConfigController extends BaseAdminController
{
/**
* The default action is displaying the variables list.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function defaultAction() {
if (null !== $response = $this->checkAuth("admin.configuration.variables.view")) return $response;
return $this->render('variables');
}
/**
* Create a new config object
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function createAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.variables.create")) return $response;
$message = false;
// Create the Creation Form
$creationForm = new ConfigCreationForm($this->getRequest());
try {
// Validate the form, create the ConfigCreation event and dispatch it.
$form = $this->validateForm($creationForm, "POST");
$data = $form->getData();
$createEvent = new ConfigCreateEvent();
$createEvent
->setEventName($data['name'])
->setValue($data['value'])
->setLocale($data["locale"])
->setTitle($data['title'])
->setHidden($data['hidden'])
->setSecured($data['secured'])
;
$this->dispatch(TheliaEvents::CONFIG_CREATE, $createEvent);
$createdObject = $createEvent->getConfig();
// Log config creation
$this->adminLogAppend(sprintf("Variable %s (ID %s) created", $createdObject->getName(), $createdObject->getId()));
// Substitute _ID_ in the URL with the ID of the created object
$successUrl = str_replace('_ID_', $createdObject->getId(), $creationForm->getSuccessUrl());
// Redirect to the success URL
$this->redirect($successUrl);
}
catch (FormValidationException $ex) {
// Form cannot be validated
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch (\Exception $ex) {
// Any other error
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
// An error has been detected: log it
Tlog::getInstance()->error(sprintf("Error during variable creation process : %s. Exception was %s", $message, $ex->getMessage()));
// Mark the form as errored
$creationForm->setErrorMessage($message);
// Pass it to the parser, along with the error message
$this->getParserContext()
->addForm($creationForm)
->setGeneralError($message)
;
}
// At this point, the form has error, and should be redisplayed.
return $this->render('variables');
}
/**
* Load a config object for modification, and display the edit template.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function changeAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.variables.change")) return $response;
// Load the config object
$config = ConfigQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('variable_id'));
if ($config != null) {
// Prepare the data that will hydrate the form
$data = array(
'id' => $config->getId(),
'name' => $config->getName(),
'value' => $config->getValue(),
'hidden' => $config->getHidden(),
'secured' => $config->getSecured(),
'locale' => $config->getLocale(),
'title' => $config->getTitle(),
'chapo' => $config->getChapo(),
'description' => $config->getDescription(),
'postscriptum' => $config->getPostscriptum()
);
// Setup the object form
$changeForm = new ConfigModificationForm($this->getRequest(), "form", $data);
// Pass it to the parser
$this->getParserContext()->addForm($changeForm);
}
// Render the edition template.
return $this->render('variable-edit', array('variable_id' => $this->getRequest()->get('variable_id')));
}
/**
* Save changes on a modified config object, and either go back to the variable list, or stay on the edition page.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function saveChangeAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.variables.change")) return $response;
$message = false;
// Create the form from the request
$changeForm = new ConfigModificationForm($this->getRequest());
// Get the variable ID
$variable_id = $this->getRequest()->get('variable_id');
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
$changeEvent = new ConfigChangeEvent($data['id']);
// Create and dispatch the change event
$changeEvent
->setEventName($data['name'])
->setValue($data['value'])
->setHidden($data['hidden'])
->setSecured($data['secured'])
->setLocale($data["locale"])
->setTitle($data['title'])
->setChapo($data['chapo'])
->setDescription($data['description'])
->setPostscriptum($data['postscriptum'])
;
$this->dispatch(TheliaEvents::CONFIG_MODIFY, $changeEvent);
// Log config modification
$changedObject = $changeEvent->getConfig();
$this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $changedObject->getName(), $changedObject->getId()));
// If we have to stay on the same page, do not redirect to the succesUrl,
// just redirect to the edit page again.
if ($this->getRequest()->get('save_mode') == 'stay') {
$this->redirect(URL::absoluteUrl(
"admin/configuration/variables/change",
array('variable_id' => $variable_id)
));
}
// Redirect to the success URL
$this->redirect($changeForm->getSuccessUrl());
}
catch (FormValidationException $ex) {
// Invalid data entered
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch (\Exception $ex) {
// Any other error
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
// Log error message
Tlog::getInstance()->error(sprintf("Error during variable modification process : %s. Exception was %s", $message, $ex->getMessage()));
// Mark the form as errored
$changeForm->setErrorMessage($message);
// Pas the form and the error to the parser
$this->getParserContext()
->addForm($changeForm)
->setGeneralError($message)
;
}
// At this point, the form has errors, and should be redisplayed.
return $this->render('variable-edit', array('variable_id' => $variable_id));
}
/**
* Change values modified directly from the variable list
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function changeValuesAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.variables.change")) return $response;
$variables = $this->getRequest()->get('variable', array());
// Process all changed variables
foreach($variables as $id => $value) {
$event = new ConfigChangeEvent($id);
$event->setValue($value);
$this->dispatch(TheliaEvents::CONFIG_SETVALUE, $event);
}
$this->redirect(URL::adminViewUrl('variables'));
}
/**
* Delete a config object
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function deleteAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.variables.delete")) return $response;
// Get the config id, and dispatch the delet request
$event = new ConfigDeleteEvent($this->getRequest()->get('variable_id'));
$this->dispatch(TheliaEvents::CONFIG_DELETE, $event);
$this->redirect(URL::adminViewUrl('variables'));
}
}

View File

@@ -0,0 +1,270 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\MessageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Tools\URL;
use Thelia\Core\Event\MessageChangeEvent;
use Thelia\Core\Event\MessageCreateEvent;
use Thelia\Log\Tlog;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Security\Exception\AuthorizationException;
use Thelia\Model\MessageQuery;
use Thelia\Form\MessageModificationForm;
use Thelia\Form\MessageCreationForm;
/**
* Manages messages sent by mail
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class MessageController extends BaseAdminController
{
/**
* The default action is displaying the messages list.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function defaultAction() {
if (null !== $response = $this->checkAuth("admin.configuration.messages.view")) return $response;
return $this->render('messages');
}
/**
* Create a new message object
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function createAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.messages.create")) return $response;
$message = false;
// Create the Creation Form
$creationForm = new MessageCreationForm($this->getRequest());
try {
// Validate the form, create the MessageCreation event and dispatch it.
$form = $this->validateForm($creationForm, "POST");
$data = $form->getData();
$createEvent = new MessageCreateEvent();
$createEvent
->setMessageName($data['name'])
->setLocale($data["locale"])
->setTitle($data['title'])
->setSecured($data['secured'])
;
$this->dispatch(TheliaEvents::MESSAGE_CREATE, $createEvent);
$createdObject = $createEvent->getMessage();
// Log message creation
$this->adminLogAppend(sprintf("Variable %s (ID %s) created", $createdObject->getName(), $createdObject->getId()));
// Substitute _ID_ in the URL with the ID of the created object
$successUrl = str_replace('_ID_', $createdObject->getId(), $creationForm->getSuccessUrl());
// Redirect to the success URL
$this->redirect($successUrl);
}
catch (FormValidationException $ex) {
// Form cannot be validated
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch (\Exception $ex) {
// Any other error
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
// An error has been detected: log it
Tlog::getInstance()->error(sprintf("Error during message creation process : %s. Exception was %s", $message, $ex->getMessage()));
// Mark the form as errored
$creationForm->setErrorMessage($message);
// Pass it to the parser, along with the error message
$this->getParserContext()
->addForm($creationForm)
->setGeneralError($message)
;
}
// At this point, the form has error, and should be redisplayed.
return $this->render('messages');
}
/**
* Load a message object for modification, and display the edit template.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function changeAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.messages.change")) return $response;
// Load the message object
$message = MessageQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('message_id'));
if ($message != null) {
// Prepare the data that will hydrate the form
$data = array(
'id' => $message->getId(),
'name' => $message->getName(),
'secured' => $message->getSecured(),
'locale' => $message->getLocale(),
'title' => $message->getTitle(),
'subject' => $message->getSubject(),
'html_message' => $message->getHtmlMessage(),
'text_message' => $message->getTextMessage()
);
// Setup the object form
$changeForm = new MessageModificationForm($this->getRequest(), "form", $data);
// Pass it to the parser
$this->getParserContext()->addForm($changeForm);
}
// Render the edition template.
return $this->render('message-edit', array('message_id' => $this->getRequest()->get('message_id')));
}
/**
* Save changes on a modified message object, and either go back to the message list, or stay on the edition page.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function saveChangeAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.messages.change")) return $response;
$message = false;
// Create the form from the request
$changeForm = new MessageModificationForm($this->getRequest());
// Get the message ID
$message_id = $this->getRequest()->get('message_id');
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
$changeEvent = new MessageChangeEvent($data['id']);
// Create and dispatch the change event
$changeEvent
->setMessageName($data['name'])
->setSecured($data['secured'])
->setLocale($data["locale"])
->setTitle($data['title'])
->setSubject($data['subject'])
->setHtmlMessage($data['html_message'])
->setTextMessage($data['text_message'])
;
$this->dispatch(TheliaEvents::MESSAGE_MODIFY, $changeEvent);
// Log message modification
$changedObject = $changeEvent->getMessage();
$this->adminLogAppend(sprintf("Variable %s (ID %s) modified", $changedObject->getName(), $changedObject->getId()));
// If we have to stay on the same page, do not redirect to the succesUrl,
// just redirect to the edit page again.
if ($this->getRequest()->get('save_mode') == 'stay') {
$this->redirect(URL::absoluteUrl(
"admin/configuration/messages/change",
array('message_id' => $message_id)
));
}
// Redirect to the success URL
$this->redirect($changeForm->getSuccessUrl());
}
catch (FormValidationException $ex) {
// Invalid data entered
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch (\Exception $ex) {
// Any other error
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
// Log error message
Tlog::getInstance()->error(sprintf("Error during message modification process : %s. Exception was %s", $message, $ex->getMessage()));
// Mark the form as errored
$changeForm->setErrorMessage($message);
// Pas the form and the error to the parser
$this->getParserContext()
->addForm($changeForm)
->setGeneralError($message)
;
}
// At this point, the form has errors, and should be redisplayed.
return $this->render('message-edit', array('message_id' => $message_id));
}
/**
* Delete a message object
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function deleteAction() {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.messages.delete")) return $response;
// Get the message id, and dispatch the delet request
$event = new MessageDeleteEvent($this->getRequest()->get('message_id'));
$this->dispatch(TheliaEvents::MESSAGE_DELETE, $event);
$this->redirect(URL::adminViewUrl('messages'));
}
}

View File

@@ -51,13 +51,16 @@ class SessionController extends BaseAdminController
public function checkLoginAction()
{
$adminLoginForm = new AdminLogin($this->getRequest());
$request = $this->getRequest();
$authenticator = new AdminUsernamePasswordFormAuthenticator($request, $adminLoginForm);
$adminLoginForm = new AdminLogin($request);
try {
$form = $this->validateForm($adminLoginForm, "post");
$authenticator = new AdminUsernamePasswordFormAuthenticator($request, $adminLoginForm);
$user = $authenticator->getAuthentifiedUser();
// Success -> store user in security context
@@ -85,7 +88,7 @@ class SessionController extends BaseAdminController
// Log authentication failure
AdminLog::append(sprintf("Undefined error: %s", $ex->getMessage()), $request);
$message = "Unable to process your request. Please try again.";
$message = "Unable to process your request. Please try again.".$ex->getMessage();
}
// Store error information in the form
@@ -93,7 +96,7 @@ class SessionController extends BaseAdminController
$adminLoginForm->setErrorMessage($message);
// Store the form name in session (see Form Smarty plugin to find usage of this parameter)
$this->getParserContext()->setErrorForm($adminLoginForm);
$this->getParserContext()->addForm($adminLoginForm);
// Display the login form again
return $this->render("login");

View File

@@ -35,6 +35,7 @@ use Thelia\Core\Factory\ActionEventFactory;
use Thelia\Form\BaseForm;
use Thelia\Form\Exception\FormValidationException;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\DefaultActionEvent;
/**
*
@@ -60,10 +61,12 @@ class BaseController extends ContainerAware
* Dispatch a Thelia event
*
* @param string $eventName a TheliaEvent name, as defined in TheliaEvents class
* @param Event $event the event
* @param Event $event the action event, or null (a DefaultActionEvent will be dispatched)
*/
protected function dispatch($eventName, Event $event = null)
protected function dispatch($eventName, ActionEvent $event = null)
{
if ($event == null) $event = new DefaultActionEvent();
$this->getDispatcher()->dispatch($eventName, $event);
}
@@ -117,6 +120,29 @@ class BaseController extends ContainerAware
return $request->getSession();
}
/**
* Get all errors that occured in a form
*
* @param \Symfony\Component\Form\Form $form
* @return string the error string
*/
private function getErrorMessages(\Symfony\Component\Form\Form $form) {
$errors = '';
foreach ($form->getErrors() as $key => $error) {
$errors .= $error->getMessage() . ', ';
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors .= $this->getErrorMessages($child) . ', ';
}
}
return rtrim($errors, ', ');
}
/**
* Validate a BaseForm
*
@@ -135,17 +161,20 @@ class BaseController extends ContainerAware
if ($form->isValid()) {
return $form;
} else {
throw new FormValidationException("Missing or invalid data");
}
} else {
else {
throw new FormValidationException(sprintf("Missing or invalid data: %s", $this->getErrorMessages($form)));
}
}
else {
throw new FormValidationException(sprintf("Wrong form method, %s expected.", $expectedMethod));
}
}
/**
*
* redirect request to specify url
* redirect request to the specified url
*
* @param string $url
*/
public function redirect($url, $status = 302)
@@ -154,12 +183,21 @@ class BaseController extends ContainerAware
}
/**
* If success_url param is present in request, follow this link.
* If success_url param is present in request or in the provided form, redirect to this URL.
*
* @param BaseForm $form a base form, which may contains the success URL
*/
protected function redirectSuccess()
protected function redirectSuccess(BaseForm $form = null)
{
if (null !== $url = $this->getRequest()->get("success_url")) {
$this->redirect($url);
if ($form != null) {
$url = $form->getSuccessUrl();
}
else {
$url = $this->getRequest()->get("success_url");
}
echo "url=$url";
if (null !== $url) $this->redirect($url);
}
}

View File

@@ -63,7 +63,7 @@ class CartController extends BaseFrontController
if ($message) {
$cartAdd->setErrorMessage($message);
$this->getParserContext()->setErrorForm($cartAdd);
$this->getParserContext()->addForm($cartAdd);
}
}

View File

@@ -22,8 +22,6 @@
/*************************************************************************************/
namespace Thelia\Controller\Front;
use Propel\Runtime\Exception\PropelException;
use Symfony\Component\Validator\Exception\ValidatorException;
use Thelia\Core\Event\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\CustomerLoginEvent;
use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator;
@@ -37,65 +35,101 @@ use Thelia\Form\Exception\FormValidationException;
use Thelia\Model\Customer;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CustomerEvent;
use Thelia\Core\Factory\ActionEventFactory;
use Thelia\Tools\URL;
use Thelia\Log\Tlog;
use Thelia\Core\Security\Exception\WrongPasswordException;
class CustomerController extends BaseFrontController
{
/**
* create a new Customer. Retrieve data in form and dispatch a action.createCustomer event
*
* if error occurs, message is set in the parserContext
* Create a new customer.
* On success, redirect to success_url if exists, otherwise, display the same view again.
*/
public function createAction()
{
$request = $this->getRequest();
$customerCreation = new CustomerCreation($request);
try {
$form = $this->validateForm($customerCreation, "post");
if (! $this->getSecurityContext()->hasCustomerUser()) {
$customerCreateEvent = $this->createEventInstance($form->getData());
$message = false;
$this->getDispatcher()->dispatch(TheliaEvents::CUSTOMER_CREATEACCOUNT, $customerCreateEvent);
$customerCreation = new CustomerCreation($this->getRequest());
$this->processLogin($customerCreateEvent->getCustomer());
try {
$form = $this->validateForm($customerCreation, "post");
$this->redirectSuccess();
$customerCreateEvent = $this->createEventInstance($form->getData());
} catch (FormValidationException $e) {
$customerCreation->setErrorMessage($e->getMessage());
$this->getParserContext()->setErrorForm($customerCreation);
} catch (PropelException $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("error during customer creation process in front context with message : %s", $e->getMessage()));
$this->getParserContext()->setGeneralError($e->getMessage());
$this->dispatch(TheliaEvents::CUSTOMER_CREATEACCOUNT, $customerCreateEvent);
$this->processLogin($customerCreateEvent->getCustomer());
$this->redirectSuccess($customerCreation);
}
catch (FormValidationException $e) {
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch (\Exception $e) {
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf("Error during customer creation process : %s. Exception was %s", $message, $e->getMessage()));
$customerCreation->setErrorMessage($message);
$this->getParserContext()
->addForm($customerCreation)
->setGeneralError($message)
;
}
}
}
/**
* Update customer data. On success, redirect to success_url if exists.
* Otherwise, display the same view again.
*/
public function updateAction()
{
$request = $this->getRequest();
$customerModification = new CustomerModification($request);
if ($this->getSecurityContext()->hasCustomerUser()) {
try {
$message = false;
$customer = $this->getSecurityContext()->getCustomerUser();
$customerModification = new CustomerModification($this->getRequest());
$form = $this->validateForm($customerModification, "post");
try {
$customerChangeEvent = $this->createEventInstance($form->getData());
$customerChangeEvent->setCustomer($customer);
$customer = $this->getSecurityContext()->getCustomerUser();
$this->getDispatcher()->dispatch(TheliaEvents::CUSTOMER_UPDATEACCOUNT, $customerChangeEvent);
$form = $this->validateForm($customerModification, "post");
$this->processLogin($customerChangeEvent->getCustomer());
$customerChangeEvent = $this->createEventInstance($form->getData());
$customerChangeEvent->setCustomer($customer);
$this->redirectSuccess();
$this->dispatch(TheliaEvents::CUSTOMER_UPDATEACCOUNT, $customerChangeEvent);
} catch (FormValidationException $e) {
$customerModification->setErrorMessage($e->getMessage());
$this->getParserContext()->setErrorForm($customerModification);
} catch (PropelException $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("error during updating customer in front context with message : %s", $e->getMessage()));
$this->getParserContext()->setGeneralError($e->getMessage());
$this->processLogin($customerChangeEvent->getCustomer());
$this->redirectSuccess($customerModification);
}
catch (FormValidationException $e) {
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch (\Exception $e) {
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf("Error during customer modification process : %s. Exception was %s", $message, $e->getMessage()));
$customerModification->setErrorMessage($message);
$this->getParserContext()
->addForm($customerModification)
->setGeneralError($message)
;
}
}
}
@@ -103,39 +137,75 @@ class CustomerController extends BaseFrontController
* Perform user login. On a successful login, the user is redirected to the URL
* found in the success_url form parameter, or / if none was found.
*
* If login is not successfull, the same view is dispolyed again.
* If login is not successfull, the same view is displayed again.
*
*/
public function loginAction()
{
$request = $this->getRequest();
if (! $this->getSecurityContext()->hasCustomerUser()) {
$message = false;
$customerLoginForm = new CustomerLogin($request);
$request = $this->getRequest();
$authenticator = new CustomerUsernamePasswordFormAuthenticator($request, $customerLoginForm);
try {
try {
$customer = $authenticator->getAuthentifiedUser();
$customerLoginForm = new CustomerLogin($request);
$this->processLogin($customer);
$form = $this->validateForm($customerLoginForm, "post");
$this->redirectSuccess();
} catch (ValidatorException $e) {
$authenticator = new CustomerUsernamePasswordFormAuthenticator($request, $customerLoginForm);
} catch(UsernameNotFoundException $e) {
$customer = $authenticator->getAuthentifiedUser();
} catch(AuthenticationException $e) {
$this->processLogin($customer);
} catch (\Exception $e) {
$this->redirectSuccess($customerLoginForm);
}
catch (FormValidationException $e) {
$message = sprintf("Please check your input: %s", $ex->getMessage());
}
catch(UsernameNotFoundException $e) {
$message = "This customer email was not found.";
}
catch (WrongPasswordException $e) {
$message = "Wrong password. Please try again.";
}
catch(AuthenticationException $e) {
$message = "Sorry, we failed to authentify you. Please try again.";
}
catch (\Exception $e) {
$message = sprintf("Sorry, an error occured: %s", $ex->getMessage());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf("Error during customer login process : %s. Exception was %s", $message, $e->getMessage()));
$customerLoginForm->setErrorMessage($message);
$this->getParserContext()->addForm($customerLoginForm);
}
}
}
public function processLogin(Customer $customer)
/**
* Perform customer logout.
*
* @param Customer $customer
*/
public function logoutAction()
{
$this->getSecurityContext()->setCustomerUser($customer);
if ($this->getSecurityContext()->hasCustomerUser()) {
$this->dispatch(TheliaEvents::CUSTOMER_LOGOUT);
}
if($event) $this->dispatch(TheliaEvents::CUSTOMER_LOGIN, new CustomerLoginEvent($customer));
// Redirect to home page
$this->redirect(URL::getIndexPage());
}
protected function processLogin(Customer $customer)
{
$this->dispatch(TheliaEvents::CUSTOMER_LOGIN, new CustomerLoginEvent($customer));
}
/**
@@ -161,10 +231,9 @@ class CustomerController extends BaseFrontController
$this->getRequest()->getSession()->getLang(),
isset($data["reseller"])?$data["reseller"]:null,
isset($data["sponsor"])?$data["sponsor"]:null,
isset($data["discount"])?$data["discount"]:nullsch
isset($data["discount"])?$data["discount"]:null
);
return $customerCreateEvent;
}
}