AbonneController.php 42.7 KB
Newer Older
llaffont's avatar
llaffont committed
1
<?php
2

llaffont's avatar
llaffont committed
3 4 5
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
Laurent's avatar
Laurent committed
6
 * BOKEH is free software; you can redistribute it and/or modify
llaffont's avatar
llaffont committed
7 8 9 10 11 12
 * 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).
 *
Laurent's avatar
Laurent committed
13
 * BOKEH is distributed in the hope that it will be useful,
llaffont's avatar
llaffont committed
14 15 16 17 18
 * 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
Laurent's avatar
Laurent committed
19
 * along with BOKEH; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
llaffont's avatar
llaffont committed
21
 */
Ghislain Loas's avatar
Ghislain Loas committed
22

23
class AbonneController extends ZendAfi_Controller_Action {
24
  protected $_user = null;                // Le user connecté
llaffont's avatar
llaffont committed
25

26 27 28
  public function init()  {
    parent::init();
    if ('authenticate' == $this->getRequest()->getActionName())
efalcy's avatar
efalcy committed
29
      return;
30

Laurent's avatar
Laurent committed
31
    $this->_user = Class_Users::getIdentity();
32

33
    $this->clearEmprunteurCache();
34

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


39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  public function preDispatch() {
    parent::preDispatch();

    if ($this->_isMultimediaHoldAction()
        && !Class_AdminVar::isMultimediaEnabled()) {
      $this->_helper->notify($this->_('AFI-Multimédia n\'est pas activé'));
      $this->_redirect('/abonne');
      $this->_request->setDispatched();
      return;
    }
  }


  protected function _isMultimediaHoldAction() {
    return 'multimedia' == substr($this->_request->getActionName(), 0, 10);
  }


57
  protected function clearEmprunteurCache() {
58 59
    if (in_array($this->getRequest()->getActionName(), ['prets',
                                                        'reservations',
60 61
                                                        'fiche',
                                                        'loans-history']))
62 63
      Class_WebService_SIGB_EmprunteurCache::newInstance()->remove($this->_user);
  }
llaffont's avatar
llaffont committed
64 65


66 67 68
  public function indexAction() {
    $this->_forward('fiche');
  }
llaffont's avatar
llaffont committed
69 70


71
  public function inscrireSessionAction() {
72
    $this->_redirectToReferer();
Laurent's avatar
Laurent committed
73

74
    if ((!$session = Class_SessionActivity::find((int)$this->_getParam('id')))
Laurent's avatar
Laurent committed
75 76 77 78 79 80 81
        || $session->isInscriptionClosed())
      return $this->_helper->notify($this->_('L\'inscription à cette session est fermée'));

    $session->addStagiaire($this->_user);
    if (!$session->save())
      return $this->_helper->notify(implode('<br/>', $session->getErrors()));

82
    (new Class_Activity_RegistrationMail($session, $this->_user))->send();
Laurent's avatar
Laurent committed
83

84
    $this->_helper->notify($this->_('Vous êtes inscrit à la session du %s de l\'activité %s',
Laurent's avatar
Laurent committed
85
                                    $this->view->humanDate($session->getDateDebut(), 'd MMMM YYYY'),
86
                                    $session->getLibelleActivity()));
87
  }
llaffont's avatar
llaffont committed
88 89


90
  public function desinscrireSessionAction() {
91
    if (!$session = Class_SessionActivity::find((int)$this->_getParam('id'))) {
Laurent's avatar
Laurent committed
92
      $this->_helper->notify($this->_('Session non trouvée'));
93
      $this->_redirectToReferer();
94 95
      return;
    }
llaffont's avatar
llaffont committed
96

97
    $this->_user->removeSessionActivity($session);
98
    if ($this->_user->save()) {
99
      $this->_helper->notify($this->_('Vous n\'êtes plus inscrit à la session du %s de l\'activité %s',
100
                                     $this->view->humanDate($session->getDateDebut(), 'd MMMM YYYY'),
101
                                     $session->getLibelleActivity()));
102

103
      (new Class_Activity_UnregistrationMail($session, $this->_user))->send();
104
    };
llaffont's avatar
llaffont committed
105

106
    $this->_redirectToReferer();
107
  }
llaffont's avatar
llaffont committed
108 109


110 111 112
  public function subscribeNewsletterAction() {
    $this->_stayOnPage();
    if (!$newsletter = Class_Newsletter::find((int)$this->_getParam('id'))) {
Laurent's avatar
Laurent committed
113
      $this->_helper->notify($this->_('Newsletter non trouvée'));
114 115
      return;
    }
116

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

119
    if ($this->_user->save()) {
Laurent's avatar
Laurent committed
120 121
      $this->_helper->notify($this->_('Vous êtes inscrit à la liste de diffusion: %s',
                                      $newsletter->getTitre()));
efalcy's avatar
efalcy committed
122
    };
123
  }
124 125


126 127 128
  public function unsubscribeNewsletterAction() {
    $this->_stayOnPage();
    if (!$newsletter = Class_Newsletter::find((int)$this->_getParam('id'))) {
Laurent's avatar
Laurent committed
129
      $this->_helper->notify($this->_('Newsletter non trouvée'));
130 131
      return;
    }
132

133

134
    $this->_user->unsubscribeNewsletter($newsletter);
135

136
    if ($this->_user->save()) {
Laurent's avatar
Laurent committed
137 138
      $this->_helper->notify($this->_('Vous êtes désinscrit de la liste de diffusion: %s',
                                      $newsletter->getTitre()));
efalcy's avatar
efalcy committed
139
    };
140
  }
141 142 143



llaffont's avatar
llaffont committed
144

145

146 147 148
  public function viewavisAction(){
    $this->_forward('viewauteur', 'blog', 'opac', ['id' => $this->_user->getId()]);
  }
149 150


151 152 153 154 155
  public function delavisnoticeAction(){
    $this->_forward('delavisnotice', 'blog', 'opac', ['id' => $this->_getParam('id'),
                                                      'redirect' =>'abonne/viewavis/id/'.$this->_user->getId(),
                                                      'js_redirect' => $this->_getParam('expressionRecherche')? true: false]);
  }
156

llaffont's avatar
llaffont committed
157

158 159
  public function avisAction()  {
    $id_notice = $this->_request->getParam('id_notice', 0);
llaffont's avatar
llaffont committed
160

161
    $notice = Class_Notice::find($id_notice);
162 163 164 165 166
    $avis = $this->_user->getFirstAvisByIdNotice($id_notice);

    if ($this->_request->isPost()) {
      if ($avis == null)
        $avis = new Class_AvisNotice();
167

168 169 170 171 172
      $avis
        ->setEntete($this->_request->getParam('avisEntete'))
        ->setAvis($this->_request->getParam('avisTexte'))
        ->setNote($this->_request->getParam('avisNote'))
        ->setUser($this->_user)
173
        ->setIdNotice($id_notice)
174
        ->setClefOeuvre($notice->getClefOeuvre())
175
        ->setTypeDoc($notice->getTypeDoc())
176 177 178 179 180 181 182 183 184 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
        ->setStatut(0);


      if ($avis->save()) {
        $this->_user
          ->setPseudo($this->_request->getParam('avisSignature'))
          ->save();
        $this->renderPopupResult('', '<script>window.location.reload()</script>');
        return;
      }

      $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();
    }
    $this->view->avisSignature = $this->_user->getNomAff();
    $this->view->id_notice = $id_notice;

    $this->renderPopupResult($notice->getTitrePrincipal(),
                             $this->view->render('abonne/avis.phtml'));
  }


  public function editaviscmsAction () {
    $user = Class_Users::getIdentity();
    if (!$user->isBibliothecaire()
        || (!$avis = Class_Avis::find((int)$this->_getParam('id')))) {
      $this->_javascriptRedirectToReferrer();
      return;
    }

    $this->manageAvisEditWith(
efalcy's avatar
efalcy committed
214 215 216 217 218 219
                              $avis,
                              function($form) use ($avis) {
                                $avis
                                  ->setAvis($form->avis->getValue())
                                  ->setEntete($form->entete->getValue());
                              });
220 221 222 223 224 225 226 227 228 229 230 231
  }


  public function editavisnoticeAction() {
    $user = Class_Users::getIdentity();
    if (!$user->isBibliothecaire()
        || (!$avis = Class_AvisNotice::find((int)$this->_getParam('id')))) {
      $this->_javascriptRedirectToReferrer();
      return;
    }

    $this->manageAvisEditWith(
efalcy's avatar
efalcy committed
232 233 234 235 236 237 238 239 240 241
                              $avis,
                              function($form) use ($avis) {
                                $avis
                                  ->setAvis($form->avis->getValue())
                                  ->setEntete($form->entete->getValue());
                                if ($record = $form->url->getRecord()) {
                                  $avis->setClefOeuvre($record->getClefOeuvre());
                                  $avis->setTypeDoc($record->getTypeDoc());
                                }
                              });
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
  }


  protected function manageAvisEditWith($avis, $set_closure) {
    $form = ZendAfi_Form_Admin_EditAvis::newWith($avis->toArray())
      ->addPermalinkFor($avis)
      ->addBackUrl('');

    $form->setAttrib('action', $this->view->url());
    $form->addElement('submit', 'edit-avis-submit', ['label' => 'Valider']);

    if ($this->_request->isPost()
        && $form->isValid($this->_request->getPost())) {
      $set_closure($form);
      if ($avis->save()) {
        $this->_javascriptRedirectToReferrer();
        return;
      }
      $form->addModelErrors($avis);
    }

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


  public function cmsavisAction() {
    $this->view->titre = $this->_('Votre avis');

    // Validation du formulaire
    if ($this->_request->isPost()) {
      // 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->getParam('id')));

      if ($avisEntete != '' and (strlen($avisTexte)>= $longueur_min and strlen($avisTexte)<= $longueur_max ) and $avisSignature != '')  {
        Class_Avis::ecrireCmsAvis($this->_user->ID_USER,
                                  $this->_user->ROLE_LEVEL,
                                  $id,
                                  $avisNote,
                                  $avisEntete,
                                  $avisTexte);
        $this->_user
          ->setPseudo($avisSignature)
          ->save();

        $this->_redirect('/opac/cms/articleview/id/'.$id);
        return;
      }
      else
efalcy's avatar
efalcy committed
303 304 305 306 307 308 309 310 311 312 313
        {
          if(strlen($avisTexte)< $longueur_min or strlen($avisTexte) > $longueur_max)
            $this->view->message = $this->_("L'avis doit avoir une longueur comprise entre %d et %d caractères", $longueur_min, $longueur_max);
          else
            $this->view->message = $this->_('Il faut compléter tous les champs.');
          $this->view->avisSignature = $avisSignature;
          $this->view->avisEntete = $avisEntete;
          $this->view->avisTexte = $avisTexte;
          $this->view->avisNote = $avisNote;
          $this->view->id = $id;
        }
314 315 316
    }
    // Saisie du formulaire
    else
efalcy's avatar
efalcy committed
317 318 319 320 321
      {
        $id = $this->_request->getParam('id', 0);
        $this->view->message = '';
        $this->view->id = $id;
        $this->view->avisSignature = $this->_user->getNomAff();
322

efalcy's avatar
efalcy committed
323 324 325 326
        if (!$avis = Class_Avis::findFirstBy(['id_user' => $this->_user->getId(),
                                              'id_cms' => $id]))
          $avis = Class_Avis::newInstance(['id_user' => $this->_user->getId(),
                                           'id_cms' => $id]);
327

efalcy's avatar
efalcy committed
328 329 330 331
        $this->view->avisEntete = $avis->getEntete();
        $this->view->avisTexte = $avis->getAvis();
        $this->view->avisNote = $avis->getNote();
      }
332 333 334 335
  }


  public function tagnoticeAction() {
336 337
    if (!$this->_request->isPost()) {
      $this->view->titre = $this->_('Proposer des tags pour cette notice');
338 339 340 341
      $this->view->id = $this->_request->getParam('id_notice', 0);
      $viewRenderer = $this->getHelper('ViewRenderer');
      $viewRenderer->setLayoutScript('subModal.phtml');

342
      return;
343 344
    }

345 346 347 348 349 350 351 352 353
    $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>");
354 355

      $viewRenderer = $this->getHelper('ViewRenderer');
356 357
      $viewRenderer->setNoRender();
      return;
358
    }
359 360 361

    Class_TagNotice::multiForRecord([$abonneTag1, $abonneTag2, $abonneTag3], $id);
    $this->_javascriptRedirectToReferrer();
362 363 364 365 366 367 368 369 370 371 372 373 374
  }


  public function ficheAction() {
    $fiche_sigb = $this->_user->getFicheSigb();

    $this->view->error = isset($fiche_sigb['erreur']) ? $fiche_sigb["erreur"] : '';
    $this->view->user = $this->_user;
    $this->view->interdiction_modif = Class_AdminVar::get('INTERDIRE_MODIF_FICHE_ABONNE');
  }


  public function pretsAction() {
Laurent's avatar
Laurent committed
375 376 377
    $fiche = $this->_user->getFicheSigb();
    if (isset($this->fiche['error']) && $this->fiche['error'])
      $this->view->error = $this->fiche['error'];
378 379 380 381 382 383
    $this->view->user = $this->_user;
  }


  public function prolongerpretAction() {
    $id_pret = $this->_getParam('id_pret');
384 385
    $ids = array_filter(explode(';', $id_pret));
    if (!count($ids)) {
386
      $this->_renderExtendPopup($this->_('Aucune prolongation éffectué.'));
387 388
      return;
    }
389

Laurent's avatar
Laurent committed
390 391
    $cards = new Class_User_Cards($this->_user);

392
    $results = [];
393
    foreach($ids as $id) {
Laurent's avatar
Laurent committed
394
      $status = $cards->renewLoan($id);
395
      $status['id'] = $id;
Laurent's avatar
Laurent committed
396
      $results[] = $status;
397
    }
Laurent's avatar
Laurent committed
398 399 400 401 402

    $title = (count($ids)>1)
      ? $this->_('Prolongation des prêts')
      : $this->_('Prolongation du prêt');

403 404 405
    $this->_renderExtendPopup($this->view->abonne_LoansExtension($cards,
                                                                 $results,
                                                                 $ids));
406
  }
407 408


409 410 411 412 413 414 415 416 417
  protected function _renderExtendPopup($messages) {
    $this->getHelper('notify')->bePopup();

    if (!is_array($messages))
      $messages = [$messages];

    foreach($messages as $message)
      $this->_helper->notify($message);
    $this->_redirectToReferer();
418 419 420
  }


421
  public function loansHistoryAction() {
422
    try {
Laurent's avatar
Laurent committed
423
      $this->view->loans = $this->_user->getLoansHistory();
424 425
    } catch (Class_WebService_Exception $e) {
      $this->view->error = $e->getMessage();
Laurent's avatar
Laurent committed
426
      $this->view->loans = new Storm_Collection();
427
    }
428 429 430
  }


431
  public function reservationsAction()  {
Laurent's avatar
Laurent committed
432 433 434 435 436 437 438 439 440
    $cards = new Class_User_Cards($this->_user);

    if ($delete = $this->_getParam('id_delete')) {
      $title = $cards->getHoldTitle($delete);
      $result = $cards->cancelHold($delete);
      $message = array_key_exists('erreur', $result) && $result['erreur']
        ? $result['erreur']
        : $this->_('Votre réservation du document %s a bien été supprimée.', $title);

441
      return $this->_renderExtendPopup($message);
442 443
    }

Laurent's avatar
Laurent committed
444
    if ($delete = $this->_getParam('consultation_id_delete'))
lbrun's avatar
lbrun committed
445 446
      Class_CommSigb::getInstance()->onPlaceConsultationCancelBooking(Class_Users::getIdentity(), $delete);

lbrun's avatar
lbrun committed
447
    $this->view->consultations_reservations = $this->_user->getConsultations();
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    $this->view->fiche = $this->_user->getFicheSigb();
    $this->view->user = $this->_user;
  }



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

    $form = new Zend_Form;
    $form
      ->setAction($this->view->url(['action' => 'edit',
                                    'id' => $user->getId()]))
      ->setMethod('post')
      ->setAttrib('id', 'user')
      ->setAttrib('class', 'zend_form')
      ->setAttrib('autocomplete', 'off');

466 467 468 469 470 471 472 473
    $textfields = ['nom' => $this->_('Nom'),
                   'prenom' => $this->_('Prénom'),
                   'pseudo' => $this->_('Pseudo'),
                   'adresse' => $this->_('Adresse'),
                   'code_postal' => $this->_('Code postal'),
                   'ville' => $this->_('Ville'),
                   'mail' => $this->_('E-Mail'),
                   'telephone' => $this->_('Téléphone')];
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 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

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

      $element = $form
        ->createElement('text', $field)
        ->setLabel($label)
        ->setAttrib('size', 30);
      $form->addElement($element);
    }

    if ($mail_element = $form->getElement('mail'))
      $mail_element->addValidator(new ZendAfi_Validate_EmailAddress());

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


    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'],
efalcy's avatar
efalcy committed
528
                                              $fields_to_show))
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
      $form->addDisplayGroup($coordonnees_fields,
                             'coordonnees',
                             ['legend' => 'Coordonnées']);

    if ($contact_fields = array_intersect(['mail', 'telephone'],
                                          $fields_to_show))
      $form->addDisplayGroup($contact_fields,
                             'contact',
                             ['legend' => 'Contact']);

    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']);
    }


    /* Abonnements aux newsletters*/
    $subscriptions = new Zend_Form_Element_MultiCheckbox('subscriptions');
    $subscriptions->setLabel($this->_("Abonnement aux lettres d'information"));


556
    $newsletters = Class_Newsletter::getPublishedNewsletters();
efalcy's avatar
efalcy committed
557

558
    if (count($newsletters)>0) {
559 560
      $checked_subscriptions = [];
      foreach($newsletters as $nl) {
561
        $subscriptions->addMultiOption($nl->getId(), $nl->getTitre());
562 563 564
        if ($nl->hasRecipient($user))
          $checked_subscriptions []= $nl->getId();
      }
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
      $subscriptions->setValue($checked_subscriptions);
      $form
        ->addElement($subscriptions)
        ->addDisplayGroup(['subscriptions'],
                          'newsletters',
                          ['legend' => 'Lettres d\'information']);
    }


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

    return $form;
  }


  public function editAction() {
    $form = $this->_userForm($this->_user);
583 584
    $this->view->form = $form;
    $this->view->help = nl2br(Class_AdminVar::get('AIDE_FICHE_ABONNE'));
585

586 587 588 589
    if (!$this->getRequest()->isPost())
      return ;
    if (!$form->isValid($_POST))
      return;
590 591 592 593
    $subscriptions = $this->_request->getParam('subscriptions', []);
    $newsletters = $subscriptions ?
      Class_Newsletter::findAllBy(['id' => $subscriptions]) :
      [];
594

595 596 597 598
    try {
      $password = $this->_request->getParam('password');
      if (empty($password))
        $password = $this->_user->getPassword();
599

600
      $this->_user->updateSIGBOnSave();
601

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

607 608 609 610
      $this->_user
        ->updateAttributes($attributes)
        ->setPassword($password)
        ->setNewsletters($newsletters);
611

612 613 614
      if ($this->_user->save()) {
        $this->_redirect('/abonne/fiche');
      }
615

616 617 618 619 620 621
      $form->addDecorator('Errors');
      foreach($this->_user->getErrors() as $error)
        $form->addError($error);
    } catch(Exception $e) {
      $form->addError($e->getMessage());
      $form->addDecorator('Errors');
efalcy's avatar
efalcy committed
622
    }
623 624 625 626 627 628 629

  }


  public function authenticateAction() {
    $this->getHelper('ViewRenderer')->setNoRender();

630 631 632 633 634 635 636
    $mode = $this->_getParam('mode', '');
    if ($mode === 'holdable-day')
      return $this->_forward('is-holdable-day', 'multimedia', $this->_request->getModuleName(),
                              $this->_request->getParams());
    if ($mode === 'hold')
      return $this->_forward('hold-device', 'multimedia', $this->_request->getModuleName(),
                              $this->_request->getParams());
637

638 639 640
    if ($mode === 'modified-hold')
      return $this->_forward('close-holding', 'multimedia', $this->_request->getModuleName(),
                              $this->_request->getParams());
641

642 643
    return $this->_forward('authenticate', 'multimedia', $this->_request->getModuleName(),
                              $this->_request->getParams());
644 645 646 647 648 649 650 651 652 653 654 655 656 657
  }


  public function multimediaHoldLocationAction() {
    $bean = Class_Multimedia_ReservationBean::newInSession();

    if (null != $this->_getParam('location')) {
      $bean->location = $this->_getParam('location');
      $this->_redirect('/abonne/multimedia-hold-day');
      return;
    }

    $this->view->locations = array_filter(Class_Multimedia_Location::findAllBy(['order' => 'libelle']),
                                          function($location) {
658
                                                                 return $location->numberOfOuverturesMultimedia() > 0;});
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    $this->view->timelineActions = $this->_getTimelineActions('location');
  }


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

    /* Vérification du quota sur le jour choisi */
    $day = $this->_getParam('day');
    $this->view->location = $bean->getLocation()->getLibelleBib();
    $quotaErrorType = null;
    if (null != $day) {
      $quotaErrorType = $this->_user->getMultimediaQuotaErrorForDay($day);
      switch ($quotaErrorType) {
        case Class_Multimedia_DeviceHold::QUOTA_NONE:
          $this->view->quotaError = $this->_('Vous n\'êtes pas autorisé à effectuer une réservation');
          break;
        case Class_Multimedia_DeviceHold::QUOTA_DAY:
          $this->view->quotaError = $this->_('Quota déjà atteint ce jour, choisissez un autre jour.');
          break;
        case Class_Multimedia_DeviceHold::QUOTA_WEEK:
          $this->view->quotaError = $this->_('Quota déjà atteint cette semaine, choisissez une autre semaine.');
          break;
        case Class_Multimedia_DeviceHold::QUOTA_MONTH:
          $this->view->quotaError = $this->_('Quota déjà atteint ce mois, choisissez un autre mois.');
          break;
      }
    }

    /* Choix valide, passage à l'écran suivant */
    if (null != $day && null == $quotaErrorType) {
      $bean->day = $day;
      $this->_redirect('/abonne/multimedia-hold-hours');
      return;
    }

    $this->getRequest()->setParam('day', 0);
    if (!$bean->isCurrentStateValidForRequest($this->getRequest())) {
      $this->_redirect('/abonne/'.$bean->currentState());
      return;
    }

    /* Rendu du calendrier avec les jours sélectionnables */
    $location = $bean->getLocation();
    $this->view->minDate = $location->getMinDate();
    $this->view->maxDate = $location->getMaxDate();
    $holidayStamps = array_map(
efalcy's avatar
efalcy committed
706 707 708 709 710
                               function($item) {return $item * 1000;},
                               array_merge(
                                           Class_Date_Holiday::getTimestampsForYear(),
                                           Class_Date_Holiday::getTimestampsForYear(date('Y') + 1)
                               )
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    );

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


    $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;
      }
    });
    if (-1 == $.inArray($.datepicker.formatDate(\'yy-mm-dd\', date),
731
                        [' . $js_opened_days . '])) {
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
      result[0] = false;
    }
    return result;';

    $this->view->beforeShowDay = $beforeShowDay;
    $this->view->location = $bean->getLocation()->getLibelleBib();
    $this->view->timelineActions = $this->_getTimelineActions('day');
  }


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

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

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

      if ($start < $location->getMinTimeForDate($bean->day)
efalcy's avatar
efalcy committed
757
          || $end > $location->getMaxTimeForDate($bean->day)) {
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
        $this->view->error = $this->_('Ce créneau n\'est pas dans les heures d\'ouverture.');
      }

      if (!$this->view->error) {
        $bean->time = $this->_getParam('time');
        $bean->duration = (int)$this->_getParam('duration');
        $this->_redirect('/abonne/multimedia-hold-group');
        return;
      }
    }

    $this->view->timelineActions = $this->_getTimelineActions('hours');
    $this->view->form = $this->multimediaHoldHoursForm($bean, $location);
    $this->view->day = strftime('%d %B %Y', strtotime($bean->day));
  }


  public function multimediaHoldHoursForm($bean, $location) {
    return $this->view
      ->newForm(['id' => 'hold-hours'])
      ->setMethod('get')
      ->addElement('select', 'time', ['label' => $this->_('À partir de quelle heure ?'),
                                      'multiOptions' => $location->getStartTimesForDate($bean->day)])
      ->addElement('select', 'duration', ['label' => $this->_('Pour quelle durée ?'),
                                          'multiOptions' => $location->getDurations()])
      ->addDisplayGroup(['time', 'duration'], 'choix', ['legend' => ''])
      ->addElement('submit', 'submit', ['label' => $this->_('Choisir')]);
  }


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

    $this->view->groups = $bean->getGroups();
    $this->view->timelineActions = $this->_getTimelineActions('group');
    $this->view->location = $bean->getLocation()->getLibelleBib();
    $this->view->day = strftime('%d %B %Y', strtotime($bean->day));
    $this->view->time = str_replace(':', 'h', $bean->time);
    $this->view->duration = $bean->duration . 'mn';
  }


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

    $this->view->timelineActions = $this->_getTimelineActions('device');
    $this->view->devices = $bean->getGroup()->getHoldableDevicesForDateTimeAndDuration($bean->day,
                                                                                       $bean->time,
                                                                                       $bean->duration);
    $this->view->location = $bean->getLocation()->getLibelleBib();
    $this->view->day = strftime('%d %B %Y', strtotime($bean->day));
    $this->view->time = str_replace(':', 'h', $bean->time);
    $this->view->duration = $bean->duration . 'mn';
    $this->view->group = $bean->getGroup()->getLibelle();
  }


  public function multimediaHoldConfirmAction() {
    if (!$bean = $this->_getDeviceHoldBean())
      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');
    $this->view->location = $bean->getLocation()->getLibelleBib();
    $this->view->day = strftime('%d %B %Y', strtotime($bean->day));
    $this->view->time = str_replace(':', 'h', $bean->time);
    $this->view->duration = $bean->duration . 'mn';

    $device = $bean->getDevice();
    $this->view->device = $device->getLibelle() . ' - ' . $device->getOs();
  }


  public function multimediaHoldViewAction() {
    if (null == ($hold = Class_Multimedia_DeviceHold::find((int)$this->_getParam('id')))) {
      $this->_redirect('/abonne/fiche');
      return;
    }

    if ($this->_user != $hold->getUser()) {
      $this->_redirect('/abonne/fiche');
      return;
    }

    if ($this->_getParam('delete')) {
      $hold->delete();
      $this->_redirect('/abonne/fiche');
      return;
    }

    $this->view->location = $hold->getLibelleBib();
    $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';
    $this->view->device = $hold->getLibelleDevice() . ' - ' . $hold->getOs();
  }


  /**
   * @param $current string
   * @return array
   */
  protected function _getTimelineActions($current) {
    $knownActions = ['location' => $this->_('Lieu'),
                     'day' => $this->_('Jour'),
                     'hours' => $this->_('Horaires'),
                     'group' => $this->_('Secteur'),
                     'device' => $this->_('Poste'),
                     'confirm' => $this->_('Confirmation')];

    $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;
  }


  /** @return array */
  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));
  }


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

    return $bean;
  }


  public function suggestionAchatAction() {
910
    if (Class_AdminVar::areSuggestionsDisabled()) {
911 912 913
      $this->_forward('suggestion-achat-inactive');
      return;
    }
914 915 916 917
  }


  public function suggestionAchatAddAction() {
918
    if (Class_AdminVar::areSuggestionsDisabled()) {
919 920 921
      $this->_forward('suggestion-achat-inactive');
      return;
    }
922 923 924 925 926 927 928 929 930 931 932 933 934 935
    if (Class_SuggestionAchat::find($this->_getParam('id'))) {
      $this->_forward('suggestion-achat-ok');
      return;
    }

    $form = ZendAfi_Form_SuggestionAchat::forUser($this->_user);

    if ($this->_request->isPost()) {
      $post = $this->_request->getPost();
      unset($post['submit']);

      $suggestion = $form->newBuySuggest($post);

      if ($form->isValid($suggestion)) {
936 937

        // $suggestion->save(); always return true without considering webservice answers. UX choice ?
938
        $suggestion->save();
939

940 941 942 943 944
        try {
          $suggestion->sendMail('noreply@'.$this->_request->getHttpHost());
        } catch (Zend_Mail_Exception $e) {
          $this->_helper->notify($this->_('Aucun courriel envoyé, erreur: ').$this->_($e->getMessage()));
        }
945

946 947 948 949 950 951 952 953 954 955
        $this->_helper->notify($this->_('Suggestion d\'achat enregistrée'));
        $this->_redirect('/opac/abonne/suggestion-achat');
      }
    }

    $this->view->form = $form;
    $this->view->preferences = Class_Profil::getCurrentProfil()->getCfgModulesPreferences('abonne', 'suggestion-achat-add');
  }


956
  public function suggestionAchatOkAction() {
957
    if (Class_AdminVar::areSuggestionsDisabled()) {
958 959 960 961
      $this->_forward('suggestion-achat-inactive');
      return;
    }
  }
962

963
  public function suggestionAchatInactiveAction() {}
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978


  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');
  }


  public function getPaniersJsonAction() {
    $data[] = $this->_user->getPaniersJson();
979

980 981 982
    if ($this->_user->canAccessBackend())
      $data[] = (new Class_Catalogue())->getDomainesJson(['removeCheckbox' => true]);

983
    $this->_helper->json($data);
984
  }
985 986


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

990 991 992 993 994
    $datas = [];
    $emprunts = $this->_user->getLoansWithoutPNB();
    foreach($emprunts as $emprunt) {
      if (!$exemplaire = $emprunt->getExemplaireOPAC())
        continue;
995

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

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

1003 1004 1005 1006
    $response->setHeader('Content-Type', 'application/octet-stream; name="' . $filename . '"', true);
    $response->setHeader('Content-Disposition', 'attachment; filename="'.$filename.'"', true);
    $response->setBody(implode('', $datas));
  }
1007 1008


Ghislain Loas's avatar
Ghislain Loas committed
1009
  public function settingsAction() {
1010 1011 1012
    if(!Class_Users::getIdentity())
      return $this->_forward('popup-login', 'auth', 'opac', ['redirect' => $this->view->url()]);

Ghislain Loas's avatar
Ghislain Loas committed
1013 1014 1015 1016 1017
    $this->view->form = $form = ZendAfi_Form_User_Settings::forUser($this->_user);

    if ($this->_request->isPost()) {
      $data = $this->_request->getPost();
      unset($data['id_items']);
1018 1019
      $this->_user->setSettings(Class_User_Settings::serializeSettings($data));
      $this->_user->save();
Ghislain Loas's avatar
Ghislain Loas committed
1020
      $this->_javascriptRedirectToReferrer();
Ghislain Loas's avatar
Ghislain Loas committed
1021
    }
Ghislain Loas's avatar
Ghislain Loas committed
1022 1023

    $this->view->titre = $this->view->_('Gérer mes favoris');
Ghislain Loas's avatar
Ghislain Loas committed
1024
  }
1025 1026


1027
  public function viewableLibrariesJsonAction() {
1028
    $this->_helper->json([$this->view->TreeSelect_Json_Libraries(Class_Profil::getCurrentProfil()->getLibraries())]);
1029 1030 1031
  }


1032
  public function viewableDomainsJsonAction() {
1033
    $this->_helper->json([$this->view->TreeSelect_Json_Domains(Class_Catalogue::findAllCataloguesAIndexer())]);
1034
  }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054


  public function addLibraryToBookmarksAction() {
    $viewRenderer = $this->getHelper('ViewRenderer');
    $viewRenderer->setNoRender();

    $this->_user->addLibraryToBookmarks($this->_getParam('library_id', null));
    $this->_user->save();
    $this->_javascriptRedirectToReferrer();
  }


  public function removeLibraryFromBookmarksAction() {
    $viewRenderer = $this->getHelper('ViewRenderer');
    $viewRenderer->setNoRender();

    $this->_user->removeLibraryFromBookmarks($this->_getParam('library_id', null));
    $this->_user->save();
    $this->_javascriptRedirectToReferrer();
  }
1055 1056 1057 1058


  public function cardsAction() {
    $this->view->titre = $this->_('Mes cartes');
Laurent's avatar
Laurent committed
1059
    $this->view->child_cards = new Class_User_Cards($this->_user);
1060
    $this->view->parent_cards = $this->_user->getParentCards();
1061 1062 1063 1064
  }


  public function unlinkCardAction() {
1065 1066 1067 1068 1069 1070 1071
    return $this->_unlinkCard(['parent_id' => $this->_user->getId(),
                               'child_id' => (int)$this->_getParam('id')],
                              function($child)
                              {
                                return $this->_('Vous n\'utilisez plus la carte de %s',
                                        $child->getNomComplet());
                              });
1072 1073 1074 1075
  }


  public function unlinkParentCardAction() {
1076 1077 1078 1079 1080 1081 1082 1083 1084
    return $this->_unlinkCard(['parent_id' => (int)$this->_getParam('id'),
                               'child_id' => $this->_user->getId()],
                              function($parent)
                              {
                                return $this->_('Votre carte a été retirée à %s',
                                                $parent->getNomComplet());
                              });
  }

1085

1086 1087 1088
  protected function _unlinkCard($params, $message_callback) {
    if (!$user = Class_Users::find((int)$this->_getParam('id')))
      return $this->_unlinkResponseNotFound();
1089

1090 1091
    if (!$lc = Class_LinkedCard::findFirstBy($params))
      return $this->_unlinkResponseNotFound();
1092 1093

    $lc->delete();
1094 1095 1096 1097 1098 1099 1100 1101
    $this->_unlinkResponseDone($message_callback($user));
  }


  protected function _unlinkResponseNotFound() {
    return $this->_unlinkResponseDone($this->_('Carte introuvable'));
  }

1102

1103 1104
  protected function _unlinkResponseDone($message) {
    $this->_helper->notify($message);
1105
    $this->_redirect('/abonne/cards');
1106 1107 1108 1109 1110 1111 1112 1113
  }


  public function addCardAction() {
    $this->view->titre = $this->_('Ajouter une carte');

    $form = new ZendAfi_Form();
    $form
1114 1115 1116 1117 1118 1119
      ->addElement('text', 'login', ['label' => 'Identifiant',
                                     'required' => true,
                                     'allowEmpty' => false])
      ->addElement('password', 'password', ['label' => 'Mot de passe',
                                            'required' => true,
                                            'allowEmpty' => false])
1120 1121 1122 1123 1124 1125 1126 1127
      ->setAction($this->view->url())
      ->addDisplayGroup(['login', 'password'],
                        'add-card',
                        ['legend' => $this->_('Carte')]);

    $this->view->form = $form;


1128
    if (!$this->_request->isPost() || !$form->isValid($this->_request->getPost()))
1129 1130
      return $this;

1131 1132 1133
    if ((!$child = Class_Users::findFirstBy(['login' => $this->_getPost('login'),
                                             'password' => $this->_getPost('password')]))
        || !$child->isAbonne()) {
1134

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
      $this->_helper->notify($this->_('Identifiant et/ou mot de passe incorrect'));
      return $this->_redirect('/abonne/add-card');
    }

    if ($child->getId() == $this->_user->getId()) {
      $this->_helper->notify($this->_('Vous ne pouvez pas ajouter votre propre carte'));
      return $this->_redirect('/abonne/add-card');
    }

    if (Class_LinkedCard::findFirstBy(['parent_id' => $this->_user->getId(),
                                       'child_id' => $child->getId()])) {
      $this->_helper->notify($this->_('Vous avez déjà ajouté la carte de "%s"',
                                      $child->getNomComplet()));
      return $this->_redirect('/abonne/add-card');
    }
1150

1151 1152 1153 1154 1155
    if($this->_user->addChildCard($child)->save()) {
      $this->_helper->notify($this->_('Carte de "%s" ajoutée',
                                      $child->getNomComplet()));
      return $this->_javascriptRedirectToReferrer();
    }
1156

1157 1158 1159
    $this->_helper->notify($this->_('Une erreur s\'est produite en ajoutant la carte de "%s" : %s',
                                    $child->getNomComple