<?php

namespace Neag\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response; 
use Neag\MainBundle\Entity\Category;
use Neag\MainBundle\Entity\Article;
use Neag\MainBundle\Entity\SimplePagePage;
use Neag\MainBundle\Entity\SimplePagePageRevision;
use Neag\MainBundle\Entity\Person;
use Neag\MainBundle\Entity\PersonArticle;

class PageController extends ControllerAbstract
{

    /**
     * @Route("/article/{id}")
     * @Template("NeagMainBundle:Page:show.html.twig")
     */
    public function showAction($id, $article_alias = null)
    {     
        $page = $this->getDoctrine()->getManager()->find('NeagMainBundle:SimplePagePage', $id);        
        if (!empty($page)) {
            $globals = $this->get('globals');
            $article_alias_current = $page->getArticleAlias();
            if (empty($article_alias_current)) {
                $article_alias_current = $globals->updateArticleAlias($page);
            }
            if ($article_alias_current != $article_alias) {                
                // Переадресация на правильный адрес
                //return $this->redirect($globals->buildPageLink($page));            
            }
            //$this->trace($globals->buildPageLink($page));
            return $this->showPage($page, $article_alias);
        }
        return $this->getErrorResponse();         
    }
    
    /**
     * @Template("NeagMainBundle:Page:show.html.twig")
     */
    public function showAliasAction($alias)
    {         
        $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
        ->select(Array('p'))
        ->from('NeagMainBundle:SimplePagePage', 'p')
        ->where('p.path = :path')
        ->setParameter('path', $alias);
        $rows = $qb->getQuery()->getResult();
        if (!empty($rows)) {
            $page = $rows[0];
            if ($page->getActive()) {
                return $this->showPage($rows[0]);
            } else {
                return $this->showPage(null);
            }
        } else {
            return $this->showPage(null);
        }
    }    
    
    /**
     * Отображает страницу
     * 
     * @param object | null
     * 
     */
    public function showPage($page)
    {
        if (!empty($page) ? $page->getActive() : false) {
            
            $globals = $this->get('globals');
            $templating = $this->get('templating'); 
            $request = $this->get('request');
            
            $desktop_link = $globals->buildPageLink($page, false, false);
            $mobile_link = $globals->buildPageLink($page, false, true);
            $globals->setDesktopLink($desktop_link);
            $globals->setMobileLink($mobile_link);
            
            $is_mobile = $globals->isMobile();
                                  
            $revision = $globals->getPageCurrentRevision($page);
            $article = $globals->getPageArticle($page);
            $category = $article->getCategory();
            
            $globals->setDisableYandexAds($page->getDisableYandexAds());
 
            $title_page = $revision->getTitle();
            $title_extra = '';
            if ($article->getIsShort()) {
                $title_extra = 'Новости';
            } else if (!empty($article)) {
                if (!empty($category)) {
                    $title_extra = $category->getTitle();
                }
            }
            
            $thumb_image_preset = $globals->articleImagePresets['thumb']; 
            
            // Дополнительные ссылки, размещаемые в тексте публикации
            $inner_more_links = Array();          
            
            // Читайте также
            $similar_html = '';
            if ($article->getShowCategoryTitle() && !empty($category)) {
                $similar_links = Array();
                $similar_links_total = 10;
                $params['title'] = $category->getTitle();
                $params['title_link'] = $globals->buildCategoryLink($category);
                $last_half = floor($similar_links_total/2);
                $category_id = $category->getId();
                $similar_links = Array();
                $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
                //->select(Array('a', 'p', 'pr'))
                ->select('p.id as id, p.path as path, p.articleAlias as article_alias, p.time as time, pr.title as title, a.annotation as annotation, a.id as aid, a.thumbImageFormat as thumb_image_format, a.thumbImageWidth as thumb_image_width, a.thumbImageHeight as thumb_image_height')
                ->from('NeagMainBundle:SimplePagePage', 'p')
                ->leftJoin('p.revisions', 'pr')
                ->leftJoin('p.articles', 'a');
                $qb->andWhere('p.active = :active')
                ->setParameter('active', true);
                $qb->andWhere('a.isShort = :isShort')
                ->setParameter('isShort', false);
                $qb->andWhere('a.showOnMain = :showOnMain')
                ->setParameter('showOnMain', true);
                $qb->andWhere('pr.current = :current')
                ->setParameter('current', true);
                $qb->andWhere('a.category = :category')
                ->setParameter('category', $category);
                $qb->andWhere('p.id != :id')
                ->setParameter('id', $page->getId());
                $qb->andWhere('p.time > :time')
                ->setParameter('time', $page->getTime());
                $qb->orderBy('p.time', 'ASC'); 
                $qb->setMaxResults($last_half);
                $rows = $qb->getQuery()->getResult();
                foreach ($rows as $row) {
                    $article_similar = null;
                    $image_thumb_created = false;
                    if (!$globals->hasImagePreset($row['aid'], $row['thumb_image_format'], $thumb_image_preset)) {                       
                        $repository = $this->getDoctrine()->getRepository('NeagMainBundle:Article');
                        $qb2 = $repository->createQueryBuilder('a')
                        ->select(Array('a'))
                        ->where('a.id = :aid')
                        ->setParameter('aid', $row['aid']);
                        $rows2 = $qb2->getQuery()->getResult();
                        if (!empty($rows2[0])) {
                            $article_similar = $rows2[0];
                            $globals->createArticleImagePreset($article_similar, 'thumb');
                            $image_thumb_created = true;
                        }                       
                    }
                    $image_info = Array();
                    if ($image_thumb_created) {
                        $image_info = $globals->getArticlePresetImageInfo($article_similar, 'thumb');
                    } else {
                        $image_info['width'] = $row['thumb_image_width'];
                        $image_info['height'] = $row['thumb_image_height'];
                        $image_info['format'] = $row['thumb_image_format'];        
                        $filepath = 'filedata/'.$thumb_image_preset['dir'].'/'.$row['aid'].'.'.$image_info['format'];
                        if (file_exists($filepath)) {
                            $image_info['src'] = $this->get('request')->getBasePath().'/'.$filepath;
                        } else {
                            $image_info['src'] = null;
                        }
                    }
                    $title = $row['title'];
                    $link = $globals->buildPageLink(Array('id' => $row['id'], 'path' => $row['path'], 'article_alias' => $row['article_alias']));
                    $similar_links[] = Array(
                        'title' => $title,
                        'link' => $link,
                        'annotation' => $row['annotation'],
                        'date' => $row['time']->format('d.m.Y'), 
                        'image' => $image_info,
                    );
                    $inner_more_links[] = Array(
                        'id' => $row['id'],
                        'title' => $title,
                        'link' => $link,
                        'displayed' => false,
                    );
                    /*
                    $revision = $globals->getPageCurrentRevision($row);
                    $article = $globals->getPageArticle($row);
                    if (!empty($revision) && !empty($article)) {
                        if (!$globals->hasArticleImagePreset($article, 'thumb')) {
                            $globals->createArticleImagePreset($article, 'thumb');
                        }
                        $title = $revision->getTitle();
                        $link = $globals->buildPageLink($row);
                        $similar_links[] = Array(
                            'title' => $title,
                            'link' => $link,
                            'annotation' => $article->getAnnotation(),
                            'date' => $row->getTime()->format('d.m.Y'), 
                            'image' => $globals->getArticlePresetImageInfo($article, 'thumb'),
                        );
                        $inner_more_links[] = Array(
                            'id' => $row->getId(),
                            'title' => $title,
                            'link' => $link,
                            'displayed' => false,
                        );
                    }
                    */
                    /*
                    $similar_links[] = Array(
                        'title' => $row['title'],
                        'link' => $globals->buildPageLink($row),
                    );
                    */  
                }
                $similar_links = array_reverse($similar_links);
                $last_half = count($rows);
                $prev_half = $similar_links_total - $last_half;
                $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
                //->select('p.id, p.path, p.time, pr.title')
                //->select(Array('a', 'p', 'pr'))
                ->select('p.id as id, p.path as path, p.articleAlias as article_alias, p.time as time, pr.title as title, a.annotation as annotation, a.id as aid, a.thumbImageFormat as thumb_image_format, a.thumbImageWidth as thumb_image_width, a.thumbImageHeight as thumb_image_height')
                ->from('NeagMainBundle:SimplePagePage', 'p')
                ->leftJoin('p.revisions', 'pr')
                ->leftJoin('p.articles', 'a');
                $qb->andWhere('p.active = :active')
                ->setParameter('active', true);
                $qb->andWhere('a.isShort = :isShort')
                ->setParameter('isShort', false);
                $qb->andWhere('a.showOnMain = :showOnMain')
                ->setParameter('showOnMain', true);
                $qb->andWhere('pr.current = :current')
                ->setParameter('current', true);
                $qb->andWhere('a.category = :category')
                ->setParameter('category', $category);
                $qb->andWhere('p.id != :id')
                ->setParameter('id', $page->getId());
                $qb->andWhere('p.time < :time')
                ->setParameter('time', $page->getTime());
                $qb->orderBy('p.time', 'DESC'); 
                $qb->setMaxResults($prev_half);
                $rows = $qb->getQuery()->getResult();
                foreach ($rows as $row) {
                    $article_similar = null;
                    $image_thumb_created = false;
                    if (!$globals->hasImagePreset($row['aid'], $row['thumb_image_format'], $thumb_image_preset)) {                       
                        $repository = $this->getDoctrine()->getRepository('NeagMainBundle:Article');
                        $qb2 = $repository->createQueryBuilder('a')
                        ->select(Array('a'))
                        ->where('a.id = :aid')
                        ->setParameter('aid', $row['aid']);
                        $rows2 = $qb2->getQuery()->getResult();
                        if (!empty($rows2[0])) {
                            $article_similar = $rows2[0];
                            $globals->createArticleImagePreset($article_similar, 'thumb');
                            $image_thumb_created = true;
                        }                       
                    }
                    $image_info = Array();
                    if ($image_thumb_created) {
                        $image_info = $globals->getArticlePresetImageInfo($article_similar, 'thumb');
                    } else {
                        $image_info['width'] = $row['thumb_image_width'];
                        $image_info['height'] = $row['thumb_image_height'];
                        $image_info['format'] = $row['thumb_image_format'];        
                        $filepath = 'filedata/'.$thumb_image_preset['dir'].'/'.$row['aid'].'.'.$image_info['format'];
                        if (file_exists($filepath)) {
                            $image_info['src'] = $this->get('request')->getBasePath().'/'.$filepath;
                        } else {
                            $image_info['src'] = null;
                        }
                    }
                    $title = $row['title'];
                    $link = $globals->buildPageLink(Array('id' => $row['id'], 'path' => $row['path'], 'article_alias' => $row['article_alias']));
                    $similar_links[] = Array(
                        'title' => $title,
                        'link' => $link,
                        'annotation' => $row['annotation'],
                        'date' => $row['time']->format('d.m.Y'), 
                        'image' => $image_info,
                    );
                    $inner_more_links[] = Array(
                        'id' => $row['id'],
                        'title' => $title,
                        'link' => $link,
                        'displayed' => false,
                    );
                    /*
                    $revision = $globals->getPageCurrentRevision($row);
                    $article = $globals->getPageArticle($row);
                    if (!empty($revision) && !empty($article)) {
                        if (!$globals->hasArticleImagePreset($article, 'thumb')) {
                            $globals->createArticleImagePreset($article, 'thumb');
                        }
                        $title = $revision->getTitle();
                        $link = $globals->buildPageLink($row);
                        $similar_links[] = Array(
                            'title' => $title,
                            'link' => $link,
                            'annotation' => $article->getAnnotation(),
                            'date' => $row->getTime()->format('d.m.Y'), 
                            'image' => $globals->getArticlePresetImageInfo($article, 'thumb'),
                        );
                        $inner_more_links[] = Array(
                            'id' => $row->getId(),
                            'title' => $title,
                            'link' => $link,
                            'displayed' => false,
                        );
                    }
                    */
                    /*
                    $similar_links[] = Array(
                        'title' => $row['title'],
                        'link' => $globals->buildPageLink($row),
                    );
                    */
                }
                //$this->trace($similar_links);
                $more_text = 'Другие материалы по теме "'.$category->getTitle().'" >>';
                $params = Array(
                    'rows' => $similar_links,
                    'more_link' => $globals->buildCategoryLink($category),
                    'more_text' => $more_text,
                );
                $similar_html = $templating->render(
                    'NeagMainBundle:Page:similar.html.php',
                    $params
                );
            }
            
            // Другие материалы автора
            $similar_author_html = '';
            $owner = $page->getUser();
            //$this->trace('chp 1');
            if (!empty($owner)) {
                $similar_author_links = Array();
                $similar_author_links_total = 10;
                $last_half = floor($similar_author_links_total/2);
                $owner_id = $owner->getId();
                $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
                //->select(Array('a', 'p', 'pr'))
                ->select('p.id as id, p.path as path, p.articleAlias as articleAlias, pr.title as title, a.annotation as annotation, p.time as time')
                ->from('NeagMainBundle:SimplePagePage', 'p')
                ->leftJoin('p.revisions', 'pr')
                ->leftJoin('p.articles', 'a');
                $qb->andWhere('p.active = :active')
                ->setParameter('active', true);
                //$qb->andWhere('a.showOnMain = :showOnMain')
                //->setParameter('showOnMain', true);
                $qb->andWhere('pr.current = :current')
                ->setParameter('current', true);
                $qb->andWhere('p.user = :user')
                ->setParameter('user', $owner);
                $qb->andWhere('p.id != :id')
                ->setParameter('id', $page->getId());
                $qb->andWhere('p.time > :time')
                ->setParameter('time', $page->getTime());
                $qb->orderBy('p.time', 'ASC'); 
                $qb->setMaxResults($last_half);
                $rows = $qb->getQuery()->getResult();
                foreach ($rows as $row) {
                    $title = $row['title'];
                    $link = $globals->buildPageLink(Array('id' => $row['id'], 'path' => $row['path'], 'article_alias' => $row['articleAlias']));
                    $annotation = $row['annotation'];
                    $date = $row['time']->format('d.m.Y');
                    $similar_author_links[] = Array(
                        'title' => $title,
                        'link' => $link,
                        'annotation' => $annotation,
                        'date' => $date
                    );
                    $inner_more_links[] = Array(
                        'id' => $row['id'],
                        'title' => $title,
                        'link' => $link,
                        'displayed' => false,
                    );
                    /*
                    $revision = $globals->getPageCurrentRevision($row);
                    $article = $globals->getPageArticle($row);
                    if (!empty($revision) && !empty($article)) {
                        $title = $revision->getTitle();
                        $link = $globals->buildPageLink($row);
                        $similar_author_links[] = Array(
                            'title' => $title,
                            'link' => $link,
                            'annotation' => $article->getAnnotation(),
                            'date' => $row->getTime()->format('d.m.Y')
                        );
                        $inner_more_links[] = Array(
                            'id' => $row->getId(),
                            'title' => $title,
                            'link' => $link,
                            'displayed' => false,
                        );
                    }
                    */ 
                }
                $similar_author_links = array_reverse($similar_author_links);
                $last_half = count($rows);
                $prev_half = $similar_author_links_total - $last_half;
                $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
                //->select(Array('a', 'p', 'pr'))
                ->select('p.id as id, p.path as path, p.articleAlias as articleAlias, pr.title as title, a.annotation as annotation, p.time as time')
                ->from('NeagMainBundle:SimplePagePage', 'p')
                ->leftJoin('p.revisions', 'pr')
                ->leftJoin('p.articles', 'a');
                $qb->andWhere('p.active = :active')
                ->setParameter('active', true);
                //$qb->andWhere('a.showOnMain = :showOnMain')
                //->setParameter('showOnMain', true);
                $qb->andWhere('pr.current = :current')
                ->setParameter('current', true);
                $qb->andWhere('p.user = :user')
                ->setParameter('user', $owner);
                $qb->andWhere('p.id != :id')
                ->setParameter('id', $page->getId());
                $qb->andWhere('p.time < :time')
                ->setParameter('time', $page->getTime());
                $qb->orderBy('p.time', 'DESC'); 
                $qb->setMaxResults($prev_half);
                $rows = $qb->getQuery()->getResult();
                foreach ($rows as $row) {
                    $title = $row['title'];
                    $link = $globals->buildPageLink(Array('id' => $row['id'], 'path' => $row['path'], 'article_alias' => $row['articleAlias']));
                    $annotation = $row['annotation'];
                    $date = $row['time']->format('d.m.Y');
                    $similar_author_links[] = Array(
                        'title' => $title,
                        'link' => $link,
                        'annotation' => $annotation,
                        'date' => $date
                    );
                    $inner_more_links[] = Array(
                        'id' => $row['id'],
                        'title' => $title,
                        'link' => $link,
                        'displayed' => false,
                    );
                    /*
                    $revision = $globals->getPageCurrentRevision($row);
                    $article = $globals->getPageArticle($row);
                    if (!empty($revision) && !empty($article)) {
                        $title = $revision->getTitle();
                        $link = $globals->buildPageLink($row);
                        $similar_author_links[] = Array(
                            'title' => $revision->getTitle(),
                            'link' => $globals->buildPageLink($row),
                            'annotation' => $article->getAnnotation(),
                            'date' => $row->getTime()->format('d.m.Y'),            
                        );
                        $inner_more_links[] = Array(
                            'id' => $row->getId(),
                            'title' => $title,
                            'link' => $link,
                            'displayed' => false,
                        );
                    }
                    */
                }
                //$this->trace($similar_author_links);
                //$more_text = 'Другие материалы автора "'.$owner->getName().'" >>';
                $params = Array(
                    'rows' => $similar_author_links,
                    'is_mobile' => $is_mobile,
                    //'more_link' => $globals->buildCategoryLink($owner),
                    //'more_text' => $more_text,
                );
                $similar_html = $templating->render(
                    'NeagMainBundle:Page:similar_author.html.php',
                    $params
                );
            }
            //$this->trace($similar_html);
            //$this->trace($inner_more_links);
            
            // Смотрите на форуме
            $similar_forum_topics_html = '';
            $forum_topics = Array();
            if (!empty($category)) {
                // Поиск по разделу
                $rows = $this->getDoctrine()->getManager()->createQueryBuilder()
                ->select('l', 'ft')
                ->from('NeagMainBundle:ForumTopicCategory', 'l')
                ->leftJoin('l.forumTopic', 'ft')
                ->leftJoin('ft.forumCategory', 'fc')
                ->leftJoin('l.category', 'c')
                ->andWhere('l.category = :category')
                ->setParameter('category', $category)
                ->andWhere('c.active = :active')
                ->setParameter('active', true)      
                ->andWhere('fc.active = :active')
                ->setParameter('active', true)
                ->andWhere('fc.promote = :promote')
                ->setParameter('promote', true)
                ->orderBy('ft.timeUpdate', 'DESC')
                ->setMaxResults(10)
                ->getQuery()
                ->getResult();
                foreach ($rows as $row) {
                    $forumTopic = $row->getForumTopic();
                    $forum_topics[$forumTopic->getId()] = Array(
                        'id' => $forumTopic->getId(),
                        'title' => $forumTopic->getTitle(),
                        'link' => $globals->buildForumTopicLink($forumTopic),
                        'time_update' => $forumTopic->getTimeUpdate()->getTimestamp(),
                        'rang' => 1,
                    );
                }
            }
            $personArticles = $article->getPersonArticles();
            foreach ($personArticles as $pa) {
                $person = $pa->getPerson();
                // Поиск по персоналии
                $rows = $this->getDoctrine()->getManager()->createQueryBuilder()
                ->select('l', 'ft')
                ->from('NeagMainBundle:ForumTopicPerson', 'l')
                ->leftJoin('l.forumTopic', 'ft')
                ->leftJoin('ft.forumCategory', 'fc')
                ->leftJoin('l.person', 'p')
                ->andWhere('l.person = :person')
                ->setParameter('person', $person)
                ->andWhere('p.active = :active')
                ->setParameter('active', true)      
                ->andWhere('fc.active = :active')
                ->setParameter('active', true)
                ->andWhere('fc.promote = :promote')
                ->setParameter('promote', true)
                ->orderBy('ft.timeUpdate', 'DESC')
                ->setMaxResults(10)
                ->getQuery()
                ->getResult();
                foreach ($rows as $row) {
                    $forumTopic = $row->getForumTopic();
                    $id = $forumTopic->getId();
                    if (!isset($forum_topics[$id])) {                        
                        $forum_topics[$id] = Array(
                            'id' => $id,
                            'title' => $forumTopic->getTitle(),
                            'link' => $globals->buildForumTopicLink($forumTopic),
                            'time_update' => $forumTopic->getTimeUpdate()->getTimestamp(),
                            'rang' => 2,
                        );
                    } else {
                        $forum_topics[$id]['rang'] = $forum_topics[$id]['rang'] + 2;
                    }
                }
            }
            usort($forum_topics, Array($this, 'cmpForumTopicInfo'));
            $forum_topics = array_slice($forum_topics, 0, 20);
            $params = Array(
                'is_mobile' => $is_mobile,
                'rows' => $forum_topics,
            );
            $similar_forum_topics_html = $templating->render(
                'NeagMainBundle:Page:similar_forum_topics.html.php',
                $params
            );
            //$this->trace($forum_topics);
            
            // Случайная дата
            $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
            //->select(Array('a', 'p', 'pr'))
            ->select('p.id as id')
            ->from('NeagMainBundle:SimplePagePage', 'p')
            ->leftJoin('p.revisions', 'pr')
            ->leftJoin('p.articles', 'a');
            $qb->andWhere('p.active = :active')
            ->setParameter('active', true);
            $qb->andWhere('a.showOnMain = :showOnMain')
            ->setParameter('showOnMain', true);
            $qb->andWhere('a.isShort = :isShort')
            ->setParameter('isShort', false);
            $qb->andWhere('pr.current = :current')
            ->setParameter('current', true);
            $qb->andWhere('p.id != :id')
            ->setParameter('id', $page->getId());
            //$qb->andWhere('p.time < :time')
            //->setParameter('time', $page->getTime());
            //$qb->orderBy('p.time', 'ASC');
            $qb->orderBy('p.id', 'DESC'); 
            $qb->setMaxResults(1);
            $rows = $qb->getQuery()->getResult();
            if (!empty($rows[0])) {
                $id_last = $rows[0]['id'] - 100;
                //$id_last = $rows[0]->getId() - 100;
                $id_rand = rand(1, $id_last);
                if (!empty($id_rand)) {
                    $ids_exclude = Array();
                    $ids_exclude[] = $page->getId();
                    foreach ($inner_more_links as $e) {
                        $ids_exclude[] = $e['id'];
                    }
                    $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
                    //->select(Array('a', 'p', 'pr'))
                    ->select('p.id as id, p.path as path, p.articleAlias as articleAlias, pr.title as title')
                    ->from('NeagMainBundle:SimplePagePage', 'p')
                    ->leftJoin('p.revisions', 'pr')
                    ->leftJoin('p.articles', 'a');
                    $qb->andWhere('p.active = :active')
                    ->setParameter('active', true);
                    $qb->andWhere('a.showOnMain = :showOnMain')
                    ->setParameter('showOnMain', true);
                    $qb->andWhere('a.isShort = :isShort')
                    ->setParameter('isShort', false);
                    $qb->andWhere('pr.current = :current')
                    ->setParameter('current', true);
                    foreach ($ids_exclude as $id_exclude) {
                         $qb->andWhere('p.id != :id')
                         ->setParameter('id', $id_exclude);
                    }
                    $qb->andWhere('p.id > :id')
                    ->setParameter('id', $id_rand);
                    $qb->orderBy('p.id', 'ASC'); 
                    $qb->setMaxResults(20);
                    $rows2 = $qb->getQuery()->getResult();
                    foreach ($rows2 as $row2) {
                        $title = $row2['title'];
                        $link = $globals->buildPageLink(Array('id' => $row2['id'], 'path' => $row2['path'], 'article_alias' => $row2['articleAlias']));
                        $inner_more_links[] = Array(
                            'id' => $row2['id'],
                            'title' => $title,
                            'link' => $link,
                            'displayed' => false,
                        );
                        /*
                        $r = $globals->getPageCurrentRevision($row2);
                        $a = $globals->getPageArticle($row2);
                        if (!empty($r) && !empty($a)) {
                            $title = $r->getTitle();
                            $link = $globals->buildPageLink($row2);
                            $inner_more_links[] = Array(
                                'id' => $row2->getId(),
                                'title' => $title,
                                'link' => $link,
                                'displayed' => false,
                            );
                        }
                        */
                    }
                }
                /*
                $time_begin = strtotime($rows[0]->getTime()->format('d.m.Y H:i:s'));
                $time_now = time();
                // Случайное время
                $time_rand = rand($time_begin, $time_now - 3600*24*30);
                $this->trace($time_begin);
                $this->trace($time_now);
                $this->trace($time_rand);
                $this->trace(date('d.m.Y H:i:s', $time_begin));
                $this->trace(date('d.m.Y H:i:s', $time_rand));
                */
                /*
                if (!empty($time_rand)) {
                    $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
                    ->select(Array('a', 'p', 'pr'))
                    ->from('NeagMainBundle:SimplePagePage', 'p')
                    ->leftJoin('p.revisions', 'pr')
                    ->leftJoin('p.articles', 'a');
                    $qb->andWhere('p.active = :active')
                    ->setParameter('active', true);
                    $qb->andWhere('a.showOnMain = :showOnMain')
                    ->setParameter('showOnMain', true);
                    $qb->andWhere('a.isShort = :isShort')
                    ->setParameter('isShort', false);
                    $qb->andWhere('pr.current = :current')
                    ->setParameter('current', true);
                    $qb->andWhere('p.id != :id')
                    ->setParameter('id', $page->getId());
                    $qb->andWhere('p.time > :time')
                    ->setParameter('time', date('d.m.Y H:i:s', $time_rand));
                    $qb->orderBy('p.time', 'ASC'); 
                    $qb->setMaxResults(20);
                    $rows2 = $qb->getQuery()->getResult();
                    foreach ($rows2 as $row2) {
                        $r = $globals->getPageCurrentRevision($row2);
                        $a = $globals->getPageArticle($row2);
                        if (!empty($r) && !empty($a)) {
                            $title = $r->getTitle();
                            $link = $globals->buildPageLink($row2);
                            $inner_more_links[] = Array(
                                'title' => $title,
                                'link' => $link,
                                'displayed' => false,
                            );
                        }
                    }
                }
                */
            }
            
            shuffle($inner_more_links);
            
            //$this->trace($inner_more_links);
            
            $globals->setInnerMoreLinks($inner_more_links); 
            
            $content = $this->loadPageContent($page);           
            
            if ($content === false) {
                return Array(
                    'is_mobile' => $is_mobile,
                    'title' => 'Доступ запрещён',
                    'title_extra' => '',
                    'content' => 'Доступ запрещён',
                    'similar' => '',
                    'similar_forum_topics' => '',
                ); 
            }          
            
            return Array(
                'is_mobile' => $is_mobile,
                'title' => $title_page,
                'title_extra' => $title_extra,
                'content' => $content,  
                'similar' => $similar_html,
                'similar_forum_topics' => $similar_forum_topics_html,
            );         
        }
        return $this->getErrorResponse();
        /*
        header('HTTP/1.1 404 Not Found');
        return Array(
            'title_extra' => '',
            'title' => 'Страница не найдена',
            'content' => 'Запрашиваемая страница не найдена на сайте. Попробуйте воспользоваться разделами меню или поиском.',
            'similar' => '',
        );
        */
    }
    
    /**
     * Загрузка содержимого страницы
     * 
     * @access      public
     * @param       object
     * @return      string
     */
    public function loadPageContent ($page)
    {
        $globals = $this->get('globals');
        $is_mobile = $globals->isMobile();
        $templating = $this->get('templating');
        $revision = $globals->getPageCurrentRevision($page);
        $article = $globals->getPageArticle($page); 
        $is_admin = $this->isAdmin();       
        $is_moderator = $is_admin;
        $is_owner = false;
        $content = '';          
        
        $is_logged_in = false;
        if ($globals->isUserLoggedIn()) {
            $is_logged_in = true;
        } else {
            $user_info = $globals->getUserInfo();
        } 
        
        $owner = $page->getUser();
        if (!empty($owner)) {            
            if ($is_logged_in) {
                $user_info = $globals->getUserInfo();
                $user = $user_info['entity'];
                if ($user->getId() == $owner->getId()) {
                    $globals->setDisableYandexAds(true);
                    $is_moderator = true;
                    $is_owner = true;
                }
            }
        }        
        $owner_name = null;
        if (!empty($owner)) {
            $owner_name = $globals->formatUserName($owner->getName(), $owner);
        }
        
        $is_user_editable = false;
        if ($is_owner && !$is_admin) {            
            $is_moderator = $globals->isUserPageEditable($page);
        }
        
        if (!$is_owner && !$is_admin && !$is_moderator && $article->getWaiting()) {
            return false;
        }
        
        //$this->trace($is_owner ? 'is owner' : 'is not owner');
        //$this->trace($is_moderator ? 'is moderator' : 'is not moderator');
        
        //$this->trace('format: '.$revision->getFormat());
        $image_format = $article->getImageFormat();
        $image_ad = '';
        //$this->trace('chp 1');
        //$this->trace('$image_format: '.$image_format);
        //$this->trace($globals->getDisableYandexAds() ? 'disable' : 'enable');
        if (!empty($image_format) && !$globals->getDisableYandexAds()) {
            //$this->trace('chp 2');
            if ($globals->isShowYandexDirect('content')) {
                $image_ad = $globals->yandexBlock('content', 1);
            }
        }    
        
        $body = $globals->formatPageContent($revision->getContent(), $revision->getFormat());
        $link = $globals->buildPageLink($page, false);
        $link_abs = $globals->buildPageLink($page, true);
        $params = Array();
        $params['title'] = $revision->getTitle(); 
        $params['article_link'] = $link_abs; 
        $params['waiting'] = $article->getWaiting();
        $params['is_admin'] = $is_admin;  
        $params['is_moderator'] = $is_moderator;    
        $params['is_owner'] = $is_owner;  
        if ($is_moderator) {
            if (!$is_owner) {
                $args = Array('edit' => $page->getId(), 'redirect' => $link);
                $edit_link = $this->generateURL('admin_article_edit', Array('id' => $page->getId(), 'redirect' => $link));
                $owner_link = $this->generateURL('admin_article_owner', Array('id' => $page->getId()));
                $delete_link = $this->generateURL('admin_article_list', Array('del' => $page->getId()));
                $params['edit_link'] = $edit_link; 
                $params['owner_link'] = $owner_link;
                $params['delete_link'] = $delete_link; 
            } else {
                //$this->trace($owner->getId());
                $args = Array('edit' => $page->getId(), 'redirect' => $link);
                $owner_link = $this->generateURL('admin_article_owner', Array('id' => $page->getId()));
                if (!$is_mobile) {
                    $edit_link = $this->generateURL('user_blog_edit', Array('id' => $page->getId(), 'redirect' => $link));
                    $delete_link = $this->generateURL('user_blog_list', Array('del' => $page->getId()));
                } else {
                    $edit_link = $this->generateURL('user_blog_edit_m', Array('id' => $page->getId(), 'redirect' => $link));
                    $delete_link = $this->generateURL('user_blog_list_m', Array('del' => $page->getId()));
                }
                $params['edit_link'] = $edit_link;
                $params['owner_link'] = $owner_link; 
                $params['delete_link'] = $delete_link;
            }
        }
        $params['annotation'] = $article->getAnnotation();
        $params['body'] = $body;
        $image_format = $article->getImageFormat();
        if (!empty($image_format)) {
            $params['image_src'] = $this->get('request')->getBasePath().'/filedata/images_article/'.$article->getId().'.'.$article->getImageFormat();
            $params['image_width'] = $article->getImageWidth();
            $params['image_height'] = $article->getImageHeight();
            $params['image_title'] = $article->getImageTitle();
            $params['image_ad'] = '';
            $params['image_ad'] = $image_ad;
        }
        /*
        $image_info = $globals->getArticlePresetImageInfo($article, 'thumb');          
        if (!empty($image_info['src'])) {                    
            $params['image_width'] = $image_info['width'];
            $params['image_height'] = $image_info['height'];
            $params['image_src'] = $image_info['src'];
            $params['image_title'] = $article->getImageTitle();
        }
        */
        if ($article->getShowDate()) {
            $params['date'] = $page->getTime()->format('d.m.Y H:i:s O');
        }
        if ($globals->getConfigVar('allow_post_comments') && $article->getAllowComment()) {
            $params['allow_post_comment'] = true;
            if (!$is_mobile) {
                $params['post_comment_link'] = $this->generateURL('post_comment', Array('id' => $page->getId()));
            } else {
                $params['post_comment_link'] = $this->generateURL('post_comment_m', Array('id' => $page->getId()));
            }
        } else {
            $params['allow_post_comment'] = false;
        }
        if ($globals->getConfigVar('allow_show_comments') && $article->getShowComment()) {
            $params['allow_show_comments'] = true;
            if (!$is_mobile) {
                $params['show_comments_link'] = $this->generateURL('comments', Array('id' => $page->getId()));
            } else {
                $params['show_comments_link'] = $this->generateURL('comments_m', Array('id' => $page->getId()));
            }
            // Подсчёт кол-ва комментариев
            /*
            if ($is_moderator) {
                $count = $globals->countComments($page, true);
            } else {
                $count = $globals->countComments($page, false);
            }
            */
            $count = $globals->countComments($page, false);
            $params['comments_count'] = $count;
        } else {
            $params['allow_show_comments'] = false; 
        }
        // Ссылки
        $links = Array();
        if ($article->getIsShort()) {
            if (!$is_mobile) { 
                $links[] = Array(
                    'title' => 'Новости',
                    'link' => $this->generateURL('news'),
                );
            } else {
                $links[] = Array(
                    'title' => 'Новости',
                    'link' => $this->generateURL('news_m'),
                );
            }
        }         
        if ($article->getShowCategoryTitle()) {
            $category = $article->getCategory();
            if (!empty($category)) {
                $links[] = Array(
                    'title' => $category->getTitle(),
                    'link' => $globals->buildCategoryLink($category),
                );
            }
        }
        $personArticles = $article->getPersonArticles();
        foreach ($personArticles as $pa) {
            $person = $pa->getPerson();
            $links[] = Array(
                'title' => $person->getTitle(),
                'link' => $globals->buildPersonLink($person),
            );
        }
        $tagArticles = $article->getTagArticles();
        foreach ($tagArticles as $pa) {
            $tag = $pa->getTag();
            // Поиск главного синонима
            $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
            ->select(Array('ts'))
            ->from('NeagMainBundle:TagSynonym', 'ts');
            $qb->andWhere('ts.tag = :tag')
            ->setParameter('tag', $tag);
            $qb->andWhere('ts.main = :main')
            ->setParameter('main', true);
            $rows2 = $qb->getQuery()->getResult();            
            if (!empty($rows2)) {
                $title = $rows2[0]->getTitle();
                $links[] = Array(
                    'title' => $title,
                    'link' => $globals->buildTagLink($tag),
                );
            }            
        }
        $params['links'] = $links;
        $params['owner'] = $owner_name;
        $params['is_mobile'] = $is_mobile;
        $params['feedback_link'] = $this->generateURL('feedback');
        //$this->trace($params);
        $window_width = null;
        if (!empty($_COOKIE['width'])) {
            $window_width = $_COOKIE['width'];
        }
        //$this->trace($_COOKIE);
        $params['window_width'] = $window_width;
        return $templating->render(
            'NeagMainBundle:Page:show.html.php',
            $params
        );
    }
    
    /**
     * Сравнивает два элемента массива тем форума
     */
    public function cmpForumTopicInfo($a, $b)
    {
        if ($a['time_update'] == $b['time_update'] && $a['count'] == $b['count']) {
            return 0;
        }
        if ($a['rang'] > $b['rang']) {
            return -1;
        } elseif ($a['rang'] < $b['rang']) {
            return 1;
        } else {
            if ($a['time_update'] > $b['time_update']) {
                return -1;
            } elseif ($a['time_update'] < $b['time_update']) {
                return 1;
            } else {
                return 0;
            }
        }
    }    

}
