/**
  * Transforms an object to a string (id).
  *
  * @param  Publication|null $publication
  * @return string
  */
 public function transform($publication)
 {
     if (null === $publication) {
         return '';
     }
     return $publication->getId();
 }
Example #2
0
 /**
  * Показывает форму добавления публикации если HTTP-метод - GET. Обрабатывает форму если HTTP-метод - POST
  *
  * @Route("/post/{feedType}/{id}/{action}", name = "post", defaults = {"action" = "", "feedType" = "any", "id" = "0"}, options = {"expose" = true})
  * @Secure(roles = "ROLE_DOCTOR, ROLE_STUDENT, ROLE_COMPANY")
  */
 public function postAction($feedType, $id, $action)
 {
     $em = $this->getDoctrine()->getManager();
     $publication = new Publication();
     $publication->setAuthor($this->getUser());
     if ($feedType == 'group_feed') {
         $group = $em->getRepository('EvrikaMainBundle:ThematicGroup')->find($id);
         $publication->setThematicGroup($group);
     }
     $user = $this->getUser();
     $publicationForm = $this->createForm(new PublicationType(), $publication, array('em' => $em, 'user' => $user, 'id' => $id));
     $request = $this->getRequest();
     if ($request->isMethod('POST')) {
         $publicationForm->bind($request);
         # если пользователь забанен - добавляем в форму ошибку
         $r = $user->getRoles();
         if ($r[0] = 'ROLE_DOCTOR' && $user instanceof Doctor) {
             $now = new \DateTime();
             $banned = $user->getBanned();
             if ($banned > $now) {
                 $publicationForm->addError(new FormError('Вы временно не можете добавлять публикации по причине бана до ' . $banned->format('d.m.Y H:i')));
             }
         }
         if ($publicationForm->isValid()) {
             $publication = $publicationForm->getData();
             $rootDir = '/var/www/evrika.ru/upload/publication';
             $files = $request->files->get('crm_mainbundle_user');
             //				if (isset($files['typeCardFile']) && $files['typeCardFile']['file'] != null){
             //					$typeCardFile = $files['typeCardFile']['file'];
             //					$info = new \SplFileInfo($typeCardFile->getClientOriginalName());
             //					$ex = $info->getExtension();
             //					$filename = time().'.'.$ex;
             //					$typeCardFile->move($rootDir, $filename);
             //
             //					$publication->setImageFile($this->getImgToArray($filename));
             //				}
             if ($action == 'preview') {
                 return $this->render('EvrikaMainBundle:Index:show_publication.html.twig', array('publication' => $publication, 'publication_form' => $publicationForm->createView(), 'preview' => true, 'feedType' => $feedType));
             } elseif ($action != 'edit') {
                 $em->persist($publication);
                 $em->flush();
                 // $cb = Codebird::getInstance();
                 // /*foreach($publication->getSearchTags() as $tag)
                 // {
                 // 	$tags[] = $tag->getText();
                 // }*/
                 // $tags = [];
                 //       $tags = explode(",",$publication->getKeywords());
                 //       $lineTag = "";
                 //       //publication
                 //       $title = $publication->getTitle();
                 //       $link = "evrika.ru/show/".$publication->getId();
                 //       //counter
                 //       $cLink = mb_strlen($link);
                 //       $cTitle = mb_strlen($title);
                 //       if(($cLink+$cTitle+1) < 140)  {
                 //           foreach($tags as $tag) {
                 //               $lin = " #".str_replace(" ","",str_replace("-","",$this->sentence_case($tag)))."";
                 //               if(($cLink+$cTitle+1)+mb_strlen($lin) < 140) {
                 //                   $lineTag .= $lin;
                 //               }
                 //           }
                 //       } else {
                 //           $title = mb_substr($title, 0, trim($cTitle-(($cLink+$cTitle+4)-140)),'UTF-8')."...";
                 //       }
                 //       $params = array(
                 //           'status' => $title." ".$link."".$lineTag,
                 //       );
                 // $cb->statuses_update($params);
                 $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:publication_notice.html.twig', array('publication' => $publication)));
                 $this->get('mailer')->send($message);
                 return $this->redirect($this->generateUrl('show_publication', array('publicationId' => $publication->getId())));
             }
         }
     }
     return $this->render('EvrikaMainBundle:Post:post.html.twig', array('publication_form' => $publicationForm->createView()));
 }
Example #3
0
    /**
     * Находим рекомендуемые к просмотру публикации
     * @param Publication $publication
     * @param bool $includeRestricted
     * @param int $limit
     * @return array
     */
    public function findReadAlso($publication, $includeRestricted = false, $limit = 4)
    {
        $em = $this->getEntityManager();
        $id = $publication->getId();
        $publications = array();
        $restrictedCategoriesDQL = $includeRestricted ? '' : ' AND c.public = 1';
        # получаем идентификаторы тегов публикации
        foreach ($publication->getSearchTags() as $tag) {
            $tagIds[] = $tag->getId();
        }
        # берем публикации по этим тегам (до лимита)
        if (!empty($tagIds)) {
            $publications = $em->createQuery('SELECT p
				FROM EvrikaMainBundle:Publication p
				LEFT JOIN p.searchTags s
				LEFT JOIN p.category c
				WHERE s.id IN(:tagIds)
					AND p.id != :id AND p.enabled = TRUE AND p.created < CURRENT_TIMESTAMP() ' . $restrictedCategoriesDQL . ' GROUP BY p.id' . ' ORDER BY p.created DESC					')->setParameters(array('id' => $id, 'tagIds' => $tagIds))->setMaxResults((int) $limit / 2)->getResult();
        }
        # получаем идентификаторы найденных публикаций, чтоб не повторяться с последующей выборкой
        $dqlNotIn = '';
        if (!empty($publications)) {
            $publicationIds = [];
            foreach ($publications as $p) {
                $publicationIds[] = $p->getId();
            }
            $publicationIdsStr = implode(',', $publicationIds);
            $dqlNotIn = empty($publicationIds) ? '' : " AND p . id NOT IN({$publicationIdsStr})";
        }
        # получаем идентификаторы специальностей публикации
        foreach ($publication->getSpecialties() as $specialty) {
            $specialtyIds[] = $specialty->getId();
        }
        # берем пару последних публикаций по этим специальностям
        if (!empty($specialtyIds)) {
            $publicationsBySpecialty = $em->createQuery('SELECT p
				FROM EvrikaMainBundle:Publication p
				LEFT JOIN p.specialties s
				LEFT JOIN p.category c
				WHERE s.id IN(:specialtyIds) AND
					p.id != :id AND
					p.enabled = TRUE AND
					p.created < CURRENT_TIMESTAMP()' . $dqlNotIn . $restrictedCategoriesDQL . 'GROUP BY p.id
				 ORDER BY p.created DESC')->setParameters(array('id' => $id, 'specialtyIds' => $specialtyIds))->setMaxResults($limit - count($publications))->getResult();
            $publications = array_merge($publications, $publicationsBySpecialty);
        }
        # если мы до сих пор не собрали нужное количество (limit) - добираем последними публикациями
        if (count($publications) < $limit) {
            # получаем идентификаторы найденных публикаций, чтоб не повторяться с последующей выборкой
            $dqlNotIn = '';
            if (!empty($publications)) {
                $publicationIds = [];
                foreach ($publications as $p) {
                    $publicationIds[] = $p->getId();
                }
                $publicationIdsStr = implode(',', $publicationIds);
                $dqlNotIn = empty($publicationIds) ? '' : " AND p . id NOT IN({$publicationIdsStr})";
            }
            $publicationsByDate = $em->createQuery('SELECT p
				FROM EvrikaMainBundle:Publication p
				LEFT JOIN p.category c
				WHERE p.id != :id AND
					p.id != :id AND
					p.enabled = TRUE
					AND p.created < CURRENT_TIMESTAMP() ' . $dqlNotIn . $restrictedCategoriesDQL . ' ORDER BY p.created DESC')->setParameter('id', $id)->setMaxResults($limit - count($publications))->getResult();
            $publications = array_merge($publications, $publicationsByDate);
        }
        return $publications;
    }