From 02c42a094cf96496bcd6c1dcd5a25c91ad9116db Mon Sep 17 00:00:00 2001
From: Ghislain Loas <ghislo@sandbox.pergame.net>
Date: Fri, 22 Aug 2014 15:53:51 +0200
Subject: [PATCH] dev #15694 implements logging user action

---
 .../opac/controllers/AuthController.php       | 76 ++++++++++---------
 .../scripts/auth/newsletter-register.phtml    |  2 +-
 library/Class/Users.php                       |  1 -
 library/ZendAfi/Form/NewsletterRegister.php   |  9 ++-
 .../opac/controllers/AbonneVSmartTest.php     | 17 ++---
 .../opac/controllers/AuthControllerTest.php   | 48 +++++++++++-
 6 files changed, 100 insertions(+), 53 deletions(-)

diff --git a/application/modules/opac/controllers/AuthController.php b/application/modules/opac/controllers/AuthController.php
index bd078d671c2..80e9a21e3f4 100644
--- a/application/modules/opac/controllers/AuthController.php
+++ b/application/modules/opac/controllers/AuthController.php
@@ -16,7 +16,7 @@
  *
  * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
  * along with AFI-OPAC 2.0; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA 
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
 class AuthController extends ZendAfi_Controller_Action {
@@ -33,8 +33,8 @@ class AuthController extends ZendAfi_Controller_Action {
 	public function isCasRequest() {
 		return strlen($this->getCasServerUrl())>0;
 	}
-	
-	
+
+
 	public function getCasServerUrl() {
 		return $this->_request->getParam('service');
 	}
@@ -49,7 +49,7 @@ class AuthController extends ZendAfi_Controller_Action {
 		return $this->_request->getParam('redirect','/opac');
 	}
 
-	
+
 	public function redirect($redirect_url) {
 		$this->_redirect($redirect_url);
 	}
@@ -68,7 +68,7 @@ class AuthController extends ZendAfi_Controller_Action {
 
 		if (!ZendAfi_Auth::getInstance()->authenticateLoginPassword($username, $password))
 			return $this->view->_('Identifiant ou mot de passe incorrect.');
-				
+
 		$user = Class_Users::getIdentity();
 		$this->_helper->trackEvent('authentification', 'connexion', 'utilisateur', $user->getId());
 	}
@@ -81,29 +81,29 @@ class AuthController extends ZendAfi_Controller_Action {
 
 
 	function loginAction() {
-		$this->view->preferences = Class_Profil::getCurrentProfil()->getCfgModulesPreferences('auth','login');		
+		$this->view->preferences = Class_Profil::getCurrentProfil()->getCfgModulesPreferences('auth','login');
 		$redirect = $this->_getParam('redirect', '/opac');
-		$this->view->redirect = $redirect; 
+		$this->view->redirect = $redirect;
 		$service = $this->_getParam('service','');
-		$this->view->service = $service; 
-		$this->view->titre = $this->view->_('Connexion'); 
+		$this->view->service = $service;
+		$this->view->titre = $this->view->_('Connexion');
 
 		$strategy = Auth_Strategy_Abstract::strategyForController($this);
 		$strategy->setDefaultUrl($this->_getParam('redirect','/opac'));
 		$strategy->processLogin();
-		
+
 	}
 
 
 	public function ajaxLoginAction(){
-		$this->view->preferences = Class_Profil::getCurrentProfil()->getCfgModulesPreferences('auth','login');	
+		$this->view->preferences = Class_Profil::getCurrentProfil()->getCfgModulesPreferences('auth','login');
 		$strategy = Auth_Strategy_Abstract::strategyForController($this);
 		$strategy->disableRedirect();
 		$strategy->processLogin();
 
 		$redirect = urldecode($this->_getParam('redirect'));
-		
-		if (!Class_Users::getLoader()->getIdentity()==null) {			
+
+		if (!Class_Users::getLoader()->getIdentity()==null) {
 			$this->renderPopup($redirect);
 			return ;
 		}
@@ -118,7 +118,7 @@ class AuthController extends ZendAfi_Controller_Action {
 		$widget_settings = Class_Profil::getCurrentProfil()
 			->getModuleAccueilPreferencesByType('LOGIN');
 
-		$this->view->preferences = $widget_settings ? 
+		$this->view->preferences = $widget_settings ?
 			$widget_settings :
 			($page_settings ? $page_settings : []);
 
@@ -137,7 +137,7 @@ class AuthController extends ZendAfi_Controller_Action {
 		$strategy->setDefaultUrl($this->_request->getServer('HTTP_REFERER'));
 		$strategy->processLogin();
 	}
-	
+
 
 	public function ajaxlostpassAction()	{
 		if ($this->_request->isPost()) {
@@ -156,7 +156,7 @@ class AuthController extends ZendAfi_Controller_Action {
 	public function logoutAction()	{
 		ZendAfi_Auth::getInstance()->clearIdentity();
 		$profil = Class_Profil::getCurrentProfil();
-		$this->_redirectToLogoutProfil($profil->getModuleAccueilPreferencesByType('LOGIN')); 
+		$this->_redirectToLogoutProfil($profil->getModuleAccueilPreferencesByType('LOGIN'));
 	}
 
 
@@ -205,7 +205,7 @@ class AuthController extends ZendAfi_Controller_Action {
 																			'required' => true,
 																			'validators' => [new ZendAfi_Validate_MailEquals('mail')]])
 
-			->addDisplayGroup(['login', 'mdp', 'mdp2', 'mail', 'mail2'], 
+			->addDisplayGroup(['login', 'mdp', 'mdp2', 'mail', 'mail2'],
 												'fields',
 												['legend' => ''])
 
@@ -214,7 +214,7 @@ class AuthController extends ZendAfi_Controller_Action {
 																							 'captchaOptions' => array('font' => PATH_FONTS.'/Vera.ttf',
 																																				 'imgDir' => PATH_CAPTCHA,
 																																				 'imgUrl' => URL_CAPTCHA)))
-			->addDisplayGroup(['captcha'], 
+			->addDisplayGroup(['captcha'],
 												'security',
 												['legend' => $this->view->_('Sécurité'),
 												 'required' => true])
@@ -245,18 +245,22 @@ class AuthController extends ZendAfi_Controller_Action {
 			$viewRenderer->renderScript('auth/message.phtml');
 		}
 	}
-	
+
 
 	public function newsletterRegisterAction() {
 		if('' != $this->_request->getParam('emailCheck'))
 			return $this->_redirect('/');
-		
+
 		if(!($id_newsletter = $this->_request->getParam('id')))
 			return $this->_redirect('/');
 
 		if(!($newsletter = Class_Newsletter::find($id_newsletter)))
 			return $this->_redirect('/');
 
+		if(null != Class_Users::getIdentity()) {
+			return $this->_forward('subscribe-newsletter', 'abonne', 'opac', ['id' => $id_newsletter]);
+		}
+
 		$this->view->titre = $this->view->_('Inscription à la newsletter: ') . $newsletter->getTitre();
 		$this->view->error = '';
 		if ($this->_request->isPost() && ('' != ($email = $this->_request->getParam('email')))) {
@@ -267,19 +271,19 @@ class AuthController extends ZendAfi_Controller_Action {
 	}
 
 
-	
+
 	protected function newsletterRegisterSendMail($newsletter, $non_valid_user) {
 		$result = (new Class_Users)->newsletterRegisterSendMail($newsletter, $non_valid_user);
 		if(!$result['success'])
 			return $this->view->error = $result['error'];
-		
+
 		$this->view->titre = $this->view->_('Demande d\'inscription à la newsletter: ').$newsletter->getTitre();
 		$this->view->message = $result['success'];
 		$this->getHelper('ViewRenderer')->renderScript('auth/newsletter-message.phtml');
 	}
-	
 
-	
+
+
 	public function activeuserAction() {
 		if (!$cle = $this->_request->getParam('c'))
 			$this->_redirect('/');
@@ -299,15 +303,15 @@ class AuthController extends ZendAfi_Controller_Action {
 			return $this->_redirect('/');
 
 		$this->view->titre = $this->view->_("Confirmation d'inscription à la newsletter: ").$newsletter->getTitre();
-		($user = Class_UsersNonValid::activateForNewsletterBy($key)) 
-			? $this->newsletterRegisterUser($newsletter, $user) 
+		($user = Class_UsersNonValid::activateForNewsletterBy($key))
+			? $this->newsletterRegisterUser($newsletter, $user)
 			: $this->view->message =  $this->view->_("Inscription à la newsletter invalide.");
 	}
 
-	
+
 	protected function newsletterRegisterUser($newsletter, $user) {
-		
-		Class_NewsletterSubscription::newWith($newsletter, $user) 
+
+		Class_NewsletterSubscription::newWith($newsletter, $user)
 			?	$this->view->message = $this->view->_('Vous avez bien été abonné à la newsletter: ').$newsletter->getTitre().$this->view->_(' avec l\'adresse suivante: ').$user->getMail()
 			: $this->view->message = $this->view->_('Erreur lors de l\inscription à la newsletter.');
 	}
@@ -335,25 +339,25 @@ class AuthController extends ZendAfi_Controller_Action {
 abstract class Auth_Strategy_Abstract {
 	protected $redirect_url = '';
 	protected $disable_redirect = false;
-	
+
 	static public function strategyForController($controller) {
 		if ($controller->isCasRequest() && static::isLogged())
 			return new Auth_Strategy_Cas_Logged($controller);
-		
+
 		if ($controller->isCasRequest() && !static::isLogged())
 			return new Auth_Strategy_Cas_NotLogged($controller);
 
-		if (static::isLogged()) 
+		if (static::isLogged())
 			return new Auth_Strategy_Logged($controller);
 
 		return new Auth_Strategy_NotLogged($controller);
 	}
-	
+
 
 	static protected function isLogged() {
 		return Class_Users::getIdentity();
 	}
-	
+
 	public function disableRedirect() {
 		$this->disable_redirect = true;
 	}
@@ -374,7 +378,7 @@ abstract class Auth_Strategy_Abstract {
 		if ($this->shouldRedirect())
 			$this->controller->redirect($this->redirect_url);
 	}
-	
+
 	public function setDefaultUrl($url) {
 		$this->default_url=$url;
 	}
@@ -442,7 +446,7 @@ class Auth_Strategy_Cas_Abstract extends Auth_Strategy_Abstract{
 			$musicme = new Class_Systeme_ModulesMenu_MusicMe();
 			return $musicme->getDynamiqueUrl();
 		}
-		return false;	
+		return false;
 	}
 }
 
diff --git a/application/modules/opac/views/scripts/auth/newsletter-register.phtml b/application/modules/opac/views/scripts/auth/newsletter-register.phtml
index f638dd860b6..960bea29618 100644
--- a/application/modules/opac/views/scripts/auth/newsletter-register.phtml
+++ b/application/modules/opac/views/scripts/auth/newsletter-register.phtml
@@ -1,6 +1,6 @@
 <?php
 $this->openBoite($this->titre);
-echo $this->renderForm($this->newsletterRegister());
+echo $this->newsletterRegister();
 echo $this->error ? $this->renderError($this->error) : '';
 echo $this->tagAnchor($this->url(['controller' => 'auth',
 																	'action' => 'ajax-login']),
diff --git a/library/Class/Users.php b/library/Class/Users.php
index 0bd19e4f27b..64f70923c82 100644
--- a/library/Class/Users.php
+++ b/library/Class/Users.php
@@ -955,7 +955,6 @@ class Class_Users extends Storm_Model_Abstract {
 
 
 	public function newsletterRegisterSendMail($newsletter, $non_valid_user) {
-		xdebug_break();
 		$ret = ['error' => '', 'success' => ''];
 		$message_mail = [];
 		$message_mail[] = $this->_("Bonjour,");
diff --git a/library/ZendAfi/Form/NewsletterRegister.php b/library/ZendAfi/Form/NewsletterRegister.php
index 46bfd81dafc..354044de128 100644
--- a/library/ZendAfi/Form/NewsletterRegister.php
+++ b/library/ZendAfi/Form/NewsletterRegister.php
@@ -16,7 +16,7 @@
  *
  * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
  * along with AFI-OPAC 2.0; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA 
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
 
@@ -28,13 +28,14 @@ class ZendAfi_Form_NewsletterRegister extends ZendAfi_Form {
 		parent::init();
 		$this
 			->setAttrib('id', 'newsletter_register')
-			->addElement('text', 'email', [
+			->addElement('email', 'email', [
 				'label' => $this->_('Votre adresse e-mail'),
-				'size' => 75,	
+				'size' => 75,
 				'required' => true,
 				'allowEmpty'=> false])
 			->addElement('text', 'emailCheck', [
-				'data-spambots' => 'negative-captcha']);
+				'data-spambots' => 'negative-captcha'])
+			->addElement('submit', 'submit', ['label' => $this->_('Valider')]);
 	}
 }
 ?>
\ No newline at end of file
diff --git a/tests/application/modules/opac/controllers/AbonneVSmartTest.php b/tests/application/modules/opac/controllers/AbonneVSmartTest.php
index 25e865a03e1..57999abf09e 100644
--- a/tests/application/modules/opac/controllers/AbonneVSmartTest.php
+++ b/tests/application/modules/opac/controllers/AbonneVSmartTest.php
@@ -16,7 +16,7 @@
  *
  * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
  * along with AFI-OPAC 2.0; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA 
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
  */
 
 require_once 'AbstractControllerTestCase.php';
@@ -32,7 +32,7 @@ abstract class AbonneVSmartTestCase extends AbstractControllerTestCase {
 		Class_Notice::beVolatile();
 		Class_PanierNotice::beVolatile();
 		Class_PanierNoticeCatalogue::beVolatile();
-		$this->manon = Class_Users::newInstanceWithId(34, ['pseudo' => 'Marcus', 
+		$this->manon = Class_Users::newInstanceWithId(34, ['pseudo' => 'Marcus',
 																											'login' => 'mlaffont',
 																											'password' => '123',
 																									 'role_level' =>ZendAfi_Acl_AdminControllerRoles::ABONNE_SIGB]);
@@ -62,13 +62,13 @@ abstract class AbonneVSmartTestCase extends AbstractControllerTestCase {
 			->method('getUserInformationsPopupUrl')
 			->will($this->returnValue('http://12.34.56.78/moulins/LoginWebSSo.csp'));
 
-		$this->manon 
+		$this->manon
 			->setPrenom('Manon')
 			->setNom('Laffont')
 			->setMail('mlaffont@gmail.com')
 			->setPseudo('manoune')
 			->setDateDebut(null)
-			->setFicheSIGB(array('type_comm' => Class_IntBib::COM_VSMART, 
+			->setFicheSIGB(array('type_comm' => Class_IntBib::COM_VSMART,
 													 'nom_aff' => 'Marcus',
 													 'fiche' => $emprunteur))
 			->setRole('abonne_sigb')
@@ -94,7 +94,6 @@ abstract class AbonneVSmartTestCase extends AbstractControllerTestCase {
 																																	'notices' => 'MONTESPAN',
 																																	'user' => $this->manon]);
 		$this->panier_romans->save();
-		xdebug_break();
 	}
 }
 
@@ -104,7 +103,7 @@ abstract class AbonneVSmartTestCase extends AbstractControllerTestCase {
 class AbonneVSmartTest extends AbonneVSmartTestCase {
 	public function setUp() {
 		parent::setUp();
-		
+
 		Class_AdminVar::newInstanceWithId('INTERDIRE_MODIF_FICHE_ABONNE', ['valeur' => false]);
 		$this->dispatch('/opac/abonne/fiche/id/34', true);
 	}
@@ -118,21 +117,21 @@ class AbonneVSmartTest extends AbonneVSmartTestCase {
 
 	/** @test */
 	function aDivAbonneFicheShouldContainsVousAvezDeuxPretsEnCoursUnEnRetard() {
-		$this->assertXPathContentContains('//div/a[contains(@href, "abonne/prets")]', 
+		$this->assertXPathContentContains('//div/a[contains(@href, "abonne/prets")]',
 																			'Vous avez 2 prêts en cours (1 en retard)');
 	}
 
 
 	/** @test */
 	function aDivAbonneFicheShouldContainsVousAvezTroisReservationsEnCours() {
-		$this->assertXPathContentContains('//div/a[contains(@href, "abonne/reservations")]', 
+		$this->assertXPathContentContains('//div/a[contains(@href, "abonne/reservations")]',
 																			'Vous avez 3 réservations en cours');
 	}
 
 
 	/** @test */
 	function aDivAbonneFicheShouldContainsVousAvezDeuxPaniersDeNotice() {
-		$this->assertXPathContentContains('//div/a[contains(@href, "panier")]', 
+		$this->assertXPathContentContains('//div/a[contains(@href, "panier")]',
 																			'Vous avez 2 paniers',$this->_response->getBody());
 	}
 
diff --git a/tests/application/modules/opac/controllers/AuthControllerTest.php b/tests/application/modules/opac/controllers/AuthControllerTest.php
index 7a8b7687598..b1b365b7d39 100644
--- a/tests/application/modules/opac/controllers/AuthControllerTest.php
+++ b/tests/application/modules/opac/controllers/AuthControllerTest.php
@@ -1546,7 +1546,7 @@ class AuthControllerNobodyLoggedAndRegisterNewsletterTest extends AuthController
 
 	/** @test */
 	public function titleShouldBeAsExpected() {
-		$this->assertXPathContentContains('//div[@class="titre"]//h1', 'Inscription à la newsletter: Daily News', $this->_response->getBody());
+		$this->assertXPathContentContains('//div[@class="titre"]//h1', 'Inscription à la newsletter: Daily News');
 	}
 
 
@@ -1558,7 +1558,7 @@ class AuthControllerNobodyLoggedAndRegisterNewsletterTest extends AuthController
 
 	/** @test */
 	public function mailInputShouldBePresent() {
-		$this->assertXPath('//form//input[@name="email"]');
+		$this->assertXPath('//form//input[@name="email"][@type="email"]');
 	}
 
 
@@ -1566,6 +1566,12 @@ class AuthControllerNobodyLoggedAndRegisterNewsletterTest extends AuthController
 	public function negativeCaptchaShouldBePresent() {
 		$this->assertXPath('//form//input[@name="emailCheck"][@data-spambots="negative-captcha"]');
 	}
+
+
+	/** @test */
+	public function submitButtonShouldBePresent() {
+		$this->assertXPath('//form//input[@type="submit"][@value="Valider"]');
+	}
 }
 
 
@@ -1802,4 +1808,42 @@ class AuthControllerNewsletterActiveUserTest extends AuthControllerNoBodyLoggedT
 		$this->assertXPathContentContains('//p', "Vous avez bien été abonné à la newsletter: News of the month avec l'adresse suivante: future@i.am");
 	}
 }
+
+
+
+class AuthControllerTomLoggedRegisterNewsletterTestCase extends AbstractControllerTestCase {
+	public function setUp() {
+		parent::setUp();
+	  $_SERVER['HTTP_REFERER'] = '/';
+		Class_NewsletterSubscription::beVolatile();
+		$this->fixture('Class_Newsletter',
+									 ['id' => 5,
+										'titre' => 'Daily News']);
+
+		ZendAfi_Auth::getInstance()
+			->logUser($this->fixture('Class_Users',
+															 ['id' => 156,
+																'login' => 'tomato',
+																'password' => 'pwd']));
+		$this->dispatch('auth/newsletter-register/id/5', true);
+	}
+
+
+	/** @test */
+	public function dispatchShouldRedirectToIndex() {
+		$this->assertRedirectTo('/');
+	}
+
+
+	/** @test */
+	public function flashMessengerShouldBeReadyWithExpectedMessage() {
+		$this->assertFlashMessengerEquals(['Vous êtes inscrit à la liste de diffusion: Daily News']);
+	}
+
+
+	/** @test */
+	public function tomatoShouldBeInDailyNewsSubscribers() {
+		$this->assertEquals('tomato' , Class_NewsletterSubscription::find(1)->getUser()->getLogin());
+	}
+}
 ?>
\ No newline at end of file
-- 
GitLab