<?php

if(!defined('DATALIFEENGINE')) {
   define('DATALIFEENGINE', true);
}
if(!defined('ROOT_DIR')) {
   define('ROOT_DIR', substr(dirname(__file__), 0, -25));
}
if(!defined('ENGINE_DIR')) {
   define('ENGINE_DIR', ROOT_DIR . '/engine');
}
if(!class_exists('bullet_api')) {
   class bullet_api
   {
      public $db = null;
      public $dle_config = array();
      public $bullet_config = array();
      public $bullet_lng = array();
      public $router = array();
      public $bullet_cpu = false;
      public $homeUrl = '';
      public $bulletCasheDir = '';
      public $time = 0;
      public $timeValidSession = 0;
      public $member_id = array();
      public $action = '';
      public $endLinckSymbol = '';
      public function __construct()
      {
         global $config, $bullet_energy_config, $db, $member_id, $do, $bulletRouter, $bullet_energy_lang,$langdates,$langtranslit;
         if(!$bullet_energy_config['version']) {
            include_once (ENGINE_DIR . '/bullet_energy/data/forum_config.php');
         }
         if(!$bulletRouter['main']) {
            include_once (ENGINE_DIR . '/bullet_energy/data/router_param_type_' . $bullet_energy_config['is_cpu_type'] . '.php');
         }
         if(!$config['version_id']) {
            include_once (ENGINE_DIR . '/data/config.php');
         }
         if(!isset($db)) {
            include_once (ENGINE_DIR . '/classes/mysql.php');
            include_once (ENGINE_DIR . '/data/dbconfig.php');
         }
         if(!empty($bullet_energy_config['slash'])) {
            $this->endLinckSymbol = '/';
         }
         $this->router = $bulletRouter;
         $this->db = $db;
         $this->action = strip_tags(totranslit($_REQUEST['do'], true, true));
         $this->member_id = $member_id;
         $this->dle_config = $config;
         $this->time = time() + ($this->dle_config['date_adjust'] * 60);
         $this->bullet_config = $bullet_energy_config;
         $this->bulletCasheDir = ENGINE_DIR . '/bullet_energy/cache/system/';
         if(!$bullet_energy_lang) {
            require_once (ENGINE_DIR . '/bullet_energy/library/language/' . $this->dle_config['langs'] . '/site.lng');
         }
         $this->bullet_lng = $bullet_energy_lang;
         $this->bullet_cpu = $this->bullet_config['cpu'] ? true : false;
         $this->homeUrl = $this->bullet_cpu ? $this->dle_config['http_home_url'] : $this->dle_config['http_home_url'] . 'index.php';
         $this->timeValidSession = $this->time - ($this->bullet_config['session_time'] * 60);
         //$this->setSesionForum(array());
      }
      public function setSesionForum(array $data = array())
      {

         if(!$this->bullet_config['session_check'] or $this->action == 'forum') {
            return false;
         }
         $option = array();
         $robotIsArray = array("#.*(yandex|yadirectbot).*#si" => "Yandex", "#.*(google|accoona|gsa-crawler).*#si" => "Google", "#.*rambler.*#si" => "Rambler", '#.*mail.ru.*#si' => "Mail Ru", "#.*aport.*#si" => "Aport", "#.*TurtleScanner.*#si" => "Turtle", "#.*slurp.*#si" => "Inktomi Spider", "#.*msnbot.*#si" => "Msn", "#.*(askjeeves|ask jeeves).*#si" => "Ask Com", "#.*yahoo.*#si" => "Yahoo", "#.*scooter.*#si" => "AltaVista", "#.*lycos.*#si" => "Lycos.com", "#.*libwww.*#si" => "Punto", "#.*picsearch.*#si" => "PicSearch", "#.*mnogosearch.*#si" => "mnoGoSearch", "#.*(is_archiver|archive_org).*#si" => "Archive Org");
         $result = preg_replace(array_keys($robotIsArray), $robotIsArray, $_SERVER['HTTP_USER_AGENT']);
         if($result == $_SERVER['HTTP_USER_AGENT']) {
            $option['agent'] = $this->member_id['name'] ? $this->member_id['name'] : $this->bullet_lng['side_bar_4'];
            $option['isRobot'] = 0;
         } else {
            $option['agent'] = $result;
            $option['isRobot'] = 1;
         }
         $this->member_id['user_id'] = $this->member_id['user_id'] ? $this->member_id['user_id'] : 0;
         $option = array('ip' => $this->db->safesql(ip2long($_SERVER['REMOTE_ADDR'])), 'session' => $this->db->safesql(session_id()), 'user_group' => $this->db->safesql($this->member_id['user_group']), 'typyInfo' => 0, 'paramState' => $this->db->safesql(serialize(array('stuck' => $this->db->safesql($this->bullet_lng['side_bar_33']), 'agensi' => $option['agent'], 'isRobot' => $option['isRobot']))), 'key' => $this->member_id['user_id'] ? $this->member_id['user_id'] : $this->db->safesql(ip2long($_SERVER['REMOTE_ADDR'])));
         $this->db->query("INSERT INTO " . PREFIX . "_be_session 
                      (`session_id`, `user_id`, `key`, `ip`, `date`, `user_group`, `info_type`, `param_state`)
                       VALUES ('{$option['session']}', '{$this->member_id['user_id']}', '{$option['key']}' ,'{$option['ip']}', '{$this->time}', '{$option['user_group']}', '{$option['typyInfo']}', '{$option['paramState']}')
                       ON DUPLICATE KEY UPDATE 
                         session_id = '{$option['session']}', 
                         ip = '{$option['ip']}', 
                         date = '{$this->time}', 
                         user_group = '{$option['user_group']}', 
                         info_type = '{$option['typyInfo']}', 
                         param_state = '{$option['paramState']}'");
      }
      /**
       * bullet_api::setLinckTopicUser()
       * Метод формирования ссылки на страницу тем пользователя.
       * @param mixed $data['name']    - Имя пользователя.
       * @param mixed $data['border']  - Декоратор ссылки.
       * @param mixed $data['count']   - Колличество тем.
       * @param mixed $data['aTxt']    - Текст ссылки.
       * @return string - Ссылка в случае если тем больше нуля.
       */
      public function setLinckTopicUser(array $data = array())
      {
         $data['url'] = $this->bullet_cpu ? "{$this->homeUrl}user/" . urlencode($data['name']) . "/topic" : "{$this->homeUrl}?do=forum&amp;action=topic&amp;name=" . urlencode($data['name']);
         $data['border'] = explode(' ', $data['border']);
         return !empty($data['count']) ? $data['border'][0] . '<a href="' . $data['url'] . '">' . $data['aTxt'] . '</a>' . $data['border'][1] : '';
      }
      /**
       * bullet_api::setLinckMessageUser()
       * Метод формирования ссылки на страницу сообщений пользователя.
       * @param mixed $data['name']    - Имя пользователя.
       * @param mixed $data['border']  - Декоратор ссылки.
       * @param mixed $data['count']   - Колличество сообщений.
       * @param mixed $data['aTxt']    - Текст ссылки.
       * @return string - Ссылка в случае если сообщений больше нуля.
       */
      public function setLinckMessageUser(array $data = array())
      {
         $data['url'] = $this->bullet_cpu ? "{$this->homeUrl}user/" . urlencode($data['name']) . "/message" : "{$this->homeUrl}?do=forum&amp;action=message&amp;name=" . urlencode($data['name']);
         $data['border'] = explode(' ', $data['border']);
         return !empty($data['count']) ? $data['border'][0] . '<a href="' . $data['url'] . '">' . $data['aTxt'] . '</a>' . $data['border'][1] : '';
      }
      public function getLastPost(array $data = array())
      {
         global $tpl;
         $data['tree'] = $this->_loadCasheForum('tree_permanent', 'array');
         $data['groupCache'] = $this->_loadCasheForum('sys_cashe_group_' . $this->member_id['user_group'], 'array');
         if($data['groupCache']) {
            $data['groupCache'] = $data['groupCache']['parse'];
         } else {
            $this->_setForumCache('sys_cashe_group');
            $data['groupCache'] = $this->_loadCasheForum('sys_cashe_group_' . $this->member_id['user_group'], 'array');
            if(!$data['groupCache']) {
               return false;
            }
            $data['groupCache'] = $data['groupCache']['parse'];
         }
         if(!$data['tree']) {
            $this->_setForumCache('tree_permanent');
            $data['tree'] = $this->_loadCasheForum('tree_permanent', 'array');
            if(!$data['tree']) {
               return false;
            }
         }
         if(!$data['groupCache'] or $this->action == 'forum') {
            return '';
         }
         $this->db->query("SELECT id, id_parent, title, reply_count, view_count, autor_id, autor, last_reply_date, last_reply_info FROM " . PREFIX . "_be_topic WHERE id_parent IN ({$data['groupCache']}) ORDER BY last_reply_date DESC LIMIT 0, {$data['count']}");
         if(!$this->db->num_rows()) {
            return '';
         }
         $tpl->load_template('last_topic_content.tpl');
         while ($row = $this->db->get_row()) {
            $row['title'] = stripcslashes($row['title']);
            $row['ajaxAutor'] = "onclick=\"ShowProfile('" . urlencode($row['autor']) . "', '{$this->dle_config['http_home_url']}/user/" . urlencode($row['autor']) . "/', '" . $row['autor_id'] . "'); return false;\"";
            $row['ajaxAutor'] = $this->dle_config['allow_alt_url'] == 'yes' ? "<a {$row['ajaxAutor']} href=\"{$this->dle_config['http_home_url']}user/" . urlencode($row['autor']) . "/\">" : "<a {$row['ajaxAutor']} href=\"{$this->dle_config['http_home_url']}?subaction=userinfo&amp;user=" . urlencode($row['autor']) . "\">";
            $row['last_reply_info'] = unserialize($row['last_reply_info']);
            $row['ajax'] = "onclick=\"ShowProfile('" . urlencode($row['last_reply_info'][0]) . "', '{$this->dle_config['http_home_url']}/user/" . urlencode($row['last_reply_info'][0]) . "/', '" . $row['last_reply_info'][5] . "'); return false;\"";
            $row['ajax'] = $this->dle_config['allow_alt_url'] == 'yes' ? "<a {$row['ajax']} href=\"{$this->dle_config['http_home_url']}user/" . urlencode($row['last_reply_info'][0]) . "/\">" : "<a {$row['ajax']} href=\"{$this->dle_config['http_home_url']}?subaction=userinfo&amp;user=" . urlencode($row['last_reply_info'][0]) . "\">";
            $tpl->set('[linck]', $this->dle_config['allow_alt_url'] == 'yes' ? "<a href=\"" . $this->topic_linck($row['id'], totranslit($row['title'], true, true)) . "\">" : "<a href=\"" . $this->topic_linck($row['id'], totranslit($row['title'], true, true)) . "\">");
            $tpl->set('[/linck]', '</a>');
            $tpl->set('[topicAutor]', $row['ajaxAutor']);
            $tpl->set('[/topicAutor]', '</a>');
            $tpl->set('{topicAutorName}', $row['autor']);
            $tpl->set('[lastMessageLinck]', '<a href="' . $row['last_reply_info'][3] . '">');
            $tpl->set('[/lastMessageLinck]', '</a>');
            $tpl->set('[popupUserCard]', $row['ajax']);
            $tpl->set('[/popupUserCard]', '</a>');
            $tpl->set('{title}', stripcslashes($row['title']));
            $tpl->set('{replyCount}', $row['reply_count']);
            $tpl->set('[profile]', $this->dle_config['allow_alt_url'] == 'yes' ? "<a href=\"{$this->dle_config['http_home_url']}user/" . urlencode($row['last_reply_info'][0]) . "/\">" : "<a href=\"{$this->dle_config['http_home_url']}?subaction=userinfo&amp;user=" . urlencode($row['last_reply_info'][0]) . "\">");
            $tpl->set('[/profile]', '</a>');
            $tpl->set('{viewCount}', $row['view_count']);
            if(date('Ymd', $row['last_reply_info'][1]) == date('Ymd', time())) {
               $tpl->set('{lastMessageDate}', 'Сегодня' . langdate(", H:i", $row['last_reply_info'][1]));
            } elseif(date('Ymd', $row['last_reply_info'][1]) == date('Ymd', (time() - 86400))) {
               $tpl->set('{lastMessageDate}', 'Вчера' . langdate(", H:i", $row['last_reply_info'][1]));
            } else {
               $tpl->set('{lastMessageDate}', langdate($this->dle_config['timestamp_active'], $row['last_reply_info'][1]));
            }
            $row['linckTree'] = $this->cat_linck($data['tree'][$row['id_parent']]['tree_id'], totranslit($data['tree'][$row['id_parent']]['tree_title'], true, true));
            $row['linckTree'] = '<a href="' . $row['linckTree'] . '">' . $data['tree'][$row['id_parent']]['tree_title'] . '</a>';
            $tpl->set('{lastAutorName}', $row['last_reply_info'][0]);
            $tpl->set('{infoTopic}', 'Тема в разделе:' . $row['linckTree']);
            $tpl->set('{lastAutorAvatarLinck}', $row['last_reply_info'][4] ? $this->dle_config['http_home_url'] . 'uploads/fotos/' . $row['last_reply_info'][4] : $this->dle_config['http_home_url'] . 'templates/' . $this->dle_config['skin'] . '/bullet_energy/images/noavatar.png');
            $tpl->compile('last_topic_content');
         }
         $tpl->load_template('last_topic_box.tpl');
         $tpl->set('{contentListLast}', $tpl->result['last_topic_content']);
         $tpl->compile('last_topic_box');
      }
      public function setLinckDiscus(array $data = array())
      {

         $row = array();
         $data['lng'] = explode('|', $data['lng']); // var_dump( $data  );
         if(empty($data['id'])) {
            return '<a href="' . $this->dle_config['http_home_url'] . 'forum/discussion-' . $data['idPost'] . '">' . $data['lng'][0] . '</a>';
         } else {
            $row = $this->db->super_query("SELECT reply_count,title FROM " . PREFIX . "_be_topic WHERE id = {$data['id']}");
            return '<a href="' . $this->topic_linck($data['id'], totranslit($row['title'], true, true)) . '">' . $data['lng'][1] . '(' . $data['lng'][2] . $row['reply_count'] . ')' . '</a>';
         }
      }
      private function _loadCasheForum($name = '', $type = 'array')
      {
         if(file_exists($this->bulletCasheDir . $name . ".tmp")) {
            if($type == 'txt') {
               return file_get_contents($this->bulletCasheDir . $name . ".tmp");
            } elseif($type == 'array') {
               return unserialize(file_get_contents($this->bulletCasheDir . $name . ".tmp"));
            }
         } else {
            return false;
         }
      }
      public function topic_linck($id = '', $name = '')
      {
         $result = '';
         if($this->bullet_config['cpu']) {
            if($this->bullet_config['is_cpu_type']) {
               $result = $this->dle_config['http_home_url'] . $this->router['main'] . '/' . $this->router['topic'] . $id . $this->endLinckSymbol;
            } else {
               $result = $this->dle_config['http_home_url'] . $this->router['main'] . '/' . $this->router['topic'] . '/' . $id . '-' . $name . $this->endLinckSymbol;
            }
         } else {
            $result = $this->dle_config['http_home_url'] . '?do=forum&amp;action=showtopic&amp;id=' . $id;
         }
         return $result;
      }
      public function cat_linck($id = '', $name = '')
      {
         $result = '';
         if($this->bullet_config['cpu']) {
            if($this->bullet_config['is_cpu_type']) {
               $result = $this->dle_config['http_home_url'] . $this->router['main'] . '/' . $this->router['tree'] . $id . $this->endLinckSymbol;
            } else {
               $result = $this->dle_config['http_home_url'] . $this->router['main'] . '/' . $this->router['tree'] . '/' . $id . '-' . $name . $this->endLinckSymbol;
            }
         } else {
            $result = $this->dle_config['http_home_url'] . '?do=forum&amp;action=categories&amp;id=' . $id;
         }
         return $result;
      }
      private function _setForumCache($action = '')
      {
         if($action == 'sys_cashe_group') {
            $id = $this->member_id['user_group'];
            $this->db->query("SELECT tree_id FROM " . PREFIX . "_be_tree where tree_access_view like '%{$id}%'");
            if(!$this->db->num_rows()) {
               return false;
            }
            $tpm = array();
            while ($row = $this->db->get_row()) {
               foreach ($row as $key => $value) {
                  $tpm[] = $row['tree_id'];
               }
            }
            $this->db->query("SELECT tree_id FROM " . PREFIX . "_be_tree where tree_access_topic_read like '%{$id}%'");
            if(!$this->db->num_rows()) {
               return false;
            }
            $tpm_ = array();
            while ($row = $this->db->get_row()) {
               foreach ($row as $key => $value) {
                  $tpm_[] = $row['tree_id'];
               }
            }
            $inter = $this->db->safesql(implode(',', array_intersect($tpm, $tpm_))) ? $this->db->safesql(implode(',', array_intersect($tpm, $tpm_))) : 0;
            $this->_writeSysCashe('sys_cashe_group_' . $id, array('parse' => $inter, 'accessTreeView' => $this->db->safesql(implode(',', $tpm)), 'accessTopicView' => $this->db->safesql(implode(',', $tpm_))));
            return true;
         } elseif($action == 'tree_permanent') {
            $tree = array();
            $this->db->query("SELECT * FROM " . PREFIX . "_be_tree ORDER BY tree_display ASC");
            while ($row = $this->db->get_row()) {
               $tree[$row['tree_id']] = array();
               foreach ($row as $key => $value) {
                  $tree[$row['tree_id']][$key] = stripslashes($value);
               }
            }
            $this->_writeSysCashe('tree_permanent', $tree);
            return true;
         } else {
            return false;
         }
      }
      private function _writeSysCashe($file, $data)
      {
         $fp = fopen($this->bulletCasheDir . $file . '.tmp', 'wb+');
         fwrite($fp, serialize($data));
         fclose($fp);
         @chmod($this->bulletCasheDir . $file . '.tmp', 0666);
      }
   }
}
$apiBullet = new bullet_api();
//var_dump($metatags);


?>