/** * Показывает публикацию. Также, если метод POST - обрабатывает форму добавления комментария * * @Route("/show/{publicationId}/{feedType}/{category}", name = "show_publication", defaults = {"feedType" = "main_feed", "category" = "all"}, options = {"expose" = true}) * @Route("/company-show/{groupId}/{publicationId}/{category}", name = "company_publication", defaults = {"feedType" = "company_feed", "category" = "all"}, options = {"expose" = true}) */ public function showPublicationAction(Request $request, $publicationId, $feedType, $category, $groupId = null) { if ($publicationId > 100000) { $publicationId = substr($publicationId, 3); return $this->redirect($this->generateUrl('show_publication', array('publicationId' => $publicationId, 'feedType' => $feedType, 'category' => $category, 'groupId' => $groupId)), 301); } $em = $this->getDoctrine()->getManager(); $security = $this->get('security.context'); $isDoctor = $security->isGranted('ROLE_DOCTOR') || $security->isGranted('ROLE_STUDENT'); $myCalendar = null; $group = $groupId ? $em->getRepository('EvrikaMainBundle:ThematicGroup')->find($groupId) : null; if ($group) { $feedType = 'group_feed'; } $templateParameters = array('group' => $group); $user = $this->getUser(); if ($groupId && $security->isGranted('IS_AUTHENTICATED_REMEMBERED')) { if ($security->isGranted('ROLE_COMPANY')) { if ($user->getCompany()->getId() == $groupId) { $feedType = 'my_company'; $templateParameters['my_company'] = true; $templateParameters['groupId'] = $groupId; $templateParameters['publicationId'] = $publicationId; $templateParameters['category'] = $category; } } else { $templateParameters['inGroup'] = $em->getRepository('EvrikaMainBundle:Doctor')->isGroupSubscriber($groupId, $user->getId()); } } if ($feedType == 'event') { $publication = $em->find('EvrikaMainBundle:Event', $publicationId); $myCalendar = $em->getRepository('EvrikaMainBundle:UserCalendar')->findOneBy(array('user' => $this->getUser(), 'event' => $publication)); if ($myCalendar != null) { $myCalendar = $myCalendar->getId(); } } else { $publication = $em->find('EvrikaMainBundle:Publication', $publicationId); } if (!$publication) { throw $this->createNotFoundException('Публикация не найдена'); } if ($publication->getEnabled() == false) { throw $this->createNotFoundException('Публикация не активна в данный момент'); } if ($feedType != 'event') { $publication->countView(); } $pubCategory = $publication->getCategory(); if (!$isDoctor && ($pubCategory && !$pubCategory->isPublic())) { if ($security->isGranted('IS_AUTHENTICATED_REMEMBERED')) { throw new AccessDeniedException('Извините, у вас нет доступа к этой публикации'); } else { return $this->redirect($this->generateUrl('loginpage')); } } // незарегинный пользователь может оставлять комментарии только в дискуссиях (id = 7) if ($isDoctor || $pubCategory && $pubCategory->getId() == 7) { if ($feedType == 'event') { $comment = new EventComment(); $comment->setEvent($publication); } else { $comment = new PublicationComment(); $comment->setPublication($publication); } if ($isDoctor) { $comment->setAuthor($user); } $commentForm = $this->createForm(new CommentType(), $comment, array('em' => $em, 'anonymus' => !$isDoctor)); if ($request->isMethod('POST')) { $commentForm->bind($request); # если врач забанен - добавляем в форму ошибку $now = new \DateTime(); if ($isDoctor && !$security->isGranted('ROLE_COMPANY') && $user->getBanned() > $now) { $commentForm->addError(new FormError('Вы временно не можете оставлять комментарии по причине бана до ' . $user->getBanned()->format('d.m.Y H:i'))); } elseif ($commentForm->isValid()) { $postedComment = $commentForm->getData(); $bbCodeParser = new \HTML_BBCodeParser2(); $bbCodeParser->addFilter('Basic'); $bbCodeParser->addFilter('Images'); $bbCodeParser->addFilter('Links'); $bbCodeParser->addFilter('Lists'); $postedComment->setText($bbCodeParser->qparse(strip_tags($postedComment->getText()))); $postedComment->setText(preg_replace('/\\[(\\w+)(?!\\w)[^\\]]*\\]((?:(?!\\[\\/\\1).)*?)\\[\\/\\1\\]/i', "", $postedComment->getText())); $postedComment->setText(nl2br($postedComment->getText())); # посчитать комментарий у публикации if ($publication instanceof Publication) { $publication->countComment(); } if ($request->request->get('iBot') != 'Я точно не бот') { $refferer = $request->headers->get('referer'); return $this->redirect($refferer); } $em->persist($postedComment); $em->flush(); $em->refresh($postedComment); $log = new CommentLog(); $log->setUser($this->getUser()); $log->setType($feedType); $logCat = $publication->getCategory()->getId(); $log->setCategory($logCat == null ? $category : $logCat); $em->persist($log); $em->flush(); # уведомление редакторов о добавленном комментарии $message = \Swift_Message::newInstance()->setSubject('Новый комментарий')->setContentType('text/html')->setCharset('utf-8')->setFrom('*****@*****.**', 'Уведомление «Evrika.ru»')->setTo($this->container->getParameter('editor_emails'))->setBody($this->renderView('EvrikaMainBundle:Email:comment_notice.html.twig', array('comment' => $postedComment))); $this->get('mailer')->send($message); # уведомление пользователю, кому ответили (если тот подписан на эти уведомления) if ($parentComment = $postedComment->getParentComment()) { if ($quotedUser = $parentComment->getAuthor()) { if ($quotedUser->getCommentSubscribed()) { $message = \Swift_Message::newInstance()->setSubject('На ваш комментарий ответили')->setContentType('text/html')->setCharset('utf-8')->setFrom('*****@*****.**', 'Уведомление «Evrika.ru»')->setTo($quotedUser->getUsername())->setBody($this->renderView('EvrikaMainBundle:Email:comment_replied.html.twig', array('comment' => $postedComment, 'parentComment' => $parentComment))); $headers = $message->getHeaders(); $headers->addTextHeader('X-Mailru-Msgtype', 'doctor_commented'); $this->get('mailer')->send($message); } # создаем уведомление тому, кого откоментировали $this->get('evrika.notice_manager')->commentCommented($postedComment, $quotedUser); } } # создаем уведомление тому, чью публикацию откоментировали if ($feedType != 'event') { $this->get('evrika.notice_manager')->publicationCommented($postedComment, $publication); } # перенаправляем на комментарий, если он сохранен $url = $groupId ? $this->generateUrl('company_publication', array('groupId' => $groupId, 'publicationId' => $publicationId, 'category' => $category)) . '#comment_' . $postedComment->getId() : $this->generateUrl('show_publication', array('publicationId' => $publicationId, 'feedType' => $feedType, 'category' => $category)) . '#comment_' . $postedComment->getId(); return $this->redirect($url); } } $templateParameters['comment_form'] = $commentForm->createView(); } # находим рекомендуемые к просмотру публикации if ($feedType != 'event') { $readAlso = $em->getRepository('EvrikaMainBundle:Publication')->findReadAlso($publication, $isDoctor); $templateParameters['readAlso'] = $readAlso; } /** * Проверяем если это новость группы, подписан ли на нее пользователь. * Если не подписан, то вместо комментариев выводим сообщение */ $linkEr = null; if ($feedType == 'group_feed') { $links = $this->getUser()->getThematicGroupLinks(); $group = $this->getDoctrine()->getRepository('EvrikaMainBundle:Publication')->findOneById($publicationId)->getThematicGroup(); $linkEr = 1; foreach ($links as $link) { if ($link->getThematicGroup()->getId() == $group->getId()) { $linkEr = null; break; } } } $pubTitle = $publication->getTitle(); $templateParameters['publication'] = $publication; $templateParameters['feedType'] = $group ? 'group_feed' : $feedType; $templateParameters['category'] = $category; $templateParameters['group'] = $group; $templateParameters['bookmarks'] = $this->get('evrika.session_manager')->getBookmarks(); $templateParameters['myCalendar'] = $myCalendar; $templateParameters['isLink'] = $linkEr; # meta title/description/keywords if ($pubCategory) { $metaTitle = $publication->getMetaTitle(); $description = $publication->getDescription(); $keywords = $publication->getKeywords(); $templateParameters['seotitle'] = empty($metaTitle) ? $pubTitle . $pubCategory->getItemSeotitle() : $metaTitle; $templateParameters['description'] = empty($description) ? $pubCategory->getItemDescription() . $pubTitle . '.' : $description; $templateParameters['keywords'] = empty($keywords) ? $pubTitle . $pubCategory->getItemKeywords() : $keywords; } $em->flush(); # если поисковая строка задана - подсвечиваем if ($request->query->has('string')) { $string = $request->query->get('string'); if (!empty($string)) { $body = $publication->getBody(); $title = $publication->getTitle(); $shortText = $publication->getShortText(); $search = preg_replace('/ {2,}/', ' ', $string); //Удаляем лишние пробелы $search = trim($search); $ligua = $this->get('evrika.lingua_stem'); $search = $ligua->stem_string($search); //Удаляем окончания # надо сделать подсветку частей с найденными словами $words = explode(' ', $search); $rep = array('$1<span class="yellow">$2</span>', '<span class="yellow">$0</span>'); foreach ($words as $word) { if (!empty($word)) { $pat = array('/([ ,><\\[\\]\\.\\-\\(\\)])(' . $word . '[a-zа-я]*)/iu', '/^' . $word . '[a-zа-я]*/iu'); $body = preg_replace($pat, $rep, $body); $title = preg_replace($pat, $rep, $title); if (!empty($shortText)) { $shortText = preg_replace($pat, $rep, $shortText); } } } $templateParameters['searchBody'] = $body; $templateParameters['searchTitle'] = $title; if (!empty($shortText)) { $templateParameters['searchShortText'] = $shortText; } } } # если авторизован, надо узнать, лайкал ли публикацию и комментарии публикации if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $templateParameters['hasLiked'] = $em->getRepository('EvrikaMainBundle:User')->hasLikedPublication($publicationId, $user->getId()); } # Open Graph $templateParameters['ogTitle'] = $this->strip($publication->getTitle()); $templateParameters['ogDescription'] = $publication->isEvent() ? $publication->getSourceUrl() : $this->strip($publication->getShortText()); $image = $publication->getImageFile(); if ($image && isset($image['path'])) { $templateParameters['ogImage'] = $image['path']; } return $this->render('EvrikaMainBundle:Index:show_publication.html.twig', $templateParameters); }
/** * Выводит информацию о компании * @Route("/about/{category}/{partnerId}", name = "about", defaults = {"category" = "about", "partnerId" = 0}) */ public function aboutAction($category = "about", $partnerId = 0) { $parameters = array('category' => $category); if ($category == 'partners') { $repository = $this->getDoctrine()->getManager()->getRepository('EvrikaMainBundle:Partner'); if ($partnerId) { $parameters['partner'] = $repository->find($partnerId); } else { $parameters['partners'] = $repository->findBy(array(), array('position' => 'ASC')); } } elseif ($category == 'news' and $partnerId == 0) { $parameters['publications'] = $this->getDoctrine()->getManager()->getRepository('EvrikaMainBundle:Publication')->orderPublications('21'); $parameters['bookmarks'] = $this->get('evrika.session_manager')->getBookmarks(); $parameters['feedType'] = 'fresh_feed'; } elseif ($category == 'news' and $partnerId != 0) { $parameters['publication'] = $this->getDoctrine()->getManager()->getRepository('EvrikaMainBundle:Publication')->findOneById($partnerId); $parameters['bookmarks'] = $this->get('evrika.session_manager')->getBookmarks(); $parameters['feedType'] = 'fresh_feed'; $em = $this->getDoctrine()->getManager(); $security = $this->get('security.context'); if ($security->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $isDoctor = $security->isGranted('ROLE_DOCTOR') || $security->isGranted('ROLE_STUDENT'); $comment = new PublicationComment(); $comment->setPublication($parameters['publication']); $commentForm = $this->createForm(new CommentType(), $comment, array('em' => $em, 'anonymus' => !$isDoctor)); $request = $this->getRequest(); if ($request->isMethod('POST')) { $commentForm->bind($request); if ($commentForm->isValid()) { $postedComment = $commentForm->getData(); $bbCodeParser = new \HTML_BBCodeParser2(); $bbCodeParser->addFilter('Basic'); $bbCodeParser->addFilter('Images'); $bbCodeParser->addFilter('Links'); $bbCodeParser->addFilter('Lists'); $postedComment->setText($bbCodeParser->qparse(strip_tags($postedComment->getText()))); $postedComment->setText(preg_replace('/\\[(\\w+)(?!\\w)[^\\]]*\\]((?:(?!\\[\\/\\1).)*?)\\[\\/\\1\\]/i', "", $postedComment->getText())); $postedComment->setText(nl2br($postedComment->getText())); # посчитать комментарий у публикации if ($parameters['publication'] instanceof Publication) { $parameters['publication']->countComment(); } $em->persist($postedComment); $em->flush(); # уведомление редакторов о добавленном комментарии $message = \Swift_Message::newInstance()->setSubject('Новый комментарий')->setContentType('text/html')->setCharset('utf-8')->setFrom('*****@*****.**', 'Уведомление «Evrika.ru»')->setTo($this->container->getParameter('editor_emails'))->setBody($this->renderView('EvrikaMainBundle:Email:comment_notice.html.twig', array('comment' => $postedComment))); $this->get('mailer')->send($message); # уведомление пользователю, кому ответили (если тот подписан на эти уведомления) if ($parentComment = $postedComment->getParentComment()) { if ($quotedUser = $parentComment->getAuthor()) { if ($quotedUser->getCommentSubscribed()) { $message = \Swift_Message::newInstance()->setSubject('На ваш комментарий ответили')->setContentType('text/html')->setCharset('utf-8')->setFrom('*****@*****.**', 'Уведомление «Evrika.ru»')->setTo($quotedUser->getUsername())->setBody($this->renderView('EvrikaMainBundle:Email:comment_replied.html.twig', array('comment' => $postedComment, 'parentComment' => $parentComment))); $this->get('mailer')->send($message); } } } $url = $this->generateUrl('about', array('category' => $category, 'partnerId' => $partnerId)) . '#comment_' . $postedComment->getId(); return $this->redirect($url); } } $parameters['comment_form'] = $commentForm->createView(); } } $parameters['partnerId'] = $partnerId; return $this->render('EvrikaMainBundle:Info:about.html.twig', $parameters); }