vendor/elements/blog-bundle/src/Controller/BlogController.php line 23

Open in your IDE?
  1. <?php
  2. namespace Elements\Bundle\BlogBundle\Controller;
  3. use Carbon\Carbon;
  4. use Elements\Bundle\BlogBundle\Tools\BlogBundleGenerator;
  5. use Pimcore\Controller\FrontendController;
  6. use Pimcore\Google\Cse;
  7. use Pimcore\Logger;
  8. use Pimcore\Model\DataObject\BlogBundleArticle;
  9. use Pimcore\Model\DataObject\BlogBundleAuthor;
  10. use Pimcore\Model\DataObject\BlogBundleCategory;
  11. use Pimcore\Model\DataObject\BlogBundleConfig;
  12. use Pimcore\Model\Document\Page;
  13. use Symfony\Component\EventDispatcher\GenericEvent;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Knp\Component\Pager\Paginator;
  18. use Knp\Component\Pager\PaginatorInterface;
  19. use Doctrine\DBAL\Query\QueryBuilder;
  20. class BlogController extends FrontendController
  21. {
  22.     /**
  23.      * @param Request $request
  24.      * @throws \Exception
  25.      */
  26.     public function overviewAction(Request $requestPaginatorInterface $paginator): \Symfony\Component\HttpFoundation\JsonResponse|Response
  27.     {
  28.         if ($this->document) {
  29.             $config $this->document->getProperty('blog_config');
  30.         }
  31.         if (!$config) {
  32.             $configListing = new BlogBundleConfig\Listing();
  33.             $config $configListing->current();
  34.         }
  35.         $sorting null;
  36.         $articles = new BlogBundleArticle\Listing();
  37.         $articles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  38.         if ($request->get('from'false)) {
  39.             $articles->addConditionParam('publishDate > :from', ['from' => Carbon::createFromTimeString($request->get('from'))->getTimestamp()]);
  40.         }
  41.         if ($request->get('to'false)) {
  42.             $articles->addConditionParam('publishDate < :to', ['to' => Carbon::createFromTimeString($request->get('to'))->getTimestamp()]);
  43.         }
  44.         if ($request->get('q''') != '') {
  45.             $articles->addConditionParam('(title LIKE :search OR shortDescription LIKE :search)', ['search' => '%' $request->get('q') . '%'] );
  46.         }
  47.         if ($request->get('category')){
  48.             $articles->addConditionParam('categories LIKE "%,' intval($request->get('category')) . ',%"');
  49.         }
  50.          if ($request->get('categories', [])) {
  51.             $orCondition = [];
  52.             foreach ($request->get('categories', []) as $category) {
  53.                 if($category) {
  54.                     $orCondition[] = 'categories LIKE "%,' intval($category) . ',%"';
  55.                 }
  56.             }
  57.             if(!empty($orCondition)) {
  58.                 $articles->addConditionParam('(' implode(' OR ',  $orCondition) . ')');
  59.             }
  60.         }
  61.         if ($config) {
  62.             if ($config->getIsMultiSite()) {
  63.                 $articles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  64.             }
  65.             $sorting $config->getSorting();
  66.         }
  67.         if (!$sorting) {
  68.             $sorting 'topArticle DESC, publishDate DESC';
  69.         }
  70.         $articles->setOrderKey($sortingfalse);
  71.         $params = [
  72.             'config' => $config
  73.         ];
  74.         $eventParams = [
  75.             'articleListing' => $articles,
  76.             'params' => $params
  77.         ];
  78.         $eventDispatcher \Pimcore::getEventDispatcher();
  79.         /** @var GenericEvent $articleListingEvent */
  80.         $articleListingEvent $eventDispatcher->dispatch(new GenericEvent('articleListing'$eventParams), 'articleListing');
  81.         if ($articleListingEvent->hasArgument('articleListing')) {
  82.             $articles $articleListingEvent->getArgument('articleListing');
  83.         }
  84.         if ($articleListingEvent->hasArgument('params')) {
  85.             $params $articleListingEvent->getArgument('params');
  86.         }
  87.         $paginator $paginator->paginate($articles$request->get('page'1), $config && $config->getItemsPerPage() ? $config->getItemsPerPage() : 4);
  88.         if ($config) {
  89.             if ($config->getPageRange()) {
  90.                 $paginator->setPageRange($config->getPageRange());
  91.             }
  92.         }
  93.         $params['paginator'] = $paginator;
  94.         if ($request->isXmlHttpRequest()) {
  95.             $html $this->renderView('@ElementsBlog/Includes/articlesContainer.html.twig'$params);
  96.             return $this->json(['success' => true'html' => $html]);
  97.         }
  98.         return $this->render('@ElementsBlog/Blog/overview.html.twig'$params);
  99.     }
  100.     /**
  101.      * @param Request $request
  102.      * @throws \Exception
  103.      */
  104.     public function detailAction(Request $request): \Symfony\Component\HttpFoundation\Response
  105.     {
  106.         if ($this->document) {
  107.             $config $this->document->getProperty('blog_config');
  108.         }
  109.         if (!$config) {
  110.             $configListing = new BlogBundleConfig\Listing();
  111.             $config $configListing->current();
  112.         }
  113.         $article BlogBundleArticle::getById($request->get('id'));
  114.         if ($request->get('pimcore_object_preview') == '' || !$article instanceof BlogBundleArticle) {
  115.             if (!$article instanceof BlogBundleArticle || !$article->isPublished() || $article->getPublishDate()->timestamp time()) {
  116.                 throw new NotFoundHttpException('The requested Article doesn\'t exist (anymore)');
  117.             }
  118.         }
  119.         if ($request->get('pimcore_object_preview') != '') {
  120.             $this->addResponseHeader'x-robots-tag''noindex,nofollow');
  121.         }
  122.         $relatedArticlesCount $config $config->getRelatedArticlesCount() : null;
  123.         if ($relatedArticlesCount === null) {
  124.             $relatedArticlesCount 3;
  125.         }
  126.         $sorting $config $config->getSorting() : 'topArticle DESC, publishDate DESC';
  127.         if(empty($article->getRelatedArticles())) {
  128.             $relatedArticles = new BlogBundleArticle\Listing();
  129.             $relatedArticles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  130.             $relatedArticles->addConditionParam('o_id != :id', ['id' => $article->getId()]);
  131.             $condition = [];
  132.             foreach ($article->getCategories() ?? [] as $category) {
  133.                 $ignoreCategory false;
  134.                 if($config
  135.                     && method_exists($category'getSite')
  136.                     && !empty($category->getSite())
  137.                     && !in_array($config->getId(), $category->getSite())
  138.                 ) {
  139.                     $ignoreCategory true;
  140.                 }
  141.                 if(!$ignoreCategory) {
  142.                     $condition[] = 'categories LIKE "%,' $category->getId() . ',%"';
  143.                 }
  144.             }
  145.             if (count($condition)) {
  146.                 $relatedArticles->addConditionParam('(' implode(' OR '$condition) . ')');
  147.             }
  148.             if ($config) {
  149.                 if ($config->getIsMultiSite()) {
  150.                     $relatedArticles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  151.                 }
  152.             }
  153.             $relatedArticles->setOrderKey($sortingfalse);
  154.             $relatedArticles->setLimit($relatedArticlesCount 3);
  155.             $relatedArticles->setOrderKey('RAND(' Carbon::now()->hour ')'false);
  156.             $count $relatedArticles->getCount();
  157.             $relatedArticles->setOrderKey('RAND(' Carbon::now()->hour ')'false);
  158.             $relatedArticles $relatedArticles->load();
  159.         } else { // use manual articles
  160.             $relatedArticles $article->getRelatedArticles();
  161.             $count count($relatedArticles);
  162.         }
  163.         $articles = [];
  164.         if ($count $relatedArticlesCount) {
  165.             $articlesArray $relatedArticles;
  166.             for ($i 0$i $relatedArticlesCount$i++) {
  167.                 $articles[] = $articlesArray[$i];
  168.             }
  169.         } else {
  170.             $notIds = [$article->getId()];
  171.             foreach ($relatedArticles as $relatedArticle) {
  172.                 $articles[] = $relatedArticle;
  173.                 $notIds[] = $relatedArticle->getId();
  174.             }
  175.             if (!$article->getNotfillWithRandomTeaser() && $count $relatedArticlesCount) {
  176.                 $fillArticles = new BlogBundleArticle\Listing();
  177.                 $fillArticles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  178.                 $fillArticles->addConditionParam('o_id NOT IN (' implode(','$notIds) . ')');
  179.                 if ($config) {
  180.                     $fillArticles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  181.                 }
  182.                 $fillArticles->setOrderKey($sortingfalse);
  183.                 $fillArticles->setLimit($relatedArticlesCount $count);
  184.                 foreach ($fillArticles as $fillArticle) {
  185.                     $articles[] = $fillArticle;
  186.                 }
  187.             }
  188.         }
  189.         return $this->render('@ElementsBlog/Blog/detail.html.twig', [
  190.             'article' => $article,
  191.             'articles' => $articles,
  192.             'config' => $config
  193.         ]);
  194.     }
  195.     /**
  196.      * @param Request $request
  197.      * @return array
  198.      * @throws \Exception
  199.      */
  200.     public function categoryAction(Request $requestPaginatorInterface $paginator): \Symfony\Component\HttpFoundation\JsonResponse|Response
  201.     {
  202.         if ($this->document) {
  203.             $config $this->document->getProperty('blog_config');
  204.         }
  205.         if (!$config) {
  206.             $configListing = new BlogBundleConfig\Listing();
  207.             $config $configListing->current();
  208.         }
  209.         $category BlogBundleCategory::getById($request->get('id'));
  210.         if (!$category instanceof BlogBundleCategory || !$category->isPublished()) {
  211.             throw new NotFoundHttpException('The requested Category doesn\'t exist (anymore)');
  212.         }
  213.         $articles = new BlogBundleArticle\Listing();
  214.         $articles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  215.         if ($request->get('from'false)) {
  216.             $articles->addConditionParam('publishDate > :from', ['from' => Carbon::createFromTimeString($request->get('from'))->getTimestamp()]);
  217.         }
  218.         if ($request->get('to'false)) {
  219.             $articles->addConditionParam('publishDate < :to', ['to' => Carbon::createFromTimeString($request->get('to'))->getTimestamp()]);
  220.         }
  221.         if ($request->get('q''') != '') {
  222.             $articles->addConditionParam('(title LIKE :search OR shortDescription LIKE :search)', ['search' => '%' $request->get('q') . '%'] );
  223.         }
  224.         $articles->addConditionParam('categories LIKE :categoryId', ['categoryId' => "%," $category->getId() . ",%"]);
  225.         if ($config) {
  226.             if ($config->getIsMultiSite()) {
  227.                 $articles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  228.             }
  229.             $sorting $config->getSorting();
  230.         }
  231.         if (!$sorting) {
  232.             $sorting 'topArticle DESC, publishDate DESC';
  233.         }
  234.         $articles->setOrderKey($sortingfalse);
  235.         $paginator $paginator->paginate($articles$request->get('page'1),$config->getItemsPerPage() ?? 4);
  236.         if ($config){
  237.             if ($config->getPageRange()) {
  238.                 $paginator->setPageRange($config->getPageRange());
  239.             }
  240.         }
  241.         $params['paginator'] = $paginator;
  242.         $params['category'] = $category;
  243.         $params['config'] = $config;
  244.         if ($request->isXmlHttpRequest()) {
  245.             $html $this->renderView('@ElementsBlog/Includes/articlesContainer.html.twig'$params);
  246.             return $this->json(['success' => true'html' => $html]);
  247.         }
  248.         return $this->render('@ElementsBlog/Blog/category.html.twig'$params);
  249.     }
  250.     /**
  251.      * @param Request $request
  252.      * @return array
  253.      * @throws \Exception
  254.      */
  255.     public function archiveAction(Request $requestPaginatorInterface $paginator): \Symfony\Component\HttpFoundation\Response
  256.     {
  257.         if ($this->document) {
  258.             $config $this->document->getProperty('blog_config');
  259.         }
  260.         if (!$config) {
  261.             $configListing = new BlogBundleConfig\Listing();
  262.             $config $configListing->current();
  263.         }
  264.         if (!intval($request->get('year'))) {
  265.             throw new NotFoundHttpException('The requested Archive date is invalid');
  266.         }
  267.         if (intval($request->get('month'))) {
  268.             $dateFrom Carbon::createFromDate($request->get('year'), $request->get('month'));
  269.             $dateFrom->startOfMonth();
  270.             $dateTo = clone $dateFrom;
  271.             $dateTo->endOfMonth();
  272.         } else {
  273.             $dateFrom Carbon::createFromDate($request->get('year'));
  274.             $dateFrom->startOfYear();
  275.             $dateTo = clone $dateFrom;
  276.             $dateTo->endOfYear();
  277.         }
  278.         $articles = new BlogBundleArticle\Listing();
  279.         $articles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  280.         $articles->addConditionParam('publishDate > :dateFrom AND publishDate < :dateTo', ['dateTo' => $dateTo->timestamp'dateFrom' => $dateFrom->timestamp] );
  281.         if ($config) {
  282.             if ($config->getIsMultiSite()) {
  283.                 $articles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  284.             }
  285.             $sorting $config->getSorting();
  286.         }
  287.         if (!$sorting) {
  288.             $sorting 'topArticle DESC, publishDate DESC';
  289.         }
  290.         $articles->setOrderKey($sortingfalse);
  291.         $paginator $paginator->paginate($articles$request->get('page'1), $config->getItemsPerPage() ?? 4);
  292.         if ($config){
  293.             if ($config->getPageRange()) {
  294.                 $paginator->setPageRange($config->getPageRange());
  295.             }
  296.         }
  297.         return $this->render('@ElementsBlog/Blog/archive.html.twig', [
  298.             "paginator" => $paginator,
  299.             'config' => $config
  300.         ]);
  301.     }
  302.     /**
  303.      * @param Request $request
  304.      * @return array
  305.      * @throws \Exception
  306.      */
  307.     public function authorOverviewAction(Request $requestPaginatorInterface $paginator): \Symfony\Component\HttpFoundation\Response
  308.     {
  309.         if ($this->document) {
  310.             $config $this->document->getProperty('blog_config');
  311.         }
  312.         if (!$config) {
  313.             $configListing = new BlogBundleConfig\Listing();
  314.             $config $configListing->current();
  315.         }
  316.         $authors = new BlogBundleAuthor\Listing();
  317.         $authors->onCreateQueryBuilder(function (\Doctrine\DBAL\Query\QueryBuilder $query) use ($authors$request) {
  318.             $query->distinct()->leftJoin(
  319.                 'object_localized_' $authors->getClassId() . '_' $request->getLocale(),
  320.                 'object_localized_' \Pimcore\Model\DataObject\BlogBundleArticle::classId() . '_' $request->getLocale(),
  321.                 'articles',
  322.                 'articles.author__id = object_localized_' $authors->getClassId() . '_' $request->getLocale() . '.o_id AND articles.o_published = 1 AND IFNULL(articles.title,"") != "" AND articles.publishDate < ' time()
  323.             );
  324.         });
  325.         if ($config) {
  326.             if ($config->getIsMultiSite()) {
  327.                 $authors->addConditionParam('articles.site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  328.             }
  329.             $sorting $config->getAuthorSorting();
  330.         }
  331.         if (!$sorting) {
  332.             $sorting 'lastname ASC, firstname ASC';
  333. //            Todo: COUNT(articles.o_id) --> einbauen
  334. //            $sorting = 'articleCount DESC,  lastname ASC, firstname ASC';
  335.         }
  336.         $authors->setOrderKey($sortingfalse);
  337.         $paginator $paginator->paginate($authors$request->get('page'1), $config->getItemsPerPage() ?? 4);
  338.         if ($config) {
  339.             if ($config->getPageRange()) {
  340.                 $paginator->setPageRange($config->getPageRange());
  341.             }
  342.         }
  343.         return $this->render('@ElementsBlog/Blog/authorOverview.html.twig', [
  344.             "paginator" => $paginator,
  345.             'config' => $config
  346.         ]);
  347.     }
  348.     /**
  349.      * @param Request $request
  350.      * @return array
  351.      * @throws \Exception
  352.      */
  353.     public function authorDetailActionPaginatorInterface $paginatorRequest $request): \Symfony\Component\HttpFoundation\Response
  354.     {
  355.         if ($this->document) {
  356.             $config $this->document->getProperty('blog_config');
  357.         }
  358.         if (!$config) {
  359.             $configListing = new BlogBundleConfig\Listing();
  360.             $config $configListing->current();
  361.         }
  362.         $author BlogBundleAuthor::getById($request->get('id'));
  363.         if (!$author instanceof BlogBundleAuthor || !$author->isPublished()) {
  364.             throw new NotFoundHttpException('The requested Author doesn\'t exist (anymore)');
  365.         }
  366.         if ($request->get('pimcore_object_preview') != '') {
  367.             $this->addResponseHeader'x-robots-tag''noindex,nofollow');
  368.         }
  369.         $articles = new BlogBundleArticle\Listing();
  370.         $articles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  371.         $articles->addConditionParam('author__id = :authorId', ['authorId' => $author->getId()]);
  372.         if ($config) {
  373.             if ($config->getIsMultiSite()) {
  374.                 $articles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  375.             }
  376.             $sorting $config->getSorting();
  377.         }
  378.         if (!$sorting) {
  379.             $sorting 'topArticle DESC, publishDate DESC';
  380.         }
  381.         $articles->setOrderKey($sortingfalse);
  382.         $paginator $paginator->paginate($articles$request->get('page'1), $config->getAuthorItemsPerPage() ?? 4);
  383.         if ($config){
  384.             if ($config->getPageRange()) {
  385.                 $paginator->setPageRange($config->getPageRange());
  386.             }
  387.         }
  388.         return $this->render('@ElementsBlog/Blog/authorDetail.html.twig', [
  389.             'author' => $author,
  390.             'paginator' => $paginator,
  391.             'config' => $config
  392.         ]);
  393.     }
  394.     public function cseAction (Request $requestPaginatorInterface $paginator): \Symfony\Component\HttpFoundation\Response
  395.     {
  396.         if ($this->document) {
  397.             $config $this->document->getProperty('blog_config');
  398.         }
  399.         if (!$config) {
  400.             $configListing = new BlogBundleConfig\Listing();
  401.             $config $configListing->current();
  402.         }
  403.         if ($request->get('q')) {
  404.             try {
  405.                 $page $request->get('page'1);
  406.                 $perPage $config->getSearchResultCount() ?? 10;
  407.                 $search $request->get('q') . ' site:' \Pimcore\Tool::getHostUrl() . $config->getOverviewDocument();
  408.                 $result Cse::search($search, (($page 1) * $perPage), null, [
  409.                     'cx' => $config->getGoogleCseCx()
  410.                 ], $request->get('facet'));
  411.                 $paginator $paginator->paginate($result$page$perPage);
  412.                 return $this->render('@ElementsBlog/Blog/cse.html.twig', [
  413.                     'paginator' => $paginator,
  414.                     'config' => $config
  415.                 ]);
  416.             } catch (\Exception $e) {
  417.                 Logger::err($e->getMessage());
  418.             }
  419.         }
  420.     }
  421.     /**
  422.      * @param Request $request
  423.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  424.      */
  425.     public function languageRedirectAction(Request $request)
  426.     {
  427.         if ($this->document) {
  428.             $config $this->document->getProperty('blog_config');
  429.         }
  430.         if (!$config) {
  431.             $configListing = new BlogBundleConfig\Listing();
  432.             $config $configListing->current();
  433.         }
  434.         $language substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 02);
  435.         if (!in_array($language\Pimcore\Tool::getValidLanguages()) || !$config->getOverviewDocument($language) instanceof Page) {
  436.             if ($config->getOverviewDocument('en') instanceof Page) {
  437.                 $language 'en';
  438.             } else {
  439.                 $language 'de';
  440.             }
  441.         }
  442.         return $this->redirect($config->getOverviewDocument($language)->getFullPath());
  443.     }
  444.     public function rssAction(Request $requestBlogBundleGenerator $blogBundleGenerator) {
  445.         if ($this->document) {
  446.             $config $this->document->getProperty('blog_config');
  447.         }
  448.         if (!$config) {
  449.             $configListing = new BlogBundleConfig\Listing();
  450.             $config $configListing->current();
  451.         }
  452.         $articles = new BlogBundleArticle\Listing();
  453.         $articles->addConditionParam('IFNULL(title,"") != "" AND publishDate < :now', ['now' => time()]);
  454.         if ($config) {
  455.             if ($config->getIsMultiSite()) {
  456.                 $articles->addConditionParam('site LIKE :site', ['site' => '%,' $config->getId() . ',%']);
  457.             }
  458.             $sorting $config->getSorting();
  459.         }
  460.         if (!$sorting) {
  461.             $sorting 'topArticle DESC, publishDate DESC';
  462.         }
  463.         $articles->setOrderKey($sortingfalse);
  464.         $rssString '<?xml version="1.0" encoding="ISO-8859-1"?><rss version="2.0"><channel>';
  465.         $rssString .= '<title>' $this->config $this->config->getRssTitle() : '' '</title>';
  466.         $rssString .= '<link>' \Pimcore\Tool::getHostUrl() . $this->config->getOverviewDocument() . '</link>';
  467.         $rssString .= '<description>' $this->config $this->config->getRssDescription() : '' '</description>';
  468.         $rssString .= '<language>' $request->getLocale() . '</language>';
  469.         $rssString .= '<copyright>' $this->config $this->config->getCopyright() : '' '</copyright>';
  470.         foreach ($articles as $article) {
  471.             $articleString '<item>';
  472.             $articleString .= '<title>' $article->getTitle() . '</title>';
  473.             $articleString .= '<description>' $article->getShortDescription() . '</description>';
  474.             $articleString .= '<link>' \Pimcore\Tool::getHostUrl() . $blogBundleGenerator->generate($article) . '</link>';
  475.             $articleString .= '<pubDate>' $article->getPublishDate()->toIso8601String() . '</pubDate>';
  476.             $articleString .= '</item>';
  477.             $rssString .= $articleString;
  478.         }
  479.         $rssString .= '</channel></rss>';
  480.         return new Response($rssString200, [
  481.             'Content-Type' => 'application/rss+xml; charset=UTF8'
  482.         ]);
  483.     }
  484. }