<?php

/*
////////////////////////////////////////////////////////////////////////////////
// JohnCMS                             Content Management System              //
// Официальный сайт сайт проекта:      http://johncms.com                     //
// Дополнительный сайт поддержки:      http://gazenwagen.com                  //
////////////////////////////////////////////////////////////////////////////////
// JohnCMS core team:                                                         //
// Евгений Рябинин aka john77          john77@gazenwagen.com                  //
// Олег Касьянов aka AlkatraZ          alkatraz@gazenwagen.com                //
//                                                                            //
// Информацию о версиях смотрите в прилагаемом файле version.txt              //
////////////////////////////////////////////////////////////////////////////////
*/

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

/*
-----------------------------------------------------------------
Запуск ботов
-----------------------------------------------------------------
*/
$bot_mass = unserialize($k_d['bot']);
$sql = '';
foreach ($bot_mass as $val) {
    if ($sw)
        $sql .= ' OR ';
    $sortid = intval($val);
    $sql .= "`id` = '$sortid'";
    $sw = 1;
}
$bot = mysql_query("SELECT * FROM `chat_bot` WHERE " . $sql . ""); // Получение данных.

while ($bot_d = mysql_fetch_assoc($bot)) { 
  $bot_id = $bot_d['id'];
  $mass_bot = unserialize($bot_d['mass_bot']);
  if (mysql_num_rows($bot) || !empty($mass_bot)) {
    $soob_d = mysql_fetch_assoc(mysql_query("SELECT `id_bot`, `time`, `tip` FROM `chat_room_" . $id . "` WHERE `id_u` = '" . $bot_id . "' AND `tip` > '2' ORDER BY `time` DESC LIMIT 1")); // Получение данных
    $tim = $soob_d['time'] - 2;
    $tip = '';
    /*
    -----------------------------------------------------------------
    Переключаем режим работы бота в зависимости от его типа 
    -----------------------------------------------------------------
    */
    switch ($bot_d['tip']) {

      case 1:
        /*
        -----------------------------------------------------------------
        Вопрос
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Вопрос
            if ($tim < $realtime - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 6;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vik['vopros'],
                '[text_count]' => mb_strlen($vik['otvet'])
              ));
            }
          break;

          case 6:
            // никто не ответил
            if ($tim < $realtime - $mass_bot['time_on'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 7;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['no_otv'], array(
                '[text]' => $vik['otvet']
              ));
           }
          break;

          default:
            // новый вопрос через...
             $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' ORDER BY RAND() LIMIT 1"));
            $tip = 3;
            $id_bot = $vop_d['id'];
            $text = strtr($mass_bot['nev_vop'], array(
              '[time]' => $mass_bot['time_off']
            ));
        }
     break;

      case 2:
        /*
        -----------------------------------------------------------------
        Вопрос с подсказкой
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Вопрос
            if ($tim < $realtime - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 4;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vik['vopros'],
                '[text_count]' => mb_strlen($vik['otvet'])
              ));
            }
           break;

          case 4:
            // Подсказка
            if ($tim < $realtime - $mass_bot['time_1'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 6;
              $ans = $vik['otvet'];
              $b = mb_strlen($ans);
              $d = round($b / 4);
              $c = mb_substr($ans, 0, $d);
              for ($z = $d; $z < $b; ++$z) {
                $c = "$c*";
              }
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['pods_1'], array(
                '[text]' => $c
              ));
            }
           break;

          case 6:
            // никто не ответил
            if ($tim < $realtime - $mass_bot['time_on'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 7;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['no_otv'], array(
                '[text]' => $vik['otvet']
              ));
           }
          break;

          default:
            // новый вопрос через...
            $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' ORDER BY RAND() LIMIT 1"));
            $tip = 3;
            $id_bot = $vop_d['id'];
            $text = strtr($mass_bot['nev_vop'], array(
              '[time]' => $mass_bot['time_off']
            ));
        }
     break;

      case 3:
        /*
        -----------------------------------------------------------------
        Вопрос с 2 подсказками
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Вопрос
            if ($tim < $realtime - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 4;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vik['vopros'],
                '[text_count]' => mb_strlen($vik['otvet'])
              ));
            }
           break;
   
          case 4:
            // Подсказка
            if ($tim < $realtime - $mass_bot['time_1'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 5;
              $ans = $vik['otvet'];
              $b = mb_strlen($ans);
              $d = round($b / 4);
              $c = mb_substr($ans, 0, $d);
              for ($z = $d; $z < $b; ++$z) {
                $c = "$c*";
              }
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['pods_1'], array(
                '[text]' => $c
              ));
            }
           break;
 
          case 5:
            // Вторая подсказка
            if ($tim < $realtime - $mass_bot['time_2'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $ans = $vik['otvet'];
              $b = mb_strlen($ans);
              $d = round($b / 3) + 1;
              $c = mb_substr($ans, 0, $d);
              for ($z = $d; $z < $b; ++$z) {
                $c = "$c*";
              }
              $tip = 6;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['pods_2'], array(
                '[text]' => $c
              ));
            }
           break;

          case 6:
            // никто не ответил
            if ($tim < $realtime - $mass_bot['time_on'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 7;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['no_otv'], array(
                '[text]' => $vik['otvet']
              ));
           }
          break;

          default:
            // новый вопрос через...
            $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' ORDER BY RAND() LIMIT 1"));
            $tip = 3;
            $id_bot = $vop_d['id'];
            $text = strtr($mass_bot['nev_vop'], array(
              '[time]' => $mass_bot['time_off']
            ));
        }
     break;

      case 4:
        /*
        -----------------------------------------------------------------
        Диалог
        -----------------------------------------------------------------
        */
        $soob2 = mysql_query("SELECT `id_bot`, `time`, `text`, `tip` FROM `chat_room_" . $id . "` WHERE `id_u`='" . $user_id . "' AND `id_bot`='0' OR `id_bot`='" . $user_id . "' AND `id_u`='" . $bot_id . "' ORDER BY `time` DESC LIMIT 1");
        if (mysql_num_rows($soob2) != 0) {
          $soob_d2 = mysql_fetch_assoc($soob2);
          if (empty($soob_d2['id_bot'])) {
            $ttt = $soob_d2['time'] + $mass_bot['time_off'];
            if ($ttt < $realtime) {
              $text2 = $soob_d2['text'];
              $text2 = preg_replace('#\[c\](.*?)\[/c\]#si', '', $text2);
              $text2 = strtr($text2, array (
                '.' => '',
                ',' => '',
                '?' => ' ?',
                '!' => ' !',
                ':' => ' :',
                ')' => ' )',
                '(' => ' (',
                'www' => ' www ',
                '"' => '',
                '*' => '',
                '/' => ''
              ));
              $top = 0;
              $b2 = explode(' ', $text2);
              $col = count($b2);
              for ($i2 = 0; $i2 < $col; ++$i2) {
                $umnik2 = mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot`='" . $bot_id . "' AND `vopros` like '%" . $b2[$i2] . "%'");
                if (mysql_num_rows($umnik2)) {
                  while($umnik2_post = mysql_fetch_assoc($umnik2)) {
                    $sov = 0;
                    $vop = mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $umnik2_post['id'] . "' LIMIT 1");
                    $vop_d = mysql_fetch_assoc($vop);
                    $mass = $vop_d['vopros'];
                    $vs = explode(' ', $mass);
                    $i3 = 0;
                    while($i3 < $col) {
                      if (in_array($b2[$i3], $vs)) {
                        ++$sov;
                      }
                     ++$i3;
                    }
                    if ($top <= $sov) {
                      $top = $sov;
                      $otvet = $vop_d['otvet'];
                      if (count($vs) == $sov) {
                        ++$top;
                      }
                    }
                  }
                }
              }
              if ($top) {
                // Ответ из базы
                $otvet = explode("|", $otvet);
                $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
                $otvet = strtr($mass_bot['vopros'], array(
                  '[text]' => $otvet
                ));
                $tip = 8;
              } else {
                // неизвестная фраза
                $otvet = explode("|", $mass_bot['no_otv']); 
                $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
                $tip = 8;
              }
            }
          } elseif ($soob_d2['id_bot'] == $user_id && $soob_d2['tip'] != 9) {
            if (($soob_d2['time'] + $mass_bot['time_1']) < $realtime) {
              // вышло время ожидания на вопрос  
              $otvet = explode("|", $mass_bot['nev_vop']);
              $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
              $tip = 9;
            }
          }  
        } else {
          // поговорим? 
          $otvet = explode("|", $mass_bot['pods_1']);
          $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
          $tip = 8;
        }
        if ($tip) {
          $id_bot = $user_id;  
          $text = strtr($otvet, array(
            '[login]' => $login
          ));
        }
     break;



      default:
         /*
        -----------------------------------------------------------------
        Фраза
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Фраза
            if ($tim < $realtime - $mass_bot['time_off']) {
              $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
              $num = rand(1, $v1) - 1;
              $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id`, `vopros` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
              $tip = 3;
              $id_bot = $vop_d['id'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vop_d['vopros']
              ));
            }
           break;

          default:
            // Новая фраза
            $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
            $num = rand(1, $v1) - 1;
            $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id`, `vopros` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
            $tip = 3;
            $id_bot = $vop_d['id'];
            $text = strtr($mass_bot['vopros'], array(
              '[text]' => $vop_d['vopros']
            ));
        }
    }
    // Заносим сообщение в б.д.
    if ($tip) {
      $mass_bot_post = serialize(array (
        'av' => $mass_bot['av'],
        'sex' => $mass_bot['sex'],
        'status' => $mass_bot['status'],
        'name' => $bot_d['name'],
        'name_delete' => '',
        'cvet' => '',
        'cvet_n' => '',
        'ip' => '127.0.0.1',
        'soft' => 'k_2_bot'
        ));
      mysql_query("INSERT INTO `chat_room_" . $id . "` SET
        `id_u` = '" . $bot_id . "',
        `id_bot` = '" . $id_bot . "',
        `time` = '" . ($realtime+2) . "',
        `text` = '" . mysql_real_escape_string($text) . "',
        `author` = '" . mysql_real_escape_string($mass_bot_post) . "',
        `tip` = '" . $tip . "'
      ");
    }
  } 
}
?>