AbonneController.php 30.4 KB
Newer Older
llaffont's avatar
llaffont committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
 * AFI-OPAC 2.0 is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
 * AFI-OPAC 2.0 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 AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * 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 
 */
21
class AbonneController extends ZendAfi_Controller_Action {
22 23
	use Trait_Translator;

24
	protected $_user = null;								// Le user connecté
llaffont's avatar
llaffont committed
25

26
	public function init()	{
27
		parent::init();
28

29
		if ('authenticate' == $this->getRequest()->getActionName())
llaffont's avatar
llaffont committed
30
				return;
31 32

		$this->_user = Class_Users::getLoader()->getIdentity();
33
		
34
		$this->clearEmprunteurCache();
35 36

		$this->view->getHelper('PageContext')->setContextHelper('Abonne_Resume', [$this->_user]);
37 38 39 40 41
	}


	protected function clearEmprunteurCache() {
		if (in_array($this->getRequest()->getActionName(), array('prets', 'reservations', 'fiche')))
llaffont's avatar
llaffont committed
42
			Class_WebService_SIGB_EmprunteurCache::newInstance()->remove($this->_user);
llaffont's avatar
llaffont committed
43 44 45 46 47 48 49 50 51 52 53
	}


	public function indexAction() {
		$this->_forward('fiche');
	}


	public function formationsAction() {
		$this->sessions_inscrit = array();
		$this->view->formations_by_year = Class_Formation::indexByYear(Class_Formation::getLoader()->findAll());
llaffont's avatar
llaffont committed
54
		$this->view->user = $this->_user;
llaffont's avatar
llaffont committed
55 56 57
	}


58
	public function inscrireSessionAction() {
llaffont's avatar
llaffont committed
59 60
		if (($session = Class_SessionFormation::getLoader()->find((int)$this->_getParam('id'))) && 
				!$session->isInscriptionClosed()) {
llaffont's avatar
llaffont committed
61
			$session->addStagiaire($this->_user);
llaffont's avatar
llaffont committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

			if (!$session->save())
				$this->_helper->notify(implode('<br/>', $session->getErrors()));
			else
				$this->_helper->notify(sprintf('Vous êtes inscrit à la session du %s de la formation %s',
																			 $this->view->humanDate($session->getDateDebut(), 'd MMMM YYYY'),
																			 $session->getLibelleFormation()));
		} else {
			$this->_helper->notify('L\'inscription à cette session est fermée');
		}
		
		$this->_redirect('/abonne/formations');
	}


77
	public function desinscrireSessionAction() {
llaffont's avatar
llaffont committed
78 79 80 81 82 83
		if (!$session = Class_SessionFormation::getLoader()->find((int)$this->_getParam('id'))) {
			$this->_helper->notify('Session non trouvée');
			$this->_redirect('/abonne/formations');
			return;
		}

llaffont's avatar
llaffont committed
84 85
		$this->_user->removeSessionFormation($session);
		if ($this->_user->save()) {
llaffont's avatar
llaffont committed
86 87 88 89 90 91 92 93 94
			$this->_helper->notify(sprintf('Vous n\'êtes plus inscrit à la session du %s de la formation %s',
																		 $this->view->humanDate($session->getDateDebut(), 'd MMMM YYYY'),
																		 $session->getLibelleFormation()));
		};

		$this->_redirect('/abonne/formations');
	}


95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
	public function subscribeNewsletterAction() {
		$this->_stayOnPage();
		
		if (!$newsletter = Class_Newsletter::find((int)$this->_getParam('id'))) {
			$this->_helper->notify('Newsletter non trouvée');
			return;
		}

		
		$this->_user->addNewsletter($newsletter);

		if ($this->_user->save()) {
			$this->_helper->notify(sprintf('Vous êtes inscrit à la liste de diffusion: %s',
																		 $newsletter->getTitre()));
																		 };
	}


	public function unsubscribeNewsletterAction() {
		$this->_stayOnPage();
		if (!$newsletter = Class_Newsletter::find((int)$this->_getParam('id'))) {
			$this->_helper->notify('Newsletter non trouvée');
			return;
		}

		
		$this->_user->removeNewsletter($newsletter);

		if ($this->_user->save()) {
			$this->_helper->notify(sprintf('Vous êtes désinscrit de la liste de diffusion: %s',
																		 $newsletter->getTitre()));
																		 };
	}



131
	public function detailSessionAction() {
llaffont's avatar
llaffont committed
132 133 134 135 136 137
		if (!$session = Class_SessionFormation::getLoader()->find((int)$this->_getParam('id')))
			$this->_redirect('/abonne/formations');
		$this->view->retour_action  = $this->_getParam('retour', 'formations');
		$this->view->session = $session;
	}

138

llaffont's avatar
llaffont committed
139
	public function viewavisAction(){
140 141 142 143 144 145
		$this->_forward('viewauteur', 'blog', 'opac', ['id' => $this->_user->getId()]);
	}


	public function delavisnoticeAction(){
		$this->_forward('delavisnotice', 'blog', 'opac', ['id' => $this->_getParam('id'),
146
																											'redirect' =>'abonne/viewavis/id/'.$this->_user->getId(),
147
																											'js_redirect' => $this->_getParam('expressionRecherche')? true: false]);
llaffont's avatar
llaffont committed
148
	}
149
		
llaffont's avatar
llaffont committed
150

151
	private function handleAvis($readSourceMethod, $writeAvisMethod) {
llaffont's avatar
llaffont committed
152 153 154 155 156
		$cls_user= new Class_Users();

		$avis = new Class_Avis();

		// Validation du formulaire
157
		if ($this->_request->isPost()) {
llaffont's avatar
llaffont committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
			// Bornage du texte
			$longueur_min = Class_AdminVar::get("AVIS_MIN_SAISIE");
			$longueur_max = Class_AdminVar::get("AVIS_MAX_SAISIE");
			if(!$longueur_min) $longueur_min=10;
			if(!$longueur_max) $longueur_max=250;


			$filter = new Zend_Filter_StripTags();
			$avisSignature = trim($filter->filter($this->_request->getPost('avisSignature')));
			$avisEntete = trim($filter->filter($this->_request->getPost('avisEntete')));
			$avisTexte = trim($filter->filter($this->_request->getPost('avisTexte')));
			$avisNote = trim($filter->filter($this->_request->getPost('avisNote')));
			$id = trim($filter->filter($this->_request->getPost('id')));

			if ($avisEntete != '' and (strlen($avisTexte)>= $longueur_min and strlen($avisTexte)<= $longueur_max ) and $avisSignature != '')
			{
				$avis->$writeAvisMethod($this->_user->ID_USER,$this->_user->ROLE_LEVEL,$id,$avisNote,$avisEntete,$avisTexte);
				$cls_user->updatePseudo($this->_user, $avisSignature);

				$this->_renderRefreshOnglet();
			}
			else
			{
				if(strlen($avisTexte)< $longueur_min or strlen($avisTexte) > $longueur_max)
182
					$this->view->message = $this->_("L'avis doit avoir une longueur comprise entre %d et %d caractères", $longueur_min, $longueur_max);
llaffont's avatar
llaffont committed
183
				else
184
					$this->view->message = $this->_('Il faut compléter tous les champs.');
llaffont's avatar
llaffont committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
				$this->view->avisSignature = $avisSignature;
				$this->view->avisEntete = $avisEntete;
				$this->view->avisTexte = $avisTexte;
				$this->view->avisNote = $avisNote;
				$this->view->id = $id;

				$viewRenderer = $this->getHelper('ViewRenderer');
				$viewRenderer->setLayoutScript('subModal.phtml');
			}
		}
		// Saisie du formulaire
		else
		{
			$id = $this->_request->getParam('id', 0);
			$this->view->message = '';
			$this->view->id = $id;
			$this->view->avisSignature = $cls_user->getNomAff($this->_user->ID_USER);
			$data = $avis->$readSourceMethod($this->_user->ID_USER, $id);

			$this->view->avisEntete = $data[0]["ENTETE"];
			$this->view->avisTexte = $data[0]["AVIS"];
			if(!$data[0]["NOTE"]) $data[0]["NOTE"]="0";
			$this->view->avisNote = $data[0]["NOTE"];
			if($this->view->avisEntete) $this->view->mode_modif=true;
			else $this->view->mode_modif=false;

			$viewRenderer = $this->getHelper('ViewRenderer');
			$viewRenderer->setLayoutScript('subModal.phtml');
		}
	}


	protected function _renderRefreshOnglet() {
		$this->getResponse()->setHeader('Content-Type', 'text/html;charset=utf-8');
219
		$js = 'location.reload()';
llaffont's avatar
llaffont committed
220
		if (array_key_exists('onglets', $_SESSION))
221 222
			$js = "refreshOnglet('" . $_SESSION["onglets"]["avis"] . "')";
		$this->getResponse()->setBody("<script>window.top.hidePopWin(false);window.top." . $js. ";</script>");
llaffont's avatar
llaffont committed
223 224 225 226 227
		$viewRenderer = $this->getHelper('ViewRenderer');
		$viewRenderer->setNoRender();
	}


228
	public function avisAction()	{
llaffont's avatar
llaffont committed
229 230 231
		$id_notice = $this->_request->getParam('id_notice', 0);

		$notice = Class_Notice::getLoader()->find($id_notice);
llaffont's avatar
llaffont committed
232
		$avis = $this->_user->getFirstAvisByIdNotice($id_notice);
llaffont's avatar
llaffont committed
233 234 235 236

		if ($this->_request->isPost()) {
			if ($avis == null)
				$avis = new Class_AvisNotice();
237
		
llaffont's avatar
llaffont committed
238 239 240 241
			$avis
				->setEntete($this->_request->getParam('avisEntete'))
				->setAvis($this->_request->getParam('avisTexte'))
				->setNote($this->_request->getParam('avisNote'))
llaffont's avatar
llaffont committed
242
				->setUser($this->_user)
llaffont's avatar
llaffont committed
243 244 245 246 247
				->setClefOeuvre($notice->getClefOeuvre())
				->setStatut(0);


			if ($avis->save()) {
llaffont's avatar
llaffont committed
248
				$this->_user
llaffont's avatar
llaffont committed
249 250
					->setPseudo($this->_request->getParam('avisSignature'))
					->save();
251 252
				$this->renderPopupResult('', '<script>window.location.reload()</script>');
				return;
llaffont's avatar
llaffont committed
253 254 255 256 257 258 259 260 261 262 263 264
			}

			$this->view->message = implode('.', $avis->getErrors());
		}


		if ($avis != null) {
			$this->view->id = $avis->getId();
			$this->view->avisEntete = $avis->getEntete();
			$this->view->avisTexte = $avis->getAvis();
			$this->view->avisNote = $avis->getNote();
		}
llaffont's avatar
llaffont committed
265
		$this->view->avisSignature = $this->_user->getNomAff();
llaffont's avatar
llaffont committed
266
		$this->view->id_notice = $id_notice;
267 268 269

		$this->renderPopupResult($notice->getTitrePrincipal(),
														 $this->view->render('abonne/avis.phtml'));
llaffont's avatar
llaffont committed
270 271 272
	}


273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
	public function editaviscmsAction () {
		$user = Class_Users::getIdentity();
		if (!$user->isBibliothecaire()
				|| (!$avis = Class_Avis::find((int)$this->_getParam('id')))) {
			$this->_javascriptRedirectToReferrer();
			return;
		}

		$this->manageAvisEditWith(
			$avis, 
			function($form) use ($avis) {
				$avis
					->setAvis($form->avis->getValue())
					->setEntete($form->entete->getValue());				
			});
	}


291 292 293 294 295 296 297 298
	public function editavisnoticeAction() {
		$user = Class_Users::getIdentity();
		if (!$user->isBibliothecaire()
				|| (!$avis = Class_AvisNotice::find((int)$this->_getParam('id')))) {
			$this->_javascriptRedirectToReferrer();
			return;
		}

299 300 301 302 303 304 305 306 307 308 309 310 311
		$this->manageAvisEditWith(
			$avis, 
			function($form) use ($avis) {
				$avis
					->setAvis($form->avis->getValue())
					->setEntete($form->entete->getValue());
				if ($record = $form->url->getRecord())
					$avis->setClefOeuvre($record->getClefOeuvre());
			});
	}


	protected function manageAvisEditWith($avis, $set_closure) {
312 313 314 315 316 317
		$form = ZendAfi_Form_Admin_EditAvis::newWith($avis, '');
		$form->setAttrib('action', $this->view->url());
		$form->addElement('submit', 'edit-avis-submit', ['label' => 'Valider']);

		if ($this->_request->isPost()
				&& $form->isValid($this->_request->getPost())) {
318
			$set_closure($form);
319 320 321 322 323 324
			if ($avis->save()) {
				$this->_javascriptRedirectToReferrer();
				return;
			}
			$form->addModelErrors($avis);
		}
325

326
		$this->view->form = $form;
327 328 329 330 331
		$this->renderPopupResult($this->view->_('Modifier l\'avis "%s"', $avis->getEntete()),
														 $this->view->render('abonne/editavisnotice.phtml'));
	}


332
	public function cmsavisAction()	{
llaffont's avatar
llaffont committed
333 334 335 336
		$this->handleAvis('getCmsAvisById', 'ecrireCmsAvis');
	}


337 338
	public function tagnoticeAction() {
		if ($this->_request->isPost()) {
llaffont's avatar
llaffont committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
			$filter = new Zend_Filter_StripTags();
			$abonneTag1 = trim($filter->filter($this->_request->getPost('abonneTag1')));
			$abonneTag2 = trim($filter->filter($this->_request->getPost('abonneTag2')));
			$abonneTag3 = trim($filter->filter($this->_request->getPost('abonneTag3')));
			$id = trim($filter->filter($this->_request->getPost('id')));

			if ($abonneTag1 == '' && $abonneTag2 == '' && $abonneTag3 == '')
			{
				$this->getResponse()->setHeader('Content-Type', 'text/html;charset=utf-8');
				$this->getResponse()->setBody("<script>window.top.hidePopWin(false);</script>");

				$viewRenderer = $this->getHelper('ViewRenderer');
				$viewRenderer->setNoRender();
			}
			else
			{
				$tag= new Class_TagNotice();
				$tag->creer_tag($abonneTag1,$id);
				$tag->creer_tag($abonneTag2,$id);
				$tag->creer_tag($abonneTag3,$id);

				$this->getResponse()->setHeader('Content-Type', 'text/html;charset=utf-8');
				$this->getResponse()->setBody("<script>window.top.hidePopWin(false);window.top.refreshOnglet('".$_SESSION["onglets"]["tags"]."');</script>");

				$viewRenderer = $this->getHelper('ViewRenderer');
				$viewRenderer->setNoRender();
			}
		}
		else
		{
			$this->view->id = $this->_request->getParam('id_notice', 0);
			$viewRenderer = $this->getHelper('ViewRenderer');
			$viewRenderer->setLayoutScript('subModal.phtml');
		}
	}

375 376

	public function ficheAction() {
llaffont's avatar
llaffont committed
377
		$fiche_sigb = $this->_user->getFicheSigb();
llaffont's avatar
llaffont committed
378

379
		$this->view->error = isset($fiche_sigb['erreur']) ? $fiche_sigb["erreur"] : '';
llaffont's avatar
llaffont committed
380
		$this->view->user = $this->_user;
381
		$this->view->interdiction_modif = Class_AdminVar::get('INTERDIRE_MODIF_FICHE_ABONNE');
llaffont's avatar
llaffont committed
382 383
	}

384 385

	public function pretsAction()	{
llaffont's avatar
llaffont committed
386
		$this->view->fiche = $this->_user->getFicheSigb();
387
		$this->view->user = $this->_user;
llaffont's avatar
llaffont committed
388
		Class_ScriptLoader::getInstance()->loadTableSorter();
llaffont's avatar
llaffont committed
389 390 391
	}


392
	public function prolongerpretAction() {
llaffont's avatar
llaffont committed
393 394 395
		$id_pret = $this->_request->getParam('id_pret');
		$cls_comm = new Class_CommSigb();

llaffont's avatar
llaffont committed
396
		$result = $cls_comm->prolongerPret($this->_user, $id_pret);
llaffont's avatar
llaffont committed
397

llaffont's avatar
llaffont committed
398
		$this->view->fiche = $this->_user->getFicheSigb();
llaffont's avatar
llaffont committed
399 400 401
		$this->_helper->notify($result['statut'] == 1 
													 ? $this->_('Prêt prolongé')
													 : $result['erreur']);
llaffont's avatar
llaffont committed
402

llaffont's avatar
llaffont committed
403
		$this->_redirect('/opac/abonne/prets');
llaffont's avatar
llaffont committed
404 405
	}

406 407

	public function reservationsAction()	{
llaffont's avatar
llaffont committed
408 409 410 411 412 413
		// Mode Suppression
		if (null !== ($delete = $this->_getParam('id_delete'))) {
			$cls_comm = new Class_CommSigb();
			$statut_suppr = $cls_comm->supprimerReservation($this->_user, $delete);
		}

llaffont's avatar
llaffont committed
414
		$this->view->fiche = $this->_user->getFicheSigb();
415
		$this->view->user = $this->_user;
llaffont's avatar
llaffont committed
416
		Class_ScriptLoader::getInstance()->loadTableSorter();
llaffont's avatar
llaffont committed
417 418 419 420 421
	}



	protected function _userForm($user) {
422 423
		$fields_to_show = Class_AdminVar::getChampsFicheUtilisateur();

llaffont's avatar
llaffont committed
424 425
		$form = new Zend_Form;
		$form
426 427
			->setAction($this->view->url(['action' => 'edit',
																		'id' => $user->getId()]))
llaffont's avatar
llaffont committed
428 429
			->setMethod('post')
			->setAttrib('id', 'user')
430
			->setAttrib('class', 'zend_form')
llaffont's avatar
llaffont committed
431 432
			->setAttrib('autocomplete', 'off');

433 434 435
		$textfields = array('nom' => $this->_('Nom'),
												'prenom' => $this->_('Prénom'),
												'pseudo' => $this->_('Pseudo'),
436 437 438 439 440
												'adresse' => $this->_('Adresse'),
												'code_postal' => $this->_('Code postal'),
												'ville' => $this->_('Ville'),
												'mail' => $this->_('E-Mail'),
												'telephone' => $this->_('Téléphone'));
llaffont's avatar
llaffont committed
441 442

		foreach($textfields	as $field => $label) {
443 444 445
			if (!in_array($field, $fields_to_show))
				continue;

llaffont's avatar
llaffont committed
446 447 448 449 450 451 452
			$element = $form
				->createElement('text', $field)
				->setLabel($label)
				->setAttrib('size', 30);
			$form->addElement($element);
		}

453
		if ($mail_element = $form->getElement('mail'))
454
			$mail_element->addValidator(new ZendAfi_Validate_EmailAddress());
llaffont's avatar
llaffont committed
455

456 457 458 459
		if ($phone_element = $form->getElement('telephone'))
			$phone_element->addValidator(new ZendAfi_Validate_PhoneNumber());


460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
		if (in_array('password', $fields_to_show)) {
			$fields_to_show []= 'confirm_password';
			$new_password = new Zend_Form_Element_Password('password');
			$new_password
				->setLabel($this->_('Nouveau mot de passe'))
				->addValidator('Identical',
											 false,
											 array('token' => $this->_request->getParam('confirm_password'),
														 'messages' => array('missingToken' => $this->_('Vous devez confirmer le mot de passe'),
																								 'notSame' => $this->_('Les mots de passe ne correspondent pas'))))
				->addValidator('StringLength', false, array(4,24));

			$confirm_password = new Zend_Form_Element_Password('confirm_password');
			$confirm_password
				->setLabel($this->_('Confirmez le mot de passe'))
				->addValidator('Identical',
											 false,
											 array('token' => $this->_request->getParam('password'),
														 'messages' => array('missingToken' => $this->_('Vous devez saisir un mot de passe'),
																								 'notSame' => $this->_('Les mots de passe ne correspondent pas'))))
				->setValue($user->getPassword());


			$form
				->addElement($new_password)
				->addElement($confirm_password);
		}

		if ($identification_fields = array_intersect(['nom', 'prenom', 'pseudo', 'password', 'confirm_password'],
																								 $fields_to_show))
			$form->addDisplayGroup($identification_fields, 
														 'identification', 
														 ['legend' => 'Identification']);

		if ($coordonnees_fields = array_intersect(['adresse', 'code_postal', 'ville'],
																								$fields_to_show))
			$form->addDisplayGroup($coordonnees_fields, 
														 'coordonnees', 
														 ['legend' => 'Coordonnées']);

500
		if ($contact_fields = array_intersect(['mail', 'telephone'],
501 502 503 504
																					$fields_to_show)) 
			$form->addDisplayGroup($contact_fields, 
														 'contact', 
														 ['legend' => 'Contact']);
llaffont's avatar
llaffont committed
505

506 507 508 509 510 511 512 513 514 515 516 517
		if (in_array('mode_contact', $fields_to_show)) {
			$form->addElement('radio', 
												'mode_contact', 
												['label' => '',
												 'multiOptions' => [Class_Users::MODE_CONTACT_LETTER => $this->_(' par courrier postal'),
																						Class_Users::MODE_CONTACT_MAIL => $this->_(' par E-Mail'),
																						Class_Users::MODE_CONTACT_SMS => $this->_(' par SMS')],
												 'value' => $user->getModeContact()]);
			$form->addDisplayGroup(['mode_contact'], 'mode_de_contact', ['legend' => 'Recevoir mes notificactions de réservation et de rappel']);
		}


llaffont's avatar
llaffont committed
518 519
		/* Abonnements aux newsletters*/
		$subscriptions = new Zend_Form_Element_MultiCheckbox('subscriptions');
520
		$subscriptions->setLabel($this->_("Abonnement aux lettres d'information"));
llaffont's avatar
llaffont committed
521 522 523 524 525 526 527 528 529 530 531 532


		$newsletters = Class_Newsletter::getLoader()->findAll();
		if (count($newsletters)>0) {
			foreach($newsletters as $nl)
				$subscriptions->addMultiOption($nl->getId(), $nl->getTitre());

			$checked_subscriptions = array();
			foreach($user->getNewsletters() as $nl)
				$checked_subscriptions []= $nl->getId();

			$subscriptions->setValue($checked_subscriptions);
533 534 535 536 537
			$form
			  ->addElement($subscriptions)
			  ->addDisplayGroup(['subscriptions'], 
													'newsletters', 
													['legend' => 'Lettres d\'information']); 
llaffont's avatar
llaffont committed
538 539 540 541 542 543 544 545 546 547
		}


		$form
			->populate($user->toArray());

		return $form;
	}


548
	public function editAction() {
llaffont's avatar
llaffont committed
549
		$form = $this->_userForm($this->_user);
llaffont's avatar
llaffont committed
550 551 552 553 554 555 556 557 558 559 560

		if ($this->getRequest()->isPost() && $form->isValid($_POST)) {
			$newsletters = array();

			$newsletters_id = $this->_request->getParam('subscriptions', array());
			foreach($newsletters_id as $nl_id)
				$newsletters []= Class_Newsletter::getLoader()->find($nl_id);

			try {
				$password = $this->_request->getParam('password');
				if (empty($password))
llaffont's avatar
llaffont committed
561
					$password = $this->_user->getPassword();
llaffont's avatar
llaffont committed
562

563 564 565 566 567 568 569
				$this->_user->updateSIGBOnSave();

				$fields_to_save = Class_AdminVar::getChampsFicheUtilisateur();
				$attributes = [];
				foreach($fields_to_save as $field) 
				  $attributes[$field] = $this->_request->getParam($field);

llaffont's avatar
llaffont committed
570
				$this->_user
571 572 573 574 575 576 577
						->updateAttributes($attributes)
						->setPassword($password)
						->setNewsletters($newsletters);

				if ($this->_user->save()) {
					$this->_redirect('/abonne/fiche');
				}
llaffont's avatar
llaffont committed
578

579
				$form->addDecorator('Errors');
580 581
				foreach($this->_user->getErrors() as $error)
				  $form->addError($error);
llaffont's avatar
llaffont committed
582 583 584 585 586 587 588 589 590
			} catch(Exception $e) {
				$form->addError($e->getMessage());
				$form->addDecorator('Errors');
			}
		}

		$this->view->form = $form;
		$this->view->help = nl2br(Class_AdminVar::get('AIDE_FICHE_ABONNE'));
	}
591 592


593
	public function authenticateAction() {
llaffont's avatar
llaffont committed
594 595
		$this->getHelper('ViewRenderer')->setNoRender();
		
596 597 598 599
		$response = new StdClass();
		$response->auth = 0;
		$response->until = '';

600
		$request = Class_Multimedia_AuthenticateRequest::newWithRequest($this->_request);		
601
		if ($user = $request->getUser()) {
602 603
			foreach (['id', 'login', 'password', 'nom', 
								'prenom', 'date_debut', 'date_fin'] as $attribute)
604 605 606 607
				$response->$attribute = $user->$attribute;
			$response->groupes = $user->getUserGroupsLabels();
			$response->date_naissance = $user->getDateNaissanceIso8601();
		}
608

609
		if (!$request->isValid()) {
610
			$response->error = $request->getError();
611 612 613
			$this->_response->setBody(json_encode($response));
			return;
		}
614

615 616
		$response->auth = 1;
		$response->until = date('c', $request->getCurrentHoldEnd());
617

llaffont's avatar
llaffont committed
618 619
		$this->_response->setBody(json_encode($response));
	}
620 621 622


	public function multimediaHoldLocationAction() {
623
		$bean = Class_Multimedia_ReservationBean::newInSession();
624 625 626 627

		if (null != $this->_getParam('location')) {
			$bean->location = $this->_getParam('location');
			$this->_redirect('/abonne/multimedia-hold-day');
pbarroca's avatar
pbarroca committed
628
			return;
629 630
		}

631
		$this->view->locations = array_filter(Class_Multimedia_Location::findAllBy(['order' => 'libelle']),
632 633
																					function($location) {
																							return $location->numberOfOuvertures() > 0;});
634
		$this->view->timelineActions = $this->_getTimelineActions('location');
635 636 637 638
	}


	public function multimediaHoldDayAction() {
639
		$bean = Class_Multimedia_ReservationBean::current();
640

641
		/* Vérification du quota sur le jour choisi */
642 643 644 645 646 647
		$day = $this->_getParam('day');
		$quotaErrorType = null;
		if (null != $day) {
			$quotaErrorType = $this->_user->getMultimediaQuotaErrorForDay($day);
			switch ($quotaErrorType) {
			  case Class_Multimedia_DeviceHold::QUOTA_NONE:
648
					$this->view->quotaError = $this->_('Vous n\'êtes pas autorisé à effectuer une réservation');
649 650
					break;
			  case Class_Multimedia_DeviceHold::QUOTA_DAY:
651
					$this->view->quotaError = $this->_('Quota déjà atteint ce jour, choisissez un autre jour.');
652 653
					break;
			  case Class_Multimedia_DeviceHold::QUOTA_WEEK:
654
					$this->view->quotaError = $this->_('Quota déjà atteint cette semaine, choisissez une autre semaine.');
655 656
					break;
			  case Class_Multimedia_DeviceHold::QUOTA_MONTH:
657
					$this->view->quotaError = $this->_('Quota déjà atteint ce mois, choisissez un autre mois.');
658 659 660 661
					break;
			}
		}
				
662
		/* Choix valide, passage à l'écran suivant */
663 664
		if (null != $day && null == $quotaErrorType) {
			$bean->day = $day;
665 666 667
			$this->_redirect('/abonne/multimedia-hold-hours');
			return;
		}
668 669 670 671 672 673
		
		$this->getRequest()->setParam('day', 0);
		if (!$bean->isCurrentStateValidForRequest($this->getRequest())) {
			$this->_redirect('/abonne/'.$bean->currentState());
			return;
		}
674

675
		/* Rendu du calendrier avec les jours sélectionnables */
676
		$location = $bean->getLocation();
677 678
		$this->view->minDate = $location->getMinDate();
		$this->view->maxDate = $location->getMaxDate();
679 680 681 682 683 684 685
		$holidayStamps = array_map(
			function($item) {return $item * 1000;},
			array_merge(
				Class_Date_Holiday::getTimestampsForYear(),
				Class_Date_Holiday::getTimestampsForYear(date('Y') + 1)
			)
		);
686 687 688

		$js_opened_days = implode(',', array_map(
																						 function ($day) { return '"'.$day.'"'; }, 
689
																						 $location->getHoldableDays()));
690 691


692 693 694 695 696 697 698 699 700 701 702 703
		$beforeShowDay = 'var result = [true, \'\'];
		var stamps = [' . implode(', ', $holidayStamps) . '];
		$.each(stamps, function(i, stamp) {
			var holiday = new Date();
			holiday.setTime(stamp);
			if (date.getDate() == holiday.getDate()
				&& date.getMonth() == holiday.getMonth()
				&& date.getFullYear() == holiday.getFullYear()) {
			  result[0] = false;
			  return result;
			}
		});
704 705
		if (-1 == $.inArray($.datepicker.formatDate(\'yy-mm-dd\', date), 
                        [' . $js_opened_days . '])) {
706 707 708
			result[0] = false;
		}
	  return result;';
709 710

		$this->view->beforeShowDay = $beforeShowDay;
711
		$this->view->timelineActions = $this->_getTimelineActions('day');
712 713 714 715
	}


	public function multimediaHoldHoursAction() {
716
		if (!$bean = $this->_getDeviceHoldBean())
717 718
			return;

719
		$location = $bean->getLocation();
720
		if ($this->_getParam('time') && $this->_getParam('duration')) {
721 722 723 724
			$holdLoader = Class_Multimedia_DeviceHold::getLoader();
			$start = $holdLoader->getTimeFromDayAndTime($bean->day, $this->_getParam('time'));
			$end = $holdLoader->getTimeFromStartAndDuration($start, $this->_getParam('duration'));

725
			if (0 < $holdLoader->countBetweenTimesForUser($start, $end, $this->_user)) {
726
				$this->view->error = $this->_('Vous avez déjà une réservation dans ce créneau horaire');
727 728 729 730
			}

			if ($start < $location->getMinTimeForDate($bean->day)
				|| $end > $location->getMaxTimeForDate($bean->day)) {
731
				$this->view->error = $this->_('Ce créneau n\'est pas dans les heures d\'ouverture.');
732 733 734
			}

			if (!$this->view->error) {
735 736
				$bean->time = $this->_getParam('time');
				$bean->duration = (int)$this->_getParam('duration');
737
				$this->_redirect('/abonne/multimedia-hold-group');
738 739
				return;
			}
740 741
		}
		
742
		$this->view->timelineActions = $this->_getTimelineActions('hours');
llaffont's avatar
llaffont committed
743 744 745
		$this->view->form = $this->multimediaHoldHoursForm($bean, $location);
	}

746

llaffont's avatar
llaffont committed
747 748 749 750
	public function multimediaHoldHoursForm($bean, $location) {
		return $this->view
			->newForm(['id' => 'hold-hours'])
			->setMethod('get')
751
			->addElement('select', 'time', ['label' => $this->_('À partir de quelle heure ?'),
llaffont's avatar
llaffont committed
752
																			'multiOptions' => $location->getStartTimesForDate($bean->day)])
753
			->addElement('select', 'duration', ['label' => $this->_('Pour quelle durée ?'),
llaffont's avatar
llaffont committed
754 755
																					'multiOptions' => $location->getDurations()])
			->addDisplayGroup(['time', 'duration'], 'choix', ['legend' => ''])
756
			->addElement('submit', 'submit', ['label' => $this->_('Choisir')]);
757 758 759
	}


760
	public function multimediaHoldGroupAction() {
761
		if (!$bean = $this->_getDeviceHoldBean())
762 763
			return;

764
		$this->view->groups = $bean->getGroups();
765 766 767 768
		$this->view->timelineActions = $this->_getTimelineActions('group');
	}


769
	public function multimediaHoldDeviceAction() {
770
		if (!$bean = $this->_getDeviceHoldBean())
771
			return;
772

773
		$this->view->timelineActions = $this->_getTimelineActions('device');
774 775 776
		$this->view->devices = $bean->getGroup()->getHoldableDevicesForDateTimeAndDuration($bean->day,
																																											 $bean->time,
																																											 $bean->duration);
777
	}
778 779 780


	public function multimediaHoldConfirmAction() {
781
		if (!$bean = $this->_getDeviceHoldBean())
782 783 784 785 786 787 788 789 790 791
			return;

		if ($this->_getParam('validate')) {
			$hold = Class_Multimedia_DeviceHold::getLoader()->newFromBean($bean);
			$hold->save();
			$this->_redirect('/abonne/multimedia-hold-view/id/' . $hold->getId());
			return;
		}

		$this->view->timelineActions = $this->_getTimelineActions('confirm');
792
		$this->view->location = $bean->getLocation()->getLibelleBib();
793 794 795
		$this->view->day = strftime('%d %B %Y', strtotime($bean->day));
		$this->view->time = str_replace(':', 'h', $bean->time);
		$this->view->duration = $bean->duration . 'mn';
796 797

		$device = $bean->getDevice();
798 799 800 801 802
		$this->view->device = $device->getLibelle() . ' - ' . $device->getOs();
	}


	public function multimediaHoldViewAction() {
803
		if (null == ($hold = Class_Multimedia_DeviceHold::find((int)$this->_getParam('id')))) {
804 805 806 807 808 809 810 811
			$this->_redirect('/abonne/fiche');
			return;
		}

		if ($this->_user != $hold->getUser()) {
			$this->_redirect('/abonne/fiche');
			return;
		}
812 813 814 815 816 817

		if ($this->_getParam('delete')) {
			$hold->delete();
			$this->_redirect('/abonne/fiche');
			return;
		}
818
			
819
		$this->view->location = $hold->getLibelleBib();
820 821 822
		$this->view->day = strftime('%d %B %Y', $hold->getStart());
		$this->view->time = strftime('%Hh%M', $hold->getStart());
		$this->view->duration = (($hold->getEnd() - $hold->getStart()) / 60)  . 'mn';
823
		$this->view->device = $hold->getLibelleDevice() . ' - ' . $hold->getOs();
824 825
	}
		
826

827 828 829 830 831
	/**
	 * @param $current string
	 * @return array
	 */
	protected function _getTimelineActions($current) {
832 833 834
		$knownActions = ['location' => $this->_('Lieu'),
										 'day' => $this->_('Jour'),
										 'hours' => $this->_('Horaires'),
835
										 'group' => $this->_('Secteur'),
836 837
										 'device' => $this->_('Poste'),
										 'confirm' => $this->_('Confirmation')];
838 839 840 841 842 843 844 845 846 847 848 849

		$actions = array();
		foreach ($knownActions as $knownAction => $label) {
			$action = $this->_getTimelineActionWithNameAndAction($label, $knownAction);
			if ($current == $knownAction)
				$action[ZendAfi_View_Helper_Timeline::CURRENT] = true;
			$actions[] = $action;
		}
		return $actions;
	}


850
	/** @return array */
851 852 853 854 855 856 857
	protected function _getTimelineActionWithNameAndAction($name, $action) {
		return array(ZendAfi_View_Helper_Timeline::LABEL => $name,
			           ZendAfi_View_Helper_Timeline::CURRENT => false,
			           ZendAfi_View_Helper_Timeline::URL => $this->view->url(array('controller' => 'abonne',
										                                                         'action' => 'multimedia-hold-' . $action),
									                                                     null, true));
	}
858 859 860 861


	/** @return stdClass */
	protected function _getDeviceHoldBean() {
862 863 864 865 866
		$bean = Class_Multimedia_ReservationBean::current();
		if (!$bean->isCurrentStateValidForRequest($this->getRequest())) {
			$this->_redirect('/abonne/'.$bean->currentState());
			return null;
		}
867 868 869

		return $bean;
	}
870 871 872


	public function suggestionAchatAction() {
873 874 875 876
	}


	public function suggestionAchatAddAction() {
llaffont's avatar
llaffont committed
877 878 879 880 881
		if (Class_SuggestionAchat::find($this->_getParam('id'))) {
			$this->_forward('suggestion-achat-ok');
			return;
		}
			
882
		$form = new ZendAfi_Form_SuggestionAchat();
883

llaffont's avatar
llaffont committed
884 885 886 887 888 889
		if ($this->_request->isPost()) {
			$post = $this->_request->getPost();
			unset($post['submit']);
			$suggestion = (new Class_SuggestionAchat())
				->updateAttributes($post)
				->setUserId(Class_Users::currentUserId());
890 891 892

			if ($form->isValid($suggestion)) {
				$suggestion->save();
893 894 895
				try {
					$suggestion->sendMail('noreply@'.$this->_request->getHttpHost());
				} catch (Zend_Mail_Exception $e) {
896
					$this->_helper->notify($this->_('Aucun courriel envoyé, erreur: ').$this->_($e->getMessage()));
897
				}
898
				$this->_redirect('/opac/abonne/suggestion-achat-add/id/'.$suggestion->getId());
899
			}
llaffont's avatar
llaffont committed
900 901
		}

902
		$this->view->form = $form;
903 904 905
	}


906
	public function suggestionAchatOkAction() {}
907 908 909 910 911 912 913 914 915 916 917


	public function webkioskReservationAction() {
		if ($this->_user->isAbonne()) {
			$url = Class_WebkioskLink::forUser($this->_user)->url();
			$this->_redirect($url);
			return;
		}
		$this->_helper->notify('Votre abonnement ne vous permet pas de réserver un poste multimédia');
		$this->_redirect('/abonne/fiche');
	}
918 919 920 921 922 923


	public function getPaniersJsonAction() {
		$this->_helper->viewRenderer->setNoRender();

		$data = [];
924 925 926
		$data[] = $this->_user->getPaniersJson();
		if ($this->_user->canAccessBackend())
			$data[] = (new Class_Catalogue())->getDomainesJson(['removeCheckbox' => true]);
927 928 929 930 931
		$JSON = json_encode($data);
		
		$this->getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');
		$this->getResponse()->setBody($JSON);
	}
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952


	public function loanExportAction() {
		$this->_helper->viewRenderer->setNoRender();

		$datas = [];
		foreach($this->_user->getEmprunts() as $emprunt) {
			if (!$exemplaire = $emprunt->getExemplaireOPAC())
				continue;

			$datas[] = $exemplaire->toUnimarcIso2709();
		}

		$response = $this->_response;
		$response->clearAllHeaders();
		$filename = 'prets_' . $this->_user->getId() . '-' . uniqid() . '.txt';

		$response->setHeader('Content-Type', 'application/octet-stream; name="' . $filename . '"', true);
		$response->setHeader('Content-Disposition', 'attachment; filename="'.$filename.'"', true);
		$response->setBody(implode('', $datas));
	}
953 954
}
?>