public function searchListAction()
 {
     // Check the form validity
     $form = new WishListSearchForm();
     if (!$form->isValid($_GET)) {
         Flash::addItems($form->getFailureMessages());
         HTTPHelper::redirectToReferer();
     } else {
         $searchTerm = $this->_getParam('wishedListSearchTerm', "");
         Trace::addItem($searchTerm);
         $users = UserDao::getInstance()->getListByKeywordAndWishedUserBooks($searchTerm);
         // Remove connected user and admin user
         $cleanedUsers = $this->cleanUsersList($users);
         // Display specific message when connected user found in list
         if ($this->connectedUSerFound) {
             Flash::addItem(__("Si vous cherchez votre liste, c'est raté ;-) La surprise n'en sera que plus grande.", "s1b"));
         }
         if (count($cleanedUsers) == 0) {
             // Getting user without wish list
             $usersWithoutWishList = UserDao::getInstance()->getListByKeyword($searchTerm);
             $cleanedUsersWithoutWishList = $this->cleanUsersList($usersWithoutWishList);
             if (count($cleanedUsersWithoutWishList) != 0) {
                 Flash::addItem(sprintf(__("Aucun utilisateur '%s' n'a créé de liste d'envies ou bien sa liste est privée.", "s1b"), $searchTerm));
             } else {
                 Flash::addItem(__("Aucun utilisateur ne correspond à votre recherche.", "s1b"));
             }
             HTTPHelper::redirectToReferer();
         }
         $this->view->users = $cleanedUsers;
         $this->view->form = $form;
     }
 }
Ejemplo n.º 2
0
 public function searchAction()
 {
     $searchTerm = ArrayHelper::getSafeFromArray($_REQUEST, "searchTerm", null);
     if (strlen($searchTerm) <= 2) {
         Flash::addItem(__("Votre terme de recherche doit être constitué de plus de 2 caractères.", "s1b"));
         HTTPHelper::redirectToReferer();
     }
     $_SESSION[SessionKeys::SEARCH_A_BOOK_PAGE_ID] = 1;
     $bookSearch = $this->getBooks(true, $searchTerm, 1);
     if (!$bookSearch->getHasResults()) {
         // Redirect to home
         $this->redirectToHome();
     } else {
         // Redirect to show page
         HTTPHelper::redirect(Urls::BOOK_SEARCH_SHOW, array("searchTerm" => $searchTerm));
     }
 }
 /**
  * Action called when posting press reviews subscription form
  */
 public function postAction()
 {
     try {
         // Form is not posted correctly, we redirect to the previous page
         if (!$this->getRequest()->isPost()) {
             Flash::addItem(__("Requête invalide.", "s1b"));
             return HTTPHelper::redirectToReferer();
         }
         // Check the form validity
         $form = new PressReviewsSusbcriptionForm();
         if (!$form->isValid($_POST)) {
             Flash::addItems($form->getFailureMessages());
         } else {
             // Try to get an existing PressReviewsSubscriber
             /* @var $existingPressReviewSubscriber PressReviewsSubscriber */
             $existingPressReviewSubscriber = PressReviewsSubscriberDao::getInstance()->getByEmail($form->getEmail());
             if ($existingPressReviewSubscriber) {
                 // Update press reviews subscriber (reactivation)
                 $existingPressReviewSubscriber->setIs_deleted(false);
                 PressReviewsSubscriberDao::getInstance()->update($existingPressReviewSubscriber);
                 // Set success flash message
                 Flash::addItem(__("Votre abonnement a été réactivé.", "s1b"));
             } else {
                 // Add press reviews subscriber to database
                 $pressReviewsSubscribers = new PressReviewsSubscriber();
                 $pressReviewsSubscribers->setEmail($form->getEmail());
                 PressReviewsSubscriberDao::getInstance()->add($pressReviewsSubscribers);
                 // Set success flash message
                 Flash::addItem(__("Votre abonnement a bien été pris en compte.", "s1b"));
             }
         }
         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");
     }
 }
Ejemplo n.º 4
0
 public function sendAction()
 {
     return;
     try {
         $globalContext = new \Sb\Context\Model\Context();
         $user = $globalContext->getConnectedUser();
         $friends = $user->getFriendsForEmailing();
         $nbRecipients = count($friends);
         if ($nbRecipients <= 0) {
             Flash::addItem(__("Pas de destinataire possible. Vous devez ajouter des amis pour pouvoir envoyer des messages.", "s1b"));
             HTTPHelper::redirectToReferer();
         }
         $friendSelectionsFromPost = ArrayHelper::getSafeFromArray($_POST, 'selection', null);
         $friendSelectionsFromGet = ArrayHelper::getSafeFromArray($_GET, 'selection', null);
         $sendingMessage = ArrayHelper::getSafeFromArray($_POST, 'go', null);
         $friendList = null;
         if ($friendSelectionsFromGet || $friendSelectionsFromPost || $sendingMessage) {
             // coming from friend selection page
             if ($friendSelectionsFromPost || $friendSelectionsFromGet) {
                 if ($friendSelectionsFromPost) {
                     $friendSelectionsIds = ArrayHelper::getSafeFromArray($_POST, 'Friends', null);
                 } elseif ($friendSelectionsFromGet) {
                     $fid = ArrayHelper::getSafeFromArray($_GET, 'Friends', null);
                     if ($fid) {
                         $friendSelectionsIds = array($fid);
                     }
                 }
                 if ($friendSelectionsIds) {
                     $friendList = array();
                     $friendIdList = "";
                     foreach ($friendSelectionsIds as $friendSelection) {
                         $friend = UserDao::getInstance()->get($friendSelection);
                         $friendList[] = $friend;
                         $friendIdList .= $friend->getId() . ",";
                     }
                     $this->view->friendList = $friendList;
                     $this->view->friendIdList = $friendIdList;
                 }
             } elseif ($sendingMessage) {
                 // Validating the mailing form
                 if (!empty($_POST['Title']) && !empty($_POST['Message']) && !empty($_POST['IdAddressee'])) {
                     $titleVal = trim($_POST['Title']);
                     $messageVal = trim($_POST['Message']);
                     $recipients = ArrayHelper::getSafeFromArray($_POST, 'IdAddressee', null);
                     $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(__("Un message vous a été envoyé depuis le site %s", "s1b"), Constants::SITENAME), $body);
                                 }
                             }
                         }
                     }
                     Flash::addItem(__("Message envoyé.", "s1b"));
                     HTTPHelper::redirect(Urls::USER_MAILBOX);
                 } else {
                     Flash::addItem(__("Au moins l'un des champs n'est pas rempli", "s1b"));
                 }
             }
         }
     } 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");
     }
 }
Ejemplo n.º 5
0
 /**
  * Shows friends search
  */
 public function searchAction()
 {
     try {
         $allUsers = UserDao::getInstance()->getAll();
         $allUsers = array_filter($allUsers, array(&$this, "isNotDeleted"));
         $this->view->nbUsers = count($allUsers);
         $this->view->query = null;
         if ($_GET) {
             $this->view->query = ArrayHelper::getSafeFromArray($_GET, 'q', null);
             if (strpos($this->view->query, "%") !== false && strlen($this->view->query) == 1) {
                 Flash::addItem(__("Le caractère % n'est pas autorisé lors des recherches.", "s1b"));
                 HTTPHelper::redirectToReferer();
             }
             if ($this->view->query) {
                 $foundUsers = \Sb\Db\Dao\UserDao::getInstance()->getListByKeyword($this->view->query);
                 $foundUsers = array_filter($foundUsers, array(&$this, "isNotMe"));
                 $foundUsers = array_filter($foundUsers, array(&$this, "isNotAdmin"));
                 $foundUsers = array_filter($foundUsers, array(&$this, "isNotDeleted"));
                 if ($foundUsers && count($foundUsers) > 0) {
                     // preparing pagination
                     $paginatedList = new PaginatedList($foundUsers, 9);
                     $this->view->firstItemIdx = $paginatedList->getFirstPage();
                     $this->view->lastItemIdx = $paginatedList->getLastPage();
                     $this->view->nbItemsTot = $paginatedList->getTotalPages();
                     $this->view->navigation = $paginatedList->getNavigationBar();
                     $this->view->foundUsers = $paginatedList->getItems();
                 }
             }
         }
     } 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");
     }
 }
Ejemplo n.º 6
0
 public function profileAction()
 {
     $globalContext = new \Sb\Context\Model\Context();
     // Users profile are only accessible for connected users
     AuthentificationSvc::getInstance()->checkUserIsConnected();
     $noUser = true;
     $friendId = $this->_getParam("uid");
     if ($friendId) {
         $friend = UserDao::getInstance()->get($friendId);
         $this->view->friend = $friend;
         if ($friend) {
             $noUser = false;
             if ($friend->getId() == $globalContext->getConnectedUser()->getId()) {
                 Flash::addItem(__("Il s'agit de votre profil!", "s1b"));
                 HTTPHelper::redirectToReferer();
             } else {
                 $requestingUser = $globalContext->getConnectedUser();
                 if (SecurityHelper::IsUserAccessible($friend, $requestingUser)) {
                     $this->view->friendSetting = $friend->getSetting();
                     $this->view->isFriend = UserSvc::getInstance()->areUsersFriends($globalContext->getConnectedUser(), $friend);
                     // getting currently reading or lastly read books
                     $currentlyReading = UserBookDao::getInstance()->getReadingNow($friend->getId());
                     $lastlyReads = UserBookDao::getInstance()->getListLastlyRead($friend->getId());
                     if ($currentlyReading && $lastlyReads) {
                         $this->view->currentlyReadingOrLastlyReadBooks = array_merge(array($currentlyReading), $lastlyReads);
                     } elseif ($lastlyReads) {
                         $this->view->currentlyReadingOrLastlyReadBooks = $lastlyReads;
                     } elseif ($currentlyReading) {
                         $this->view->currentlyReadingOrLastlyReadBooks = array($currentlyReading);
                     }
                     // Getting friend currently reading user books
                     $this->view->allCurrentlyReadingUserBooks = UserBookDao::getInstance()->getCurrentlyReadingsNow($friend->getId());
                     if (count($this->view->allCurrentlyReadingUserBooks) > 1) {
                         $this->view->placeholder('footer')->append("<script src=\"" . $globalContext->getBaseUrl() . 'Resources/js/simple-carousel/simple.carousel.js' . "\"></script>\n");
                         $this->view->placeholder('footer')->append("<script>\$(function() {initCarousel('carousel-currentreadings', 298, 190)});</script>\n");
                     }
                     // Getting friend last boh books
                     $bohUserBooks = UserBookDao::getInstance()->getListUserBOH($friend->getId());
                     $this->view->bohBooks = array_map(array($this, "getBook"), $bohUserBooks);
                     // Getting books friend could like
                     $this->view->booksHeCouldLikes = BookSvc::getInstance()->getBooksUserCouldLike($friend->getId());
                     if ($this->view->booksHeCouldLikes && count($this->view->booksHeCouldLikes) > 0) {
                         $this->view->placeholder('footer')->append("<script src=\"" . $globalContext->getBaseUrl() . 'Resources/js/waterwheel-carousel/jquery.waterwheelCarousel.min.js' . "\"></script>\n");
                         $this->view->placeholder('footer')->append("<script>\$(function() {initCoverFlip('bookUserCouldLike', 90)});</script>\n");
                     }
                     // Getting friend's friends last reviews
                     $this->view->friendLastReviews = UserEventSvc::getInstance()->getUserLastEventsOfType($friend->getId(), EventTypes::USERBOOK_REVIEW_CHANGE);
                     // Getting friend last friends added events
                     $this->view->friendLastFriendsAddedEvents = UserEventSvc::getInstance()->getUserLastEventsOfType($friend->getId(), EventTypes::USER_ADD_FRIEND);
                     if (count($this->view->friendLastFriendsAddedEvents) > 1) {
                         $this->view->placeholder('footer')->append("<script src=\"" . $globalContext->getBaseUrl() . 'Resources/js/simple-carousel/simple.carousel.js' . "\"></script>\n");
                         $this->view->placeholder('footer')->append("<script>\$(function() {initCarousel('carousel-friendlastfriends', 298, 85)});</script>\n");
                     }
                     // Getting friend last events
                     $this->view->friendLastEvents = UserEventSvc::getInstance()->getUserLastEventsOfType($friend->getId(), null, 15);
                     $this->view->placeholder('footer')->append("<script>\n\n                            toInit.push(\"attachUserEventsExpandCollapse()\");\n\n                            function attachUserEventsExpandCollapse() {_attachExpandCollapseBehavior(\"js_userLastEvents\", \"userEvent\", \"Voir moins d'activités\", \"Voir plus d'activités\");}\n\n                        </script>\n");
                 } else {
                     Flash::addItem(__("Vous ne pouvez pas accéder à ce profil.", "s1b"));
                     HTTPHelper::redirectToReferer();
                 }
             }
         }
     }
     if ($noUser) {
         Flash::addItem(__("Cet utilisateur n'existe pas.", "s1b"));
         HTTPHelper::redirectToReferer();
     }
 }
Ejemplo n.º 7
0
 public function facebookLogAction()
 {
     try {
         $globalConfig = new Sb\Config\Model\Config();
         $accountDeleted = __("Votre compte a été supprimé.", "s1b");
         $home = HTTPHelper::Link("");
         $loginFaceBook = HTTPHelper::Link(Urls::LOGIN_FACEBOOK);
         // Testing if user is facebook connected
         $facebookSvc = new FacebookSvc($globalConfig->getFacebookApiId(), $globalConfig->getFacebookSecret(), $loginFaceBook, $home);
         $facebookUser = $facebookSvc->getUser();
         if ($facebookUser) {
             // If yes, testing if a user exist in db (and not deleted)
             // Search a matching activated user in DB
             $faceBookEmail = $facebookUser->getEmail();
             $facebookId = $facebookUser->getUid();
             $userInDB = \Sb\Db\Dao\UserDao::getInstance()->getFacebookUser($faceBookEmail);
             if (!$userInDB) {
                 // If no existing user => create an account and redirect to user homepage
                 // create user in db
                 $userFromFB = new User();
                 UserMapper::mapFromFacebookUser($userFromFB, $facebookUser);
                 $userFromFB->setToken(sha1(uniqid(rand())));
                 $userFromFB->setDeleted(false);
                 $setting = new UserSetting();
                 UserSettingHelper::loadDefaultSettings($setting);
                 $userFromFB->setSetting($setting);
                 $userInDB = UserDao::getInstance()->add($userFromFB);
                 // send confirmation email
                 $subject = sprintf(__("Votre compte %s a été créé avec Facebook", "s1b"), Constants::SITENAME);
                 MailSvc::getInstance()->send($userInDB->getEmail(), $subject, MailHelper::faceBookAccountCreationEmailBody($userInDB->getFirstName()));
                 // Test if the email matches invitations and set them to accepted and validated
                 InvitationSvc::getInstance()->setInvitationsAccepted($userInDB->getEmail());
                 // Send warning email to webmaster
                 MailSvc::getInstance()->send(\Sb\Entity\Constants::WEBMASTER_EMAIL . ", berliozd@gmail.com, rebiffe_olivier@yahoo.fr", __("nouveau user via facebook", "s1b"), $userInDB->getEmail());
                 // send message in user internal mailbox
                 MessageSvc::getInstance()->createWelcomeMessage($userInDB->getId());
                 // redirect to user homepage
                 AuthentificationSvc::getInstance()->loginSucces($userInDB);
             } elseif ($userInDB->getDeleted()) {
                 // In user deleted, display a message and redirect to referer
                 Flash::addItem($accountDeleted);
                 $facebookSvc->cleanUser();
                 $facebookUser = null;
                 $faceBookEmail = null;
                 $facebookId = null;
                 HTTPHelper::redirectToReferer();
             } else {
                 // If yes => connect and redirect to user homepage
                 if (!$userInDB->getConnexionType() != ConnexionType::FACEBOOK) {
                     $userInDB->setConnexionType(ConnexionType::FACEBOOK);
                 }
                 if (!$userInDB->getFacebookId()) {
                     $userInDB->setFacebookId($facebookUser->getUid());
                 }
                 if (!$userInDB->getPicture()) {
                     $userInDB->setPicture($facebookUser->getPic_small());
                 }
                 if (!$userInDB->getPictureBig()) {
                     $userInDB->setPictureBig($facebookUser->getPic());
                 }
                 if (!$userInDB->getFacebookLanguage()) {
                     $userInDB->setFacebookLanguage($facebookUser->getLocale());
                 }
                 if (!$userInDB->getGender()) {
                     $userInDB->setGender($facebookUser->getSex());
                 }
                 if (!$userInDB->getCity()) {
                     $userInDB->setCity($facebookUser->getHometown_location());
                 }
                 if (!$userInDB->getBirthDay()) {
                     $userInDB->setBirthDay($facebookUser->getBirthday());
                 }
                 $userInDB->setLastLogin(new \DateTime());
                 UserDao::getInstance()->update($userInDB);
                 AuthentificationSvc::getInstance()->loginSucces($userInDB);
             }
         } else {
             // If no, redirect to facebook login page
             HTTPHelper::redirectToUrl($facebookSvc->getFacebookLogInUrl());
         }
     } 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");
     }
 }
Ejemplo n.º 8
0
 public function friendLibraryAction()
 {
     try {
         // Set friend library data
         $this->setFriendLibaryData();
         $key = $this->getListKey();
         // Get the list key (allBooks, wishedBooks, etc...)
         $fullKey = $this->formateListKey($key);
         // Reset the list options (sorting, searching, paging, filtering) if requested
         if (ArrayHelper::getSafeFromArray($_GET, "reset", false)) {
             $this->resetListOption($fullKey);
         }
         $filteringOrSearching = array_key_exists("searchvalue", $_GET) || array_key_exists("filter", $_GET) && array_key_exists("filtertype", $_GET);
         // Get the books
         $books = UserBookSvc::getInstance()->getUserBooks($key, $this->getContext()->getLibraryUserId(), $filteringOrSearching);
         // Set list meta data if getting list first time
         if (!$filteringOrSearching) {
             $this->setListMetaData($books, $fullKey);
         }
         // Set filtering and searching options
         if ($filteringOrSearching) {
             $this->setFilteringAndSearching($fullKey);
         }
         $booksTableView = $this->createBookTableView($key, $books, false);
         $this->view->list = new BookListView($key, $booksTableView, $key);
         $this->view->header = new LibraryHeader($this->getContext()->getLibraryUserId(), $key);
         $this->view->friendLibrary = $this->getContext()->getIsShowingFriendLibrary();
     } catch (\Exception $e) {
         Flash::addItem($e->getMessage());
         HTTPHelper::redirectToReferer();
     }
 }
Ejemplo n.º 9
0
 /**
  * The default action - show a chronicle detail page
  */
 public function indexAction()
 {
     try {
         // Get chronicle id from request
         $chronicleId = $this->getParam("cid");
         // Get chronicle page
         $chroniclePage = ChroniclePageSvc::getInstance()->get($chronicleId);
         if ($chroniclePage) {
             // Check chronicle validity
             if (!$chroniclePage->getChronicle()->getIs_validated()) {
                 Flash::addItem(__("La chronique que vous souhaitez consulter n'existe pas.", "s1b"));
                 HTTPHelper::redirectToReferer();
             }
             // Increment chronicle nb views
             $this->incrementChronicleNbViews($chroniclePage->getChronicle()->getId());
             // Add main chronicle view model to model view
             $chronicleView = new ChronicleDetail($this->getRequest(), $chroniclePage->getChronicleViewModel());
             $this->view->chronicle = $chronicleView->get();
             // Get similar chronicles (with same tag or with similar keywords) and add it to model view
             $similarChronicles = $chroniclePage->getSimilarChronicles();
             if ($similarChronicles && count($similarChronicles) > 0) {
                 $otherChoniclesSameTypeView = new OtherChroniclesSameType($similarChronicles);
                 $this->view->otherChoniclesSameType = $otherChoniclesSameTypeView->get();
             }
             // Get same author chronicles and add it to model view
             if ($chroniclePage->getSameAuthorChronicles()) {
                 $authorChroniclesView = new ChroniclesBlock($chroniclePage->getSameAuthorChronicles(), __("<strong>Chroniques</strong> du même auteur", "s1b"));
                 // Add author chronicles to model
                 $this->view->authorChroniclesView = $authorChroniclesView->get();
             }
             // Get press reviews
             if ($chroniclePage->getPressReviews()) {
                 $pressReviewsView = new BookPressReviews($chroniclePage->getPressReviews());
                 $this->view->pressReviewsView = $pressReviewsView->get();
             }
             // Get reviews and add it to model view
             if ($chroniclePage->getUserBooksReviews()) {
                 $paginatedList = new PaginatedList($chroniclePage->getUserBooksReviews(), 5);
                 $reviewsView = new BookReviews($paginatedList, $chroniclePage->getChronicle()->getBook()->getId());
                 $this->view->reviews = $reviewsView->get();
             }
             // Get video press review and add it to view model
             if ($chroniclePage->getVideoPressReview()) {
                 $this->view->videoUrl = $chroniclePage->getVideoPressReview()->getLink();
             }
             //
             // Add common items to model view
             $this->addCommonItemsToModelView();
             // Set SEO information
             $headerInformation = HeaderInformationSvc::getInstance()->getForChroniclePage($chroniclePage);
             $this->view->tagTitle = $headerInformation->getTitle();
             $this->view->metaDescription = $headerInformation->getDescription();
             $this->view->metaKeywords = $headerInformation->getKeywords();
             $this->view->urlCanonical = $headerInformation->getUrlCanonical();
             $this->view->pageImage = $headerInformation->getPageImage();
         } else {
             Flash::addItem(__("La chronique que vous souhaitez consulter n'existe pas.", "s1b"));
             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");
     }
 }
Ejemplo n.º 10
0
 private function checkUserCanEditChronicle(Chronicle $chronicle)
 {
     $globalContext = new \Sb\Context\Model\Context();
     $chronicleGroupId = $chronicle->getGroup()->getId();
     $found = false;
     foreach ($globalContext->getConnectedUser()->getGroupusers() as $groupUser) {
         /* @var $groupUser GroupUser */
         if ($groupUser->getGroup()->getId() == $chronicleGroupId) {
             $found = true;
             break;
         }
     }
     if (!$found) {
         Flash::addItem(__("Vous ne pouvez pas éditer cette chronique.", "s1b"));
         HTTPHelper::redirectToReferer();
     }
 }
Ejemplo n.º 11
0
 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");
     }
 }
Ejemplo n.º 12
0
 private function getBook($bookId)
 {
     if (!$bookId) {
         Flash::addItem(__("Vous devez sélectionner un livre.", "s1b"));
         HTTPHelper::redirectToReferer();
     }
     $book = BookDao::getInstance()->get($bookId);
     if (!$book) {
         Flash::addItem(__("Le livre n'existe pas.", "s1b"));
         HTTPHelper::redirectToReferer();
     }
     return $book;
 }