<?php

/*
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                     Чат v.:6.0 для JohnCMS v.:4.3.x                        //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                               Автор: k_2                                   //
//                                                                            //
//                Благодарности выражать на: WMR 250322967425.                //
//                                                                            //
//                     Обратная связь: k2022@rambler.ru                       //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
*/

defined('_IN_JOHNCMS') or die('Error: restricted access');

// Проверяем права доступа
if ($rights < 9) {
  header("Location: $home");
 exit;
}
if ($mod)
  echo '<div class="phdr"><a href="menu.php?act=mod_bots"><b>' . $lng_chat['bots'] . '</b></a> | ' . $lng_chat['control_bots'] . '</div>';
else
  echo '<div class="phdr"><a href="../' . $set['admp'] . '/index.php"><b>' . $lng['admin_panel'] . '</b></a> | ' . $lng_chat['control_bots'] . '</div>';
switch ($mod) {

  case 'bak' :
    /*
    -----------------------------------------------------------------
    Бекап бота
    -----------------------------------------------------------------
    */
    if (!$id) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $bot_d = mysql_fetch_assoc(mysql_query("SELECT `name`, `tip`, `mass_bot`, `mass_author` FROM `chat_bot` WHERE `id` = '" . $id . "' LIMIT 1")); // Получение данных.
    if (isset ($_GET['yes'])) {
      $delf = opendir('bak');
      while ($tt = readdir($delf)) {
        if ($tt != "." && $tt != ".." && $tt != 'index.php' && $tt != '.svn') {
          $tm[] = $tt;
        }
      }
      closedir($delf);
      $totalt = count($tm);
      for ($it = 0; $it < $totalt; $it++) {
        $filtime[$it] = filemtime("bak/$tm[$it]");
        $tim = time();
        $ftime1 = $tim - 300;
        if ($filtime[$it] < $ftime1) {
          unlink("bak/$tm[$it]");
        }
      }
      $mass_bot = unserialize($bot_d['mass_bot']);
      $mass_author = unserialize($bot_d['mass_author']);
      $bot_v = mysql_query("SELECT * FROM `chat_vop` WHERE `id_bot` = '" . $id . "'");
      $name_file = time().$id;  
      // Сохраняем бота в текстовом формате
      $text = "                 ---------\r\n                -=- Inf -=-\r\n                 ---------\r\n";
      $text = $text."Name file                          = '".$name_file."'\r\n";
      $text = $text."Name bot                           = '".$bot_d["name"]."'\r\n";
      $text = $text."Version chat                       = '600'\r\n";
      $text = $text."Version bot                        = '".$mass_author["version"]."'\r\n";
      $text = $text."ISO                                = '".$mass_author["iso"]."'\r\n";
      $text = $text."Author                             = '".$mass_author["author"]."'\r\n";
      $text = $text."E-mail                             = '".$mass_author["author_email"]."'\r\n";
      $text = $text."URL                                = '".$mass_author["author_url"]."'\r\n";
      $text = $text."Description                        = '".$mass_author["description"]."'\r\n";
      $text = $text."                 ---------\r\n                -=- Bot -=-\r\n                 ---------\r\n";
      $text = $text."Time off                           = '".$mass_bot["time_off"]."'\r\n";
      $text = $text."Time on                            = '".$mass_bot["time_on"]."'\r\n";
      $text = $text."Time 1                             = '".$mass_bot["time_1"]."'\r\n";
      $text = $text."Time 2                             = '".$mass_bot["time_2"]."'\r\n";
      $text = $text."Tip bot                            = '".$bot_d["tip"]."'\r\n";
      $text = $text."Phrase 1                           = '".str_replace("\r\n", '\r\n', $mass_bot['pods_1'])."'\r\n";
      $text = $text."Phrase 2                           = '".str_replace("\r\n", '\r\n', $mass_bot['pods_2'])."'\r\n";
      $text = $text."Phrase                             = '".str_replace("\r\n", '\r\n', $mass_bot['vopros'])."'\r\n";
      $text = $text."Phrase nev                         = '".str_replace("\r\n", '\r\n', $mass_bot['nev_vop'])."'\r\n";
      $text = $text."Phrase no reply                    = '".str_replace("\r\n", '\r\n', $mass_bot['no_otv'])."'\r\n";     
      $text = $text."Ответ без подсказок                = '".str_replace("\r\n", '\r\n', $mass_bot['otv_0'])."'\r\n";
      $text = $text."Ответ с 1 подсказкой               = '".str_replace("\r\n", '\r\n', $mass_bot['otv_1'])."'\r\n";
      $text = $text."Ответ с 2 подсказками              = '".str_replace("\r\n", '\r\n', $mass_bot['otv_2'])."'\r\n";      
      $text = $text."Points                             = '".$mass_bot['pods_0_n']."'\r\n";
      $text = $text."Points 1                           = '".$mass_bot['pods_1_n']."'\r\n";
      $text = $text."Points 2                           = '".$mass_bot['pods_2_n']."'\r\n";
      $text = $text."Name avatar bot                    = '".$mass_bot['av']."'\r\n";
      $text = $text."Sex bot                            = '".$mass_bot['sex']."'\r\n";
      $text = $text."Status                             = '".$mass_bot['status']."'\r\n";
      $text = $text."               -------------\r\n              -=- Phrase -=-\r\n               -------------\r\n";
      while ($bot_v_d = mysql_fetch_assoc($bot_v)) {
        $text = $text.str_replace("\r\n", '\r\n', $bot_v_d['vopros'])."||".str_replace("\r\n", '\r\n', $bot_v_d['otvet'])."\r\n";
      }
      $fp = fopen("bak/$name_file.txt", "a+");
      flock($fp, LOCK_EX);
      fputs($fp, "$text\r\n");
      fflush($fp);
      flock($fp, LOCK_UN);
      fclose($fp);
      @chmod("$fp", 0777);
      @chmod("bak/$name_file.txt", 0777);
      $fls = @filesize('bak/' . $name_file . '.txt');
      $fls = round($fls / 1024, 0);
      echo '<div class="menu">' . $lng_chat['download_topic_help'] . '<p><a href="?act=mod_bots&amp;mod=loadbot&amp;n=' . $name_file . '">' . $lng['download'] . '</a> <font color="gray"><small>(' . $fls . ' kb.)</small></font></p></div>';
    } else {
      echo '<div class="menu">' . $lng_chat["bak_bot"] . ': <b>' . $bot_d['name'] . '</b>?<br /><a href="?act=mod_bots&amp;mod=bak&amp;id=' . $id . '&amp;yes">' . $lng_chat['action_yes'] . '</a> | <a href="?act=mod_bots">' . $lng_chat['action_no'] . '</a></div>';
    }
    echo '<div class="phdr"><a href="index.php">' . $lng_chat["to_chat"] . '</a></div>';
  break;

  case 'loadbot' :
    if (empty ($_GET['n'])) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $n = $_GET['n'];
    $o = opendir("bak");
    while ($f = readdir($o)) {
      if ($f != "." && $f != ".." && $f != "index.php" && $f != ".htaccess") {
        $ff = functions::format($f);
        $f1 = str_replace(".$ff", "", $f);
        $a[] = $f;
        $b[] = $f1;
      }
    }
    $tt = count($a);
    if (!in_array($n, $b)) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    for ($i = 0; $i < $tt; $i++) {
      $tf = functions::format($a[$i]);
      $tf1 = str_replace(".$tf", "", $a[$i]);
      if ($n == $tf1) {
        header("Location: bak/$n.$tf");
      }
    }
  break;

  case 'del' :
    /*
    -----------------------------------------------------------------
    Удаление бота
    -----------------------------------------------------------------
    */
    if (!$id) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $bot_d = mysql_fetch_assoc(mysql_query("SELECT `name` FROM `chat_bot` WHERE `id` = '" . $id . "'"));
    if (isset ($_GET['yes'])) {
      // Удаляем из базы все упоминания о боте и оптимизируем её
      mysql_query("DELETE FROM `chat_vop` WHERE `id_bot` = '" . $id . "'");
      mysql_query("DELETE FROM `chat_bot` WHERE `id` = '" . $id . "'");
      mysql_query("OPTIMIZE TABLE `chat_vop`");
      mysql_query("OPTIMIZE TABLE `chat_bot`");
      header("Location: ?act=mod_bots&do=b_u");
     exit;
    } else {
      echo '<div class="rmenu">' . $lng_chat['you_sure_to_remove_bot'] . '<b>' . $bot_d['name'] . '</b>?<p><a href="?act=mod_bots&amp;mod=del&amp;id=' . $id . '&amp;yes">' . $lng_chat['action_yes'] . '</a> | <a href="?act=mod_bots">' . $lng_chat['action_no'] . '</a></p></div>';
      echo '<div class="phdr"><a href="index.php">' . $lng_chat['to_chat'] . '</a></div>';
    }
  break;
  
  case 'nev' :
    /*
    -----------------------------------------------------------------
    Добавление нового бота
    -----------------------------------------------------------------
    */
    // Принимаем и фильтруем переменные
    $tip = isset($_POST['tip']) ? functions::check(mb_substr($_POST['tip'], 0, 10)) : '';
    $name = isset($_POST['name']) ? functions::check(mb_substr($_POST['name'], 0, 50)) : '';
    $description = isset($_POST['description']) ? functions::check(mb_substr($_POST['description'], 0, 500)) : '';
    $mass_bot['status'] = isset($_POST['status']) ? functions::check(mb_substr($_POST['status'], 0, 500)) : '';
    $mass_bot['sex'] = isset($_POST['sex']) && $_POST['sex'] == 'm' ? 'm' : 'zh';
    $mass_bot['av'] = isset($_POST['av']) ? functions::check(mb_substr($_POST['av'], 0, 50)) : '';
    $mass_bot['time_off'] = isset($_POST['time_off']) ? abs(intval($_POST['time_off'])) : 0;
    $mass_bot['vopros'] = isset($_POST['vopros']) ? functions::check($_POST['vopros']) : '';
    $mass_bot['time_on'] = isset($_POST['time_on']) ? abs(intval($_POST['time_on'])) : 0;
    $mass_bot['time_1'] = isset($_POST['time_1']) ? abs(intval($_POST['time_1'])) : 0;
    $mass_bot['time_2'] = isset($_POST['time_2']) ? abs(intval($_POST['time_2'])) : 0;
    $mass_bot['nev_vop'] = trim($_POST['nev_vop']);
    $mass_bot['pods_1'] = trim($_POST['pods_1']);
    $mass_bot['pods_2'] = trim($_POST['pods_2']);
    $mass_bot['no_otv'] = trim($_POST['no_otv']);
    $mass_bot['otv_0'] = trim($_POST['otv_0']);
    $mass_bot['otv_1'] = trim($_POST['otv_1']);
    $mass_bot['otv_2'] = trim($_POST['otv_2']);
    $mass_bot['pods_0_n'] = isset($_POST['pods_0_n']) ? abs(intval($_POST['pods_0_n'])) : 0;
    $mass_bot['pods_1_n'] = isset($_POST['pods_1_n']) ? abs(intval($_POST['pods_1_n'])) : 0;
    $mass_bot['pods_2_n'] = isset($_POST['pods_2_n']) ? abs(intval($_POST['pods_2_n'])) : 0;
    if (mysql_num_rows(mysql_query("SELECT * FROM `chat_bot` WHERE `name` = '$name'"))) {
      echo functions::display_error($lng_chat['this_bot_is_already'], '<a href="?act=mod_bots&amp;mod=nev">' . $lng['back'] . '</a>');
      require("../incfiles/end.php");
     exit;
    }
    // Сохранение данных нового бота
    if ((isset($_POST['submit'])) && (isset($_GET['yes']))) { 
      $error = '';
      if (!$mass_bot['time_off'] || !$name || !$mass_bot['time_on'] && $tip && $tip < 4 || !$mass_bot['time_1'] && $tip > 1 || !$mass_bot['time_2'] && $tip==3)
        $error = $lng_chat['not_filled_in_all_required_fields'];
      elseif ($mass_bot['time_1'] >= $mass_bot['time_on'] && $tip >= 2 && $tip < 4 || $mass_bot['time_2'] >= $mass_bot['time_on'] && $tip==3 || $mass_bot['time_1'] >= $mass_bot['time_2'] && $tip==3)
        $error = $error . $lng_chat['invalid_time'] . '<br />';
      if ($error) {
        echo functions::display_error($error, '<a href="?act=mod_bots&amp;mod=nev">' . $lng['back'] . '</a>');
        require('../incfiles/end.php');
       exit;
      }
      $site_iso = core::$lng_iso;
      $mass_author = serialize(array (
        'author' => $login,
        'author_email' => $datauser['mail'],
        'author_url' => $datauser['www'],
        'description' => $description,
        'version' => '1',
        'iso' => $site_iso
      ));
      // Заносим данные в базу
      mysql_query("INSERT INTO `chat_bot` SET
        `name` = '".$name."',
        `tip` = '".$tip."',
        `mass_bot` = '" . mysql_real_escape_string(serialize($mass_bot)) . "',
        `mass_author` = '" . mysql_real_escape_string($mass_author) . "'");
      header("Location: ?act=mod_bots&do=b_d");
     exit;
    } elseif (isset($_POST['submit'])) {
      // Ввод данных бота (в соответствии с его типом)
      switch ($tip) {

        case 'frazy' :
          $tip = 0;
          $tip_n = '<b>' . $lng_chat['phrases'] . '</b>';
        break;
     
        case 'dialog' :
          $tip = 4;
          $tip_n = '<b>' . $lng_chat['dialogue'] . '</b>';
        break;
     
        case 'vopros' :
          $pods = isset($_REQUEST['pods']) ? trim($_REQUEST['pods']) : '';
          switch ($pods) {
        
            case 1 :
              $tip = 2;
              $tip_n = '<b>' . $lng_chat['question'] . '</b><br /><small>' . $lng_chat['with_a_hint'] . '</small>';
            break;
     
            case 2 :
              $tip = 3;
              $tip_n = '<b>' . $lng_chat['question'] . '</b><br /><small>' . $lng_chat['with_2_tips'] . '</small>';
            break;
     
            default :
              $tip = 1;
              $tip_n = '<b>' . $lng_chat['question'] . '</b>';  
          }
        break;
 
        default :
          $tip = false;
          $tip_n = false;
      }
      // Сообщение об ошибке
      if (empty($tip_n) || empty($name)) {
        echo functions::display_error($lng['error_empty_fields'].'!', '<a href="?act=mod_bots&amp;mod=nev">' . $lng['back'] . '</a>');
        require('../incfiles/end.php');
       exit;
      }
      echo '<form action="?act=mod_bots&amp;mod=nev&amp;yes" method="post">';      
      echo '<div class="user">';
      echo '<p><h3><img src="img/bot.png" width="16" height="16" class="left"/>&#160;' . $lng_chat['adding_a_bot'] . ':</h3><ul>';            
      // Информация о боте    
        echo '<table cellpadding="0" cellspacing="0"><tr><td>';
        if (file_exists(('img/' . $mass_bot['av']) . '.png'))
          echo '<img src="img/' . $mass_bot['av'] . '.png" width="32" height="32" alt="" />&#160;';
        else
          echo '<img src="../images/empty.png" width="32" height="32" alt="" />&#160;';
        echo '</td><td>';
      if ($mass_bot['sex'])
        echo '<img src="../theme/' . $set_user['skin'] . '/images/' . ($mass_bot['sex'] == 'm' ? 'm' : 'w') . '.png" width="16" height="16" align="middle"/>&#160;';
      else
        echo '<img src="../images/del.png" width="12" height="12" align="middle" />&#160;';
      echo  '<b>' . $name . '</b>';
      echo '<span class="green"> [ON]</span>';
      if (!empty($mass_bot['status']))
        echo '<div class="status"><img src="../theme/' . $set_user['skin'] . '/images/label.png" alt="" align="middle" />&#160;' . $mass_bot['status'] . '</div>';
        echo '</td></tr></table>';
      echo '<li>' . $lng_chat['type'] . ': ' . $tip_n . '</li>';
      echo '<input type="hidden" name="description" value="' . $description . '"/>';
      echo '<input type="hidden" name="name" value="' . $name . '"/>';
      echo '<input type="hidden" name="tip" value="' . $tip . '"/>';
      echo '<input type="hidden" name="av" value="' . $mass_bot['av'] . '"/>';
      if ($mass_bot['status'])
        echo '<input type="hidden" name="status" value="' . $mass_bot['status'] . '"/>';
      echo '<input type="hidden" name="sex" value="' . $mass_bot['sex'] . '"/>';
      echo '</ul></p>';
      echo '</div>';
      echo '<div class="list1"><p><h3><img src="img/time_plus.png" width="16" height="16" class="left" />&#160;' . $lng['time'] . ':</h3><ul>';     
      echo '<li><input type="text" name="time_off" size="3" maxlength="3"/> ' . ($tip == 4 ? $lng_chat['prior_to_reply_to_the_post'] : $lng_chat['between_phrases']) . '</li>';
      if ($tip && $tip < 4)
        echo '<li><input type="text" name="time_on" size="3" maxlength="3"/> ' . $lng_chat['waiting_for_reply'] . '</li>';
      if ($tip > 1)
        echo '<li><input type="text" name="time_1" size="3" maxlength="3"/> ' . ($tip == 4 ? $lng_chat['waiting_for_the_post'] : $lng_chat['until_tips']) . '</li>';
      if ($tip == 3)
        echo '<li><input type="text" name="time_2" size="3" maxlength="3"/> ' . $lng_chat['up_to_2_tips'] . '</li>';
      echo '</ul></p>';
      echo '<p><h3><img src="img/balloons_plus.png" width="16" height="16" class="left" />&#160;' . $lng_chat['phrases'] . ':</h3><ul>';
      echo '<li><p>'.(!$tip || $tip == 4 ? $lng_chat['phrase'] . ($ms['tip'] == 4 ? ':*' : ':') : $lng_chat['before_the_issue']) . '<br /><input type="text" name="vopros"/><br />'; 
      echo '<small>&#160;&#160;<span style="color:blue">[text]</span> - ' . $lng_chat['phrases_question'] . '<br />';
      if ($tip && $tip != 4)
        echo '&#160;&#160;<span style="color:blue">[text_count]</span> - ' . $lng_chat['number_of_characters_answer'];
      echo '</small></p></li>';
      if ($tip > 1) {
        echo '<li><p>'.($tip == 4 ? $lng_chat['before_tip'] : $lng_chat['clues1']).'<br /><textarea rows="' . $set_user['field_h'] . '" name="pods_1"></textarea><br />';
        echo '<small>';
        if ($tip != 4)
          echo '&#160;&#160;<span style="color:blue">[text]</span> - ' . $lng_chat['clues'];
        echo '</small></p></li>';
      }
      if ($tip == 3) {
        echo '<li><p>' . $lng_chat['before_2_tip'] . '<br /><textarea rows="' . $set_user['field_h'] . '" name="pods_2"></textarea><br />'; 
        echo '<small>&#160;&#160;<span style="color:blue">[text]</span> - ' . $lng_chat['clues'] . '</small></p></li>';
      }
      if ($tip) {
        echo '<li><p>'.($tip == 4 ? $lng_chat['if_the_user_is_silent'] : $lng_chat['before_new_issue']) . '<br /><textarea rows="' . $set_user['field_h'] . '" name="nev_vop"></textarea><br />';
        echo '<small>';
        if ($tip != 4)
          echo '&#160;&#160;<span style="color:blue">[time]</span> - ' . $lng_chat['time_vopros'];
        echo '</small></p></li>';
        echo '<li><p>'.($tip == 4 ? $lng_chat['if_database_is_not_answer'] : $lng_chat['fact_that_no_one_answered']) . '<br /><textarea rows="' . $set_user['field_h'] . '" name="no_otv"></textarea><br />';
        echo '<small>';
        if ($tip != 4)
          echo '&#160;&#160;<span style="color:blue">[text]</span> - ' . $lng_chat['reply'];
        echo '</small></p></li>';
      }
      if ($tip && $tip != 4) {
        echo '<li><p>'.($tip == 1 ? $lng_chat['yes_post'] : $lng_chat['yes_post_0']) . '<br /><textarea rows="' . $set_user['field_h'] . '" name="otv_0"></textarea><br />';
        echo '</p></li>';
      }
      if ($tip > 1 && $tip != 4)
        echo '<li>' . $lng_chat['yes_post_1'] . '<br /><textarea rows="' . $set_user['field_h'] . '" name="otv_1"></textarea></li>';
      if ($tip == 3)
        echo '<li>' . $lng_chat['yes_post_2'] . '<br /><textarea rows="' . $set_user['field_h'] . '" name="otv_2"></textarea></li>';
      if ($tip && $tip != 4) {  
        echo '<p>*<small>';
        echo '&#160;&#160;<span style="color:blue">[login]</span> - ' . $lng_chat['login_user'] . '<br />';
        echo '&#160;&#160;<span style="color:blue">[text]</span> - ' . $lng_chat['reply'] . '<br />';
        echo '&#160;&#160;<span style="color:blue">[time]</span> - ' . $lng_chat['time_z'] . '<br />';
        echo '&#160;&#160;<span style="color:blue">[balls]</span> - ' . $lng_chat['ballov_otvet'] . '<br />';
        echo '&#160;&#160;<span style="color:blue">[balans]</span> - ' . $lng_chat['ballov_count'] . '<br />';
        echo '&#160;&#160;<span style="color:blue">[otvetov]</span> - ' . $lng_chat['otvet_count'] . '<br />';
        echo '&#160;&#160;' . $lng_chat['faq_m_j'];
        echo '</small></p>';
      } elseif ($tip == 4) {
         echo '<p>*<small>';
         echo '&#160;&#160;<span style="color:blue">[login]</span> - ' . $lng_chat['login_user'] . '<br /></small>';
         echo '**<small>&#160;&#160;' . $lng_chat['faq_f_mass'];
         echo '</small></p>';
      }
      echo '</ul></p>';
      echo '</div>';
      if ($tip && $tip != 4) {
        echo '<div class="list2"><p><h3><img src="img/medal_plus.png" width="16" height="16" class="left" />&#160;' . $lng_chat['avard'] . ':</h3><ul>';
        echo '<li><input type="text" name="pods_0_n" size="3" maxlength="3"/> ' . $lng_chat['for_the_ansfer'] . '</li>'; 
        if ($tip > 1)
          echo '<li><input type="text" name="pods_1_n" size="3" maxlength="3"/> ' . $lng_chat['for_the_ansfer_to_the_clue'] . '</li>'; 
        if ($tip > 2)
          echo '<li><input type="text" name="pods_2_n" size="3" maxlength="3"/> ' . $lng_chat['for_response_with_2_tips'] . '</li>'; 
        echo '</ul></p>';
        echo '</div>';  
      }
      echo '<div class="gmenu">';      
      echo '<input type="submit" name="submit" value="' . $lng['save'] . '"/>';
      echo '</div>';
      echo '</form>';
      echo '<div class="phdr"><a href="?act=mod_bots">' . $lng['back'] . '</a></div>';
    } else { 
      // Ввод основных данных нового бота
      echo '<form action="?act=mod_bots&amp;mod=nev" method="post">';      
      echo '<div class="menu">';
      echo '<p><h3><img src="img/bot.png" width="16" height="16" class="left"/>&#160;' . $lng_chat['adding_a_bot'] . ':</h3><ul>';      
      echo '<li>' . $lng['name'] . ': <br /><input type="text" name="name"/></li>';
      echo '<li>' . $lng['avatar'] . ': <br /><input type="text" name="av"/></li>';
      echo '<li>' . $lng['status'] . ': <br /><input type="text" name="status"/></li>';
      echo '<li>' . $lng['description'] . ': <br /><textarea rows="' . $set_user['field_h'] . '" name="description"></textarea></li>';
      echo '<li>' . $lng_chat['sex'] . ':<br />';
      echo '<input type="radio" value="m" name="sex" checked="checked"/>&#160;' . $lng_chat['male'] . '<br />';
      echo '<input type="radio" value="zh" name="sex"/>&#160;' . $lng_chat['female'] . '</li></ul></p>';
      echo '</div><div class="gmenu"><p><h3>&#160;' . $lng_chat['type'] . ':</h3><ul>';
      echo '<li><input type="radio" name="tip" value="frazy" checked="checked"/>';
      echo '<b>' . $lng_chat['phrases'] . '</b></li>';
      echo '<li><input type="radio" name="tip" value="dialog"/>';
      echo '<b>' . $lng_chat['dialogue'] . '</b></li>';
      echo '<li><input type="radio" name="tip" value="vopros"/>';
      echo '<b>' . $lng_chat['question'] . '</b></li>';
      echo '<ul><li><input type="radio" name="pods" value="0" checked="checked"/>';
      echo '<b>' . $lng_chat['no_clues'] . '</b></li>';
      echo '<li><input type="radio" name="pods" value="1"/>';
      echo '<b>' . $lng_chat['with_a_hint'] . '</b></li>';
      echo '<li><input type="radio" name="pods" value="2"/>';
      echo '<b>' . $lng_chat['with_2_tips'] . '</b></li></ul>';
      echo '</ul></p>';
      echo '</div>';
      echo '<div class="gmenu">';      
      echo '<input type="submit" name="submit" value="' . $lng['save'] . '"/>';
      echo '</div>';
      echo '</form>';
      echo '<div class="phdr"><a href="?act=mod_bots">' . $lng['back'] . '</a></div>';
    }
  break;

  case 'edit' :
    /*
    -----------------------------------------------------------------
    Редактирование бота
    -----------------------------------------------------------------
    */
    if (!$id) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $typ = mysql_query("SELECT * FROM `chat_bot` WHERE `id` = '" . $id . "'");
    if (!mysql_num_rows($typ)) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $ms = mysql_fetch_array($typ);
    $mass_bot = unserialize($ms['mass_bot']);
    echo '<div class="topmenu"><b>'.$lng_chat['bot'].'</b> | <a href="menu.php?act=mod_bots&amp;mod=edit_author&amp;id='.$id.'">'.$lng['author'].'</a></div>';
    if (isset ($_POST['submit'])) {
      // Принимаем и фильтруем переменные
      $tip = $ms['tip'];
      $name = isset($_POST['name']) ? functions::check(mb_substr($_POST['name'], 0, 50)) : '';
      $mass_bot['status'] = isset($_POST['status']) ? functions::check(mb_substr($_POST['status'], 0, 500)) : '';
      $mass_bot['sex'] = isset($_POST['sex']) && $_POST['sex'] == 'm' ? 'm' : 'zh';
      $mass_bot['av'] = isset($_POST['av']) ? functions::check(mb_substr($_POST['av'], 0, 50)) : '';
      $mass_bot['time_off'] = isset($_POST['time_off']) ? abs(intval($_POST['time_off'])) : 0;
      $mass_bot['vopros'] = isset($_POST['vopros']) ? trim($_POST['vopros']) : '';
      $mass_bot['time_on'] = isset($_POST['time_on']) ? abs(intval($_POST['time_on'])) : 0;
      $mass_bot['time_1'] = isset($_POST['time_1']) ? abs(intval($_POST['time_1'])) : 0;
      $mass_bot['time_2'] = isset($_POST['time_2']) ? abs(intval($_POST['time_2'])) : 0;
      $mass_bot['nev_vop'] = trim($_POST['nev_vop']);
      $mass_bot['pods_1'] = trim($_POST['pods_1']);
      $mass_bot['pods_2'] = trim($_POST['pods_2']);
      $mass_bot['no_otv'] = trim($_POST['no_otv']);
      $mass_bot['otv_0'] = trim($_POST['otv_0']);
      $mass_bot['otv_1'] = trim($_POST['otv_1']);
      $mass_bot['otv_2'] = trim($_POST['otv_2']);
      $mass_bot['pods_0_n'] = isset($_POST['pods_0_n']) ? abs(intval($_POST['pods_0_n'])) : 0;
      $mass_bot['pods_1_n'] = isset($_POST['pods_1_n']) ? abs(intval($_POST['pods_1_n'])) : 0;
      $mass_bot['pods_2_n'] = isset($_POST['pods_2_n']) ? abs(intval($_POST['pods_2_n'])) : 0;
      $error = '';
      if (!$mass_bot['time_off'] || !$name || !$mass_bot['time_on'] && $tip && $tip < 4 || !$mass_bot['time_1'] && $tip > 1 || !$mass_bot['time_2'] && $tip==3)
        $error = $lng['error_empty_fields'];
      elseif ($mass_bot['time_1'] >= $mass_bot['time_on'] && $tip >= 2 && $tip < 4 || $mass_bot['time_2'] >= $mass_bot['time_on'] && $tip==3 || $mass_bot['time_1'] >= $mass_bot['time_2'] && $tip==3)
        $error = $error . $lng_chat['invalid_time'] .'<br />';
      if ($error) {
        echo '<div class="rmenu"><p><b>'.$lng['error'].'</b><br />' . $error . '</p></div>';
        require("../incfiles/end.php");
       exit;
      }
      mysql_query("UPDATE `chat_bot` SET `name` = '" . mysql_real_escape_string($name) . "', `mass_bot` = '" . mysql_real_escape_string(serialize($mass_bot)) . "' WHERE `id` = '" . $id . "';");
      header("Location: ?act=mod_bots&do=b_i");
     exit;
    } else {
      switch ($ms['tip']) {

        case 1 :
          $tip_n = '<b>'.$lng_chat['question'].'</b>';
        break;
            
        case 2 :
          $tip_n = '<b>'.$lng_chat['question'].'</b><br /><small>'.$lng_chat['with_a_hint'].'</small>';
        break;
     
        case 3 :
          $tip_n = '<b>'.$lng_chat['question'].'</b><br /><small>'.$lng_chat['with_2_tips'].'</small>';
        break;

        case 4 :
          $tip_n = '<b>'.$lng_chat['dialogue'].'</b>';
        break;

        default :
          $tip_n = '<b>'.$lng_chat['phrases'].'</b>';
      }
      echo '<form action="?act=mod_bots&amp;mod=edit&amp;id=' . $id . '" method="post">';      
      echo '<div class="user">';
      echo '<p><h3><img src="img/bot.png" width="16" height="16" class="left"/>&#160;'.$lng_chat['editing_bot'].':</h3><ul>';      
      echo '<li>'.$lng['name'].': <br /><input type="text" name="name" value="' . $ms['name'] . '"/></li>';
      echo '<li>'.$lng['avatar'].': <br /><input type="text" name="av" value="' . $mass_bot['av'] . '"/></li>';
      echo '<li>'.$lng['status'].': <br /><input type="text" name="status" value="' . $mass_bot['status'] . '"/></li>';
      echo '<li>'.$lng_chat['sex'].':<br />';
      echo '<input type="radio" value="m" name="sex" ' . ($mass_bot['sex'] == 'm' ? 'checked="checked"' : '') . '/>&#160;'.$lng_chat['male'].'<br />';
      echo '<input type="radio" value="zh" name="sex" ' . ($mass_bot['sex'] == 'zh' ? 'checked="checked"' : '') . '/>&#160;'.$lng_chat['female'].'</li>';
      echo '<li>Тип: '.$tip_n.'</li>';
      echo '</ul></p>';
      echo '</div>';
      echo '<div class="list1"><p><h3><img src="img/time_edit.png" width="16" height="16" class="left" />&#160;'.$lng['time'].':</h3><ul>';     
      echo '<li><input type="text" name="time_off" size="3" maxlength="3" value="' . $mass_bot['time_off'] . '"/> '.($ms['tip']==4 ? $lng_chat['prior_to_reply_to_the_post'] : $lng_chat['between_phrases']).'</li>';
      if ($ms['tip'] && $ms['tip'] < 4)
        echo '<li><input type="text" name="time_on" size="3" maxlength="3" value="' . $mass_bot['time_on'] . '"/> '.$lng_chat['waiting_for_reply'].'</li>';
      if ($ms['tip'] > 1)
        echo '<li><input type="text" name="time_1" size="3" maxlength="3" value="' . $mass_bot['time_1'] . '"/> '.($ms['tip']==4 ? $lng_chat['waiting_for_the_post'] : $lng_chat['until_tips']).'</li>';
      if ($ms['tip'] == 3)
        echo '<li><input type="text" name="time_2" size="3" maxlength="3" value="' . $mass_bot['time_2'] . '"/> '.$lng_chat['up_to_2_tips'].'</li>';
      echo '</ul></p>';
      echo '<p><h3><img src="img/balloons_edit.png" width="16" height="16" class="left" />&#160;'.$lng_chat['phrases'].':</h3><ul>';
      echo '<li><p>'.(!$ms['tip'] || $ms['tip'] == 4 ? $lng_chat['phrase'].($ms['tip'] == 4 ? ':*' : ':') : $lng_chat['before_the_issue']).'<br /><input type="text" name="vopros" value="' . htmlentities(str_replace('\r\n', "\r\n", $mass_bot['vopros']), ENT_QUOTES, 'UTF-8') . '"/><br />'; 
      echo '<small>&#160;&#160;<span style="color:blue">[text]</span> - '.$lng_chat['phrases_question'].'<br />';
      if ($ms['tip'] && $ms['tip'] != 4)
        echo '&#160;&#160;<span style="color:blue">[text_count]</span> - '.$lng_chat['number_of_characters_answer'];
      echo '</small></p></li>';
      if ($ms['tip'] > 1) {
        echo '<li><p>'.($ms['tip']==4 ? $lng_chat['before_tip'] : $lng_chat['clues1']).'<br /><textarea rows="' . $set_user['field_h'] . '" name="pods_1">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['pods_1']), ENT_QUOTES, 'UTF-8').'</textarea><br />'; 
        echo '<small>';
        if ($ms['tip'] != 4)
          echo '&#160;&#160;<span style="color:blue">[text]</span> - '.$lng_chat['clues'];
        echo '</small></p></li>';
      }
      if ($ms['tip'] == 3) {
        echo '<li><p>'.$lng_chat['before_2_tip'].'<br /><textarea rows="' . $set_user['field_h'] . '" name="pods_2">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['pods_2']), ENT_QUOTES, 'UTF-8').'</textarea><br />'; 
        echo '<small>&#160;&#160;<span style="color:blue">[text]</span> - '.$lng_chat['clues'].'</small></p></li>';
      }
      if ($ms['tip']) {
        echo '<li><p>'.($ms['tip']==4 ? $lng_chat['if_the_user_is_silent'] : $lng_chat['before_new_issue']).'<br /><textarea rows="' . $set_user['field_h'] . '" name="nev_vop">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['nev_vop']), ENT_QUOTES, 'UTF-8').'</textarea><br />';
        echo '<small>';
        if ($ms['tip'] != 4)
          echo '&#160;&#160;<span style="color:blue">[time]</span> - '.$lng_chat['time_vopros'];
        echo '</small></p></li>';
        echo '<li><p>'.($ms['tip']==4 ? $lng_chat['if_database_is_not_answer'] : $lng_chat['fact_that_no_one_answered']).'<br /><textarea rows="' . $set_user['field_h'] . '" name="no_otv">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['no_otv']), ENT_QUOTES, 'UTF-8').'</textarea><br />';
        echo '<small>';
        if ($ms['tip'] != 4)
          echo '&#160;&#160;<span style="color:blue">[text]</span> - '.$lng_chat['reply'];
        echo '</small></p></li>';
      }
      if ($ms['tip'] && $ms['tip'] != 4)
        echo '<li>'.($ms['tip'] == 1 ? $lng_chat['yes_post'] : $lng_chat['yes_post_0']).'<br /><textarea rows="' . $set_user['field_h'] . '" name="otv_0">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['otv_0']), ENT_QUOTES, 'UTF-8').'</textarea></li>';
      if ($ms['tip'] > 1 && $ms['tip'] != 4)
        echo '<li>'.$lng_chat['yes_post_1'].'<br /><textarea rows="' . $set_user['field_h'] . '" name="otv_1">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['otv_1']), ENT_QUOTES, 'UTF-8').'</textarea></li>';
      if ($ms['tip'] == 3)
        echo '<li>'.$lng_chat['yes_post_2'].'<br /><textarea rows="' . $set_user['field_h'] . '" name="otv_2">'.htmlentities(str_replace('\r\n', "\r\n", $mass_bot['otv_2']), ENT_QUOTES, 'UTF-8').'</textarea></li>';
      if ($ms['tip'] && $ms['tip'] != 4) {  
        echo '<p>*<small>';
        echo '&#160;&#160;<span style="color:blue">[login]</span> - '.$lng_chat['login_user'].'<br />';
        echo '&#160;&#160;<span style="color:blue">[text]</span> - '.$lng_chat['reply'].'<br />';
        echo '&#160;&#160;<span style="color:blue">[time]</span> - '.$lng_chat['time_z'].'<br />';
        echo '&#160;&#160;<span style="color:blue">[balls]</span> - '.$lng_chat['ballov_otvet'].'<br />';
        echo '&#160;&#160;<span style="color:blue">[balans]</span> - '.$lng_chat['ballov_count'].'<br />';
        echo '&#160;&#160;<span style="color:blue">[otvetov]</span> - '.$lng_chat['otvet_count'].'<br />';
        echo '&#160;&#160;'.$lng_chat['faq_m_j'];
        echo '</small></p>';
      } elseif ($ms['tip'] == 4) {
         echo '<p>*<small>';
         echo '&#160;&#160;<span style="color:blue">[login]</span> - '.$lng_chat['login_user'].'<br /></small>';
         echo '**<small>&#160;&#160;'.$lng_chat['faq_f_mass'];
         echo '</small></p>';
      }
      echo '</ul></p></div>';
      if ($ms['tip'] && $ms['tip'] != 4) {
        echo '<div class="list2"><p><h3><img src="img/medal_edit.png" width="16" height="16" class="left" />&#160;'.$lng_chat['avard'].':</h3><ul>';
        echo '<li><input type="text" name="pods_0_n" size="3" maxlength="3" value="' . $mass_bot['pods_0_n'] . '"/> '.$lng_chat['for_the_ansfer'].'</li>'; 
        if ($ms['tip'] > 1)
          echo '<li><input type="text" name="pods_1_n" size="3" maxlength="3" value="' . $mass_bot['pods_1_n'] . '"/> '.$lng_chat['for_the_ansfer_to_the_clue'].'</li>'; 
        if ($ms['tip'] > 2)
          echo '<li><input type="text" name="pods_2_n" size="3" maxlength="3" value="' . $mass_bot['pods_2_n'] . '"/> '.$lng_chat['for_response_with_2_tips'].'</li>'; 
        echo '</ul></p></div>'; 
      }
      echo '<div class="gmenu">';      
      echo '<input type="submit" name="submit" value="'.$lng['save'].'"/>';
      echo '</div>';
      echo '</form>';
      echo '<div class="phdr"><a href="?act=mod_bots">'.$lng['back'].'</a></div>';
    }
  break;
  
  case 'edit_author' :
    /*
    -----------------------------------------------------------------
    Редактирование данных автора бота
    -----------------------------------------------------------------
    */
    if (!$id) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $typ = mysql_query("SELECT * FROM `chat_bot` WHERE `id` = '" . $id . "'");
    if (!mysql_num_rows($typ)) {
      header("Location: menu.php?act=mod_bots&do=error");
     exit;
    }
    $ms = mysql_fetch_array($typ);
    $mass_author = unserialize($ms['mass_author']);
    if (isset ($_POST['submit'])) {
      // Принимаем и фильтруем переменные
      $mass_author['author'] = isset($_POST['author']) ? functions::check(mb_substr($_POST['author'], 0, 50)) : '';      
      $mass_author['author_email'] = isset($_POST['author_email']) ? functions::check(mb_substr($_POST['author_email'], 0, 500)) : '';
      $mass_author['version'] = isset($_POST['version']) ? abs(intval($_POST['version'])) : 0;
      $mass_author['description'] = isset($_POST['description']) ? functions::check(mb_substr($_POST['description'], 0, 500)) : '';
      mysql_query("UPDATE `chat_bot` SET `mass_author` = '" . mysql_real_escape_string(serialize($mass_author)) . "' WHERE `id`='" . $id . "'");
      header("Location: ?act=mod_bots&do=b_i");
     exit;
    } else {                             
      echo '<div class="topmenu"><a href="menu.php?act=mod_bots&amp;mod=edit&amp;id='.$id.'">'.$lng_chat['bot'].'</a> | <b>'.$lng['author'].'</b></div>';
      echo '<form action="?act=mod_bots&amp;mod=edit_author&amp;id=' . $id . '" method="post">';      
      echo '<div class="menu">';
      echo '<p><h3><img src="img/bot.png" width="16" height="16" class="left" />&#160;'.$lng_chat['editing_bot'].':</h3><ul>';      
      echo '<li>'.$lng['author'].': <br /><input type="text" name="author" value="' . $mass_author['author'] . '"/></li>';
      echo '<li>'.$lng_chat['version'].': <br /><input type="text" name="version" value="' . $mass_author['version'] . '"/></li>';
      echo '<li>Email: <br /><input type="text" name="author_email" value="' . $mass_author['author_email'] . '"/></li>';
      echo '<li>'.$lng['description'].': <br /><textarea rows="' . $set_user['field_h'] . '" name="description">' . str_replace('<br />', "\r\n", $mass_author['description']) . '</textarea></li>';
      echo '</ul></p></div>';
      echo '<div class="gmenu">';      
      echo '<input type="submit" name="submit" value="'.$lng['save'].'"/>';
      echo '</div>';
      echo '</form>';
      echo '<div class="phdr"><a href="?act=mod_bots">'.$lng['back'].'</a></div>';
    }
  break;

  default :
    /*
    -----------------------------------------------------------------
    Список всех ботов
    -----------------------------------------------------------------
    */
    switch ($do) {

      case 'b_u':
        echo '<div class="gmenu"><b>'.$lng_chat['bot_removed'].'</b></div>';
      break;
    
      case 'b_d':
        echo '<div class="gmenu"><b>'.$lng_chat['bot_added'].'</b></div>';
      break;
    
      case 'b_i':
        echo '<div class="gmenu"><b>'.$lng_chat['bot_changed'].'</b></div>';
      break;
    
      case 'error':
        echo '<div class="rmenu"><b>'.$lng['error'].'!</b></div>';
      break;
    
      default :
        echo '';
    }
    $req = mysql_query("SELECT `id`, `name`, `mass_bot`, `mass_author` FROM `chat_bot`");
    while ($res = mysql_fetch_assoc($req)) {
      $mass_author = unserialize($res['mass_author']);
      $mass_bot = unserialize($res['mass_bot']);
      $author_menu = array (
        (!empty($mass_author['version']) && $mass_author['iso'] ? '<small class="gray">build:</small>' . $mass_author['version'] . '&#160;<span class="green">[' . $mass_author['iso'] . ']</span>' : ''),
        (!empty($mass_author['author']) ? '<span class="gray">'.$lng['author'].':</span> ' . $mass_author['author'] : ''),
        (!empty($mass_author['author_email']) ? '<span class="gray">E-mail:</span> ' . $mass_author['author_email'] : ''),
        (!empty($mass_author['author_url']) ? '<span class="gray">URL:</span> ' . $mass_author['author_url'] : ''),
        (!empty($mass_author['description']) ? '<span class="gray">'.$lng['description'].':</span> ' . $mass_author['description'] : '')
      );
      // Кол-во фраз бота.
      $col_vo = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $res['id'] . "'"), 0);
      echo ($i % 2) ? '<div class="list2">' : '<div class="list1">';
      // Информация о боте    
      if ($set_user['avatar']) {
        echo '<table cellpadding="0" cellspacing="0"><tr><td>';
        if (file_exists(('img/' . $mass_bot['av']) . '.png'))
          echo '<img src="img/' . $mass_bot['av'] . '.png" width="32" height="32" alt="" />&#160;';
        else
          echo '<img src="' . $set['homeurl'] . '/images/empty.png" width="32" height="32" alt="" />&#160;';
        echo '</td><td>';
      }
      if ($mass_bot['sex'])
        echo '<img src="'.$set['homeurl'].'/theme/'.$set_user['skin'].'/images/'.($mass_bot['sex'] == 'm' ? 'm' : 'w').'.png" width="16" height="16" align="middle" alt="'.($mass_bot['sex'] == 'm' ? 'М' : 'Ж').'"/>&#160;';
      else
        echo '<img src="' . $set['homeurl'] . '/images/del.png" width="12" height="12" align="middle" />&#160;';
      echo '<a href="' . $set['homeurl'] . '/chat/profile.php?user=' . $res['id'] . '"><b>' . $res['name'] . '</b></a>';
      echo '<span class="green"> [ON]</span>';
      if (!empty($mass_bot['status']))
        echo '<div class="status"><img src="' . $set['homeurl'] . '/theme/' . $set_user['skin'] . '/images/label.png" alt="" align="middle" />&#160;' . $mass_bot['status'] . '</div>';
      if ($set_user['avatar'])
        echo '</td></tr></table>';
      echo '<div class="sub">';
      echo '<a href="?act=mod_phrases&amp;id=' . $res['id'] . '">'.$lng_chat['phrases'].' ('.$col_vo.')</a> | ';
      echo '<a href="?act=mod_bots&amp;mod=bak&amp;id=' . $res['id'] . '">'.$lng_chat['bak'].'</a> | ';
      echo '<a href="?act=mod_bots&amp;mod=edit&amp;id=' . $res['id'] . '">'.$lng_chat['rev'].'</a> | ';
      echo '<a href="?act=mod_bots&amp;mod=del&amp;id=' . $res['id'] . '">'.$lng['delete'].'</a><br />' . functions::display_menu($author_menu, '<br />') . '</div></div>';
     ++$i;
    }
    echo '<div class="gmenu"><form action="?act=mod_bots&amp;mod=nev" method="post"><input type="submit" value="'.$lng_chat['add_bot'].'" /></form></div>';
    echo '<div class="phdr"><a href="index.php">'.$lng_chat['to_chat'].'</a></div>';
}
echo '<p><a href="menu.php">'.$lng_chat['menu'].'</a><br /><a href="../' . $set['admp'] . '/index.php">'.$lng['admin_panel'].'</a></p>';

?>