<?php
/*
=================================================================
Bullet Energy - by White-Master 
-----------------------------------------------------------------
http://white-master.ru/
-----------------------------------------------------------------
Copyright (c) 2011 White-Master
=================================================================
Данный код защищен авторскими правами
=================================================================
Файл: ajax_handler.class.php
=================================================================
*/
class BulletAjaxHandler extends BulletAjax
{
  private $casheSysDir = '';
  private $db = null;
  private $filter = null;
  private $userID = '';
  private $userName = '';
  private $time = 0;
  private $viewer = null;
  private $linck = null;
  private $timeMarkerOldTopic = 0;
  private $id = 0;
  public function __construct()
  {
    require_once (ENGINE_DIR . '/bullet_energy/classes/filter.class.php');
    require_once (ENGINE_DIR . '/bullet_energy/classes/linck.class.php');
    $this->linck = new BulletEnergyLinck(array('cpu' => parent::$modules_config['cpu'], 'home' => parent::$dle_config['http_home_url']));
    require_once (ENGINE_DIR . '/bullet_energy/classes/ajax_viewer.class.php');
    if (!class_exists('db')) {
      require_once ENGINE_DIR . '/classes/mysql.class.php';
    }
    $this->db = new db;
    $this->filter = new BulletFilter;
    $this->filter->allow_url = parent::$group_user[parent::$id_member['user_group']]['allow_url'];
    $this->filter->allow_image = parent::$group_user[parent::$id_member['user_group']]['allow_image'];
    $this->viewer = new BulletAjaxViewer;
    $this->casheSysDir = ENGINE_DIR . '/bullet_energy/cache/system/';
    $this->userID = $this->db->safesql(parent::$id_member['user_id']);
    $this->userName = $this->db->safesql(parent::$id_member['name']);
    $this->time = time() + (parent::$dle_config['date_adjust'] * 60);
    $this->timeMarkerOldTopic = $this->time - parent::$modules_config['topic_day'] * 86400;
    $this->id = $this->getInt('id');
  }
  //  public function deleteTree()
  //  {
  //    if (!$this->_checkAdmin()) {
  //      die('die');
  //    }
  //    $option['id'] = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
  //    $option['idRemoveContent'] = $this->getInt('id_remove');
  //    $this->db->query("SELECT tree_topic,tree_parent_id FROM " . PREFIX . "_be_tree WHERE tree_id = {$option['id']}");
  //    $row = $this->db->num_rows() ? $this->db->get_row() : die('die');
  //    var_dump($this->_deleteChildTree(0, 0));
  //    die();
  //    if ($row['tree_parent_id'] > 0) {
  //      if ($option['idRemoveContent'] > 0) {
  //        $this->db->query("UPDATE " . PREFIX . "_be_topic SET id_parent = {$option['idRemoveContent']} WHERE id_parent = {$option['id']}");
  //        $this->db->query("UPDATE " . PREFIX . "_be_message SET tree_id = {$option['idRemoveContent']} WHERE tree_id = {$option['id']}");
  //      } else {
  //        $this->db->query("DELETE FROM " . PREFIX . "_be_topic WHERE id_parent = {$option['id']}");
  //        $this->db->query("DELETE FROM " . PREFIX . "_be_message WHERE tree_id = {$option['id']}");
  //      }
  //      $this->db->query("DELETE FROM " . PREFIX . "_be_tree WHERE tree_id = {$option['id']} LIMIT 1");
  //    }
  //    $this->_cacheDeleteAll();
  //    return 'ok';
  //  }
  public function deleteCache()
  {
    if (!$this->_checkAdmin()) {
      die('die');
    }
    $this->_cacheDeleteAll();
    return 'ok';
  }
  public function deleteComplain()
  {
    if (!$this->_checkAdmin()) {
      die('die');
    }
    $option['id'] = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
    $this->db->query("DELETE FROM " . PREFIX . "_be_complaint WHERE ct_id = {$option['id']} LIMIT 1");
    return 'ok';
  }
  public function deleteMessageOnlyAdmin()
  {
    if (!$this->_checkAdmin()) {
      die('die');
    }
    $option['id'] = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
    $this->db->query("SELECT parent_msg,id_topic FROM " . PREFIX . "_be_message WHERE id = {$option['id']}");
    if (!$this->db->num_rows()) {
      die('die');
    }
    $row = $this->db->get_row();
    if ($row['parent_msg']) {
      $this->db->query("DELETE FROM " . PREFIX . "_be_message WHERE id = {$option['id']} LIMIT 1");
      $this->db->query("DELETE FROM " . PREFIX . "_be_topic WHERE id = {$row['id_topic']} LIMIT 1");
      $this->db->query("SELECT * FROM " . PREFIX . "_be_complaint WHERE ct_msg_id = {$option['id']}");
      while ($row = $this->db->get_row()) {
        $option['idCompline'][] = $row['ct_id'];
      }
      $this->db->query("DELETE FROM " . PREFIX . "_be_complaint WHERE ct_id = " . implode(',', $option['idCompline']) . " LIMIT 1");
    } else {
      $this->db->query("DELETE FROM " . PREFIX . "_be_message WHERE id = {$option['id']} LIMIT 1");
      $this->db->query("SELECT * FROM " . PREFIX . "_be_complaint WHERE ct_msg_id = {$option['id']}");
      while ($row = $this->db->get_row()) {
        $option['idCompline'][] = $row['ct_id'];
      }
      $this->db->query("DELETE FROM " . PREFIX . "_be_complaint WHERE ct_id = " . implode(',', $option['idCompline']) . " LIMIT 1");
    }
    return 'ok';
  }
  public function feed()
  {
    $option = array();
    $row = array();
    $option['id'] = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['topic_57']))); //topic.id_parent
    //feed.id_user
    //topic.id_parent
    $this->db->query("SELECT topic.*, feed.*, feed.id as feedId
                      FROM " . PREFIX . "_be_topic AS topic
                      LEFT JOIN " . PREFIX . "_be_feed AS feed
                      ON (topic.id = feed.id_topic)
                      AND topic.id_parent = feed.id_tree
                      AND feed.id_user = {$this->userID}
                      WHERE topic.id = {$option['id']}
                      LIMIT 1");
    $row = $this->db->num_rows() ? $this->db->get_row() : die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['topic_57']))); //var_dump($row);
    if (!in_array($row['id_parent'], explode(',', $this->_getGroupIdParseTree()))) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['topic_56'])));
    }
    if ($row['id_user'] == null) {
      $this->db->query("INSERT INTO " . PREFIX . "_be_feed 
      (id, id_user, id_topic, id_tree, date, is_mail) VALUES (NULL, '{$this->userID}', '{$option['id']}', '{$row['id_parent']}', '{$this->time}', 'no')");
      return $this->getJson(array('param' => '1', 'data' => '<a id="feedClick" href="#" class="optionTopic" onclick="topicFeed(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['topic_55'] . '</a>', 'sub' => parent::$modules_lang['topic_58'] . stripcslashes($row['title']) . '.' . parent::$modules_lang['topic_60']));
    } elseif ($row['feedId']) {
      $this->db->query("DELETE FROM " . PREFIX . "_be_feed WHERE id = {$row['feedId']} LIMIT 1");
      return $this->getJson(array('param' => '1', 'data' => '<a id="feedClick" href="#" class="optionTopic" onclick="topicFeed(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['topic_54'] . '</a>', 'sub' => parent::$modules_lang['topic_59'] . stripcslashes($row['title'])));
    }
  }
  private function _getGroupIdParseTree()
  {
    return count(array_intersect(explode(',', parent::$sys_cashe['accessTreeView']), explode(',', parent::$sys_cashe['accessTopicView']))) ? $this->db->safesql(implode(',', array_intersect(explode(',', parent::$sys_cashe['accessTreeView']), explode(',', parent::$sys_cashe['accessTopicView'])))) : 0;
  }
  public function likeAll()
  {
    $option = array();
    $row = array();
    $option['id'] = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
    $this->db->query("SELECT msg.id, topic.title, topic.id as topId
                      FROM " . PREFIX . "_be_message AS msg
                      LEFT JOIN " . PREFIX . "_be_topic AS topic 
                      ON ( msg.id_topic = topic.id )
                      WHERE msg.id = {$option['id']}");
    $option = $this->db->num_rows() ? $this->db->get_row() : die('die');
    $option['countPostPosition'] = $this->db->super_query("SELECT COUNT(*) as count 
                                   FROM " . PREFIX . "_be_message AS msg
                                   WHERE id_topic = '{$option['topId']}'
                                   AND id <= {$option['id']}");
    $this->db->query("SELECT likes.thanks_date,user.name,user.foto,user.forum_post_count,user.forum_topic_count, 
                             user.forum_thanks_count,user.user_id,user.user_group
                             FROM " . PREFIX . "_be_thanks AS likes
                             LEFT JOIN " . PREFIX . "_users AS user
                             ON likes.thanks_id_user = user.user_id
                             WHERE likes.thanks_msg_id = '{$option['id']}'");
    while ($row = $this->db->get_row()) {
      $row['userLinck'] = $this->linck->setLinckCardUser(array($row['name'], $row['user_id'])) . $row['name'] . '</a>';
      $row['avatar'] = trim($row['foto']) ? parent::$dle_config['http_home_url'] . 'uploads/fotos/' . $row['foto'] : parent::$dle_config['http_home_url'] . 'templates/' . parent::$dle_config['skin'] . '/bullet_energy/images/noavatar.png';
      $option['return'][] = '<li>' . $this->linck->setLinckCardUser(array($row['name'], $row['user_id'])) . '<img src="' . $row['avatar'] . '" alt="" /></a><div class="memberInfo"><h3>' . $row['name'] . '</h3><div class="groupUser">' . parent::$group_user[$row['user_group']]['group_name'] . '</div><div><dl><dt>' . parent::$modules_lang['user_10'] . '</dt><dd>' . $row['forum_post_count'] . '</dd><dt>' . parent::$modules_lang['user_11'] . '</dt><dd>' . $row['forum_topic_count'] . '</dd><dt>' . parent::$modules_lang['user_12'] . '</dt><dd>' . $row['forum_thanks_count'] . '</dd></dl></div></div></li>';
    }
    $option['return'] = $this->getJson('<ol class="likeAllContent">' . implode('', $option['return']) . '</ol>');
    return '{"param": "1","data": ' . $option['return'] . ',"titl": "' . parent::$modules_lang['user_13'] . $option['countPostPosition']['count'] . '"}';
  }
  public function like()
  {
    $option = array();
    $option['id'] = $this->getInt('id') ? $this->getInt('id') : die('die');
    $this->db->query("SELECT msg.user_thanks, msg.autors_id, msg.thanks, likes.thanks_id
                      FROM " . PREFIX . "_be_message AS msg
                      LEFT JOIN " . PREFIX . "_be_thanks AS likes
                      ON likes.thanks_msg_id = msg.id
                      AND likes.thanks_id_user = {$this->userID}
                      WHERE msg.id = {$option['id']}");
    $row = $this->db->num_rows() ? $this->db->get_row() : die('die');
    if (!$row['thanks_id']) {
      $this->db->query("INSERT INTO " . PREFIX . "_be_thanks
      (thanks_id, thanks_msg_id, thanks_id_user, thanks_date, thanks_msg_id_user) 
      VALUES (NULL, '{$option['id']}', '{$this->userID}', '{$this->time}', '{$row['autors_id']}')");
      $this->db->query("UPDATE " . PREFIX . "_users SET forum_thanks_count = forum_thanks_count + 1 WHERE user_id = {$row['autors_id']} LIMIT 1");
      if ($row['thanks'] == 0) {
        $option['updateArrayLike'] = $this->db->safesql(serialize(array(array($this->userName, $this->userID))));
        $option['likeBlock'] = '<div class="likeBox-' . $option['id'] . '"><div>' . $this->viewer->card_user(array($this->userName, $this->userID)) . $this->userName . '</a>' . parent::$modules_lang['like_2'] . '</div></div>';
        $this->db->query("UPDATE " . PREFIX . "_be_message SET user_thanks = '{$option['updateArrayLike']}', thanks = thanks + 1 WHERE id = {$option['id']} LIMIT 1");
        return $this->getJson(array('param' => '1', 'linck' => '<a class="likeContent" href="#" onclick="like(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['like_1'] . '</a>', 'likeBlock' => $option['likeBlock']));
      } else {
        $row['user_thanks'] = unserialize($row['user_thanks']);
        if (count($row['user_thanks']) < 3) {
          array_push($row['user_thanks'], array($this->userName, $this->userID));
          foreach ($row['user_thanks'] as $key => $value) {
            $option['fetchLike'][] = $this->viewer->card_user(array($value[0], $value[1])) . $value[0] . '</a>';
          }
          if (($row['thanks'] - 3) > 0) {
            $option['sorseAll'] = $row['thanks'] - 3;
            $option['likeUserAll'] = parent::$modules_lang['like_3'] . $option['sorseAll'];
          }
          $option['likeBlock'] = '<div class="likeBox-' . $option['id'] . '"><div>' . implode(', ', $option['fetchLike']) . $option['likeUserAll'] . parent::$modules_lang['like_2'] . '</div></div>';
          $option['updateArrayLike'] = $this->db->safesql(serialize($row['user_thanks']));
          $this->db->query("UPDATE " . PREFIX . "_be_message SET user_thanks = '{$option['updateArrayLike']}', thanks = thanks + 1 WHERE id = {$option['id']} LIMIT 1");
          return $this->getJson(array('param' => '1', 'linck' => '<a class="likeContent" href="#" onclick="like(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['like_1'] . '</a>', 'likeBlock' => $option['likeBlock']));
        } else {
          //$row['user_thanks'] = unserialize($row['user_thanks']);
          foreach ($row['user_thanks'] as $key => $value) {
            $option['fetchLike'][] = $this->viewer->card_user(array($value[0], $value[1])) . $value[0] . '</a>';
          }
          $option['sorseAll'] = ($row['thanks'] + 1) - 3;
          $option['likeUserAll'] = parent::$modules_lang['like_4'] . '<a href="#" onclick="getAllLike(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['like_3'] . $option['sorseAll'] . '</a>';
          $option['likeBlock'] = '<div class="likeBox-' . $option['id'] . '"><div>' . implode(', ', $option['fetchLike']) . $option['likeUserAll'] . parent::$modules_lang['like_2'] . '</div></div>';
          $this->db->query("UPDATE " . PREFIX . "_be_message SET thanks = thanks + 1 WHERE id = {$option['id']} LIMIT 1");
          return $this->getJson(array('param' => '1', 'linck' => '<a class="likeContent" href="#" onclick="like(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['like_1'] . '</a>', 'likeBlock' => $option['likeBlock']));
        }
      }
      //forum_thanks_count
    } else {
      $option['unsetIs'] = false;
      $row['user_thanks'] = unserialize($row['user_thanks']);
      foreach ($row['user_thanks'] as $key => $value) {
        $option['sqlUpdate'][] = ' AND likes.thanks_id_user != ' . $value[1];
        if ($value[1] == $this->userID) {
          unset($row['user_thanks'][$key]);
          $option['unsetIs'] = true;
        }
      }
      if ($option['unsetIs']) {
        $this->db->query("SELECT * FROM " . PREFIX . "_be_thanks as likes
                                             LEFT JOIN " . PREFIX . "_users as user
                                             ON (likes.thanks_id_user = user.user_id)
                                             WHERE likes.thanks_msg_id = {$option['id']}" . implode(' ', $option['sqlUpdate']) . ' LIMIT 1');
        if ($this->db->num_rows()) {
          $rowUpdate = $this->db->get_row();
          array_push($row['user_thanks'], array($rowUpdate['name'], $rowUpdate['user_id']));
        }
      }
      if (($row['thanks'] - 1) > 0) {
        foreach ($row['user_thanks'] as $key => $value) {
          $option['fetchLike'][] = $this->viewer->card_user(array($value[0], $value[1])) . $value[0] . '</a>';
        }
        if (($row['thanks'] - 4) > 0) {
          $option['sorseAll'] = $row['thanks'] - 3;
          $option['likeUserAll'] = parent::$modules_lang['like_3'] . $option['sorseAll'];
        }
        $option['likeBlock'] = '<div class="likeBox-' . $option['id'] . '"><div>' . implode(', ', $option['fetchLike']) . $option['likeUserAll'] . parent::$modules_lang['like_2'] . '</div></div>';
      } else {
        $option['likeBlock'] = '<div class="likeBox-' . $option['id'] . '"></div>';
      }
      $row['user_thanks'] = ($row['thanks'] - 1) > 0 ? $this->db->safesql(serialize($row['user_thanks'])) : '';
      $this->db->query("UPDATE " . PREFIX . "_users SET forum_thanks_count = IF(forum_thanks_count > 1, forum_thanks_count - 1, 0) WHERE user_id = {$row['autors_id']} LIMIT 1");
      $this->db->query("UPDATE " . PREFIX . "_be_message 
                        SET user_thanks = '{$row['user_thanks']}',
                        thanks = IF(thanks > 1, thanks - 1, 0) 
                        WHERE id = {$option['id']} LIMIT 1");
      $this->db->query("DELETE FROM " . PREFIX . "_be_thanks 
                        WHERE thanks_id = {$row['thanks_id']} LIMIT 1");
      return $this->getJson(array('param' => '1', 'linck' => '<a class="likeContent" href="#" onclick="like(\'' . $option['id'] . '\'); return false;">' . parent::$modules_lang['like_0'] . '</a>', 'likeBlock' => $option['likeBlock']));
    }
  }
  public function topicOptionEdit()
  {
    $option = array();
    $option['id'] = $this->getInt('id') ? $this->getInt('id') : die('die');
    $this->db->query("SELECT * FROM " . PREFIX . "_be_topic WHERE id = {$option['id']}");
    $row = $this->db->num_rows() ? $this->db->get_row() : die('die');
    $option['title'] = htmlspecialchars(stripcslashes($row['title']));
    $option['fixed'] = intval($row['topic_fixed']) ? 'checked' : '';
    $option['type'] = intval($row['topic_type']) == 0 ? 'checked' : '';
    if ($this->ckeckModulesConfigGroup('be_moder_top_rename')) {
      $option['return']['rename'] = '<div class="paramBox"><p>' . parent::$modules_lang['topic_12'] . '</p><input type="text" maxlength="255"   value="' . $option['title'] . '" name="titl"></div>';
    }
    if ($this->ckeckModulesConfigGroup('be_moder_topic_wanted')) {
      $option['return']['wanted'] = '<li><label title="' . parent::$modules_lang['topic_14'] . '"><input type="checkbox" ' . $option['fixed'] . ' name="fixed">' . parent::$modules_lang['topic_13'] . '</label></li>';
    }
    if ($this->ckeckModulesConfigGroup('be_moder_close_to_open_topic')) {
      $option['return']['open'] = '<li><label title="' . $lang['topic_15'] . '"><input type="checkbox" ' . $option['type'] . ' name="status">' . parent::$modules_lang['topic_15'] . '</label></li>';
    }
    if ($this->ckeckModulesConfigGroup('be_moder_del_user_topic')) {
      $option['return']['delete'] = '<option value="0">' . parent::$modules_lang['topic_52'] . '</option>';
    }
    if ($this->ckeckModulesConfigGroup('be_moder_moder_access')) {
      if ($row['topic_approve']) {
        $option['isAprove'] = 'selected="selected"';
      } else {
        $option['isNoAprove'] = 'selected="selected"';
      }
      $option['return']['visible'] = "<option {$option['isNoAprove']} value=\"2\">" . parent::$modules_lang['topic_50'] . "</option><option {$option['isAprove']} value=\"1\">" . parent::$modules_lang['topic_51'] . "</option>";
    }
    if ($option['return']['delete'] or $option['return']['visible']) {
      $option['return']['statusTopic'] = "<select id=\"visible_param\" name=\"visible_param\">{$option['return']['visible']}{$option['return']['delete']}</select>";
    }
    if ($option['return']['open'] or $option['return']['wanted'] or $option['return']['statusTopic']) {
      $option['return']['ul'] = '<div class="paramBox"><ul class="topicEdit">' . $option['return']['open'] . $option['return']['wanted'] . $option['return']['statusTopic'] . '</ul></div>';
    }
    if (count($option['return'])) {
      return '<div class="inertOptionPopup">' . $option['return']['rename'] . $option['return']['ul'] . '<input type="hidden" value="' . $row['id'] . '" name="idTopic"></div>';
    }
  }
  /**
   * BulletAjaxHandler::recountTree()
   * Метод пересчета колличества тем и ответов в узле.
   * @return
   */
  public function recountTree()
  {
    if (!$this->_checkAdmin()) {
      die('die');
    }
    $option = array();
    foreach (parent::$treePermanent as $key => $value) {
      $row = $this->db->super_query("SELECT COUNT(*) as countTopic FROM " . PREFIX . "_be_topic WHERE id_parent = {$key} LIMIT 1");
      $option['countTopic'] = intval($row['countTopic']);
      $row = $this->db->super_query("SELECT COUNT(*) as countMessage FROM " . PREFIX . "_be_message WHERE tree_id = {$key} LIMIT 1");
      $option['countMessage'] = intval($row['countMessage']);
      $this->db->query("UPDATE " . PREFIX . "_be_tree 
                        SET tree_topic = '{$option['countTopic']}',
                        tree_answer = '{$option['countMessage']}' 
                        WHERE tree_id = {$key} LIMIT 1");
    }
    $this->_cacheDeleteAll();
    return 'ok';
  }
  /**
   * BulletAjaxHandler::recountTopicLast()
   * Метод обновления информации о последнем сообщение в теме.
   * @return void
   */
  public function recountTopicLast()
  {
    if (!$this->_checkAdmin()) {
      die('die');
    }
    $option = array('start' => $this->getInt('startfrom'), 'buffer' => '', 'step' => 0);
    $row = array();
    $this->db->query("SELECT topic.id, topic.title, topic.last_reply_date, message.autors_id, message.id AS post_id, 
                      user.foto, message.message_autor as name
                      FROM " . PREFIX . "_be_topic AS topic
                      LEFT JOIN " . PREFIX . "_be_message AS message 
                      ON topic.id = message.id_topic
                      AND message.message_date = topic.last_reply_date
                      LEFT JOIN " . PREFIX . "_users AS user 
                      ON message.autors_id = user.user_id
                      LIMIT {$option['start']}, 50");
    $data = array();
    while ($row = $this->db->get_row()) {
      $data[$row['id']] = array();
      foreach ($row as $key => $value) {
        $data[$row['id']][$key] = stripslashes($value);
      }
      $option['step']++;
    }
    $updateSql = array();
    foreach ($data as $keyData => $valueData) {
      if (!$valueData['id'] or !$valueData['post_id']) {
        continue;
      }
      $valueData['counts'] = $this->db->super_query("SELECT COUNT(*) as countPage
                                                     FROM " . PREFIX . "_be_message AS msg
                                                     WHERE id_topic = '{$valueData['id']}'
                                                     AND id <= {$valueData['post_id']}");
      $valueData['page'] = ceil($valueData['counts']['countPage'] / parent::$modules_config['message_count_page']);
      $valueData['page'] = $valueData['page'] == 1 ? '' : "/page-{$valueData['page']}";
      $valueData['page'] = $this->viewer->topic_linck_redirect($valueData['id']) . $valueData['page'] . '#message-' . $valueData['post_id'];
      $valueData['last'] = $this->_generateLastPostInfo(array($valueData['name'], $valueData['last_reply_date'], $valueData['title'], $valueData['page'], $valueData['foto'], $valueData['autors_id']));
      $updateSql[] = "UPDATE " . PREFIX . "_be_topic SET last_reply_info = '{$valueData['last']}' WHERE id = {$valueData['id']} LIMIT 1";
    }
    foreach ($updateSql as $sql) {
      $this->db->query($sql);
    }
    $option['countSql'] = $option['start'] + $option['step'];
    $buffer = "{\"status\": \"ok\",\"limitcount\": {$option['countSql']}}";
    die($buffer);
  }
  /**
   * BulletAjaxHandler::recountTreeLast()
   * Метод обновления информации о последнем сообщение в узле.
   * @return
   */
  public function recountTreeLast()
  {
    if (!$this->_checkAdmin()) {
      die('die');
    }
    $row = array();
    $option = array();
    $this->db->query("SELECT tree_id FROM " . PREFIX . "_be_tree WHERE tree_answer > 0");
    if (!$this->db->num_rows()) {
      return 'die';
    }
    $tpm_ = array();
    while ($row = $this->db->get_row()) {
      foreach ($row as $key => $value) {
        $tpm_[] = $row['tree_id'];
      }
    }
    foreach ($tpm_ as $key => $value) {
      $row = $this->db->super_query("SELECT user.foto, 
                                            topic.title, 
                                            message.autors_id,
                                            message.id as post_id, 
                                            topic.id as topic_id, 
                                            message.message_autor as name,
                                            message.tree_id,
                                            message.message_date   
                                     FROM dle_be_message AS message
                                     LEFT JOIN dle_users AS user ON (
                                       message.autors_id = user.user_id
                                     )
                                     LEFT JOIN dle_be_topic AS topic ON (
                                       message.id_topic = topic.id
                                     )
                                     WHERE 
                                       tree_id = {$value} 
                                     ORDER BY message.message_date  DESC
                                     LIMIT 1");
      $option[$row['tree_id']] = array();
      foreach ($row as $key => $value) {
        $option[$row['tree_id']][$key] = stripslashes($value);
      }
    }
    $updateSql = array();
    foreach ($option as $keyData => $valueData) {
      $valueData['counts'] = $this->db->super_query("SELECT COUNT(*) as countPage
                                                     FROM " . PREFIX . "_be_message AS msg
                                                     WHERE id_topic = '{$valueData['topic_id']}'
                                                     AND id <= {$valueData['post_id']}");
      $valueData['page'] = ceil($valueData['counts']['countPage'] / parent::$modules_config['message_count_page']);
      $valueData['page'] = $valueData['page'] == 1 ? '' : "/page-{$valueData['page']}";
      $valueData['page'] = $this->viewer->topic_linck_redirect($valueData['topic_id']) . $valueData['page'] . '#message-' . $valueData['post_id'];
      $valueData['last'] = $this->_generateLastPostInfo(array($valueData['name'], $valueData['message_date'], $valueData['title'], $valueData['page'], $valueData['foto'], $valueData['autors_id']));
      $updateSql[] = "UPDATE " . PREFIX . "_be_tree SET tree_last_info = '{$valueData['last']}' WHERE tree_id = {$valueData['tree_id']} LIMIT 1";
    }
    foreach ($updateSql as $sql) {
      $this->db->query($sql);
    }
    return 'ok';
  }
  /**
   * BulletAjaxHandler::moderatorDelete()
   *  Метод удаление модератора из базы данных форума (admin only)
   * @return
   */
  public function moderatorDelete()
  {
    $id = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
    $row = $this->db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_be_moderator WHERE id = {$id} LIMIT 1");
    if (!$this->_checkAdmin() or !$row['count']) {
      die('die');
    }
    $this->db->query("DELETE FROM " . PREFIX . "_be_moderator WHERE id = {$id} LIMIT 1");
    $this->_cacheDeleteAll();
    return 'ok';
  }
  /**
   * BulletAjaxHandler::advertisingDelete()
   * Метод удаления рекламного блока из базы данных форума (admin only)
   * @return
   */
  public function advertisingDelete()
  {
    $id = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
    $row = $this->db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_be_advertising WHERE advertising_id = {$id} LIMIT 1");
    if (!$this->_checkAdmin() or !$row['count']) {
      die('die');
    }
    $this->db->query("DELETE FROM " . PREFIX . "_be_advertising WHERE advertising_id = {$id} LIMIT 1");
    $this->_cacheDeleteAll();
    return 'ok';
  }
  /**
   * BulletAjaxHandler::questionsDelete()
   * Метод удаление Вопроса/Ответа из базы данных капчи (admin only)
   * @return
   */
  public function questionsDelete()
  {
    $id = $this->getInt('id') ? $this->db->safesql($this->getInt('id')) : die('die');
    $row = $this->db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_be_question WHERE id = {$id} LIMIT 1");
    if (!$this->_checkAdmin() or !$row['count']) {
      die('die');
    }
    $this->db->query("DELETE FROM " . PREFIX . "_be_question WHERE id = {$id} LIMIT 1");
    $this->_cacheDeleteAll();
    return 'ok';
  }
  /**
   * BulletAjaxHandler::_cacheDeleteAll()
   * Метод удаление всего кеша форума, используется при внесение глобальных изменений в настройки форума.
   * @return void
   */
  private function _cacheDeleteAll()
  {
    if (file_exists($this->casheSysDir . 'groups_config.tmp')) {
      @unlink($this->casheSysDir . 'groups_config.tmp');
    }
    if (file_exists($this->casheSysDir . 'question.tmp')) {
      @unlink($this->casheSysDir . 'question.tmp');
    }
    if (file_exists($this->casheSysDir . 'moderator.tmp')) {
      @unlink($this->casheSysDir . 'moderator.tmp');
    }
    if (file_exists($this->casheSysDir . 'tree_permanent.tmp')) {
      @unlink($this->casheSysDir . 'tree_permanent.tmp');
    }
    if (file_exists($this->casheSysDir . 'advertising.tmp')) {
      @unlink($this->casheSysDir . 'advertising.tmp');
    }
    $this->db->query("SELECT be_groups_id FROM " . PREFIX . "_be_groups ORDER BY be_groups_id ASC");
    while ($row = $this->db->get_row()) {
      if (file_exists($this->casheSysDir . 'sys_cashe_group_' . $row['be_groups_id'] . '.tmp')) {
        @unlink($this->casheSysDir . 'sys_cashe_group_' . $row['be_groups_id'] . '.tmp');
      }
    }
  }
  /**
   * BulletAjaxHandler::_checkAdmin()
   * Метод проверки является ли пользователь администратором, проверка по группе, если группа 1 то он администратор.
   * @return
   */
  private function _checkAdmin()
  {
    if (strip_tags($_POST['hash']) != parent::$login_hash) {
      die('die');
    }
    return intval(parent::$id_member['user_group']) == 1 ? true : false;
  }
  public function msgEditAjaxProcess()
  {
    if (!parent::$logged_is or strip_tags($_GET['hash']) != parent::$login_hash) {
      die($this->getJson(array('param' => '0', 'data' => 'die')));
    }
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_message WHERE id = {$this->id} LIMIT 1");
    if (!$row['id']) {
      die($this->getJson(array('param' => '0', 'data' => 'die')));
    }
    $edit = false; //:TODO is null time:
    if ($row['autors_id'] == $this->userID and parent::$group_config[parent::$id_member['user_group']]['be_access_edit_my_post']) {
      $edit = true;
    } elseif ($row['autors_id'] != $this->userID and parent::$group_config[parent::$id_member['user_group']]['be_moder_edit_message_user']) {
      $edit = true;
    } else {
      $edit = false;
    }
    if (!$edit) {
      die($this->getJson(array('param' => '0', 'data' => 'die')));
    }
    $text = $this->CreateEdirBlock($this->filter->decodeBBCodes($row['message_text'], false), $row['id_topic'], $row['id']);
    return $this->getJson(array('param' => '1', 'data' => $text));
  }
  public function readTreeProcess()
  {
    $id = $this->db->safesql($this->getInt('id'));
    $time = time() + (parent::$dle_config['date_adjust'] * 60);
    $topicUnreadCheck = $this->db->safesql(parent::$modules_config['topic_count'] * 3);
    $userID = $this->db->safesql(parent::$id_member['user_id']);
    if (!$id or !parent::$logged_is) {
      die('die');
    }
    $row = $this->db->super_query("SELECT tree_id FROM " . PREFIX . "_be_tree WHERE tree_id = {$id}");
    if (!$row) {
      die('die');
    }
    $this->db->query("INSERT INTO " . PREFIX . "_be_read_tree (bert_read_id,bert_user_id,bert_tree_id,bert_read_date) VALUES (NULL,'{$userID}','{$id}','{$time}') ON DUPLICATE KEY UPDATE bert_read_date = {$time}");
    $this->db->query("SELECT id FROM " . PREFIX . "_be_topic WHERE id_parent = {$id} ORDER BY last_reply_date DESC LIMIT 0 , {$topicUnreadCheck}");
    while ($row = $this->db->get_row()) {
      $tableSchema[] = "INSERT INTO " . PREFIX . "_be_read_topic (ber_read_id,ber_user_id,ber_topic_id,ber_tree_id,ber_read_date) VALUES (NULL,'{$userID}','{$row['id']}','{$id}','{$time}') ON DUPLICATE KEY UPDATE ber_read_date = {$time}";
    }
    foreach ($tableSchema as $table) {
      $this->db->query($table);
    }
    return 'ok';
  }
  public function ckeckModulesConfigGroup($val = '')
  {
    return intval(parent::$group_config[parent::$id_member['user_group']][$val]);
  }
  private function CreateEdirBlock($data = '', $idTopic = '', $idMsg = '')
  {
    $i = 0;
    $smiles = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr>";
    $smilies = explode(",", parent::$dle_config['smilies']);
    foreach ($smilies as $smile) {
      $i++;
      $smile = trim($smile);
      $smiles .= "<td style=\"padding:2px;\" align=\"center\"><a href=\"#\" onClick=\"dle_smiley(':$smile:'); return false;\"><img style=\"border: none;\" alt=\"$smile\" src=\"" . parent::$dle_config['http_home_url'] . "engine/data/emoticons/$smile.gif\" /></a></td>";
      if ($i % 4 == 0)
        $smiles .= "</tr><tr>";
    }
    $smiles .= "</tr></table>";
    $lang = parent::$modules_lang;
    if (parent::$group_user[parent::$id_member['user_group']]['allow_url']) {
      $option['url'] = '<li><span title="' . $lang['bbTitl_10'] . '" onclick="tag_url()" id="b_tag_url"></span></li><li><span title="' . $lang['bbTitl_11'] . '" onclick="tag_leech()" id="b_tag_leech"></span></li>';
    }
    if (parent::$group_user[parent::$id_member['user_group']]['allow_image']) {
      $option['images'] = '<li><span title="' . $lang['bbTitl_12'] . '" onclick="tag_image()" id="b_img"></span></li>';
    }
    //var_dump(parent::$group_user[parent::$id_member['user_group']]);
    $ret = <<< HTML
    <form action="" id="message_edit_form" name="message_edit_form" method="post">
    <div class="BoxEditMsg">
<script type="text/javascript" language="javascript">
var selField  = "editmsgform";
var fombj    = document.forms['message_edit_form'];
</script>
<div id="bbcode_bullet">
    <ol class="bbcode_forum">
   <li><span title="{$lang['bbTitl_2']}" onclick="simpletag('b')" id="b_b"></span></li>
    <li><span title="{$lang['bbTitl_3']}" onclick="simpletag('i')" id="b_i"></span></li>
    <li><span title="{$lang['bbTitl_4']}" onclick="simpletag('u')" id="b_u"></span></li>
    <li><span title="{$lang['bbTitl_5']}" onclick="simpletag('s')" id="b_s"></span></li> 
    <li class="separator"></li>
    <li><span title="{$lang['bbTitl_7']}" onclick="simpletag('left')" id="b_left"></span></li>
    <li><span title="{$lang['bbTitl_8']}" onclick="simpletag('center')" id="b_center"></span></li>
    <li><span title="{$lang['bbTitl_9']}" onclick="simpletag('right')" id="b_right"></span></li>
    <li class="separator"></li>
    <li><span title="{$lang['bbTitl_6']}" onclick="ins_emo(this);" id="b_emo"></span></li>
    {$option['url']}{$option['images']} 
    <li class="separator"></li>
    <li class="b_hide"><span title="{$lang['bbTitl_13']}" onclick="simpletag('hide')" id="b_hide"></span></li>
    <li><span title="{$lang['bbTitl_14']}" onclick="simpletag('quote')" id="b_quote"></span></li>
    <li><span title="{$lang['bbTitl_1']}" onclick="simpletag('spoiler')" id="b_spoiler"></span></li>
  </ol>
  <div id="bullet_energy_emos" style="display: none;">
    <div style="overflow: auto;">{$smiles}</div>
  </div>
</div>
<textarea rows="8" class="editmsgform" name="editmsgform" id="editmsgform">{$data}</textarea></div>
<div class="EditControl"><a href="javascript:;" onclick="MsgEditSave(); return false;" title="{$lang['msg_9']}">{$lang['msg_10']}</a> <a href="javascript:;" onclick="MsgEditCancel('{$idMsg}'); return false;" title="{$lang['msg_8']}">{$lang['msg_7']}</a></div>
<input type="hidden" value="{$idTopic}" id="topict_id" name="topict_id">
<input type="hidden" value="{$idMsg}" id="msg_id" name="msg_id">
</form>
HTML;
    return $ret;
  }
  public function EditSaveMsgProcess()
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    $option = array('topic_id' => $this->db->safesql($this->getInt('topic_id')), 'msg_id' => $this->db->safesql($this->getInt('msg_id')), 'aprove' => parent::$id_member['user_group'] == 1 ? 1 : 0, );
    if (!$option['topic_id'] or !$option['msg_id']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'])));
    }
    $row = $this->db->super_query("SELECT title,topic_approve,id_parent FROM " . PREFIX . "_be_topic WHERE id = {$option['topic_id']} LIMIT 1");
    if (!$row['id_parent']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'])));
    }
    $_POST['topic_name'] = $row['title'];
    $option['message'] = $this->db->safesql($this->filter->BB_Parse($this->filter->process(trim($this->convert_unicode($_REQUEST['text_msg']))), false));
    $option['id_parent'] = $row['id_parent'];
    if (!$option['message']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'])));
    }
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_message WHERE id = {$option['msg_id']} LIMIT 1");
    if ($row['tree_id'] != $option['id_parent'] or $row['id_topic'] != $option['topic_id']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'])));
    }
    $edit = false;
    if (in_array(parent::$id_member['user_group'], explode(',', parent::$treePermanent[$row['tree_id']]['tree_access_topic_replic']))) {
      $edit = true;
    }
    if ($row['autors_id'] == parent::$id_member['user_id'] and parent::$group_config[parent::$id_member['user_group']]['be_access_edit_my_post'] and $edit) {
      $edit = true;
    } elseif ($row['autors_id'] != parent::$id_member['user_id'] and parent::$group_config[parent::$id_member['user_group']]['be_moder_edit_message_user'] and $edit) {
      $edit = true;
    } else {
      $edit = false;
    }
    if ($this->_valueStrlen($option['message'], parent::$dle_config['charset']) > parent::$modules_config['message_count'] and $edit) {
      $edit = false;
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_1'])));
    }
    if (!$edit) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'])));
    }
    $this->db->query("UPDATE " . PREFIX . "_be_message 
                      SET message_text ='{$option['message']}', 
                      message_approve='{$option['aprove']}', 
                      msg_edit_date='{$this->time}', 
                      edit_autor='{$this->userName}' 
                      WHERE id = '{$row['id']}' 
                      LIMIT 1");
    return $this->getJson(array('param' => '1', 'id' => $row['id'], 'data' => $this->_getMsg($row['id'], $option['topic_id'])));
  }
  public function refreshAttachmentListProcess()
  {
    /*Function is modified 04.07.2011 RC 0.1*/
    $this->db->query("SELECT attachment_id,attachment_type,attachment_name,attachment_date 
                      FROM " . PREFIX . "_be_attachment 
                      WHERE attachment_user_id = '{$this->userID}' 
                      AND attachment_content_id = 0 
                      AND attachment_user_name = '{$this->userName}' 
                      ORDER BY attachment_id DESC");
    if ($this->db->num_rows()) {
      while ($row = $this->db->get_row()) {
        $data['fileType'] = intval($row['attachment_type']);
        $data['fileExtensions'] = $this->_getExtensions($row['attachment_name']);
        $data['fileDateUpload'] = date('Y-m', $row['attachment_date']);
        $data['fileName'] = $row['attachment_name'];
        $data['fileNameSiteView'] = substr($row['attachment_name'], 10, 100);
        $data['fileDbId'] = $row['attachment_id'];
        $cash .= $this->viewer->setTplAttachmentList($data);
      }
      return $cash;
    } else {
      return parent::$modules_lang['error_15'];
    }
  }
  private function _getExtensions($fileName = '')
  {
    return substr($fileName, strrpos($fileName, '.') + 1);
  }
  public function TopicEditProcess()
  {
    $id = $this->db->safesql(intval($this->getInt('id')));
    if (!$id) {
      die("die");
    }
    if (preg_match("/[\||\'|\<|\>|\"|\!|\?|\$|\@|\/|\\\|\&\~\*\+]/", $id))
      die("die");
    if (!parent::$group_config[parent::$id_member['user_group']]['be_moder_topic_moder_param']) {
      die('die');
    }
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_topic WHERE id = {$id} LIMIT 1");
    if (!$row) {
      die("die");
    }
    $titl = htmlspecialchars(stripcslashes($row['title']));
    $lang = parent::$modules_lang;
    $rename = '';
    $fixed = '';
    $wanted = '';
    $open = '';
    $type = '';
    $visibl = '';
    $del = '';
    $ap = '';
    $noap = '';
    $status = '';
    if (intval($row['topic_fixed'])) {
      $fixed = "checked";
    }
    if (intval($row['topic_type']) == 0) {
      $type = "checked";
    }
    if (parent::$group_config[parent::$id_member['user_group']]['be_moder_top_rename']) {
      $rename = '<div class="boxEditParam"><label>' . $lang['topic_12'] . ': <input type="text" maxlength="255" class="forum_input" value="' . $titl . '" name="titl"></label></div>';
    }
    if (parent::$group_config[parent::$id_member['user_group']]['be_moder_topic_wanted']) {
      $wanted = '<li><label title="' . $lang['topic_14'] . '"><input type="checkbox" ' . $fixed . ' name="fixed">' . $lang['topic_13'] . '</label></li>';
    }
    if (parent::$group_config[parent::$id_member['user_group']]['be_moder_close_to_open_topic']) {
      $open = '<li><label title="' . $lang['topic_15'] . '"><input type="checkbox" ' . $type . ' name="status">' . $lang['topic_15'] . '</label></li>';
    }
    if (parent::$group_config[parent::$id_member['user_group']]['be_moder_del_user_topic']) {
      $del = '<option value="0">Удалено</option>';
    }
    if (parent::$group_config[parent::$id_member['user_group']]['be_moder_moder_access']) {
      if ($row['topic_approve']) {
        $ap = 'selected="selected"';
      } else {
        $noap = 'selected="selected"';
      }
      $visibl = "<option {$noap} value=\"2\">На модерации</option><option {$ap} value=\"1\">Одобрено</option>";
    }
    if ($del or $visibl) {
      $status = "<div class=\"boxEditParam\"><label>Состояние:<select id=\"visible_param\" class=\"select_forum\" name=\"visible_param\">{$visibl}{$del}</select></label></div>";
    }
    if ($open != '' or $wanted != '') {
      $ul = '<div class="boxEditParam"><ul class="topicEdit">' . $open . $wanted . '</ul></div>';
    }
    $ret = <<< HTML
<li class="editTopic" id="topic_item_edit-{$row['id']}"><div class="inertBox">{$rename}{$ul}{$status}<div class="boxEditParam Bottom"><a href="javascript:;" onclick="saveEditTopic('{$row['id']}'); return false;" class="blackBotton">Сохронить</a><a href="javascript:saveCloze('{$row['id']}')" class="blackBotton">Отмена</a></div></div></li>
HTML;
    //var_dump($row);
    return $ret;
  }
  /**
   * BulletAjaxHandler::messageAddAjax()
   * Метод добавления сообщения в базу данных (Ajax)
   * @return
   */
  public function messageAddAjaxProcess()
  {
    /*Function is modified 01.07.2011 RC 0.1*/
    $row = $this->db->super_query("SELECT id,title,topic_type,reply_count,topic_approve,id_parent,topic_private_user FROM " . PREFIX . "_be_topic WHERE id = '" . $this->getInt('topic_id') . "' LIMIT 1");
    if (!$row['id']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'])));
    }
    $option = array('topicId' => $this->getInt('topic_id'), 'ipUser' => ip2long($_SERVER['REMOTE_ADDR']), 'idUser' => parent::$id_member['user_id'], 'userName' => parent::$id_member['name'], 'time' => $this->time, 'topicName' => $row['title'], 'topicType' => $row['topic_type'], 'topicReplyCount' => $row['reply_count'], 'topicAprove' => $row['topic_approve'], 'id_parent' => $row['id_parent'], 'topicUserIsPrivate' => $row['topic_private_user'], 'postMsg' => $this->db->safesql($this->filter->BB_Parse($this->filter->process(trim($this->convert_unicode($_GET['text_msg']))), false)));
    if (parent::$modules_config['message_count_mini'] and $this->_valueStrlen(str_replace(" ", "", strip_tags($option['postMsg'])), parent::$dle_config['charset']) < parent::$modules_config['message_count_mini']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_0'])));
    }
    if ($this->_valueStrlen($option['postMsg'], parent::$dle_config['charset']) > parent::$modules_config['message_count']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_1'])));
    }
    if (!parent::$group_config[parent::$id_member['user_group']]['be_captha_status']) {
      if (parent::$modules_config['captha_type']) {
        $option['jaRefresh'] = '<script type="text/javascript"language="javascript">if(document.getElementById(\'recaptcha_response_field\')){Recaptcha.reload();}</script>';
        if (!trim($_REQUEST['recaptcha_response_field'])) {
          die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_14'] . $option['jaRefresh'])));
        }
        require_once ENGINE_DIR . '/bullet_energy/modules/security.php';
        if ($_REQUEST['recaptcha_response_field'] and $_REQUEST['recaptcha_challenge_field']) {
          $resp = recaptcha_check_answer(parent::$modules_config['reprivate'], $_SERVER['REMOTE_ADDR'], $_REQUEST['recaptcha_challenge_field'], $_REQUEST['recaptcha_response_field']);
          if (!$resp->is_valid) {
            die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_14'] . $option['jaRefresh'])));
          }
        }
      } else {
        $option['jaRefresh'] = '<script type="text/javascript"language="javascript">if(document.getElementById(\'question\')){document.getElementById(\'question\').value="Введите ответ...";}</script>';
        if (!trim($_REQUEST['recaptcha_response_field'])) {
          die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_18'] . $option['jaRefresh'])));
        }
        if (!parent::$question[$this->getInt('recaptcha_challenge_field')]) {
          die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_4'] . $option['jaRefresh'])));
        }
        $capthaAnswer = trim(strip_tags(strtolower($this->filter->process($this->convert_unicode($this->getString('recaptcha_response_field'))))));
        $arrAnswer = explode('<sep>', parent::$question[$this->getInt('recaptcha_challenge_field')]['answers']);
        foreach ($arrAnswer as $key => &$answer) {
          $answer = strip_tags(strtolower($answer));
        }
        if (!in_array($capthaAnswer, $arrAnswer)) {
          die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_17'] . $option['jaRefresh'])));
        }
      }
    }
    $pages = ceil(($option['topicReplyCount'] + 2) / parent::$modules_config['message_count_page']);
    $option['pageSyfix'] = parent::$modules_config['cpu'] ? '/page-' . $pages : '&amp;page=' . $pages;
    $pages = $pages == 1 ? '' : $option['pageSyfix'];
    if (!in_array(parent::$id_member['user_group'], explode(',', parent::$treePermanent[$option['id_parent']]['tree_access_topic_replic']))) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_2'])));
    }
    if ($option['topicType'] and !in_array(parent::$id_member['name'], explode(',', $option['topicUserIsPrivate']))) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_3'])));
    }
    $row = $this->db->super_query("SELECT message_date FROM " . PREFIX . "_be_message WHERE autors_id = '{$option['idUser']}' ORDER BY id DESC LIMIT 1");
    if (parent::$group_config[parent::$id_member['user_group']]['be_time_step_msg'] and $this->time - intval($row['message_date']) < parent::$group_config[parent::$id_member['user_group']]['be_time_step_msg']) {
      die($this->getJson(array('param' => '0', 'data' => parent::$modules_lang['msg_5'])));
    }
    if (intval(parent::$modules_config['wrap_count_msg'])) {
      if (parent::$dle_config['charset'] == "utf-8")
        $utf_pref = "u";
      else
        $utf_pref = "";
      $option['postMsg'] = preg_split('((>)|(<))', $option['postMsg'], -1, PREG_SPLIT_DELIM_CAPTURE);
      $n = count($msg);
      for ($i = 0; $i < $n; $i++) {
        if ($option['postMsg'][$i] == "<") {
          $i++;
          continue;
        }
        $option['postMsg'][$i] = preg_replace("#([^\s\n\r]{" . intval(parent::$modules_config['wrap_count_msg']) . "})#{$utf_pref}i", "\\1<br />", $option['postMsg'][$i]);
      }
      $option['postMsg'] = join("", $option['postMsg']);
    }
    $combine = false;
    if (parent::$modules_config['msg_combine']) {
      $row = $this->db->super_query("SELECT id,id_topic,autors_id,message_autor,message_date,message_text FROM " . PREFIX . "_be_message where id_topic = '{$option['topicId']}' ORDER BY id DESC LIMIT 1");
      if ($row['autors_id'] == $option['idUser']) {
        $combine = true;
      }
      if (parent::$group_config[parent::$id_member['user_group']]['be_time_step_msg'] and (($row['message_date'] + (parent::$group_config[parent::$id_member['user_group']]['be_time_step_msg'] * 60)) < $this->time)) {
        $combine = false;
      }
      if (date("Y-m-d", $row['message_date']) != date("Y-m-d", $this->time)) {
        $combine = false;
      }
      if ((($this->_valueStrlen($row['message_text'], parent::$dle_config['charset']) + $this->_valueStrlen($option['postMsg'], parent::$dle_config['charset'])) > parent::$modules_config['message_count']) and $combine) {
        $combine = false;
      }
    }
    $option['foto'] = parent::$id_member['foto'] == '' ? '' : parent::$id_member['foto'];
    if (parent::$id_member['user_group'] == 1 or $this->checkModerator($option['id_parent'])) {
      $option['avprove'] = 1;
    } else {
      $option['avprove'] = 0;
    }
    if ($combine) {
      $option['postMsg'] = $this->db->safesql($row['message_text']) . '<br /><br />' . $option['postMsg'];
      $this->db->query("UPDATE " . PREFIX . "_be_message 
                        SET message_approve='{$option['avprove']}', 
                        message_text='{$option['postMsg']}', 
                        msg_edit_date= '{$this->time}', 
                        edit_autor='{$option['userName']}' 
                        WHERE id='{$row['id']}'");
      $last = $this->_generateLastPostInfo(array($option['userName'], $this->time, $option['topicName'], $this->viewer->linckTopic($option['topicId']) . $pages . '#message-' . $row['id'], $option['foto'], $option['idUser']));
      $this->db->query("UPDATE " . PREFIX . "_be_tree 
                        SET tree_last_info = '{$last}', 
                        tree_last_date = {$this->time} 
                        WHERE tree_id = {$option['id_parent']}");
      $this->db->query("UPDATE " . PREFIX . "_be_topic 
                        SET last_reply_info='{$last}', 
                        last_reply_date='{$this->time}' 
                        WHERE id = {$option['topicId']}");
      $this->db->query("INSERT INTO " . PREFIX . "_be_read_topic 
                        (ber_read_id,ber_user_id,ber_topic_id,ber_tree_id,ber_read_date) VALUES (NULL,'{$this->userID}','{$option['topicId']}','{$option['id_parent']}','{$this->time}') 
                        ON DUPLICATE KEY UPDATE ber_read_date={$this->time}");
      $this->db->query("INSERT INTO " . PREFIX . "_be_read_tree (bert_read_id,bert_user_id,bert_tree_id,bert_read_date) VALUES (NULL,'{$this->userID}','{$option['id_parent']}','{$this->time}') ON DUPLICATE KEY UPDATE bert_read_date = {$this->time}");
      return $this->getJson(array('param' => '1', 'id' => $row['id'], 'data' => $this->_getMsg($row['id'], $option['topicId']) . $option['jaRefresh']));
    } else {
      $this->db->query("INSERT INTO " . PREFIX . "_be_message 
                        (id,id_topic,autors_id,message_autor,message_autor_ip,message_date,message_text,message_approve,tree_id,parent_msg,user_thanks) 
                        VALUES (NULL,'{$option['topicId']}','{$option['idUser']}','{$option['userName']}','{$option['ipUser']}','{$this->time}','{$option['postMsg']}','{$option['avprove']}',{$option['id_parent']},'0','')");
      $option['insertId'] = $this->db->insert_id();
      $last = $this->_generateLastPostInfo(array($option['userName'], $this->time, $option['topicName'], $this->viewer->linckTopic($option['topicId']) . $pages . '#message-' . $option['insertId'], $option['foto'], $option['idUser']));
      if (parent::$treePermanent[$option['id_parent']]['tree_count'] == 1) {
        $this->db->query("UPDATE " . PREFIX . "_users 
                        SET forum_post_count = forum_post_count + 1 
                        WHERE user_id = '{$option['idUser']}'");
      }
      $this->db->query("UPDATE " . PREFIX . "_be_tree 
                        SET tree_last_info = '{$last}', 
                        tree_answer = tree_answer + 1, 
                        tree_last_date = '{$this->time}'
                        WHERE tree_id = '{$option['id_parent']}'");
      $this->db->query("UPDATE " . PREFIX . "_be_topic 
                        SET last_reply_info = '{$last}', 
                        reply_count=reply_count + 1, 
                        last_reply_date = '{$this->time}' 
                        WHERE id = '{$option['topicId']}'");
      $this->db->query("INSERT INTO " . PREFIX . "_be_read_topic 
                        (ber_read_id,ber_user_id,ber_topic_id,ber_tree_id,ber_read_date) VALUES (NULL,'{$this->userID}','{$option['topicId']}','{$option['id_parent']}','{$this->time}') 
                        ON DUPLICATE KEY UPDATE ber_read_date={$this->time}");
      $this->db->query("INSERT INTO " . PREFIX . "_be_read_tree (bert_read_id,bert_user_id,bert_tree_id,bert_read_date) VALUES (NULL,'{$this->userID}','{$option['id_parent']}','{$this->time}') ON DUPLICATE KEY UPDATE bert_read_date = {$this->time}");
      return $this->getJson(array('param' => '2', 'id' => $option['insertId'], 'data' => $this->_getMsg($option['insertId'], $option['topicId']) . $option['jaRefresh']));
    }
  }
  private function getJson($arr)
  {
    return json_encode($this->_jconvert(parent::$dle_config['charset'], 'utf-8', $arr));
  }
  private function _jconvert($from, $to, $var)
  {
    if (is_array($var)) {
      $new = array();
      foreach ($var as $key => $val) {
        $new[$this->_jconvert($from, $to, $key)] = $this->_jconvert($from, $to, $val);
      }
      $var = $new;
    } else
      if (is_string($var)) {
        $var = iconv($from, $to, $var);
      }
    return $var;
  }
  private function convertToCp($arr)
  {
    return $this->_jconvert('utf-8', 'cp1251', $arr);
  }
  private function _getMsg($id = '', $idTopic = '')
  {
    /*Function is modified 03.07.2011 RC 0.1*/
    $row = $this->db->super_query("SELECT COUNT(*) as count 
                                   FROM " . PREFIX . "_be_message AS msg
                                   WHERE id_topic = '{$idTopic}'
                                   AND id <= {$id}");
    $option = array('idPostPage' => $row['count']);
    $row = $this->db->super_query("SELECT * 
                                   FROM " . PREFIX . "_be_message AS msg
                                   LEFT JOIN " . PREFIX . "_users AS user
                                   ON msg.autors_id = user.user_id 
                                   WHERE id = {$id} LIMIT 1");
    if ($this->checkModerator($row['tree_id']) and $this->ckeckModulesConfigGroup('be_moder_ip_view')) {
      $data['message_autor_ip'] = long2ip($row['message_autor_ip']);
    }
    $data['one_message'] = $row['parent_msg'];
    $data['idPostPage'] = $option['idPostPage'];
    $data['message_autor'] = $row['message_autor'];
    $data['autors_id'] = $row['autors_id'];
    $data['message_date'] = $this->langdate(parent::$modules_config['time_step_message'], $row['message_date']);
    $data['message_text'] = stripslashes($row['message_text']);
    $data['msg_edit_date'] = $row['msg_edit_date'];
    $data['edit_autor'] = $row['edit_autor'];
    $data['news_num'] = $row['news_num'];
    $data['comm_num'] = $row['comm_num'];
    $data['forum_topic_count'] = $row['forum_topic_count'];
    $data['forum_post_count'] = $row['forum_post_count'];
    $data['id_topic'] = $row['id_topic'];
    $data['user_group'] = parent::$group_user[$row['user_group']]['group_name'];
    $data['css_name'] = parent::$group_config[$row['user_group']]['be_style_name_css'];
    $data['css_group'] = parent::$group_config[$row['user_group']]['be_style_group_css']; //var_dump(parent::$group_config[$row['user_group']]);
    $data['reg_date'] = $this->langdate(parent::$modules_config['time_step_autor'], $row['reg_date']);
    $data['foto'] = $row['foto'] ? parent::$dle_config['http_home_url'] . 'uploads/fotos/' . $row['foto'] : parent::$dle_config['http_home_url'] . 'templates/' . parent::$dle_config['skin'] . '/bullet_energy/images/noavatar.png';
    $data['signature'] = stripcslashes($row['signature']);
    $data['icq'] = stripcslashes($row['icq']);
    $data['mesage_id'] = $row['id'];
    return $this->viewer->setTplMessage($data);
  }
  public function checkModerator($id = '')
  {
    /*Function is modified 03.07.2011 RC 0.1*/
    if (in_array($id, parent::$moderator[parent::$id_member['user_id']]['treeAccess'])) {
      if (parent::$group_config[parent::$id_member['user_group']]['be_moder_topic_moder_param'] and parent::$group_config[parent::$id_member['user_group']]['be_moder_moder_access']) {
        return true;
      }
    } elseif (parent::$moderator[parent::$id_member['user_id']]['moderator_super']) {
      return true;
    } else {
      return false;
    }
  }
  private function _generateLastPostInfo($data = array())
  {
    foreach ($data as $key => $val) {
      $ret[] = stripcslashes(stripcslashes($val));
    }
    if (!$ret) {
      return false;
    }
    return $this->db->safesql(serialize($ret));
  }
  private function _valueStrlen($value = '', $charset = '')
  {
    return strtolower($charset) == "utf-8" ? iconv_strlen($value, "utf-8") : strlen($value);
  }
  public function TopicUpdateProcess()
  {
    $id = intval($this->getInt('topic_id'));
    $fixed = intval($this->getInt('topic_fixed'));
    $status = intval($this->getInt('topic_status'));
    $visible = intval($this->getInt('topic_visible'));
    if (!$status > 1 and !$fixed > 1) {
      die("die");
    }
    if ($status == 0) {
      $status = 2;
    } elseif ($status == 1) {
      $status = 0;
    }
    $name = $this->db->safesql($this->convert_unicode($this->filter->process(trim(strip_tags($_POST['topic_name'])))));
    if (parent::$modules_config['title_case']) {
      $name = ucfirst($name);
    }
    if (!$id) {
      die("die");
    }
    //  var_dump($id);
    if (!parent::$group_config[parent::$id_member['user_group']]['be_moder_topic_moder_param']) {
      die('die');
    }
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_topic WHERE id = {$id} LIMIT 1");
    if (!$row) {
      die("die");
    }
    if ($name != stripcslashes($row['title']) and parent::$group_config[parent::$id_member['user_group']]['be_moder_top_rename']) {
      $update[] = "title = '{$name}'";
    }
    if ($fixed != intval($row['topic_fixed']) and parent::$group_config[parent::$id_member['user_group']]['be_moder_topic_wanted']) {
      $update[] = "topic_fixed = '{$fixed}'";
    }
    if ($status != intval($row['topic_type']) and parent::$group_config[parent::$id_member['user_group']]['be_moder_close_to_open_topic']) {
      $update[] = "topic_type = '{$status}'";
    }
    if ($visible == 1 or $visible == 2 and parent::$group_config[parent::$id_member['user_group']]['be_moder_moder_access']) {
      if ($visible == 2) {
        $visible = 0;
      }
      if ($visible != intval($row['topic_approve'])) {
        $update[] = "topic_approve = '{$visible}'";
      }
    } elseif ($visible == 0 and parent::$group_config[parent::$id_member['user_group']]['be_moder_del_user_topic']) {
      $count = $this->db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_be_message WHERE id_topic = {$id}");
      $this->db->query("DELETE FROM " . PREFIX . "_be_topic WHERE id = {$id} LIMIT 1");
      $this->db->query("DELETE FROM " . PREFIX . "_be_message WHERE id_topic = {$id}");
      $this->db->query("UPDATE " . PREFIX . "_be_tree set tree_last_info = '', tree_topic=tree_topic-1,tree_answer=tree_answer-{$count['count']} WHERE tree_id={$row['id_parent']}");
      $this->db->query("UPDATE " . PREFIX . "_users set forum_post_count = forum_post_count-1,forum_topic_count = forum_topic_count-1 WHERE user_id = {$row['autor_id']} LIMIT 1");
      return '<li class="topicList deleteTopic">' . parent::$modules_lang['topic_16'] . '</li>';
      die();
    }
    $update = implode(', ', $update);
    if (!$update) {
      die("no_edit");
    }
    if ($visible == 1) {
      $this->db->query("UPDATE " . PREFIX . "_be_message SET message_approve = '1' WHERE id_topic = {$id}");
    } elseif ($visible == 0) {
      $this->db->query("UPDATE " . PREFIX . "_be_message SET message_approve = '0' WHERE id_topic = {$id}");
    }
    $this->db->query("UPDATE " . PREFIX . "_be_topic SET {$update} WHERE id = {$id} LIMIT 1");
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_topic
                                            LEFT JOIN " . PREFIX . "_be_read_topic 
                                            ON " . PREFIX . "_be_topic.id=" . PREFIX . "_be_read_topic.ber_topic_id 
                                            AND '{$this->userID}' = " . PREFIX . "_be_read_topic.ber_user_id 
                                            WHERE id = {$id} 
                                            LIMIT 1");
    $last = unserialize($row['last_reply_info']);
    if ($row['post_date'] < $this->timeMarkerOldTopic) {
      $data['status_read'] = 'read';
      $data['statusTitl'] = parent::$modules_lang['topic_36'];
    } else {
      if (!$row['ber_read_date']) {
        $row['ber_read_date'] = 0;
      }
      if ($last[1] > $row['ber_read_date']) {
        $data['status_read'] = 'unread';
        $data['statusTitl'] = parent::$modules_lang['topic_35'];
      } else {
        $data['status_read'] = 'read';
        $data['statusTitl'] = parent::$modules_lang['topic_36'];
      }
    }
    $data['id'] = $row['id'];
    $data['id_parent'] = $row['id_parent'];
    $data['title'] = stripslashes($row['title']);
    $data['reply_count'] = $row['reply_count'];
    $data['view_count'] = $row['view_count'];
    $data['autor'] = stripslashes($row['autor']);
    $data['site_description'] = stripslashes($row['topic_descr_site']);
    $data['post_date'] = $row['post_date'];
    $data['last'] = $last;
    $data['topic_approve'] = $row['topic_approve'];
    $data['fixed'] = $row['topic_fixed'];
    $data['topic_type'] = $row['topic_type'];
    return $this->viewer->setTplTopicShort($data);
  }
  public function deleteMsgTopicProcess()
  {
    $option = array('id' => $this->getInt('id'), 'fetch' => false);
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_message WHERE id = {$option['id']} LIMIT 1");
    if (!$row['tree_id']) {
      die('die');
    }
    if ($_POST['hash'] != '' and $_POST['hash'] == parent::$login_hash) {
      if (parent::$id_member['user_id'] == $row['autors_id'] and parent::$group_config[parent::$id_member['user_group']]['be_access_del_my_post'] or parent::$id_member['user_group'] == '1') {
        $option['fetch'] = true;
      } elseif (parent::$id_member['user_id'] != $row['autors_id'] and parent::$group_config[parent::$id_member['user_group']]['be_moder_del_message_user'] or parent::$id_member['user_group'] == '1') {
        $option['fetch'] = true;
      } else {
        die('die');
      }
    } else {
      die('die');
    }
    if ($option['fetch']) {
      $this->db->query("DELETE FROM " . PREFIX . "_be_message WHERE id = {$option['id']} LIMIT 1");
      $this->_delAttachmentMessage($option['id']);
      if (parent::$treePermanent[$row['tree_id']]['tree_count']) {
        $this->db->query("UPDATE " . PREFIX . "_users set forum_post_count=forum_post_count-1 where user_id ='{$row['autors_id']}'");
      }
      $this->db->query("UPDATE " . PREFIX . "_be_topic set reply_count=reply_count-1 where id ='{$row['id_topic']}'");
      $this->db->query("UPDATE " . PREFIX . "_be_tree set tree_answer=tree_answer-1 where tree_id={$row['tree_id']}");
      die('ok');
    }
  }
  private function _delAttachmentMessage($idMessage = '')
  {
    $this->db->query("SELECT * FROM " . PREFIX . "_be_attachment WHERE attachment_content_id = {$idMessage}");
    if ($this->db->num_rows()) {
      while ($row = $this->db->get_row()) {
        if ($row['attachment_type'] == 0) {
          if (file_exists(ROOT_DIR . '/uploads/forum/images/' . date('Y-m', $row['attachment_date']) . '/thumbs/' . $row['attachment_name'])) {
            @unlink(ROOT_DIR . '/uploads/forum/images/' . date('Y-m', $row['attachment_date']) . '/thumbs/' . $row['attachment_name']);
          }
          if (file_exists(ROOT_DIR . '/uploads/forum/images/' . date('Y-m', $row['attachment_date']) . '/' . $row['attachment_name'])) {
            @unlink(ROOT_DIR . '/uploads/forum/images/' . date('Y-m', $row['attachment_date']) . '/' . $row['attachment_name']);
          }
        } else {
          if (file_exists(ROOT_DIR . '/uploads/forum/files/' . $row['attachment_name'])) {
            @unlink(ROOT_DIR . '/uploads/forum/files/' . $row['attachment_name']);
          }
        }
      }
    }
    return false;
  }
  public function ComplaintPostProcess()
  {
    /*Function is modified 04.07.2011 RC 0.1*/
    $option['textComplaint'] = $this->db->safesql($this->filter->BB_Parse($this->filter->process(trim($this->convert_unicode($_POST['text'], parent::$dle_config['charset']))), false));
    $row = $this->db->super_query("SELECT * FROM " . PREFIX . "_be_message WHERE id = {$this->id} LIMIT 1");
    if (!$row['tree_id'] or !$option['textComplaint']) {
      die("die");
    }
    if ($row['message_autor'] == $this->userName) {
      return parent::$modules_lang['complaint_0'];
    }
    $this->db->query("SELECT ct_msg_id FROM " . PREFIX . "_be_complaint WHERE ct_msg_id='{$this->id}' AND ct_from='{$this->userName}'");
    if ($this->db->num_rows()) {
      return parent::$modules_lang['complaint_1'];
    }
    $this->db->query("INSERT INTO " . PREFIX . "_be_complaint (ct_id,ct_msg_id,ct_date,ct_text,ct_from) VALUES (NULL,'{$this->id}','{$this->time}','{$option['textComplaint']}','{$this->userName}')");
    return 'ok';
  }
  public function deleteAttachmentProcess()
  {
    /*Function is modified 04.07.2011 RC 0.1*/
    if ($_POST['hash'] != parent::$login_hash or !$this->getInt('id')) {
      die('die');
    }
    $this->db->query("SELECT * FROM " . PREFIX . "_be_attachment 
                      WHERE attachment_id = '{$this->id}' 
                      LIMIT 1");
    $row = $this->db->get_row();
    if ($row['attachment_user_name'] != $this->userName or $row['attachment_user_id'] != $this->userID) {
      return die('die');
    } else {
      $this->db->query("DELETE FROM " . PREFIX . "_be_attachment WHERE attachment_id = '{$this->id}' LIMIT 1");
      if (intval($row['attachment_type']) == 1) {
        @unlink(ROOT_DIR . '/uploads/forum/files/' . $row['attachment_name']);
      } elseif (intval($row['attachment_type']) == 0) {
        @unlink(ROOT_DIR . '/uploads/forum/images/' . date('Y-m', $row['attachment_date']) . '/' . $row['attachment_name']);
        @unlink(ROOT_DIR . '/uploads/forum/images/' . date('Y-m', $row['attachment_date']) . '/thumbs/' . $row['attachment_name']);
      }
      return 'ok';
    }
  }
  private function convert_unicode($t, $to = 'windows-1251')
  {
    $to = strtolower($to);
    if ($to == 'utf-8') {
      return $t;
    } else {
      if (function_exists('iconv'))
        $t = iconv("UTF-8", $to . "//IGNORE", $t);
      else
        $t = "The library iconv is not supported by your server";
    }
    return $t;
  }
  public function getProfileCardProcess()
  {
    /*Function is modified 15.07.2011 RC 0.1*/
    if (parent::$modules_config['session_check'] and parent::$modules_config['online']) {
      $option['dataIsOnline'] = $this->time - parent::$modules_config['session_time'] * 60;
      $option['joinStatus'] = array('table' => "LEFT JOIN " . PREFIX . "_be_session AS session 
                                                ON ( user.user_id = session.user_id )", 'select' => ', session.session_id', 'where' => "AND session.date > {$option['dataIsOnline']}");
    }
    $row = $this->db->super_query("SELECT user.* {$option['joinStatus']['select']} FROM " . PREFIX . "_users as user
                                            {$option['joinStatus']['table']}
                                            {$option['joinStatus']['where']}
                                            WHERE user.user_id = {$this->id} 
                                            LIMIT 1");
    if (!$row['user_id']) {
      die("die");
    }
    if ($row['session_id']) {
      $data['isOnline'] = true;
    } else {
      $data['isOnline'] = false;
    }
    $data['foto'] = $row['foto'] ? parent::$dle_config['http_home_url'] . "uploads/fotos/" . $row['foto'] : parent::$dle_config['http_home_url'] . 'templates/' . parent::$dle_config['skin'] . '/bullet_energy/images/noavatar.png';
    $data['reg_date'] = $this->langdate("j F Y H:i", $row['reg_date']);
    $data['lastdate'] = $this->langdate("j F Y H:i", $row['lastdate']);
    $data['fullname'] = stripslashes($row['fullname']);
    $data['comm_num'] = $row['comm_num'];
    $data['news_num'] = $row['news_num'];
    $data['user_group'] = parent::$group_user[$row['user_group']]['group_name'];
    $data['icq'] = stripslashes($row['icq']);
    $data['land'] = stripslashes($row['land']);
    $data['info'] = stripslashes($row['info']);
    $data['name'] = stripslashes($row['name']);
    $data['forum_post_count'] = $row['forum_post_count'];
    $data['forum_topic_count'] = $row['forum_topic_count'];
    $data['linckMsg'] = $row['forum_post_count'] ? $this->viewer->user_message_pages($row['name']) : '';
    $data['linckTopic'] = $row['forum_topic_count'] ? $this->viewer->user_topic_pages($row['name']) : '';
    $data['icon_group'] = parent::$group_user[$row['user_group']]['icon'] ? "<img src=\"" . parent::$group_user[$row['user_group']]['icon'] . "\" border=\"0\" />" : '';
    $data['signature'] = $row['signature'] && parent::$group_user[$row['user_group']]['allow_signature'] ? stripslashes($row['signature']) : '';
    $data['linck_news'] = $row['news_num'] ? $this->viewer->setLinckNews($row['name']) : '';
    $data['linck_comments'] = $row['comm_num'] ? $this->viewer->setLinckComment($row['user_id']) : '';
    return $this->viewer->setTpluserCard($data);
  }
  public function langdate($format, $stamp)
  {
    return strtr(@date($format, $stamp), parent::$lang_local);
  }
  public function get($name, $default, $type = 'mixed')
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    if (self::defined($name)) {
      $mixRes = $_REQUEST[$name];
    } else {
      if (null === $default) {
        return false;
      }
      $mixRes = $default;
    }
    if ($type != 'mixed') {
      if ($type == 'float') {
        $mixRes = str_replace(",", ".", $mixRes);
      }
      settype($mixRes, $type);
    }
    return $mixRes;
  }
  public function getInt($name, $default = 0)
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    return intval(self::get($name, $default, 'int'));
  }
  public function defined($name)
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    if (isset($_REQUEST[$name])) {
      return true;
    }
    return false;
  }
  private function _deleteMQR($mixValue)
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    if (get_magic_quotes_gpc()) {
      if (is_array($mixValue)) {
        foreach ($mixValue as $k => $v) {
          $mixValue[$k] = self::_deleteMQR($v);
        }
      } else {
        return stripslashes($mixValue);
      }
    }
    return $mixValue;
  }
  public function getString($name, $default = "")
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    return $this->db->safesql(trim(self::_deleteMQR(self::get($name, $default, 'string'))));
  }
  public function setGroupConfig()
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    if (file_exists($this->casheSysDir . 'groups_config.tmp')) {
      return $this->_retSysCashe('groups_config.tmp');
    } else {
      $data = array();
      $this->db->query("SELECT * FROM " . PREFIX . "_be_groups ORDER BY be_groups_id ASC");
      while ($row = $this->db->get_row()) {
        $data[$row['be_groups_id']] = array();
        foreach ($row as $key => $value) {
          $data[$row['be_groups_id']][$key] = stripslashes($value);
        }
      }
      $this->_writeSysCashe('groups_config.tmp', $data);
      return $this->_retSysCashe('groups_config.tmp');
    }
  }
  public function setQuestionConfig()
  {
    if (file_exists($this->casheSysDir . 'question.tmp')) {
      return $this->_retSysCashe('question.tmp');
    } else {
      $tree = array();
      $this->db->query("SELECT * FROM " . PREFIX . "_be_question WHERE is_active = 1 ORDER BY id ASC ");
      while ($row = $this->db->get_row()) {
        $tree[$row['id']] = array();
        foreach ($row as $key => $value) {
          $tree[$row['id']][$key] = stripslashes($value);
        }
      }
      $this->_writeSysCashe('question.tmp', $tree);
      return $this->_retSysCashe('question.tmp');
    }
  }
  public function setTreePermanentConfig()
  {
    if (file_exists($this->casheSysDir . 'tree_permanent.tmp')) {
      return $this->_retSysCashe('tree_permanent.tmp');
    } else {
      $tree = array();
      $this->db->query("SELECT tree_id,tree_parent_id,tree_type,tree_title,tree_approve,tree_count,tree_description,tree_access_topic_new,tree_access_topic_read,tree_access_topic_replic,tree_access_view FROM " . PREFIX . "_be_tree ORDER BY tree_id 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.tmp', $tree);
      return $this->_retSysCashe('tree_permanent.tmp');
    }
  }
  public function setModerConfig()
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    if (file_exists($this->casheSysDir . 'moderator.tmp')) {
      return $this->_retSysCashe('moderator.tmp');
    } else {
      $data = array();
      $this->db->query("SELECT * FROM " . PREFIX . "_be_moderator ORDER BY id ASC");
      while ($row = $this->db->get_row()) {
        $data[$row['moderator_id']] = array();
        foreach ($row as $key => $value) {
          $data[$row['moderator_id']][$key] = stripslashes($value);
          $data[$row['moderator_id']]['treeAccess'] = explode(',', $data[$row['moderator_id']]['moderator_tree_id']);
        }
      }
      $this->_writeSysCashe('moderator.tmp', $data);
      return $this->_retSysCashe('moderator.tmp');
    }
  }
  protected function setSystemCasheGroup()
  {
    $id = $this->db->safesql(parent::$id_member['user_group']);
    if (file_exists($this->casheSysDir . 'sys_cashe_group_' . $id . '.tmp')) {
      return $this->_retSysCashe('sys_cashe_group_' . $id . '.tmp');
    } else {
      $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'];
        }
      }
      $this->_writeSysCashe('sys_cashe_group_' . $id . '.tmp', array('accessTreeView' => $this->db->safesql(implode(',', $tpm)), 'accessTopicView' => $this->db->safesql(implode(',', $tpm_))));
      return $this->_retSysCashe('sys_cashe_group_' . $id . '.tmp');
    }
  }
  private function _retSysCashe($file = '')
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    return unserialize(@file_get_contents($this->casheSysDir . $file));
  }
  private function _writeSysCashe($file = '', $data = array())
  {
    /*Function is modified 05.07.2011 RC 0.1*/
    $fp = fopen($this->casheSysDir . $file, 'wb+');
    fwrite($fp, serialize($data));
    fclose($fp);
    @chmod($this->casheSysDir . $file, 0666);
  }
}

?>