Guest User

Untitled

a guest
Sep 26th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 42.21 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\MainBundle\Model;
  4.  
  5. /**
  6.  * Description of ThWordsModel
  7.  *
  8.  */
  9. class ThThemesModel extends MainBundleModel {
  10.     private $id;
  11.    
  12.     private $user_id;
  13.    
  14.     private $name;
  15.    
  16.     private $description;
  17.    
  18.     private $time_create;
  19.     //Ключевые слова для темы
  20.     private $keywords;
  21.     //стоп слова для темы
  22.     private $stopwords;
  23.     //Сообщения по темам
  24.     private $messages = array();
  25.    
  26.     private $countMessages = 0;
  27.    
  28.     private $countAuthors = 0;
  29.     //Доступные хабы для темы
  30.     private $allow_hubs = array();
  31.    
  32.     private $type_visible;
  33.    
  34.     private $allow_message;
  35.    
  36.     private $allow_comments;
  37.    
  38.     private $theme_enabled;
  39.    
  40.     private $group_id;
  41.    
  42.     private $author_filter = 0;
  43.    
  44.     private $tag_filter = 0;
  45.    
  46.     public function SetAuthor($a){
  47.         $this->author_filter =$a;
  48.     }
  49.  
  50.     public function SetTag($tag){
  51.         $this->tag_filter = $tag;
  52.     }
  53.    
  54.     public function GetThemeEnabled(){
  55.         return $this->theme_enabled;
  56.     }
  57.    
  58.     public function GetGroupId(){
  59.         return $this->group_id;
  60.     }
  61.    
  62.     public function GetTypeVisible(){
  63.         return $this->type_visible;
  64.     }
  65.    
  66.     public function GetAllowMessage(){
  67.         return $this->allow_message;
  68.     }
  69.    
  70.     public function GetTypeMessage(){
  71.         $tm = array();
  72.         if($this->allow_message == 1){
  73.             $tm[] = 1;
  74.         }
  75.        
  76.         if($this->allow_comments == 1){
  77.             $tm[] = 2;
  78.         }
  79.        
  80.         return $tm;
  81.     }
  82.    
  83.     public function GetAllowComments(){
  84.         return $this->allow_comments;
  85.     }
  86.    
  87.     public function GetId(){
  88.         return $this->id;
  89.     }
  90.  
  91.     public function GetUserID(){
  92.         return $this->user_id;
  93.     }
  94.    
  95.     public function GetAllowHubs(){
  96.         return $this->allow_hubs;
  97.     }
  98.    
  99.     public function SetAllowHubs(array $hubs){
  100.         $this->allow_hubs = $hubs;
  101.     }
  102.    
  103.     public function GetName(){
  104.         return $this->name;
  105.     }
  106.    
  107.     public function GetDescription(){
  108.         return $this->description;
  109.     }
  110.  
  111.     public function GetTimeCreate(){
  112.         return $this->time_create;
  113.     }
  114.  
  115.     public function GetKeyWords(){
  116.         return $this->keywords;
  117.     }
  118.    
  119.     public function GetStopWords(){
  120.         return $this->stopwords;
  121.     }
  122.    
  123.     //TODO подумать о кэше в коснтрукторе
  124.     public function __construct($id = 0, $arFilter = null) {
  125.         if($id!=0){
  126.             $sql = 'select user_id, name, description, time_create, type_visible,
  127.                    allow_message, allow_comments, group_id, theme_enabled
  128.                                        from th_themes
  129.                            where id = :id';
  130.            
  131.             $statement = $this->getConnection()->prepare($sql);
  132.             $statement->bindParam(':id', $id, \PDO::PARAM_INT);
  133.            
  134.             if(($statement->execute()) AND ($statement->rowCount()>0)){
  135.                 $row = $statement->fetch();
  136.                 //основные поля
  137.                 $this->id               = $id;
  138.                 $this->user_id          = $row['user_id'];
  139.                 $this->name             = $row['name'];
  140.                 $this->description      = $row['description'];
  141.                 $this->time_create      = $row['time_create'];
  142.                 $this->type_visible     = $row['type_visible'];
  143.                 $this->allow_message    = $row['allow_message'];
  144.                 $this->allow_comments   = $row['allow_comments'];
  145.                 $this->group_id         = $row['group_id'];
  146.                 $this->theme_enabled    = $row['theme_enabled'];
  147.                
  148.                 //счиаем количество авторов и сообщений
  149.                 $this->MakeCountMA($arFilter);
  150.                
  151.                 //Получаем доступные хабы для данной темы
  152.                 $this->MakeThemeHubs();
  153.                
  154.                 //Инициализация ключевых и стоп слов
  155.                 //$this->MakeWords();                            
  156.             }              
  157.         }
  158.         /*
  159.         else{
  160.             return $this;
  161.             //throw new \Exception('Такой темы не существует');
  162.         }  */
  163.     }
  164.    
  165.     public function MakeThemeHubs(){
  166.         $sql = 'select hub_id from th_themes_allowhubs where theme_id = ?';
  167.         $statement = $this->getConnection()->prepare($sql);
  168.         $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  169.         if(($statement->execute()) AND ($statement->rowCount()>0)){
  170.             $rows = $statement->fetchAll();
  171.             foreach($rows as $row){
  172.                 $this->allow_hubs[] = (int) $row['hub_id'];
  173.             }
  174.         }
  175.        
  176.        
  177.     }
  178.    // public function GetTopAuthor
  179.     //Собирает количество слов и авторов по темме
  180.     private function MakeCountMA($arFilter = null) {
  181.     $szWhereTime = '';
  182.         $ret = \ECSNData\MemC::get(MCConstants::ThThemeCOUNT_MA . $this->id.'_tf_'.$arFilter['created-from'].'_tt_'.$arFilter['created-upto']);
  183.         if (!$ret) {       
  184.                     if ($arFilter) {
  185.                         $szWhereTime = ' and time_create >= ? and time_create <= ? ';
  186.                     }
  187.                     $sql = <<<SQL
  188.                             select count(*) as c_m,
  189.                                 count(distinct author_id)  as c_a
  190.                             from th_themes_messages where theme_id = ? and exclude =0
  191.                 $szWhereTime
  192. SQL;
  193.                     $statement = $this->getConnection()->prepare($sql);
  194.                     $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  195.                     if ($arFilter) {
  196.             $statement->bindParam(2, $arFilter['created-from'], \PDO::PARAM_INT);
  197.             $statement->bindParam(3, $arFilter['created-upto'], \PDO::PARAM_INT);
  198.                     }
  199.                     $statement->execute();
  200.                     $row = $statement->fetch();
  201.                     $this->countMessages = $row['c_m'];      
  202.                     $this->countAuthors = $row['c_a'];
  203.                     \ECSNData\MemC::set(MCConstants::ThThemeCOUNT_MA . $this->id.'_tf_'.$arFilter['created-from'].'_tt_'.$arFilter['created-upto'], $row);
  204.            
  205.                 }
  206.         else{
  207.             $this->countMessages = $ret['c_m'];      
  208.             $this->countAuthors = $ret['c_a'];            
  209.         }
  210.     }
  211.    
  212.     //Возвращает общее количество сообщений для данной темы
  213.     public function GetCountMessages(){
  214.         return $this->countMessages;
  215.     }
  216.     public function SetCountMessages($count){
  217.         return $this->countMessages = $count;
  218.     }
  219.     //Возвращает общее количество авторов для данной темы
  220.     public function GetCountAuthors(){
  221.         return $this->countAuthors;
  222.     }
  223.    
  224.     //Создание списка тем по данному пользователю
  225.     public function GetThemesArrayByUser($user_id = 0){
  226.         if($user_id!=0){
  227.             $list = array();
  228.             $sql = 'select id, name from th_themes where user_id=? order by name';
  229.             $statement = $this->getConnection()->prepare($sql);
  230.             $statement->bindValue(1, $user_id, \PDO::PARAM_INT);
  231.             $statement->execute();
  232.             $rows = $statement->fetchAll();
  233.             foreach($rows as $row){
  234.                 $list[$row['id']]['id'] = $row['id'];
  235.                 $list[$row['id']]['name'] = $row['name'];
  236.             }
  237.             return $list;                    
  238.         }
  239.     }
  240.  
  241.    
  242.     public function updateTheme(\App\MainBundle\Entity\ThemeForm $theme){
  243.         $sql ='update th_themes set
  244.                    name=?, type_visible=?, allow_message=?, allow_comments=?
  245.               where id=?';
  246.         $statement = $this->getConnection()->prepare($sql);
  247.         $allow_message  = $theme->getAllowTypeMessage(1);
  248.         $allow_comments = $theme->getAllowTypeMessage(2);
  249.         $statement->bindValue(1, $theme->getName(), \PDO::PARAM_STR);
  250.         $statement->bindValue(2, $theme->getPublicvisible(), \PDO::PARAM_INT);
  251.         $statement->bindValue(3, $allow_message, \PDO::PARAM_INT);
  252.         $statement->bindValue(4, $allow_comments, \PDO::PARAM_INT);
  253.         $statement->bindValue(5, $this->id, \PDO::PARAM_INT);
  254.         $statement->execute();
  255.        
  256.         $this->name           = $theme->getName();
  257.         $this->allow_message  = $allow_message;
  258.         $this->allow_comments = $allow_comments;
  259.         $this->type_visible   = $theme->getPublicvisible();
  260.        
  261.         $id = $this->id;
  262.  
  263.         $sql = 'delete from th_themes_allowhubs where theme_id=?';
  264.         $statement = $this->getConnection()->prepare($sql);
  265.         $statement->bindValue(1, $this->id, \PDO::PARAM_INT);
  266.         $statement->execute();
  267.        
  268.  
  269.         //Записываем доступные хабы
  270.         $this->allow_hubs = $theme->getHubs();
  271.         $sql = 'insert into th_themes_allowhubs (theme_id, hub_id) values ';
  272.         foreach($this->allow_hubs as $v){
  273.             $sql.='('.$id.','.$v.'),';
  274.         }
  275.         //Убираем последнюю запятую.
  276.         $sql = substr($sql, 0, strlen($sql)-1);
  277.         //Сохраняем хабы
  278.         $statement = $this->getConnection()->prepare($sql);
  279.         $statement->execute();
  280.  
  281.  
  282.         $word = new ThWordsModel(0);
  283.         //Удаляем ключевые слова
  284.         $sql = 'delete from th_themes_keywords where theme_id=?';
  285.         $statement = $this->getConnection()->prepare($sql);
  286.         $statement->bindValue(1, $this->id, \PDO::PARAM_INT);
  287.         $statement->execute();
  288.         //Удаляем стоп слова
  289.         $sql = 'delete from th_themes_stopwords where theme_id=?';
  290.         $statement = $this->getConnection()->prepare($sql);
  291.         $statement->bindValue(1, $this->id, \PDO::PARAM_INT);
  292.         $statement->execute();
  293.        
  294.         //сохраняем ключевые слова
  295.         $keywords = explode(',', $theme->getKeywords());
  296.         $keywords_id = array();
  297.        
  298.         foreach ($keywords as $v){
  299.            $keywords_id[] = $word->setWord($v);
  300.         }
  301.        
  302.         $sql = 'insert into th_themes_keywords (theme_id, word_id) values ';
  303.         foreach($keywords_id as $v){
  304.            $sql.='('.$id.','.$v.'),';
  305.         }
  306.         //Убираем последнюю запятую.
  307.         $sql = substr($sql, 0, strlen($sql)-1);
  308.        
  309.         $statement = $this->getConnection()->prepare($sql);
  310.         $statement->execute();
  311.        
  312.         //сохраняем стоп слова
  313.         if(strlen($theme->getStopwords())){
  314.             //сохраняем ключевые слова
  315.             $stopwords = explode(',', $theme->getStopwords());
  316.             $keywords_id = array();
  317.  
  318.             foreach ($stopwords as $v){
  319.                 $keywords_id[] = $word->setWord($v);
  320.             }
  321.  
  322.             $sql = 'insert into th_themes_stopwords (theme_id, word_id) values ';
  323.             foreach($keywords_id as $v){
  324.                 $sql.='('.$id.','.$v.'),';
  325.             }
  326.             //Убираем последнюю запятую.
  327.             $sql = substr($sql, 0, strlen($sql)-1);            
  328.             $statement = $this->getConnection()->prepare($sql);
  329.             $statement->execute();          
  330.         }
  331.         return true;
  332.     }
  333.      
  334.    
  335.     //Создание новой темы -
  336.     public function createNewTheme(\App\MainBundle\Entity\ThemeForm $theme, $user_id){
  337.        $curDate = new \DateTime('now', new \DateTimeZone('Europe/Moscow'));      
  338.        $sql = 'insert into th_themes (user_id, name, time_create,
  339.           type_visible, allow_message, allow_comments)
  340.           values (?,?,?,?,?,?)';
  341.            
  342.        $statement = $this->getConnection()->prepare($sql);
  343.        //Общие параметры для темы
  344.        $allow_message  = $theme->getAllowTypeMessage(1);
  345.        $allow_comments = $theme->getAllowTypeMessage(2);
  346.        
  347.        $statement->bindValue(1, $user_id, \PDO::PARAM_INT);
  348.        $statement->bindValue(2, $theme->getName(), \PDO::PARAM_STR);
  349.        $statement->bindValue(3, $curDate->format("Y-m-d h:i:s"), \PDO::PARAM_STR);      
  350.        $statement->bindValue(4, $theme->getPublicvisible(), \PDO::PARAM_INT);      
  351.        $statement->bindValue(5, $allow_message, \PDO::PARAM_INT);
  352.        $statement->bindValue(6, $allow_comments, \PDO::PARAM_INT);
  353.    
  354.        $statement->execute();
  355.        //заполняем поля модели
  356.        $this->id = $this->getConnection()->lastInsertId();      
  357.        $this->user_id = $user_id;
  358.        $this->name  = $theme->getName();
  359.        $this->time_create = $curDate->format("Y-m-d h:i:s");
  360.        $id = $this->id;
  361.  
  362.        //Записываем доступные хабы
  363.        $this->allow_hubs = $theme->getHubs();
  364.        $sql = 'insert into th_themes_allowhubs (theme_id, hub_id) values ';
  365.        foreach($this->allow_hubs as $v){
  366.            $sql.='('.$id.','.$v.'),';
  367.        }
  368.        //Убираем последнюю запятую.
  369.        $sql = substr($sql, 0, strlen($sql)-1);
  370.        //Сохраняем хабы
  371.        $statement = $this->getConnection()->prepare($sql);
  372.        $statement->execute();
  373.        
  374.        $word = new ThWordsModel(0);
  375.        
  376.        //сохраняем ключевые слова
  377.        $keywords = explode(',', $theme->getKeywords());
  378.        $keywords_id = array();
  379.        
  380.        foreach ($keywords as $v){
  381.            $keywords_id[] = $word->setWord($v);
  382.        }
  383.        
  384.        $sql = 'insert into th_themes_keywords (theme_id, word_id) values ';
  385.        foreach($keywords_id as $v){
  386.            $sql.='('.$id.','.$v.'),';
  387.        }
  388.        //Убираем последнюю запятую.
  389.        $sql = substr($sql, 0, strlen($sql)-1);
  390.        
  391.        $statement = $this->getConnection()->prepare($sql);
  392.        $statement->execute();
  393.        
  394.        //сохраняем стоп слова
  395.        if(strlen($theme->getStopwords())){
  396.             //сохраняем ключевые слова
  397.             $stopwords = explode(',', $theme->getStopwords());
  398.             $keywords_id = array();
  399.  
  400.             foreach ($stopwords as $v){
  401.                 $keywords_id[] = $word->setWord($v);
  402.             }
  403.  
  404.             $sql = 'insert into th_themes_stopwords (theme_id, word_id) values ';
  405.             foreach($keywords_id as $v){
  406.                 $sql.='('.$id.','.$v.'),';
  407.             }
  408.             //Убираем последнюю запятую.
  409.             $sql = substr($sql, 0, strlen($sql)-1);            
  410.             $statement = $this->getConnection()->prepare($sql);
  411.             $statement->execute();          
  412.        }
  413.        return true;
  414.     }
  415.    
  416.  
  417.     //Метод получения Top хабов по теме
  418.     public function GetTopHubs($offset=0,$limit =10, $arFilter = null){
  419.     $szCacheKey = MCConstants::ThThemeTopHubs . $this->id . '_offset_' . $offset . '_limit_' . $limit.'_from_'.$arFilter['created-from'].'_to_'.$arFilter['created-upto'];
  420.         $ret = \ECSNData\MemC::get($szCacheKey);
  421.         if(!$ret) {
  422.         $szWhereTime = '';
  423.         if ($arFilter) {
  424.                     $szWhereTime = ' and time_create >= :from and time_create <= :upto ';
  425.         }
  426.                 if (count($this->allow_hubs)) {
  427.                     $szWhereCond = ' and `hub_id` in (' . join(',', $this->allow_hubs) . ') ';
  428.         }
  429.         else {
  430.             $szWhereCond = '';
  431.         }
  432.             $sql =<<<SQL
  433.                                 select hub_id, COUNT(*) as c_hub
  434.                                     from th_themes_messages
  435.                                     where theme_id = :id and exclude = 0      
  436.                                             $szWhereCond
  437.                                             $szWhereTime
  438.                                     group by hub_id order by c_hub desc
  439.                                     limit :offset, :limit
  440. SQL;
  441.             $statement = $this->getConnection()->prepare($sql);
  442.             $statement->bindParam(':id', $this->id, \PDO::PARAM_INT);
  443.             if (!empty($szWhereTime)) {
  444.                 $statement->bindParam(':from', $arFilter['created-from'], \PDO::PARAM_INT);
  445.                 $statement->bindParam(':upto', $arFilter['created-upto'], \PDO::PARAM_INT);            
  446.             }
  447. //$statement->bindParam(2, $date_from, \PDO::PARAM_INT);
  448.             //$statement->bindParam(3, $date_to, \PDO::PARAM_INT);
  449.             $statement->bindParam(':offset', $offset, \PDO::PARAM_INT);
  450.             $statement->bindParam(':limit', $limit, \PDO::PARAM_INT);
  451.  
  452.             if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  453.                 $rows = $statement->fetchAll();
  454.                 $list = array();
  455.                 $hub_title_ar = array(
  456.                     1 => 'Твиттер',
  457.                     2 => 'LiveJournal',
  458.                     3 => 'ВКонтакте ',
  459.                     8 => 'Новости'
  460.                 );
  461.                 //Для процентного соотношения для правого графика
  462.                 $p1 = 0;
  463.                 foreach ($rows as $row) {
  464.                     //Расчитываем процентное соотношение по количеству сообщений данной темы
  465.                     if ($p1 == 0) {
  466.                         $p1 = $row['c_hub'];
  467.                     }
  468.                     $hub_id = (int) $row['hub_id'];
  469.                     $list[$hub_id]['procent'] = $row['c_hub'] / $p1 * 100;
  470.                     $list[$hub_id]['c_hub'] = (int) $row['c_hub'];
  471.                     $list[$hub_id]['hub_id'] = $hub_id;
  472.                     $list[$hub_id]['hub_name'] = $hub_title_ar[$hub_id];
  473.                     //echo 'hubid '.$row['hub_id'].'</br>';
  474.                 }
  475.                 //Возвращаем массив топ авторов - ключ - ид автора, и поля count и author
  476.                 \ECSNData\MemC::set($szCacheKey, $list);
  477.                 return $list;
  478.             } else {
  479.                 return FALSE;
  480.             }
  481.         } else {
  482.             //Возвращаем кэшированный список
  483.             //echo "Возвращено из кэша";
  484.             return $ret;
  485.         }
  486.     }
  487.  
  488.     /**
  489.      *
  490.      * @return array
  491.      */
  492.     function getStatsData($arFilter) {
  493.         $arRes = array();
  494.                
  495.         $timeFrom = \DateTime::createFromFormat('U', $arFilter['created-from']);
  496.         $timeUpto = \DateTime::createFromFormat('U', $arFilter['created-upto']);
  497.         $szFrom =  $timeFrom->format('Y-m-d');
  498.         $szUpto =  $timeUpto->format('Y-m-d');     
  499.         $sql = <<<SQL
  500.                             select date, count_messages
  501.                             from `th_themes_stats_daily`
  502.                             where theme_id = :id and date > :from and date <= :upto
  503. SQL;
  504.         $stmt = $this->getConnection()->prepare($sql);
  505.         $stmt->bindParam(':id', $this->id, \PDO::PARAM_INT);
  506.         $stmt->bindParam(':from', $szFrom, \PDO::PARAM_STR);
  507.         $stmt->bindParam(':upto', $szUpto, \PDO::PARAM_STR);
  508.         if (($stmt->execute()) && ($stmt->rowCount() > 0)) {
  509.             $arRows = $stmt->fetchAll();
  510.             foreach ($arRows as $row) {
  511.                 $arRes[] = array(
  512.                     '1' => (int) $row['count_messages'],
  513.                     'date' => (int) strtotime($row['date'] . ' 00:00:00')
  514.                 );
  515.             }
  516.         }
  517.         return $arRes;
  518.     }
  519.    
  520.     public function GetMonthStatistics() {
  521.  
  522.         $today = \DateTime::createFromFormat("U", time())->setTimezone(new \DateTimeZone('Europe/Moscow'));
  523.         $month = clone $today;
  524.         $month->modify('-31 day');
  525.         $sql = 'select date, count_messages from th_themes_stats_daily
  526.                    where theme_id=? and (date <= ? and date >= ?)
  527.                order by date limit 31';
  528.  
  529.         $dateStart = $month->format('Y-m-d');
  530.         $dateEnd = $today->format('Y-m-d');
  531.         $statement = $this->getConnection()->prepare($sql);
  532.         $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  533.         $statement->bindParam(2, $dateEnd, \PDO::PARAM_STR);
  534.         $statement->bindParam(3, $dateStart, \PDO::PARAM_STR);
  535.         //var_dump($statement);
  536.         if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  537.             $rows = $statement->fetchAll();
  538.             $list = array();
  539.             //var_dump($rows);
  540.             foreach ($rows as $row) {
  541.                 $list[] = array(
  542.                     '1' => (int) $row['count_messages'],
  543.                     'date' => (int) strtotime($row['date'] . ' 00:00:00')
  544.                 );
  545.             }
  546.             return json_encode($list);
  547.         }
  548.     }
  549.  
  550.         public function getCountByHub($hub_id, $arFilter = null){
  551.             $szWhereTime = '';
  552.             if (!is_null($arFilter)) {
  553.                 $szWhereTime = ' and time_create >= :from and time_create <= :upto ';
  554.             }
  555.             $sql = 'select count(*) as c_m from th_themes_messages
  556.                        where theme_id = :theme_id
  557.                    and hub_id = :hub_id and exclude = 0
  558.                    ' .$szWhereTime;
  559.             $stmt = $this->getConnection()->prepare($sql);
  560.             $stmt->bindParam(':theme_id', $this->id, \PDO::PARAM_INT);
  561.             $stmt->bindParam(':hub_id', $hub_id, \PDO::PARAM_INT);
  562.             if (!empty($szWhereTime)) {
  563.                 $stmt->bindParam(':from', $arFilter['created-from'], \PDO::PARAM_INT);
  564.         $stmt->bindParam(':upto', $arFilter['created-upto'], \PDO::PARAM_INT);             
  565.             }            
  566.             if (($stmt->execute()) && ($stmt->rowCount() > 0)) {
  567.                 $row = $stmt->fetch();
  568.                 $count = (int) $row['c_m'];
  569.                 return $count;
  570.             }
  571.             else return 0;
  572.            
  573.         }
  574.        
  575.     //Метод вытаскивания TOP авторов для конкретной темы
  576.     public function GetTopAuthors($offset = 0, $limit = 10, $arFilter = null) {      
  577.         $szCacheKey = MCConstants::ThThemeTopAuthor . $this->id . '_offset_' . $offset . '_limit_' . $limit . '_date_'.$arFilter['created-from'].$arFilter['created-upto'];
  578.         $ret = \ECSNData\MemC::get($szCacheKey);
  579.         if (!$ret) {
  580.             $szWhereTime = '';
  581.             if (!is_null($arFilter)) {
  582.                 $szWhereTime = ' and time_create >= :from and time_create <= :upto ';
  583.             }
  584.             $sql = <<<SQL
  585.                                 select author_id, COUNT(*) as c_mess
  586.                                 from th_themes_messages
  587.                                 where theme_id = :id and exclude = 0
  588.                                 $szWhereTime
  589.                                 group by author_id
  590.                                 order by c_mess desc
  591.                                 limit :offset, :limit
  592. SQL;
  593.             $stmt = $this->getConnection()->prepare($sql);         
  594.             $stmt->bindParam(':id', $this->id, \PDO::PARAM_INT);
  595.             if (!empty($szWhereTime)) {
  596.                 $stmt->bindParam(':from', $arFilter['created-from'], \PDO::PARAM_INT);
  597.                 $stmt->bindParam(':upto', $arFilter['created-upto'], \PDO::PARAM_INT);
  598.             }
  599.             $stmt->bindParam(':offset', $offset, \PDO::PARAM_INT);
  600.             $stmt->bindParam(':limit', $limit, \PDO::PARAM_INT);
  601.  
  602.             if (($stmt->execute()) AND ($stmt->rowCount() > 0)) {
  603.                 $rows = $stmt->fetchAll();
  604.                 $list = array();
  605.                 //Для процентного соотношения для графика
  606.                 $p1 = 0;
  607.  
  608.                 foreach ($rows as $row) {
  609.                     //Расчитываем процентное соотношение по количеству сообщений данной темы
  610.                     if ($p1 == 0) {
  611.                         $p1 = $row['c_mess'];
  612.                     }
  613.                     $list[$row['author_id']]['procent'] = $row['c_mess'] / $p1 * 100;
  614.                     $list[$row['author_id']]['c_mess'] = $row['c_mess'];
  615.                     $list[$row['author_id']]['author_id'] = $row['author_id'];
  616.                     //Для имплода второго запроса выборки по никам и именам авторов
  617.                     $sql_in[] = $row['author_id'];
  618.                 }
  619.  
  620.                 $sql_author = 'select id, fullname, nickname
  621.                                        from th_authors where id in (' . implode(',', $sql_in) . ')';
  622.                 $statement = $this->getConnection()->prepare($sql_author);
  623.                 if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  624.                     $a_rows = $statement->fetchAll();
  625.                     foreach ($a_rows as $row) {
  626.                         $list[$row['id']]['fullname'] = $row['fullname'];
  627.                         $list[$row['id']]['nickname'] = $row['nickname'];
  628.                     }
  629.                 }
  630.                 //Возвращаем массив топ авторов - ключ - ид автора, и поля count и author
  631.                 \ECSNData\MemC::set($szCacheKey, $list);
  632.  
  633.                 return $list;
  634.             } else {
  635.                 return FALSE;
  636.             }
  637.         } else {
  638.             //Возвращаем кэшированный список
  639.             //echo "Возвращено из кэша";
  640.             return $ret;
  641.         }
  642.     }
  643.  
  644.     //Вытаскиваем сообщения из БД для этой темы
  645.     public function GetMessages($offset, $limit, $arFilter = null) {
  646.     $hub_str = implode('-', $this->allow_hubs);  
  647.     $memkey = MCConstants::ThThemesModel_Message . $this->id . '_OF_' . $offset . '_LIM_' . $limit . '_tf_' .$arFilter['created-from'].'_tt_'.$arFilter['created-upto'].'_hub_'.$hub_str;
  648.    
  649.     if($this->author_filter!=0) $memkey=$memkey.'_a_id_'.$this->author_filter;
  650.     if($this->tag_filter) $memkey=$memkey.'_t_id_'.$this->tag_filter;
  651.    
  652.     $ret = \ECSNData\MemC::get($memkey);
  653.             if (!$ret) {           
  654.                 if (count($this->allow_hubs) AND ($this->author_filter!=0)) {
  655.                     $szWhereHub = ' and b.hub_id in (' . join(',', $this->allow_hubs) . ')
  656.                        and b.author_id = '.$this->author_filter.' ';
  657.                        
  658.                 }
  659.                 else if(count($this->allow_hubs)){
  660.                     $szWhereHub = ' and b.hub_id in (' . join(',', $this->allow_hubs) . ') ';
  661.                 }
  662.                 else {
  663.                     $szWhereHub = '';
  664.                 }
  665.         $szWhereTime = ' and b.time_create >= ? and b.time_create <= ? ';
  666.                 if ($this->tag_filter) $szWhereTag = "and f.tag like '".$this->tag_filter."'";
  667.                     else $szWhereTag = '';
  668.         $sql = <<<SQL
  669.                         select a.id, a.id_mongo, a.id_external, a.hash, a.hub_id, a.author_id, a.title,a.text,                      
  670.                        a.url, a.time_create, a.time_modified, a.time_store, a.time_store_ecsn, a.time_updated,
  671.                        b.message_rule, b.format_text, b.format_flag,
  672.                         (
  673.                         select GROUP_CONCAT(d.tag SEPARATOR ':|:') from th_messages_tags c
  674.                         left join th_tags d on c.tag_id = d.id and c.theme_id = ?
  675.                         where c.message_id = a.id
  676.                         limit 1
  677.                         ) as tags                      
  678.                         from th_messages a
  679.                     join th_themes_messages b on a.id = b.message_id
  680.                     left join th_messages_tags e on a.id = e.message_id and e.theme_id = ?
  681.                     left join th_tags f on e.tag_id = f.id                    
  682.                         where b.theme_id = ? AND b.exclude = 0
  683.                             $szWhereTime                    
  684.                            $szWhereHub
  685.                             $szWhereTag
  686.                     order by b.time_create DESC
  687.                   limit ?, ?
  688. SQL;
  689.                
  690.         $statement = $this->getConnection()->prepare($sql);
  691.         $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  692.                 $statement->bindParam(2, $this->id, \PDO::PARAM_INT);
  693.                 $statement->bindParam(3, $this->id, \PDO::PARAM_INT);
  694.         $statement->bindParam(4, $arFilter['created-from'], \PDO::PARAM_INT);
  695.         $statement->bindParam(5, $arFilter['created-upto'], \PDO::PARAM_INT);
  696.         $statement->bindParam(6, $offset, \PDO::PARAM_INT);
  697.         $statement->bindParam(7, $limit, \PDO::PARAM_INT);
  698.                
  699.         if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  700.             $rows = $statement->fetchAll();            
  701.             $this->messages = $this->prepareMessages($rows);
  702.             \ECSNData\MemC::set($memkey, $this->messages);
  703.             return $this->messages;
  704.         }
  705.     } else {
  706.         $this->messages = $ret;
  707.         return $ret;
  708.     }
  709.     }
  710.  
  711.     protected function prepareMessages(array $messages)
  712.     {
  713.         $commentsSearch = array();
  714.         $commentsCached = array();
  715.         foreach($messages as $message)
  716.         {
  717.             $comentsCount = \ECSNData\MemC::get(MCConstants::ThThemeElasticComCount . $message['id']);
  718.             if($comentsCount)
  719.                 $commentsCached[$message['id']] = $comentsCount;
  720.             else
  721.                 $commentsSearch[$message['id_mongo']] = $message['id'];
  722.         }
  723.        
  724.         if(count($commentsSearch) > 0)
  725.         {
  726.             $commentsQuery = array(
  727.                 "filter" => array(
  728.                     "terms" => array(
  729.                         "docId" => array_keys($commentsSearch)
  730.                     )
  731.                 ),
  732.                 "size" => count($commentsSearch),
  733.                 "fields" => array("comments_count", "docId")
  734.             );
  735.             $elastic = new \ECSNData\client();
  736.             $comments = $elastic->ESearch($commentsQuery);
  737.             $commentsRows = $comments['hits']['hits'];
  738.             foreach ($commentsRows as $eC) {
  739.                 $messageId = $commentsSearch[$eC['fields']['docId']];
  740.                 $comentsCount = (int) $eC['fields']['comments_count'];
  741.                 \ECSNData\MemC::set(MCConstants::ThThemeElasticComCount . $messageId, $comentsCount, 300);
  742.                 $commentsCached[$messageId] = $comentsCount;
  743.             }
  744.         }
  745.  
  746.         $list = array();
  747.         //Creating messaging for template
  748.         foreach ($messages as $message) {
  749.             $list[$message['id']] = new ThMessagesModel(0, $message);
  750.             $list[$message['id']]->SetCommentsCount($comentsCount[$message['id']]);
  751.  
  752.  
  753.             if (strlen($message['message_rule']) > 0) {
  754.                 //echo $row['message_rule'].'</br>';
  755.                 $rule = json_decode($message['message_rule'], TRUE);
  756.                 $list[$message['id']]->parseText($rule);
  757.             } else {
  758.                 $list[$message['id']]->parseWithoutRule();
  759.             }
  760.             //var_dump($list);
  761.  
  762.  
  763.             /* Вариант на боевом сервере
  764.              *  
  765.               if($row['format_flag']==1) {
  766.               echo "1 <br>";
  767.               $list[$row['id']]->setSmallText($row['format_text']);
  768.               } elseif ((strlen($row['message_rule']) > 0) and is_null($row['format_flag'])) {
  769.               echo "2 <br>";
  770.               $rule = json_decode($row['message_rule'], TRUE);
  771.               $list[$row['id']]->parseText($rule);
  772.               } else {
  773.               echo "3 <br>";
  774.               $list[$row['id']]->parseWithoutRule();
  775.               }
  776.               /**
  777.              */
  778.         }
  779.         return $list;
  780.     }
  781.    
  782.    
  783.     public function makePaging($limit, $offset) {
  784.         $i = ceil($this->countMessages / $limit) - 1;
  785.         $j = ($offset >= 5) ? $offset - 3 : 1;
  786.         $ret = array();
  787.         if ($i >= 7) {
  788.             if ($j + 7 < $i) {
  789.                 for ($k = $j; $k <= $j + 6; $k++) {
  790.                     if ($offset > 4) {
  791.                         $ret[1] = "";
  792.                         $ret[2] = "skip";
  793.                     }
  794.                     if ($k == $offset) {
  795.                         $ret[$k] = "current";
  796.                     } else {
  797.                         if ($k == ($j + 7)) {
  798.                             $ret[$k] = "skip";
  799.                             $ret[$i] = "";
  800.                         } else {
  801.                             $ret[$k] = "";
  802.                         }
  803.                     }
  804.                     if (!isset($ret[$i - 1])) {
  805.                         $ret[$i - 1] = "skip";
  806.                     }
  807.                     if (!isset($ret[$i])) {
  808.                         $ret[$i] = "";
  809.                     }
  810.                 }
  811.             } else {
  812.                 for ($k = $j; $k <= $i; $k++) {
  813.                     if ($k == $offset) {
  814.                         $ret[$k] = "current";
  815.                     } else {
  816.                         $ret[$k] = "";
  817.                     }
  818.                 }
  819.                 $ret[1] = "";
  820.                 $ret[2] = "skip";
  821.             }
  822.         } else {
  823.             for ($k = $j; $k <= $i; $k++) {
  824.                 if ($k == $j) {
  825.                     $ret[$k] = "current";
  826.                 } else {
  827.                     if ($k == ($j + 7)) {
  828.                         $ret[$k] = "skip";
  829.                     } else {
  830.                         $ret[$k] = "";
  831.                     }
  832.                 }
  833.             }
  834.         }
  835.         ksort($ret);
  836.  
  837.         return $ret;
  838.         }
  839.  
  840.     public function MakeWords() {
  841.     $id = $this->id;
  842.         $sql = 'select word from th_words where id in(
  843.                    select word_id from th_themes_keywords where theme_id=?)';
  844.     $statement = $this->getConnection()->prepare($sql);
  845.     $statement->bindParam(1, $id, \PDO::PARAM_INT);
  846.     if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  847.             $rows = $statement->fetchAll();
  848.             $keyword = array();
  849.             foreach ($rows as $row) {
  850.         $keyword[]=$row['word'];
  851.             }
  852.             $this->keywords = implode(', ', $keyword);
  853.     }
  854.         else{
  855.             $this->keywords = '';
  856.         }
  857.        
  858.         $sql = 'select word from th_words where id in(
  859.                    select word_id from th_themes_stopwords where theme_id=?)';
  860.     $statement = $this->getConnection()->prepare($sql);
  861.     $statement->bindParam(1, $id, \PDO::PARAM_INT);
  862.     if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  863.             $rows = $statement->fetchAll();
  864.             $keyword = array();
  865.             foreach ($rows as $row) {
  866.         $keyword[]=$row['word'];
  867.             }
  868.             $this->stopwords = implode(', ', $keyword);
  869.     }
  870.         else{
  871.             $this->stopwords = '';
  872.         }
  873.        
  874.     }
  875.    
  876.     public function getMessagesByIds(array $ids)
  877.     {
  878.         if(count($ids) < 1)
  879.             return array();
  880.        
  881.         $db = $this->getConnection();
  882.        
  883.        
  884.         $sql = 'SELECT
  885.                       m.id, m.id_mongo, m.id_external, m.hash, m.hub_id, m.author_id, m.title,m.text,
  886.                       m.url, m.time_create, m.time_modified, m.time_store, m.time_store_ecsn, m.time_updated,
  887.                       "" as message_rule, tm.format_text, tm.format_flag
  888.                  FROM
  889.                        th_messages m
  890.                  INNER JOIN
  891.                        th_themes_messages tm on m.id = tm.message_id
  892.                  WHERE
  893.                        tm.theme_id = ?
  894.                        AND tm.exclude = 0
  895.                        AND m.id IN ( '.str_repeat('?, ', count($ids) - 1).' ? )
  896.                  ORDER BY tm.time_create DESC';
  897.        
  898.        
  899.         $binds = $ids;
  900.         array_unshift($binds, $this->id);
  901.         $messages = $db->executeQuery($sql, $binds)->fetchAll(\PDO::FETCH_ASSOC);
  902.         return $this->prepareMessages($messages);
  903.     }
  904.  
  905.     //Создание списка тем по данному пользователю
  906.     public function GetThemesArrayByGroup($group_id = 1){
  907.         if($group_id!=0){
  908.             $list = array();
  909.             $sql = 'select id, name from th_themes where group_id=? order by name';
  910.             $statement = $this->getConnection()->prepare($sql);
  911.             $statement->bindValue(1, $group_id, \PDO::PARAM_INT);
  912.             $statement->execute();
  913.             $rows = $statement->fetchAll();
  914.             foreach($rows as $row){
  915.                 $list[$row['id']]['id'] = $row['id'];
  916.                 $list[$row['id']]['name'] = $row['name'];
  917.             }
  918.             return $list;                    
  919.         }
  920.     }    
  921.    
  922.     public static function getIDbyGroup($group_name = 'default'){
  923.         $sql = 'select id from th_themes where group_id = (
  924.                    select group_id from th_themes_groups where group_tname=?
  925.                ) order by name limit 1';
  926.         $statement = \App\MainBundle\Entity\ConnectionDB::getInstance()->getConnection()->prepare($sql);
  927.         $statement->bindParam(1, $group_name, \PDO::PARAM_STR);
  928.         if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  929.             $row = $statement->fetch();
  930.             return $row['id'];
  931.         }
  932.         else{
  933.             return false;
  934.         }
  935.     }
  936.    
  937.    
  938.     public function GetCountMessagesByAuthor($arFilter = null) {  
  939.     $sql = 'select count(*) as c_a from th_themes_messages b
  940.                        where b.theme_id = ? AND b.exclude = 0
  941.                         and b.time_create >= ? and b.time_create <= ?
  942.                         and b.author_id = '.$this->author_filter.'
  943.                 and b.hub_id in (' . join(',', $this->allow_hubs) . ')';
  944.                                                
  945.         $statement = $this->getConnection()->prepare($sql);
  946.     $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  947.     $statement->bindParam(2, $arFilter['created-from'], \PDO::PARAM_INT);
  948.     $statement->bindParam(3, $arFilter['created-upto'], \PDO::PARAM_INT);                
  949.            
  950.     if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  951.             $row = $statement->fetch();            
  952.             $this->countMessages = $row['c_a'];
  953.             return $this->countMessages;
  954.     }
  955.     }
  956.    
  957.     public function GetCountTags($tag, $arFilter = null) {  
  958.     $sql = 'select count(*) as c_a from th_themes_messages b
  959.                        left join th_messages_tags e on b.message_id = e.message_id
  960.                        left join th_tags f on e.tag_id = f.id
  961.                        where b.theme_id = ? AND b.exclude = 0
  962.                        and f.tag = ?
  963.                        and b.time_create >= ? and b.time_create <= ?
  964.                 and b.hub_id in (' . join(',', $this->allow_hubs) . ')';
  965.                                                
  966.         $statement = $this->getConnection()->prepare($sql);
  967.     $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  968.         $statement->bindParam(2, $tag, \PDO::PARAM_STR);
  969.     $statement->bindParam(3, $arFilter['created-from'], \PDO::PARAM_INT);
  970.     $statement->bindParam(4, $arFilter['created-upto'], \PDO::PARAM_INT);                
  971.            
  972.     if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  973.             $row = $statement->fetch();            
  974.             $this->countMessages = $row['c_a'];
  975.             return $this->countMessages;
  976.     }
  977.     }    
  978.    
  979.     // Добавление тегов
  980.     public function AddTags($message_id, $tags) {
  981.         $tags_arr = explode(',', $this->_strtolower(strtolower($tags)));
  982.         foreach ($tags_arr as $key => $tag)
  983.         {
  984.             $tag = trim($tag);
  985.             if (!$tag) continue;
  986.             $sql = 'INSERT INTO th_tags SET tag = ? ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)';
  987.             $statement = $this->getConnection()->prepare($sql);
  988.             $statement->bindValue(1, trim($tag), \PDO::PARAM_STR);
  989.             $statement->execute();
  990.             $tag = htmlspecialchars($tag);
  991.             $tags_arr[$key] = "<a href=\"/events/".$this->id."/tags/$tag\">$tag</a>";
  992.             $lastInsertedID = $this->getConnection()->lastInsertId();
  993.            
  994.             $sql = 'INSERT INTO th_messages_tags SET theme_id = ?, message_id = ?, tag_id = ?';
  995.             $statement = $this->getConnection()->prepare($sql);
  996.             $statement->bindValue(1, $this->id, \PDO::PARAM_INT);
  997.             $statement->bindValue(2, $message_id, \PDO::PARAM_INT);
  998.             $statement->bindValue(3, $lastInsertedID, \PDO::PARAM_INT);
  999.             $statement->execute();
  1000.         }
  1001.         return implode(' ', $tags_arr);
  1002.     }
  1003.      
  1004.     // тэги темы
  1005.     public function GetTags()
  1006.     {
  1007.         $sql = 'SELECT DISTINCT t.tag FROM th_tags t
  1008.            LEFT JOIN th_messages_tags mt ON t.id = mt.tag_id
  1009.            WHERE mt.theme_id = ?
  1010.            GROUP BY t.tag
  1011.            ORDER BY COUNT(t.id) DESC
  1012.            LIMIT 15';
  1013.         $statement = \App\MainBundle\Entity\ConnectionDB::getInstance()->getConnection()->prepare($sql);
  1014.         $statement->bindParam(1, $this->id, \PDO::PARAM_STR);
  1015.         if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  1016.             $rows = $statement->fetchAll();
  1017.             $result = array();
  1018.             foreach($rows as $key => $row){
  1019.                 $rows[$key][0] = htmlspecialchars($row[0]);
  1020.                 $result[$key] = "<a href=\"javascript:void(0)\">$row[0]</a>";
  1021.             }
  1022.             return implode(' ', $result);
  1023.         }
  1024.         else{
  1025.             return false;
  1026.         }
  1027.     }
  1028.    
  1029.     private function _strtolower($string)
  1030.     {
  1031.         $small = array('а','б','в','г','д','е','ё','ж','з','и','й',
  1032.                        'к','л','м','н','о','п','р','с','т','у','ф',
  1033.                        'х','ч','ц','ш','щ','э','ю','я','ы','ъ','ь',
  1034.                        'э', 'ю', 'я');
  1035.         $large = array('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й',
  1036.                        'К','Л','М','Н','О','П','Р','С','Т','У','Ф',
  1037.                        'Х','Ч','Ц','Ш','Щ','Э','Ю','Я','Ы','Ъ','Ь',
  1038.                        'Э', 'Ю', 'Я');
  1039.         return str_replace($large, $small, $string);
  1040.     }
  1041.  
  1042.     //Метод вытаскивания TOP тегов для конкретной темы
  1043.     public function GetTopTags($offset = 0, $limit = 10) {      
  1044.         $ret = \ECSNData\MemC::get(MCConstants::ThThemeTopTags . $this->id . '_offset_' . $offset . '_limit_' . $limit);
  1045.         if (!$ret) {
  1046.             $sql = 'SELECT mt.tag_id, t.tag, mt.c_mess
  1047.                    FROM (
  1048.                    SELECT tag_id, COUNT(*) AS c_mess FROM th_messages_tags
  1049.                    WHERE theme_id = ?
  1050.                    GROUP BY tag_id ORDER BY c_mess DESC
  1051.                    LIMIT ?, ? ) AS mt
  1052.                    INNER JOIN th_tags t ON t.id = mt.tag_id';
  1053.  
  1054.             $statement = $this->getConnection()->prepare($sql);
  1055.             $statement->bindParam(1, $this->id, \PDO::PARAM_INT);
  1056.             $statement->bindParam(2, $offset, \PDO::PARAM_INT);
  1057.             $statement->bindParam(3, $limit, \PDO::PARAM_INT);
  1058.  
  1059.             if (($statement->execute()) AND ($statement->rowCount() > 0)) {
  1060.                 $rows = $statement->fetchAll();
  1061.                 $list = array();
  1062.                 //Для процентного соотношения для графика
  1063.                 $p1 = 0;
  1064.  
  1065.                 foreach ($rows as $row) {
  1066.                     //Расчитываем процентное соотношение по количеству сообщений данной темы
  1067.                     if ($p1 == 0) {
  1068.                         $p1 = $row['c_mess'];
  1069.                     }
  1070.                     $list[$row['tag_id']]['percent'] = $row['c_mess'] / $p1 * 100;
  1071.                     $list[$row['tag_id']]['c_mess'] = $row['c_mess'];
  1072.                     $list[$row['tag_id']]['name'] = $row['tag'];
  1073.                 }
  1074.                 //Возвращаем массив топ тегов - ключ - ид тега, и поля count и teg
  1075.                 \ECSNData\MemC::set(MCConstants::ThThemeTopTags . $this->id . '_offset_' . $offset . '_limit_' . $limit, $list);
  1076.                 return $list;
  1077.             } else {
  1078.                 return FALSE;
  1079.             }
  1080.         } else {
  1081.             //Возвращаем кэшированный список
  1082.             echo "Возвращено из кэша";
  1083.             return $ret;
  1084.         }
  1085.     }    
  1086.    
  1087. }
Add Comment
Please, Sign In to add comment