private function addUserBook(\Sb\Db\Model\Book $book, \Sb\Db\Model\User $user, \Sb\Config\Model\Config $config) { $userBookDao = UserBookDao::getInstance(); $userBook = $userBookDao->getByBookIdAndUserId($user->getId(), $book->getId()); // Testing if the user : // - doesn't already have that book or // - have it but is deleted : in this case we will undelete the book if ($userBook && !$userBook->getIs_deleted()) { $returnMsg = __("Vous avez déjà ce livre dans votre bibliothèque.", "s1b"); } else { // Getting current user current nb userbooks in libary $userNbUserBooks = count($user->getNotDeletedUserBooks()); if ($userNbUserBooks >= $config->getMaximumNbUserBooksForPublic()) { $returnMsg = sprintf(__("Vous ne pouvez pas avoir plus de %s livres dans votre bibliothèque.", "s1b"), $config->getMaximumNbUserBooksForPublic()); } else { // Ajout du UserBook $existingUserBook = false; $userBook = UserBookDao::getInstance()->getByBookIdAndUserId($user->getId(), $book->getId()); // testing if the user already had the book but deleted it : // if yes, then the userbook is undeleted if ($userBook && $userBook->getIs_deleted()) { $userBook->setIs_deleted(false); $existingUserBook = true; } else { // Création du UserBoook $userBook = new \Sb\Db\Model\UserBook(); $userBook->setCreationDate(new \DateTime()); } // Updating userbook data $userBook->setLastModificationDate(new \DateTime()); $userBook->setUser($user); $userBook->setBook($book); $bookLink = \Sb\Helpers\HTTPHelper::Link($book->getLink()); // Persisting userbook in DB $addOk = false; if ($existingUserBook) { if (UserBookDao::getInstance()->update($userBook)) { $editUserBookLink = \Sb\Helpers\HTTPHelper::Link(\Sb\Entity\Urls::USER_BOOK_EDIT, array("ubid" => $userBook->getId())); $returnMsg = sprintf(__("Vous aviez déjà le livre \"%s\" dans votre bibliothèque mais l'aviez supprimé. Il a été rajouté.<br/><a class=\"link\" href=\"%s\">Remplir votre fiche de lecture</a> ou <a class=\"link\" href=\"%s\">Voir ce livre</a>", "s1b"), $book->getTitle(), $editUserBookLink, $bookLink); $addOk = true; } } else { if (UserBookDao::getInstance()->add($userBook)) { $editUserBookLink = \Sb\Helpers\HTTPHelper::Link(\Sb\Entity\Urls::USER_BOOK_EDIT, array("ubid" => $userBook->getId())); $returnMsg = sprintf(__("Le livre \"%s\" a été ajouté à votre bibliothèque.<br/><a class=\"link\" href=\"%s\">Remplir votre fiche de lecture</a> ou <a class=\"link\" href=\"%s\">Voir ce livre</a>", "s1b"), $book->getTitle(), $editUserBookLink, $bookLink); $addOk = true; } } if ($addOk) { try { $userEvent = new \Sb\Db\Model\UserEvent(); $userEvent->setItem_id($userBook->getId()); $userEvent->setType_id(\Sb\Entity\EventTypes::USERBOOK_ADD); $userEvent->setUser($user); \Sb\Db\Dao\UserEventDao::getInstance()->add($userEvent); } catch (\Exception $exc) { Trace::addItem("Une erreur s'est produite lors de l'ajout de l'événement suite à l'ajout d'un livre " . $exc->getMessage()); } } } } return $returnMsg; }
/** * 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"); } }
/** * Get last events of a certain type for a user * @param type $userId * @param type $typeId * @return type */ public function getUserLastEventsOfType($userId, $typeId = null, $maxResult = 10) { try { $dataKey = self::USER_LAST_EVENT_OF_TYPE . "_uid_" . $userId . "_tid_" . $typeId . "_m_" . $maxResult; $result = $this->getData($dataKey); if ($result === false) { $result = UserEventDao::getInstance()->getListUserUserEventsOfType($userId, $typeId, $maxResult); // Looping all events and set nested members depending on event type foreach ($result as $event) { switch ($event->getType_id()) { case EventTypes::USERBOOK_REVIEW_CHANGE: $event = $this->getFullBookRelatedUserEvent($event); break; case EventTypes::USER_ADD_FRIEND: $friend = UserDao::getInstance()->get($event->getNew_value()); /* * IMPORTANT !!! */ // Do not remove line below : accessing a property (here username) is done to properly initialize the proxy object $friend->setUserName($friend->getUserName()); // Do not remove line below : set user userbooks list $userbooks = new \Doctrine\Common\Collections\ArrayCollection(UserBookDao::getInstance()->getListAllBooks($friend->getId(), true)); $friend->setUserBooks($userbooks); /** * End IMPORTANT */ if ($friend) { $event->setFriend($friend); } break; default: break; } } $this->setData($dataKey, $result); } return $result; } catch (\Exception $exc) { $this->logException(get_class(), __FUNCTION__, $exc); } }
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"); } }
/** * Show member home page action * @global type $globalContextMe */ public function indexAction() { try { $globalContext = new \Sb\Context\Model\Context(); $globalConfig = new Sb\Config\Model\Config(); /* @var $connectedUser User */ $connectedUser = $globalContext->getConnectedUser(); // Getting friends boh $blowOfHeartFriendsBooks = BookDao::getInstance()->getListBOHFriends($connectedUser->getId()); $this->view->isShowingFriendsBOH = false; if (!$blowOfHeartFriendsBooks || count($blowOfHeartFriendsBooks) < 5) { // Setting class property with array of friend boh books ids to use it in "notInArray" function below $this->blowOfHeartFriendsBooksId = array_map(array(&$this, "getId"), $blowOfHeartFriendsBooks); // Getting all users boh $blowOfHeartBooks = BookSvc::getInstance()->getBOHForUserHomePage(); $blowOfHeartBooks = array_filter($blowOfHeartBooks, array(&$this, "notInArray")); // Merging 2 arrays if ($blowOfHeartFriendsBooks && $blowOfHeartBooks) { $blowOfHeartBooks = array_merge($blowOfHeartFriendsBooks, $blowOfHeartBooks); } $blowOfHeartBooks = array_slice($blowOfHeartBooks, 0, 5); } else { $this->view->isShowingFriendsBOH = true; $blowOfHeartBooks = $blowOfHeartFriendsBooks; } $this->view->blowOfHeartBooks = $blowOfHeartBooks; // Getting friends user events $this->view->userEvents = UserEventDao::getInstance()->getListUserFriendsUserEvents($connectedUser->getId()); // Getting top books $this->view->topsBooks = BookSvc::getInstance()->getTopsUserHomePage(); // Getting last review by friends $lastReviews = UserEventSvc::getInstance()->getFriendsLastEventsOfType($connectedUser->getId(), EventTypes::USERBOOK_REVIEW_CHANGE); $this->view->lastReviews = $lastReviews; $this->view->lastReviewsView = new LastReviews($lastReviews, __("<strong>Dernières critiques postées par vos amis</strong>", "s1b")); // Getting User Reading Widget $allCurrentlyReadingUserBooks = UserBookDao::getInstance()->getCurrentlyReadingsNow($connectedUser->getId()); $userReading = new UserReadingWidget($connectedUser, $allCurrentlyReadingUserBooks, true); // If more than one book as 'being read', we need to set the javascript carousel if (count($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', 270, 210)});</script>\n"); } $this->view->userReading = $userReading; // Getting user wished books widget $userWishedBooks = new UserWishedBooksWidget($connectedUser, true); $this->view->userWishedBooks = $userWishedBooks; // Getting wish list search widget $this->view->wishListSearchWidget = new WishListSearchWidget(); // Getting the ad (second paramters is not used anymore) $this->view->ad = new Ad("user_homepage", "6697829998"); // Getting twitter widget $this->view->twitter = new TwitterWidget(TwitterSvc::getInstance($globalConfig)); // Getting facebook frame $this->view->facebookFrame = new FacebookFrame(); // Get create chronicle links widget if ($connectedUser->getIs_partner() && $connectedUser->getGroupusers()) { $createChroniclesLink = new CreateChroniclesLinks($connectedUser->getGroupusers()); $this->view->createChroniclesLinkView = $createChroniclesLink->get(); } } 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 borrowAction() { try { $globalContext = new \Sb\Context\Model\Context(); $idUserBook = $_GET['ubid']; if ($idUserBook) { $userBook = UserBookDao::getInstance()->get($idUserBook); if ($userBook) { $bookId = $userBook->getBook()->getId(); // We check that the userbook we want to bororow is really owned by a friend $userBookCheck = UserBookDao::getInstance()->getBookInFriendsUserBook($bookId, $globalContext->getConnectedUser()->getId()); if ($userBookCheck) { // We check if the book is owned by the user we want to borrow the book from if ($userBook->getIsOwned()) { // We check that the book is not currently lent (no lending or an inactive lending) if (!$userBook->getActiveLending()) { $existingUserBook = UserBookDao::getInstance()->getByBookIdAndUserId($globalContext->getConnectedUser()->getId(), $bookId); // We check that the connect user doesn't already have the book if ($existingUserBook) { // the user already had that book but had deleted it if ($existingUserBook->getIs_deleted()) { $newUserBook = $existingUserBook; $newUserBook->setIs_deleted(false); $newUserBook->setLastModificationDate(new \DateTime()); $newUserBook->setBorrowedOnce(true); $newUserBookPersisted = UserBookDao::getInstance()->update($newUserBook); Flash::addItem(__("Vous aviez déjà ce livre dans votre bibliothèque mais l'aviez supprimé.", "s1b")); } else { Flash::addItem(__("Vous avez déjà ce livre dans votre bibliothèque.", "s1b")); // Redirect to the main library page HTTPHelper::redirectToLibrary(); } } else { // We create a userbook for the connected user $newUserBook = new UserBook(); $newUserBook->setBook($userBook->getBook()); $newUserBook->setCreationDate(new \DateTime()); $newUserBook->setLastModificationDate(new \DateTime()); $newUserBook->setUser($globalContext->getConnectedUser()); $newUserBook->setBorrowedOnce(true); $newUserBookPersisted = UserBookDao::getInstance()->add($newUserBook); } if ($newUserBookPersisted) { // update lent userbook with Lent Once = 1 $userBook->setLentOnce(true); UserBookDao::getInstance()->update($userBook); // Lending line creation $lending = new Lending(); $lending->setUserbook($userBook); $lending->setBorrower_userbook($newUserBook); $lending->setStartDate(new \DateTime()); $lending->setState(LendingState::ACTIV); $lendingId = LendingDao::getInstance()->Add($lending); // if ok : prepare flash message if ($lendingId) { try { $userEvent = new UserEvent(); $userEvent->setNew_value($lending->getId()); $userEvent->setType_id(EventTypes::USER_BORROW_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()); } Flash::addItem(sprintf(__("Le livre %s a été emprunté à %s et ajouté à votre bibliothèque.", "sharebook"), $userBook->getBook()->getTitle(), $userBook->getUser()->getFirstName() . " " . $userBook->getUser()->getLastName())); } } } else { Flash::addItem(__("Ce livre fait l'objet d'un prêt en cours", "s1b")); } } else { Flash::addItem(__("Ce livre n'est pas possédé par l'utilisateur à qui vous tentez d'emprunter ce livre.", "s1b")); } } else { Flash::addItem(__("Vous n'êtes pas amis avec le propriétaire de ce livre.", "s1b")); } } else { Flash::addItem(__("Le livre que vous voulez emprunter n'existe pas dans la base.", "s1b")); } } // Redirect to the main library page 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"); } }