示例#1
0
 public static function completeInfos(Book &$book)
 {
     try {
         $config = self::getConfig();
         $googleBook = new \Sb\Google\Model\GoogleBook($book->getISBN10(), $book->getISBN13(), $book->getASIN(), $config->getGoogleApiKey());
         if ($googleBook->getVolumeInfo()) {
             $bookFromGoogle = new Book();
             \Sb\Db\Mapping\BookMapper::mapFromGoogleBookVolumeInfo($bookFromGoogle, $googleBook->getVolumeInfo());
             if (!$book->getDescription() && $bookFromGoogle->getDescription()) {
                 $book->setDescription($bookFromGoogle->getDescription());
             }
             if (!$book->getImageUrl() && $bookFromGoogle->getImageUrl()) {
                 $book->setImageUrl($bookFromGoogle->getImageUrl());
             }
             if (!$book->getSmallImageUrl() && $bookFromGoogle->getSmallImageUrl()) {
                 $book->setSmallImageUrl($bookFromGoogle->getSmallImageUrl());
             }
             if (!$book->getPublishingDate() && $bookFromGoogle->getPublishingDate()) {
                 $book->setPublishingDate($bookFromGoogle->getPublishingDate());
             }
         } else {
             \Sb\Trace\Trace::addItem('Le livre n\'a pas été trouvé sur Google.');
         }
     } catch (\Exception $exc) {
         $message = sprintf("Une erreur s'est produite lors de l'appel à l'api google books : %s", $exc->getMessage());
         MailSvc::getInstance()->send(Constants::WEBMASTER_EMAIL, "Erreur interne", $message);
         \Sb\Trace\Trace::addItem($message);
     }
 }
示例#2
0
 public function submitRecommandAction()
 {
     try {
         $globalContext = new \Sb\Context\Model\Context();
         $user = $globalContext->getConnectedUser();
         // Getting params
         $id = $this->getParam("id");
         $title = $this->getParam("title");
         $message = $this->getParam("message");
         $IdAddressee = $this->getParam("IdAddressee");
         // Getting book
         $book = $this->getBook($id);
         if (!empty($title) && !empty($message) && !empty($IdAddressee)) {
             $titleVal = trim($title);
             $messageVal = trim($message);
             $recipients = $IdAddressee;
             $recipientsIds = explode(",", $recipients);
             foreach ($recipientsIds as $recipientId) {
                 if (trim($recipientId) != "") {
                     $recipient = UserDao::getInstance()->get($recipientId);
                     if ($recipient) {
                         // adding message in db
                         $message = new Message();
                         $message->setSender($user);
                         $message->setRecipient($recipient);
                         $message->setIs_read(false);
                         $message->setTitle($titleVal);
                         $message->setMessage($messageVal);
                         MessageDao::getInstance()->add($message);
                         // Sending email if user authorized it
                         $userSetting = $recipient->getSetting();
                         if ($userSetting->getEmailMe() == 'Yes') {
                             $body = MailHelper::newMessageArrivedBody($user->getUserName());
                             MailSvc::getInstance()->send($recipient->getEmail(), sprintf(__("%s vous recommande %s ", "s1b"), $user->getUserName(), $book->getTitle()), $body);
                         }
                     }
                 }
             }
             Flash::addItem(__("Message envoyé.", "s1b"));
             HTTPHelper::redirect(Urls::USER_HOME);
         } else {
             Flash::addItem(__("Au moins l'un des champs n'est pas rempli", "s1b"));
             HTTPHelper::redirect(Urls::USER_MAILBOX_RECOMMAND, array("message" => $message, "id" => $id));
         }
     } catch (\Exception $e) {
         Trace::addItem(sprintf("Une erreur s'est produite dans \"%s->%s\", TRACE : %s\"", get_class(), __FUNCTION__, $e->getTraceAsString()));
         $this->forward("error", "error", "default");
     }
 }
 public function sendByEmailAction()
 {
     $uid = $this->_getParam('uid');
     $emails = $this->_getParam('emails');
     $origin = $this->getRequest()->getHeader('referer');
     $origin .= "&emails=" . $emails;
     // Checking if parameters are passed
     if ($uid && $emails) {
         // Checking if uid is a valid user
         $user = UserDao::getInstance()->get($uid);
         if ($user) {
             // Getting user wished books
             $wishedUserbooks = $user->getNotDeletedUserBooks();
             $wishedUserbooks = array_filter($wishedUserbooks, array(&$this, "isWished"));
             // Cheking if some valid emails are passed
             $emailsArray = array($emails);
             if (strpos(",", $emails) !== 0) {
                 $emailsArray = explode(",", $emails);
             }
             foreach ($emailsArray as $email) {
                 if (!StringHelper::isValidEmail($email)) {
                     Flash::addItem(__("Un des emails renseigné n'est pas valide.", "s1b"));
                     $this->_redirect($origin);
                     exit;
                 }
             }
             // Building the mail content
             $emailContent = \Sb\Helpers\MailHelper::wishedUserBooksEmailBody($user, $wishedUserbooks);
             // Sending mail
             MailSvc::getInstance()->send($emails, sprintf(__("%s - Liste des livres souhaités par %s", "s1b"), Constants::SITENAME, $user->getFriendlyName()), $emailContent);
             Flash::addItem(__("La liste a bien été envoyée par email.", "s1b"));
             $this->_redirect($origin);
             exit;
         }
     }
     Flash::addItem(__("Une erreur s'est produite lors de l'envoi de la liste par email", "s1b"));
     $this->_redirect($origin);
     exit;
 }
 public function addUserbookCommentAction()
 {
     $this->view->setEncoding('utf-8');
     $globalContext = new \Sb\Context\Model\Context();
     $this->view->errorMessage = __("Une erreur s'est produite et votre commentaire n'a pas été posté correctement.", "s1b");
     if ($globalContext->getConnectedUser()) {
         // Getting params
         $bookId = $this->_getParam('bookId');
         $reviewPageId = $this->_getParam('reviewPageId');
         $userBookId = $this->_getParam('ubid');
         $commentValue = $this->_getParam('comment');
         // Add userbook comment
         $userbook = UserBookDao::getInstance()->get($userBookId);
         $comment = new UserbookComment();
         $comment->setValue($commentValue);
         $comment->setCreation_date(new \DateTime());
         $comment->setOwner($globalContext->getConnectedUser());
         $comment->setUserbook($userbook);
         // If the adding happens correctly, we forward to the get-reviews-page action
         if (UserbookCommentDao::getInstance()->add($comment)) {
             $reviewUser = $userbook->getUser();
             // Sends a mail only if connected user is not the userbook owner
             if ($reviewUser->getId() != $globalContext->getConnectedUser()->getId() && $reviewUser->getSetting()->getEmailMe() == \Sb\Helpers\UserSettingHelper::EMAIL_ME_YES) {
                 // Send a email to the userbook owner
                 $subject = sprintf(__("%s - Un nouveau commentaire sur un de vos livres.", "s1b"), \Sb\Entity\Constants::SITENAME);
                 $body = \Sb\Helpers\MailHelper::newCommentPosted($commentValue, $userbook->getBook());
                 \Sb\Service\MailSvc::getInstance()->send($reviewUser->getEmail(), $subject, $body);
             }
             // Forward to review page action
             $this->forward("get-reviews-page", "book", "default", array("key" => $bookId, "param" => $reviewPageId, "format" => "html"));
         }
     } else {
         $this->view->errorMessage = __("Vous devez être connecté pour poster un commentaire.", "s1b");
     }
     // Otherwise, we let the message 'KO' get rendered by the view
     // This message will be intercepted in javascript code to display a coherent flash message
 }
 public function replyAction()
 {
     return;
     try {
         $globalContext = new \Sb\Context\Model\Context();
         $messageId = ArrayHelper::getSafeFromArray($_GET, 'mid', null);
         $redirect = false;
         if ($messageId) {
             $message = MessageDao::getInstance()->get($messageId);
             $this->view->message = $message;
             if ($message->getRecipient()->getId() != $globalContext->getConnectedUser()->getId()) {
                 Flash::addItem(__("Vous ne pouvez pas répondre à ce message car il ne vous est pas destiné.", "s1b"));
                 $redirect = true;
             }
         } else {
             Flash::addItem(__("Le message auquel vous tentez de répondre n'existe pas.", "s1b"));
             $redirect = true;
         }
         if ($_POST) {
             $title = htmlspecialchars($_POST['Title']);
             $messageContent = htmlspecialchars($_POST['Message']);
             /* test if form is not empty */
             if (!empty($title) && !empty($messageContent)) {
                 // create new message in db
                 $reply = new Message();
                 $reply->setRecipient($message->getSender());
                 $replySender = $globalContext->getConnectedUser();
                 $reply->setSender($replySender);
                 $reply->setDate(new \DateTime());
                 $reply->setTitle($title);
                 $reply->setMessage($messageContent);
                 $reply->setIs_read(false);
                 MessageDao::getInstance()->add($reply);
                 if ($message->getSender()->getSetting()->getEmailMe() == 'Yes') {
                     // send a email to warn the origianl sender of the email
                     $body = MailHelper::newMessageArrivedBody($replySender->getUserName());
                     MailSvc::getInstance()->send($message->getSender()->getEmail(), sprintf(__("Un message vous a été envoyé depuis le site %s", "s1b"), Constants::SITENAME), $body);
                 }
                 Flash::addItem(__("Message envoyé.", "s1b"));
                 $redirect = true;
             } else {
                 Flash::addItem(__("Vous devez renseigné le titre et le contenu du message.", "s1b"));
             }
         }
         if ($redirect) {
             HTTPHelper::redirect(Urls::USER_MAILBOX);
         }
     } catch (\Exception $e) {
         Trace::addItem(sprintf("Une erreur s'est produite dans \"%s->%s\", TRACE : %s\"", get_class(), __FUNCTION__, $e->getTraceAsString()));
         $this->forward("error", "error", "default");
     }
 }
 /**
  * Show pending friends request and allow to accepet or refuse it
  */
 public function pendingRequestsAction()
 {
     try {
         $globalContext = new \Sb\Context\Model\Context();
         $user = $globalContext->getConnectedUser();
         $this->view->user = $user;
         // Show pending requests
         if (!$_POST) {
             $totalPendingRequests = $user->getPendingFriendShips();
             if ($totalPendingRequests && count($totalPendingRequests) > 0) {
                 // Preparing pagination
                 $paginatedList = new PaginatedList($totalPendingRequests, 6);
                 $this->view->firstItemIdx = $paginatedList->getFirstPage();
                 $this->view->lastItemIdx = $paginatedList->getLastPage();
                 $this->view->nbItemsTot = $paginatedList->getTotalPages();
                 $this->view->navigation = $paginatedList->getNavigationBar();
                 $this->view->pendingRequests = $paginatedList->getItems();
             }
         } else {
             $friendShipId = ArrayHelper::getSafeFromArray($_POST, 'friendShipId', null);
             $Title = ArrayHelper::getSafeFromArray($_POST, 'Title', null);
             $Message = ArrayHelper::getSafeFromArray($_POST, 'Message', null);
             $Refused = ArrayHelper::getSafeFromArray($_POST, 'Refused', null);
             if ($friendShipId) {
                 if ($Refused == 0) {
                     // Update the requested friendship
                     $friendShip = FriendShipDao::getInstance()->get($friendShipId);
                     if ($friendShip) {
                         $friendShip->setAccepted(true);
                         $friendShip->setValidated(true);
                         if (FriendShipDao::getInstance()->update($friendShip)) {
                             // Add the userEvent
                             try {
                                 $userEvent = new UserEvent();
                                 $userEvent->setNew_value($user->getId());
                                 $userEvent->setType_id(EventTypes::USER_ADD_FRIEND);
                                 $userEvent->setUser($friendShip->getUser_source());
                                 UserEventDao::getInstance()->add($userEvent);
                             } catch (\Exception $exc) {
                                 Trace::addItem("Erreur lors de l'ajout de l'événement : " . $exc->getMEssage());
                             }
                         }
                     }
                     // Create a friendship on the other side
                     $inverseFriendShip = new FriendShip();
                     $inverseFriendShip->setAccepted(true);
                     $inverseFriendShip->setValidated(true);
                     $inverseFriendShip->setCreationDate(new \DateTime());
                     $inverseFriendShip->setUser_source($user);
                     $inverseFriendShip->setUser_target($friendShip->getUser_source());
                     if (FriendShipDao::getInstance()->add($inverseFriendShip)) {
                         // Add the userEvent
                         try {
                             $userEvent = new UserEvent();
                             $userEvent->setNew_value($friendShip->getUser_source()->getId());
                             $userEvent->setType_id(EventTypes::USER_ADD_FRIEND);
                             $userEvent->setUser($user);
                             UserEventDao::getInstance()->add($userEvent);
                         } catch (\Exception $exc) {
                             Trace::addItem("Erreur lors de l'ajout de l'événement : " . $exc->getMEssage());
                         }
                     }
                     // Send email to the requesting user
                     MailSvc::getInstance()->send($friendShip->getUser_source()->getEmail(), __("Demande d'ami", "s1b"), MailHelper::friendShipAcceptationEmailBody($user->getFirstName() . " " . $user->getLastName()));
                     // add a message in requesting user internal mailbox
                     $message = new \Sb\Db\Model\Message();
                     $message->setDate(new \DateTime());
                     $message->setMessage($Message);
                     $message->setTitle($Title);
                     $message->setRecipient($friendShip->getUser_source());
                     $message->setSender($user);
                     MessageDao::getInstance()->add($message);
                     // redirect to pending request page
                     Flash::addItem("Demande acceptée.");
                     HTTPHelper::redirect(Urls::USER_FRIENDS_PENDING_REQUEST);
                 } elseif ($Refused == 1) {
                     // update the requested friendship
                     $friendShip = FriendShipDao::getInstance()->get($friendShipId);
                     if ($friendShip) {
                         $friendShip->setAccepted(false);
                         $friendShip->setValidated(true);
                         FriendShipDao::getInstance()->update($friendShip);
                     }
                     // send email to the requesting user
                     MailSvc::getInstance()->send($friendShip->getUser_source()->getEmail(), __("Votre demande d'ami a été refusée", "s1b"), MailHelper::friendShipDenyEmailBody($user->getFirstName() . " " . $user->getLastName()));
                     // add a message in requesting user internal mailbox
                     $message = new Message();
                     $message->setDate(new \DateTime());
                     $message->setMessage($Message);
                     $message->setTitle($Title);
                     $message->setRecipient($friendShip->getUser_source());
                     $message->setSender($user);
                     MessageDao::getInstance()->add($message);
                     // redirect to pending request page
                     Flash::addItem(__("Demande refusée.", "s1b"));
                     HTTPHelper::redirect(Urls::USER_FRIENDS_PENDING_REQUEST);
                 }
             } else {
                 Flash::addItem(__("Vous devez sélectionner une demande d'ami.", "s1b"));
                 HTTPHelper::redirect(Urls::USER_FRIENDS_PENDING_REQUEST);
             }
         }
     } catch (\Exception $e) {
         Trace::addItem(sprintf("Une erreur s'est produite dans \"%s->%s\", TRACE : %s\"", get_class(), __FUNCTION__, $e->getTraceAsString()));
         $this->forward("error", "error", "default");
     }
 }
示例#7
0
 /**
  * Show and submit registration page
  */
 public function registerAction()
 {
     try {
         if ($_POST) {
             if ($this->validateRegistrationForm()) {
                 // Test if user already in DB
                 $userInDB = UserDao::getInstance()->getByEmail($_POST['email']);
                 // If yes => show message and redirect to login page
                 if ($userInDB) {
                     if ($userInDB->getDeleted()) {
                         Flash::addItem(__("Un compte correspondant à cet email existe mais il a été supprimé. Merci de nous contacter via le formulaire de contact.", "s1b"));
                     } else {
                         Flash::addItem(__("Vous avez déjà créé un compte avec cet email. Si vous l'avez créé avec Facebook, vous pouvez vous connecter avec Facebook et ajouter un mot de passe dans votre profil section mot de passe. Si ce n'est pas le cas et que vous ne vous souvenez pas du mot de passe, vous pouvez demandez à réinitialiser le mot de passe en cliquant sur le lien \"Mot de passe perdu\"", "s1b"));
                     }
                     HTTPHelper::redirect(\Sb\Entity\Urls::LOGIN);
                 } else {
                     // If Not
                     // ==> create user
                     // ==> send welcome email
                     // ==> create welcome message in internal mailbox
                     //
                     $userFromPost = new User();
                     UserMapper::map($userFromPost, $_POST);
                     $userFromPost->setToken(sha1(uniqid(rand())));
                     $userFromPost->setActivated(false);
                     $userFromPost->setDeleted(false);
                     $userFromPost->setFacebookId("");
                     $userFromPost->setGender("");
                     $userFromPost->setFacebookLanguage("");
                     $userFromPost->setTokenFacebook("");
                     $userFromPost->setPicture("");
                     $userFromPost->setPictureBig("");
                     $setting = new UserSetting();
                     UserSettingHelper::loadDefaultSettings($setting);
                     $userFromPost->setSetting($setting);
                     $userInDB = UserDao::getInstance()->add($userFromPost);
                     // send confirmation email
                     $subject = sprintf(__("Votre compte %s a été créé", "s1b"), Constants::SITENAME);
                     MailSvc::getInstance()->send($userInDB->getEmail(), $subject, MailHelper::validationAccountEmailBody($userInDB->getFirstName(), $userInDB->getToken(), $userInDB->getEmail()));
                     // Send warning email to webmaster
                     MailSvc::getInstance()->send(Constants::WEBMASTER_EMAIL . ", berliozd@gmail.com, rebiffe_olivier@yahoo.fr", __("nouveau user", "s1b"), $userInDB->getEmail());
                     // create message in user internal mailbox
                     MessageSvc::getInstance()->createWelcomeMessage($userInDB->getId());
                     // redirect to user homepage
                     $successMsg = __("Votre compte a été créé correctement. N'oubliez pas de l'activer grâce à l'email que vous avez reçu avant toute première connexion. <strong>Attention cet email pourrait tomber dans vos spams.</strong>", "s1b");
                     Flash::addItem($successMsg);
                     // Testing if the user registering match invitations and set them to validated and accepted if they exist
                     InvitationSvc::getInstance()->setInvitationsAccepted($userInDB->getEmail());
                     HTTPHelper::redirect(Urls::LOGIN);
                 }
             }
         }
     } catch (\Exception $e) {
         Trace::addItem(sprintf("Une erreur s'est produite dans \"%s->%s\", TRACE : %s\"", get_class(), __FUNCTION__, $e->getTraceAsString()));
         $this->forward("error", "error", "default");
     }
 }
 public function submitAction()
 {
     try {
         $globalContext = new \Sb\Context\Model\Context();
         if ($_REQUEST['LendingType'] == "NEW") {
             $userBookId = $_POST['ubid'];
             // getting userbook lent
             $userBook = UserBookDao::getInstance()->get($userBookId);
             $userBook->setLentOnce(true);
             // getting borrower userbook (new one)
             // checking if borrower alreday have the book
             $borrowerId = $_POST['BorrowerId'];
             $userBookBorrower = UserBookDao::getInstance()->getByBookIdAndUserId($borrowerId, $userBook->getBook()->getId());
             // if not creating a new one
             if (!$userBookBorrower) {
                 $userBookBorrower = new UserBook();
                 $userBookBorrower->setCreationDate(new \DateTime());
                 $userBookBorrower->setLastModificationDate(new \DateTime());
                 $userBookBorrower->setBook($userBook->getBook());
                 $borrower = UserDao::getInstance()->get($borrowerId);
                 $userBookBorrower->setUser($borrower);
             }
             $userBookBorrower->setIs_deleted(false);
             // set is_deleted to false in case the borrower already had the book but deleted it in the past
             $userBookBorrower->setBorrowedOnce(true);
             // creating lending
             $lending = new Lending();
             $lending->setUserbook($userBook);
             $lending->setBorrower_userbook($userBookBorrower);
             $lending->setStartDate(new \DateTime());
             $lending->setCreationDate(new \DateTime());
             $lending->setLastModificationDate(new \DateTime());
             $lending->setState(LendingState::ACTIV);
             if (LendingDao::getInstance()->add($lending)) {
                 Trace::addItem("Lending créé avec succès.");
                 Flash::addItem(__("Les informations de prêt ont bien été mises à jour.", "s1b"));
                 try {
                     $userEvent = new UserEvent();
                     $userEvent->setNew_value($lending->getId());
                     $userEvent->setType_id(EventTypes::USER_LEND_USERBOOK);
                     $userEvent->setUser($globalContext->getConnectedUser());
                     UserEventDao::getInstance()->add($userEvent);
                 } catch (Exception $exc) {
                     Trace::addItem("erreur lors de l'ajout de l'évènement suite au prêt : " . $exc->getMessages());
                 }
             }
         } else {
             // editing a lending -> ending it
             $lendingId = $_POST["LendingId"];
             $lending = LendingDao::getInstance()->get($lendingId);
             if ($lending) {
                 // Testing if the user editing the lending is either the lender or the borrower
                 $canEditLending = false;
                 if ($lending->getUserbook() && $lending->getUserbook()->getUser()->getId() == $globalContext->getConnectedUser()->getId()) {
                     $canEditLending = true;
                 }
                 if ($lending->getBorrower_userbook() && $lending->getBorrower_userbook()->getUser()->getId() == $globalContext->getConnectedUser()->getId()) {
                     $canEditLending = true;
                 }
                 if ($canEditLending) {
                     $lending->setEndDate(new \DateTime());
                     // End date set to today
                     $userIsLender = $lending->getUserbook() && $lending->getUserbook()->getUser()->getId() == $globalContext->getConnectedUser()->getId();
                     $userIsBorrower = $lending->getBorrower_userbook() && $lending->getBorrower_userbook()->getUser()->getId() == $globalContext->getConnectedUser()->getId();
                     $isBorrowedToGuest = $lending->getGuest();
                     if ($userIsLender) {
                         $lending->setState(LendingState::IN_ACTIVE);
                         // user is the lender, State set to IN_ACTIVE
                     } elseif ($userIsBorrower) {
                         if (!$isBorrowedToGuest) {
                             $lending->setState(LendingState::WAITING_INACTIVATION);
                         } else {
                             $lending->setState(LendingState::IN_ACTIVE);
                         }
                         // user is the borrower but is borrowed to a guest, State set to IN_ACTIVE
                     }
                     $lending->setLastModificationDate(new \DateTime());
                     if (LendingDao::getInstance()->update($lending)) {
                         // Send email to owner to remind him that he needs to validate the lending end
                         if ($userIsBorrower && !$isBorrowedToGuest) {
                             MailSvc::getInstance()->send($lending->getUserbook()->getUser()->getEmail(), __("Prêt en attente de retour de validation", "s1b"), $this->emailReturnValidationRequiredBody($lending->getUserbook()->getBook()->getTitle(), $lending->getBorrower_userbook()->getUser()->getUserName()));
                         }
                         Trace::addItem("Mise à jour (FIN) du lending correctement.");
                         if ($userIsBorrower && !$isBorrowedToGuest) {
                             Flash::addItem(__("Les informations de prêt ont bien été mises à jour mais le retour doit être validé par le prêteur.", "share1book"));
                         } else {
                             Flash::addItem(__("Les informations de prêt ont bien été mises à jour.", "s1b"));
                         }
                     }
                 }
             }
         }
         HTTPHelper::redirectToLibrary();
     } catch (\Exception $e) {
         Trace::addItem(sprintf("Une erreur s'est produite dans \"%s->%s\", TRACE : %s\"", get_class(), __FUNCTION__, $e->getTraceAsString()));
         $this->forward("error", "error", "default");
     }
 }
 public function borrowFromGuestAction()
 {
     try {
         $globalContext = new \Sb\Context\Model\Context();
         if ($this->validateUserInputForm()) {
             $bookForm = new BookForm($_POST);
             // testing if book can be found in db by id
             if ($bookForm->getId()) {
                 $bookInDb = BookDao::getInstance()->get($bookForm->getId());
             }
             // testing if book can be found in db by isbn10, isbn13, asin
             if (!$bookInDb) {
                 $bookInDb = BookDao::getInstance()->getOneByCodes($bookForm->getISBN10(), $bookForm->getISBN13(), $bookForm->getASIN());
             }
             // getting the book data from post and adding to db
             if (!$bookInDb) {
                 // Récupération du Book depuis le POST
                 $bookInDb = new Book();
                 BookMapper::map($bookInDb, $_POST, "book_");
                 // book not in db : need to add it
                 $bookInDb->setCreationDate(new \DateTime());
                 $bookInDb->setLastModificationDate(new \DateTime());
                 BookDao::getInstance()->add($bookInDb);
             }
             if ($bookInDb) {
                 $guestName = ArrayHelper::getSafeFromArray($_POST, "guest_name", null);
                 $guestEmail = ArrayHelper::getSafeFromArray($_POST, "guest_email", null);
                 $guest = new Guest();
                 $guest->setName($guestName);
                 $guest->setEmail($guestEmail);
                 $guest->setCreation_date(new \DateTime());
                 if ($guestEmail) {
                     $friendToBorrowInDb = UserDao::getInstance()->getByEmail($guestEmail);
                     if ($friendToBorrowInDb) {
                         Flash::addItem(sprintf(__("Un utilisateur existe déjà avec l'email que vous avez saisi. Nous vous proposons de lui envoyer une demande d'ami. Vous pourrez ensuite lui emprunter ce livre directement depuis sa bibliothèque. <a class=\"link\" href=\"%s\">Envoyer une demande d'ami</a>", "s1b"), HTTPHelper::Link(Urls::USER_FRIENDS_REQUEST, array("fid" => $friendToBorrowInDb->getId()))));
                         HTTPHelper::redirectToReferer();
                     } else {
                         $token = sha1(uniqid(rand()));
                         // Send invite email
                         $message = __(sprintf("%s vous invite à rejoindre %s, réseau communautaire autour du livre et de la lecture.", sprintf("%s %s", $globalContext->getConnectedUser()->getFirstName(), $globalContext->getConnectedUser()->getLastName()), $_SERVER["SERVER_NAME"]), "s1b");
                         $message .= "<br/><br/>";
                         $message .= sprintf(__("Il a utilisé %s pour noter qu'il vous a emprunté \"%s\"."), Constants::SITENAME, $bookInDb->getTitle());
                         $message .= "<br/><br/>";
                         $message .= __("Venez échanger sur vos lectures et coups de coeur, chercher l'inspiration grâce aux recommandations, gérer et partager votre bibliothèque avec vos amis et trouver dans leurs listes d'envies des idées de cadeaux.");
                         $message .= "<br/><br/>";
                         $subscriptionLink = HTTPHelper::Link(Urls::SUBSCRIBE);
                         $refuseInvitationLink = HTTPHelper::Link(Urls::REFUSE_INVITATION, array("Token" => $token, "Email" => $guestEmail));
                         $message .= sprintf(__("L'inscription est gratuite ! Rejoignez-nous... <a href=\"%s\">S'inscrire</a> ou <a href=\"%s\">Refuser l'invitation</a>"), $subscriptionLink, $refuseInvitationLink);
                         $message .= "<br/><br/>";
                         $message .= sprintf(__("<strong>L'équipe Cherbouquin</strong>", "s1b"), Constants::SITENAME);
                         MailSvc::getInstance()->send($guestEmail, sprintf(__("Invitation à rejoindre %s", "s1b"), Constants::SITENAME), $message);
                         // Create invitation in DB
                         $invitation = new Invitation();
                         $invitation->setSender($globalContext->getConnectedUser());
                         $invitation->setGuest($guest);
                         $invitation->setCreation_date(new \DateTime());
                         $invitation->setToken($token);
                         InvitationDao::getInstance()->add($invitation);
                         Flash::addItem(__("Un email d'invitation a été envoyé à votre ami.", "s1b"));
                     }
                 } else {
                     GuestDao::getInstance()->add($guest);
                 }
                 // Testing if the user has the book in his lib but marked as deleted
                 $userBookBorrower = UserBookDao::getInstance()->getByBookIdAndUserId($globalContext->getConnectedUser()->getId(), $bookInDb->getId());
                 if ($userBookBorrower && $userBookBorrower->getIs_deleted()) {
                     $userBookBorrower->setIs_deleted(false);
                     $userBookBorrower->setLastModificationDate(new \DateTime());
                     UserBookDao::getInstance()->update($userBookBorrower);
                     Flash::addItem(sprintf(__("Vous aviez déjà le livre \"%s\" dans votre bibliothèque mais l'aviez supprimé. Il a été rajouté.", "s1b"), $bookInDb->getTitle()));
                 } else {
                     // Create userbook for connected user
                     $userBookBorrower = new UserBook();
                     $userBookBorrower->setUser($globalContext->getConnectedUser());
                     $userBookBorrower->setBook($bookInDb);
                     $userBookBorrower->setCreationDate(new \DateTime());
                     $userBookBorrower->setBorrowedOnce(true);
                     UserBookDao::getInstance()->add($userBookBorrower);
                     Flash::addItem(__("Le livre a été ajouté à votre bibliothèque.", "s1b"));
                 }
                 $lending = new Lending();
                 $lending->setBorrower_userbook($userBookBorrower);
                 $lending->setGuest($guest);
                 $lending->setCreationDate(new \DateTime());
                 $lending->setState(LendingState::ACTIV);
                 $lending->setStartDate(new \DateTime());
                 LendingDao::getInstance()->add($lending);
             }
             HTTPHelper::redirectToLibrary();
         } else {
             HTTPHelper::redirectToReferer();
         }
     } catch (\Exception $e) {
         Trace::addItem(sprintf("Une erreur s'est produite dans \"%s->%s\", TRACE : %s\"", get_class(), __FUNCTION__, $e->getTraceAsString()));
         $this->forward("error", "error", "default");
     }
 }