Ejemplo n.º 1
0
 /**
  *
  * @param type $lastname
  * @param type $firstname
  * @param type $username
  * @param type $email
  * @return \Sb\Db\Model\User
  */
 public function addLightUser($lastname, $firstname, $username, $email, $password)
 {
     $user = null;
     $userTmp = new User();
     // Création du user dans la table s1b_users
     $userTmp->setToken(sha1(uniqid(rand())));
     $userTmp->setEmail($email);
     $userTmp->setFirstName($firstname);
     $userTmp->setLastName($lastname);
     $userTmp->setPassword(sha1($password));
     $userTmp->setUserName($username);
     $userTmp->setToken(sha1(uniqid(rand())));
     $userTmp->setDeleted(false);
     $userTmp->setActivated(false);
     $userTmp->setConnexionType(\Sb\Entity\ConnexionType::SHARE1BOOK);
     $userTmp->setGender("");
     $userTmp->setFacebookLanguage("");
     $userTmp->setTokenFacebook("");
     $userTmp->setPicture("");
     $userTmp->setPictureBig("");
     $setting = new UserSetting();
     UserSettingHelper::loadDefaultSettings($setting);
     $userTmp->setSetting($setting);
     $user = UserDao::getInstance()->add($userTmp);
     return $user;
 }
 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.º 3
0
 public function __construct()
 {
     $this->setBaseDirectory(BASE_PATH);
     $this->setBaseUrl(BASE_URL);
     $this->setDefaultImage(\Sb\Helpers\BookHelper::getDefaultImage());
     // Set context param user
     $userId = \Sb\Authentification\Service\AuthentificationSvc::getInstance()->getConnectedUserId();
     if ($userId) {
         $user = \Sb\Db\Dao\UserDao::getInstance()->get($userId);
         $this->setConnectedUser($user);
     }
 }
Ejemplo n.º 4
0
 public function get()
 {
     $globalContext = \Sb\Context\Model\Context::getInstance();
     $tplHeader = new Template("header");
     $baseUrl = Urls::USER_LIBRARY;
     if ($globalContext->getIsShowingFriendLibrary()) {
         $baseUrl = Urls::FRIEND_LIBRARY;
     }
     $variables = array("allBooksUrl" => HTTPHelper::Link($baseUrl, array("key" => LibraryListKeys::ALL_BOOKS_KEY, "reset" => 1)), "borrowedBooksUrl" => HTTPHelper::Link($baseUrl, array("key" => LibraryListKeys::BORROWED_BOOKS_KEY, "reset" => 1)), "lendedBooksUrl" => HTTPHelper::Link($baseUrl, array("key" => LibraryListKeys::LENDED_BOOKS_KEY, "reset" => 1)), "wishedBooksUrl" => HTTPHelper::Link($baseUrl, array("key" => LibraryListKeys::WISHED_BOOKS_KEY, "reset" => 1)), "myBooksUrl" => HTTPHelper::Link($baseUrl, array("key" => LibraryListKeys::MY_BOOKS_KEY, "reset" => 1)), "friendLibrary" => false);
     if ($globalContext->getIsShowingFriendLibrary()) {
         $friend = UserDao::getInstance()->get($this->friendUserId);
         $variables["friendLibrary"] = true;
         $variables["friendUserName"] = $friend->getFirstName();
     }
     $tplHeader->setVariables($variables);
     $this->setActiveTab($tplHeader, $this->key);
     return $tplHeader->output();
 }
 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;
 }
Ejemplo n.º 6
0
 public function createWelcomeMessage($userId)
 {
     $siteName = \Sb\Entity\Constants::SITENAME;
     $title = __("Bienvenue au sein de la communauté", "s1b") . " " . $siteName;
     $body = __("Bonjour,", "s1b") . "<br/><br/>";
     $body .= __("Merci d'avoir rejoint", "s1b") . " " . $siteName . "<br/>";
     $body .= __("Toute l'équipe espère que vous profiterez pleinement des fonctionnalités du site, à savoir:", "s1b") . "<br/>";
     $body .= __("* partager vos lectures avec vos amis", "s1b") . "<br/>";
     $body .= __("* leurs recommander un coup de coeur", "s1b") . "<br/>";
     $body .= __("* trouver vos prochaines lectures grâce à leurs conseils", "s1b") . "<br/>";
     $body .= __("* suivre les livres que vous prêtez ou que vous avez emprunté", "s1b") . "<br/>";
     $body .= __("* utiliser les bibliothèques de vos amis, surtout leurs envies de lecture, pour leurs faire un cadeau réussi", "s1b") . "<br/><br/>";
     $body .= __("Bref, cette liste n'est pas exhaustive et nous espérons que vous nous aiderez à continuer à vous proposer de nouvelles fonctionnalités, par exemple en proposant à vos amis de rejoindre", "s1b") . " " . $siteName . "." . "<br/>";
     $body .= '<a href=' . \Sb\Helpers\HTTPHelper::Link(\Sb\Entity\Urls::USER_FRIENDS_FIND) . ' onclick="newInvite(); return false;">' . __("Inviter vos amis de Facebook à rejoindre", "s1b") . " " . $siteName . '</a>' . "<br/>";
     $body .= __("Bonne expérience.", "s1b") . "<br/><br/>";
     $body .= __("L'équipe", "s1b") . " " . $siteName;
     $message = new \Sb\Db\Model\Message();
     $message->setMessage($body);
     $message->setTitle($title);
     $message->setIs_read(false);
     $message->setRecipient(\Sb\Db\Dao\UserDao::getInstance()->get($userId));
     $message->setSender(\Sb\Db\Dao\UserDao::getInstance()->get(1));
     return \Sb\Db\Dao\MessageDao::getInstance()->add($message);
 }
Ejemplo n.º 7
0
 /**
  * Define if connected user can access another user library
  * @param $userId
  * @return bool
  */
 private function canAccessLibrary($userId)
 {
     $requestedUser = UserDao::getInstance()->get($userId);
     $requestingUser = UserDao::getInstance()->get($this->getContext()->getConnectedUser()->getId());
     return SecurityHelper::IsUserAccessible($requestedUser, $requestingUser);
 }
Ejemplo n.º 8
0
 public function get()
 {
     $baseTpl = "book/bookForm/lending/lendingForm";
     $tpl = new \Sb\Templates\Template($baseTpl);
     $tpl->set("bookId", $this->book->getId());
     $tpl->set("ubid", $this->userBook->getId());
     // Préparation de la zone de formulaire
     // ------------------------------------
     $lendingText = "";
     $warningText = "";
     if ($this->activeLending) {
         $this->setTemplateFormFields($tpl, $this->activeLending->getId(), "CURRENT", "");
         $startDate = $this->activeLending->getStartDate()->format(__("d/m/Y", "s1b"));
         $borrowerName = $this->activeLending->getBorrower_userbook()->getUser()->getFirstName() . " " . $this->activeLending->getBorrower_userbook()->getUser()->getLastName();
         $lendingText = sprintf(__("Vous prêtez actuellement ce livre à %s depuis le %s", "s1b"), $borrowerName, $startDate);
         $button1Text = __("Terminer le prêt", "s1b");
         switch ($this->activeLending->getState()) {
             case \Sb\Lending\Model\LendingState::WAITING_INACTIVATION:
                 $warningText = __("En attente de validation de retour de votre part.", "s1b");
                 break;
             default:
                 $warningText = "";
                 break;
         }
     } elseif ($this->activeBorrowing) {
         $this->setTemplateFormFields($tpl, $this->activeBorrowing->getId(), "CURRENT", "");
         $startDate = $this->activeBorrowing->getStartDate()->format(__("d/m/Y", "s1b"));
         if ($this->activeBorrowing->getUserBook()) {
             $lenderName = $this->activeBorrowing->getUserBook()->getUser()->getFirstName() . " " . $this->activeBorrowing->getUserBook()->getUser()->getLastName();
         } elseif ($this->activeBorrowing->getGuest()) {
             $lenderName = sprintf("%s (invité)", $this->activeBorrowing->getGuest()->getName());
         }
         $lendingText = sprintf(__("Vous empruntez actuellement ce livre à %s depuis le %s", "s1b"), $lenderName, $startDate);
         switch ($this->activeBorrowing->getState()) {
             case \Sb\Lending\Model\LendingState::WAITING_INACTIVATION:
                 $warningText = __("En attente de validation de retour de la part du prêteur.", "s1b");
                 break;
             default:
                 $button1Text = __("Terminer le prêt", "s1b");
                 $warningText = "";
                 break;
         }
     } elseif ($this->userBook->getIsOwned()) {
         $this->setTemplateFormFields($tpl, "", "NEW");
         $user = \Sb\Db\Dao\UserDao::getInstance()->get($this->connectedUserId);
         $userFriends = $user->getAcceptedFriends();
         $options = "";
         // si l'user a des amis, construire le liste des options
         $oneFriendAtLeast = false;
         if ($userFriends) {
             foreach ($userFriends as $userFriend) {
                 $oneFriendAtLeast = true;
                 $options .= "<option value=" . $userFriend->getId() . ">" . $userFriend->getFirstName() . " " . $userFriend->getLastName() . "</option>";
             }
         }
         if (!$oneFriendAtLeast) {
             $lendingText = __("Vous n'avez pas encore d'amis.", "s1b");
         } else {
             $friendSelection = sprintf(__("Vous souhaitez prêter ce livre à <select name=\"BorrowerId\">%s</select><input type=\"hidden\" name=\"State\" value=\"1\" />", "s1b"), $options);
             $button1Text = __("Démarrer le prêt", "s1b");
         }
     } else {
         $this->setTemplateFormFields($tpl, "", "");
         $lendingText = __("Vous ne pouvez pas prêter ce livre car vous ne le possédez pas.", "s1b");
     }
     $variables = array("lendingText" => $lendingText, "warningText" => $warningText);
     if (isset($friendSelection)) {
         $variables["friendSelection"] = $friendSelection;
     } else {
         $variables["friendSelection"] = null;
     }
     if (isset($button1Text)) {
         $variables["button1Text"] = $button1Text;
     } else {
         $variables["button1Text"] = "";
     }
     $tpl->setVariables($variables);
     return $tpl->output();
 }
Ejemplo n.º 9
0
 private function setFriendsSelectionInModel()
 {
     if ($this->getParam("Friends")) {
         $friendSelectionsIds = $this->getParam("Friends");
         $friendList = array();
         $friendIdList = "";
         foreach ($friendSelectionsIds as $friendSelection) {
             $friend = UserDao::getInstance()->get($friendSelection);
             $friendList[] = $friend;
             $friendIdList .= $friend->getId() . ",";
         }
         // Add to model
         $this->view->friendList = $friendList;
         $this->view->friendIdList = $friendIdList;
     }
 }
Ejemplo n.º 10
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.º 11
0
 public function get()
 {
     $globalContext = new \Sb\Context\Model\Context();
     $tplEvent = new \Sb\Templates\Template("userEvents/userEvent");
     $friend = $this->userEvent->getUser();
     $friendImg = UserHelper::getSmallImageTag($friend);
     if ($friendImg == "") {
         $friendImg = UserHelper::getSmallImageTag($friend);
     }
     $friendName = $friend->getUserName();
     $friendProfileLink = HTTPHelper::Link(Urls::USER_PROFILE, array("uid" => $friend->getId()));
     $userBookRelated = false;
     $friendRelated = false;
     // used for cases of new friend event
     $additionalContent = "";
     $friendId = null;
     $friendFriendImg = null;
     $friendFriendProfileLink = null;
     switch ($this->userEvent->getType_id()) {
         case EventTypes::USERBOOK_ADD:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a ajouté un livre.", $friendProfileLink, $friendName);
             $userBookRelated = true;
             break;
         case EventTypes::USERBOOK_RATING_CHANGE:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $newRating = $this->userEvent->getNew_value();
             $resume = sprintf("<div class=\"ue-rating-label\"><a href=\"%s\" class=\"link\">%s</a> a noté.</div> <div class=\"rating rating-" . $newRating . "\"></div>", $friendProfileLink, $friendName);
             $userBookRelated = true;
             break;
         case EventTypes::USERBOOK_BLOWOFHEART_CHANGE:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $isBoh = $this->userEvent->getNew_value();
             $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a supprimé son coup de coeur.", $friendProfileLink, $friendName);
             if ($isBoh) {
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a marqué comme coup de coeur.", $friendProfileLink, $friendName);
             }
             $userBookRelated = true;
             break;
         case EventTypes::USERBOOK_REVIEW_CHANGE:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $oldReview = $this->userEvent->getOld_value();
             $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a modifié son commentaire.", $friendProfileLink, $friendName);
             if ($oldReview == "") {
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a ajouté un commentaire.", $friendProfileLink, $friendName);
             }
             $additionalContent = StringHelper::tronque(strip_tags($this->userEvent->getNew_value()), 120);
             $userBookRelated = true;
             break;
         case EventTypes::USERBOOK_HYPERLINK_CHANGE:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $oldHyperLink = $this->userEvent->getOld_value();
             $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a modifié son lien hypertexte.", $friendProfileLink, $friendName);
             if ($oldHyperLink == "") {
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a ajouté un lien hypertexte.", $friendProfileLink, $friendName);
             }
             $hyperLink = "http://" . $this->userEvent->getNew_value();
             $truncatedHyperLink = \Sb\Helpers\StringHelper::tronque($hyperLink, 100);
             $additionalContent = sprintf(__("<a href=\"%s\" target=\"_blank\" class=\"hyperlink link\" >%s</a>", "s1b"), $hyperLink, $truncatedHyperLink);
             $userBookRelated = true;
             break;
         case EventTypes::USERBOOK_READINGSTATE_CHANGE:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $newReadingSateId = $this->userEvent->getNew_value();
             switch ($newReadingSateId) {
                 case ReadingStates::NOTREAD:
                     $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a marqué non lu.", $friendProfileLink, $friendName);
                     break;
                 case ReadingStates::READING:
                     $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> lit actuellement.", $friendProfileLink, $friendName);
                     break;
                 case ReadingStates::READ:
                     $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a lu.", $friendProfileLink, $friendName);
                     break;
             }
             $userBookRelated = true;
             break;
         case EventTypes::USERBOOK_WISHEDSTATE_CHANGE:
             $userBook = \Sb\Db\Dao\UserBookDao::getInstance()->get($this->userEvent->getItem_id());
             $newWishedSateValue = $this->userEvent->getNew_value();
             $oldWishedSateValue = $this->userEvent->getOld_value();
             if ($newWishedSateValue) {
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a marqué comme souhaité.", $friendProfileLink, $friendName);
             } elseif ($oldWishedSateValue) {
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> ne souhaite plus.", $friendProfileLink, $friendName);
             }
             $userBookRelated = true;
             break;
         case EventTypes::USER_ADD_FRIEND:
             $friendNewFriendProfileLink = null;
             $newFriendId = $this->userEvent->getNew_value();
             if ($this->getContext()->getConnectedUser() && $newFriendId == $this->getContext()->getConnectedUser()->getId()) {
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> est ami avec moi.", $friendProfileLink, $friendName);
                 $friendFriendImg = UserHelper::getXSmallImageTag($this->getContext()->getConnectedUser());
             } else {
                 $friendNewFriend = UserDao::getInstance()->get($newFriendId);
                 $friendNewFriendProfileLink = HTTPHelper::Link(Urls::USER_PROFILE, array("uid" => $friendNewFriend->getId()));
                 $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> est ami avec <a class=\"link\" href=\"%s\">%s</a>.", $friendProfileLink, $friendName, $friendNewFriendProfileLink, $friendNewFriend->getUserName());
                 $friendFriendImg = UserHelper::getXSmallImageTag($friendNewFriend);
             }
             $friendId = $newFriendId;
             $friendFriendProfileLink = $friendNewFriendProfileLink;
             $friendRelated = true;
             break;
         case EventTypes::USER_BORROW_USERBOOK:
             $lendingId = $this->userEvent->getNew_value();
             $lending = LendingDao::getInstance()->get($lendingId);
             $userBookBorrowed = $lending->getUserBook();
             $userBook = $userBookBorrowed;
             $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a emprunté le livre à %s.", $friendProfileLink, $friendName, $userBookBorrowed->getUser()->getUserName());
             if ($this->getContext()->getConnectedUser()) {
                 if ($userBookBorrowed->getUser()->getId() == $this->getContext()->getConnectedUser()->getId()) {
                     $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> m'a emprunté le livre.", $friendProfileLink, $friendName);
                 }
             }
             $userBookRelated = true;
             break;
         case EventTypes::USER_LEND_USERBOOK:
             $lendingId = $this->userEvent->getNew_value();
             $lending = LendingDao::getInstance()->get($lendingId);
             $userBookLended = $lending->getBorrower_UserBook();
             $userBook = $userBookLended;
             $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> a prêté le livre à %s.", $friendProfileLink, $friendName, $userBookLended->getUser()->getUserName());
             if ($this->getContext()->getConnectedUser()) {
                 if ($userBookLended->getUser()->getId() == $this->getContext()->getConnectedUser()->getId()) {
                     $resume = sprintf("<a href=\"%s\" class=\"link\">%s</a> m'a prêté le livre.", $friendProfileLink, $friendName);
                 }
             }
             $userBookRelated = true;
             break;
         default:
             break;
     }
     $creationDate = $this->userEvent->getCreation_date()->format(__("d/m/Y à H:m", "s1b"));
     $bookImageUrl = null;
     $bookLink = null;
     $bookTitle = null;
     $bookAuthor = null;
     $bookId = null;
     $bookImgTag = null;
     if ($userBookRelated) {
         $bookImageUrl = $userBook->getBook()->getSmallImageUrl();
         $bookImgTag = BookHelper::getSmallImageTag($userBook->getBook(), $this->getContext()->getDefaultImage());
         $bookLink = HTTPHelper::Link($userBook->getBook()->getLink());
         $bookTitle = $userBook->getBook()->getTitle();
         $bookAuthor = $userBook->getBook()->getOrderableContributors();
         $bookId = $userBook->getBook()->getId();
     }
     $showAddButton = false;
     if ($globalContext->getConnectedUser()) {
         $showAddButton = true;
     }
     // Set variables
     $tplEvent->setVariables(array("friendImg" => $friendImg, "friendName" => $friendName, "resume" => $resume, "bookImageUrl" => $bookImageUrl, "bookImgTag" => $bookImgTag, "friendProfileLink" => $friendProfileLink, "friendId" => $friendId, "bookTitle" => $bookTitle, "bookId" => $bookId, "bookAuthor" => $bookAuthor, "creationDate" => $creationDate, "bookLink" => $bookLink, "additionalContent" => $additionalContent, "userBookRelated" => $userBookRelated, "userFriendRelated" => $friendRelated, "friendFriendImg" => $friendFriendImg, "friendFriendProfileLink" => $friendFriendProfileLink, "showOwner" => $this->showOwner, "showAddButton" => $showAddButton));
     return $tplEvent->output();
 }
Ejemplo n.º 12
0
 private function checkUserIsMemberOfGroup($groupId)
 {
     $globalContext = new \Sb\Context\Model\Context();
     /* @var $user User */
     $user = UserDao::getInstance()->get($globalContext->getConnectedUser()->getId());
     $found = false;
     foreach ($user->getGroupusers() as $groupUser) {
         /* @var $groupUser GroupUser */
         if ($groupUser->getGroup()->getId() == $groupId) {
             $found = true;
             break;
         }
     }
     if (!$found) {
         Flash::addItem(__("Vous ne pouvez pas éditer de chronique pour ce groupe.", "s1b"));
         HTTPHelper::redirectToReferer();
     }
 }
Ejemplo n.º 13
0
 /**
  * Return a chronicle from a user id and a book id
  *
  * @param unknown $userId
  * @param unknown $bookId
  * @param string $useCache
  * @return \Sb\Db\Dao\Ambigous|NULL
  */
 public function getChronicle($userId, $bookId, $useCache = true)
 {
     try {
         $results = null;
         if ($useCache) {
             $key = self::CHRONICLE_FROM_USER_BOOK . "_uid_" . $userId . "_bid_" . $bookId;
             $result = $this->getData($key);
         }
         if (!isset($results) || $results === false) {
             $criteria["user"] = array(true, "=", UserDao::getInstance()->get($userId));
             $criteria["book"] = array(true, "=", BookDao::getInstance()->get($bookId));
             $result = $this->getDao()->getList($criteria, array('id' => 'DESC'), 1);
         }
         if ($useCache) {
             $this->setData($key, $results);
         }
         if (is_array($result) && count($result) > 0) {
             return $result[0];
         }
         return null;
     } catch (\Exception $e) {
         $this->logException(get_class(), __FUNCTION__, $e);
     }
     return $results;
 }
Ejemplo n.º 14
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.º 15
0
 /**
  * Called when submitting password
  */
 public function submitPasswordAction()
 {
     try {
         $globalContext = new \Sb\Context\Model\Context();
         /* @var $user \Sb\Db\Model\User */
         $user = $globalContext->getConnectedUser();
         $this->view->user = $user;
         $this->view->userSettings = $user->getSetting();
         if ($_POST) {
             $Password_modif = trim($_POST['Password_modif']);
             $Password_old_crypted = sha1(trim($_POST['Password_old']));
             $Password_modif_crypted = sha1(trim($_POST['Password_modif']));
             // On teste si l'utilisateur à déjà un mot de passe
             // --> si oui il est inscrit via le formulaire share1Book
             // --> si non il est inscrit via Facebook Connect
             $redirect = false;
             // No password for user
             if (!$user->getPassword()) {
                 if (strlen($Password_modif) >= 8) {
                     // update password
                     $user->setPassword($Password_modif_crypted);
                     UserDao::getInstance()->update($user);
                     // set flash message
                     Flash::addItem(__("Vos modifications ont bien été enregistrées.", "s1b"));
                     $redirect = true;
                 } else {
                     // password not long enough
                     Flash::addItem(__("Le mot de passe doit contenir au moins 8 caractères", "s1b"));
                 }
             } else {
                 // on teste si l'ancien mot de passe est bon
                 if ($user->getPassword() == $Password_old_crypted) {
                     //On verifie que le mot de passe a 8 caracteres ou plus
                     if (strlen($Password_modif) >= 8) {
                         // update password
                         $user->setPassword($Password_modif_crypted);
                         UserDao::getInstance()->update($user);
                         // set flash message
                         Flash::addItem(__("Vos modifications ont bien été enregistrées.", "s1b"));
                         $redirect = true;
                     } else {
                         //Sinon, on dit que le mot de passe n'est pas assez long
                         Flash::addItem(__("Le mot de passe doit contenir au moins 8 caractères", "s1b"));
                     }
                 } else {
                     Flash::addItem(__("Votre ancien mot de passe n'est pas correct", "s1b"));
                 }
             }
             if ($redirect) {
                 HTTPHelper::redirect(Urls::MY_PROFILE);
             } else {
                 HTTPHelper::redirect(Urls::USER_PROFILE_EDIT_PASSWORD);
             }
         }
     } 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.º 16
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");
     }
 }
Ejemplo n.º 17
0
 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");
     }
 }
Ejemplo n.º 18
0
 public function wishListAction()
 {
     try {
         $globalContext = new \Sb\Context\Model\Context();
         $user = $globalContext->getConnectedUser();
         if ($user) {
             // Get friend list for friend selection form
             $friends = $user->getAcceptedFriends();
             // Order the friends list by firstname asc
             if ($friends && count($friends) > 0) {
                 usort($friends, array($this, "compareFirstName"));
             }
             $this->view->friends = $friends;
             $this->view->user = $user;
         }
         $selectedFriendId = ArrayHelper::getSafeFromArray($_GET, "friendId", null);
         $selectedFriend = null;
         if ($selectedFriendId) {
             $selectedFriend = UserDao::getInstance()->get($selectedFriendId);
             $this->view->selectedFriend = $selectedFriend;
             $friendBooks = $selectedFriend->getNotDeletedUserBooks();
             $friendWishedBooks = array_filter($friendBooks, array($this, "isWished"));
             $this->view->friendWishedBooks = $friendWishedBooks;
         }
     } 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.º 19
0
 /**
  * Get a list of books that also liked by the people who like the book passed, the list is cached for 1 day
  * @param type $bookId
  * @return a array of Book
  */
 public function getBooksAlsoLiked($bookId, $useCache = true)
 {
     $result = null;
     if ($useCache) {
         $key = self::BOOKS_ALSO_LIKED . "_bid_" . $bookId;
         $result = $this->getData($key);
     }
     if (!isset($result) || $result === false) {
         // Get the users who liked that book
         $usersWhoLiked = UserDao::getInstance()->getListWhoLikesBooks(array($bookId));
         if (count($usersWhoLiked) > 0) {
             // Get the ids
             $usersWhoLikedIds = array_map(array(&$this, "getId"), $usersWhoLiked);
             // Get the books these user liked
             $booksLikedByUsers = BookDao::getInstance()->getListLikedByUsers($usersWhoLikedIds);
             if (count($booksLikedByUsers) > 0) {
                 // Setting the current viewed book
                 $this->currentViewedBook = BookDao::getInstance()->get($bookId);
                 $result = $booksLikedByUsers;
                 // Removing the current viewed book
                 $result = array_filter($result, array(&$this, "isNotCurrentViewedBook"));
                 // Removing the books with same authors
                 $result = array_filter($result, array(&$this, "hasNotSameContributors"));
             }
         }
         if ($useCache) {
             $this->setData($key, $result);
         }
     }
     return $this->getRandomNumber($result, 5);
 }
Ejemplo n.º 20
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.º 21
0
 /**
  * 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);
     }
 }