<?php
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', 1);
$path = preg_replace('|([^/]+)$|i', '', __FILE__);
chdir($path);
if (file_exists('runtime.log')) unlink('runtime.log');
define('LOG_CONSOLE', false);
define('LOG_FILE',    false);
/************************************************/
/* Configuration */
require_once('config.php');
$path_to_common = $quiz_config['path_to_common']; /* Is required because script MUST be in data-path. Must be slash at the end! */
define('MYSQL_SERVER',       $quiz_config['db_server']); /* define port or socket here if needed (localhost:3370 or localhost:/mysql.sock for example) */
define('MYSQL_USER',         $quiz_config['db_user']); /* MySQL user */
define('MYSQL_PASSWORD',     $quiz_config['db_pass']); /* MySQL Password */
define('MYSQL_DB',           $quiz_config['db_name']); /* database name */
define('MYSQL_TABLE_PREFIX', $quiz_config['db_prefix']); /* common table prefix */
require_once($path_to_common.'inc_common.php');
define('QUIZ_SYSDIR', $data_path.'quiz/');
/************************************************/
/* Initialize system filenames */
$pid_file    = QUIZ_SYSDIR.'quiz.pid';
$answer      = QUIZ_SYSDIR.'answer.dat';
$last_action = QUIZ_SYSDIR.'last_action.dat';
$started_at  = QUIZ_SYSDIR.'started_at.dat';
/************************************************/
/* Get restart flag */
if (function_exists('getopt')) {
	$input = getopt('r');
	if (isset($input['r'])) {
	        my_log('Restarting...');
	        if (file_exists($pid_file)) unlink($pid_file);
	}
}
/************************************************/
/* Check PID-file */
if (file_exists($pid_file)) {
    $last_action_time = (file_exists($last_action)) ? intval(file_get_contents($last_action)) : 0;
    $one_iteration_time = $quiz_config['tip_timeout']*2+$quiz_config['smoke_timeout'];
    if (time()-$one_iteration_time < $last_action_time) {
        my_log("Process is already runing. Delete ".$pid_file." to stop it.\n");
        exit("Process is already runing. Delete ".$pid_file." to stop it.\n");
    }
}
/************************************************/
/* Create PID-file */
my_log("Creating PID-file... ");
$pid = getmypid();
$f = fopen($pid_file, "w");
flock($f, LOCK_EX);
fwrite($f, $pid);
flock($f, LOCK_UN);
fclose($f);
my_log("PID-file created");
/************************************************/
/* Initializing */
define('Q_COMMON', true);
/* MySQL Connect */
my_log("Connecting database... ");
if (!mysql_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD)) {
    my_log("Cannot connect to the database. ".mysql_error());
    exit();
}
if (!mysql_select_db(MYSQL_DB)) {
    my_log("Cannot select database. ".mysql_error());
    exit();
}
define("_CONNECT_",1);
if ($quiz_config['mysql_encoding']) mysql_query('SET NAMES '.$quiz_config['mysql_encoding']);
my_log("Connected");
$room_id      = $quiz_config['room_id'];
$bot_nick     = $quiz_config['bot_nick'];
$bot_htmlnick = ($quiz_config['bot_htmlnick'] != '') ? $quiz_config['bot_htmlnick'] : $bot_nick;
/*************************************************/
/* Save startup time */
$f = fopen($started_at, "w");
fwrite($f, time());
fclose($f);
/*************************************************/
/* Engine */
$iteration        = 0;
$unanswered       = 0;
$words_count      = 0;
$answer_length    = 0;
$flood_protection = 0;
while (1) {
    /* Check PID-file */
    if (!file_exists($pid_file) || file_get_contents($pid_file) != $pid) {
        my_log("PID-file is killed. Exiting...");
        exit("PID-file is killed. Exiting...");
    }
    /* Update last action time */
    $f = fopen($last_action, 'w');
    fwrite($f, time());
    fclose($f);
    /* Reconnect if needed */
	if ($quiz_config['need_db_reconnect']) {
	    /* Destroy old connection */
	    mysql_close();
	    /* Make new connection */
	    if (!mysql_connect(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD)) {
	        my_log("Cannot connect to the database. ".mysql_error());
	        exit();
	    }
	    if (!mysql_select_db(MYSQL_DB)) {
	        my_log("Cannot select database. ".mysql_error());
	        exit();
	    }
        if ($quiz_config['mysql_encoding']) mysql_query('SET NAMES '.$quiz_config['mysql_encoding']);
	}
    $iteration++;
    my_log('Current iteration: '.$iteration);
    /* Check users count in room */
    include($engine_path."users_get_list.php");
    $room_id = $quiz_config['room_id'];
    $users_in_room = 0;
    foreach ($users as $user) {
    	$data = explode("\t", $user);
    	if ($data[10] == $room_id) $users_in_room++;
    }
    /* Sleep if nobody in room */
    if ($users_in_room < 1) {
    	sleep(20);
    	continue;
    }
    /* Sleep if too much users in room */
    if ($quiz_config['max_users'] > 0 && $users_in_room > $quiz_config['max_users']) {
    	sleep(20);
    	continue;
    }
    $question = get_question();
    $q_text = str_replace('<{QUESTION}>', $question, $w_quiz_question_text).str_replace('<{COUNT}>', intval($answer_length), $w_quiz_letters_count);
    if ($words_count > 1) $q_text .= str_replace('<{COUNT}>', intval($words_count), $w_quiz_words_count);
    $messages_to_show = array(); /* Clear variable */
    $messages_to_show[] = array(MESG_TIME=>my_time(),
                                MESG_ROOM=>$room_id,
                                MESG_FROM=> $bot_htmlnick,
                                MESG_FROMWOTAGS=>$bot_nick,
                                MESG_FROMSESSION=>0,
                                MESG_FROMAVATAR=>"",
                                MESG_FROMID=>0,
                                MESG_TO=>"",
                                MESG_TOSESSION=>"",
                                MESG_TOID=>0,
                                MESG_BODY=>'<font color="'.$registered_colors[$default_color][1].'">'.$q_text.'</font>');
    my_log('Writing question');
    include($engine_path."messages_put.php");
    sleep($quiz_config['tip_timeout']);
    /* Sleep before next question if previous answered */
    if (!file_exists($answer)) {
        sleep($quiz_config['answered_pause']);
        continue;
    }
    /* TIP 1 */
    if (file_exists($answer) && $answer_length > 1) {
        $answer_text = trim(file_get_contents($answer));
        $tip = substr($answer_text, 0, 1);
        $t_text = str_replace(array('<{TIP_NUM}>', '<{TIP_TEXT}>'), array(1, $tip), $w_quiz_tip_text);
        $messages_to_show = array(); /* Clear variable */
        $messages_to_show[] = array(MESG_TIME=>my_time(),
                                    MESG_ROOM=>$room_id,
                                    MESG_FROM=>$bot_htmlnick,
                                    MESG_FROMWOTAGS=>$bot_nick,
                                    MESG_FROMSESSION=>0,
                                    MESG_FROMAVATAR=>"",
                                    MESG_FROMID=>0,
                                    MESG_TO=>"",
                                    MESG_TOSESSION=>"",
                                    MESG_TOID=>0,
                                    MESG_BODY=>'<font color="'.$registered_colors[$default_color][1].'">'.$t_text.'</font>');
        my_log('Writing TIP #1');
        include($engine_path."messages_put.php");
        sleep($quiz_config['tip_timeout']);
    }
    /* Sleep before next question if previous answered */
    if (!file_exists($answer)) {
        sleep($quiz_config['answered_pause']);
        continue;
    }
    /* TIP 2 */
    if (file_exists($answer) && $answer_length > 3) {
        $answer_text = trim(file_get_contents($answer));
        if ($answer_length == 4) $tip_length = 2;
        else $tip_length = 3;
        $tip = substr($answer_text, 0, $tip_length);
        $t_text = str_replace(array('<{TIP_NUM}>', '<{TIP_TEXT}>'), array(2, $tip), $w_quiz_tip_text);
        $messages_to_show = array(); /* Clear variable */
        $messages_to_show[] = array(MESG_TIME=>my_time(),
                                    MESG_ROOM=>$room_id,
                                    MESG_FROM=>$bot_htmlnick,
                                    MESG_FROMWOTAGS=>$bot_nick,
                                    MESG_FROMSESSION=>0,
                                    MESG_FROMAVATAR=>"",
                                    MESG_FROMID=>0,
                                    MESG_TO=>"",
                                    MESG_TOSESSION=>"",
                                    MESG_TOID=>0,
                                    MESG_BODY=>'<font color="'.$registered_colors[$default_color][1].'">'.$t_text.'</font>');
        my_log('Writing TIP #2');
        include($engine_path."messages_put.php");
        sleep($quiz_config['tip_timeout']);
    }
    if (file_exists($answer)) {
$unanswered++;
if ($unanswered == $quiz_config['max_unanswered']) {
$unanswered = 0;
$answer_text = trim(file_get_contents($answer));
$tip = ' <i>'.$answer_text.' </i> ';
$t_text = $w_quiz_answer.' '.$answer_text;
$message_text = str_replace(array('<{ANSWER}>'), array($t_text), $w_quiz_smoke_text);
$messages_to_show = array(); // Clear variable
$messages_to_show[] = array(MESG_TIME=>my_time(),
MESG_ROOM=>$room_id,
MESG_FROM=>$bot_htmlnick,
MESG_FROMWOTAGS=>$bot_nick,
MESG_FROMSESSION=>0,
MESG_FROMAVATAR=>"",
MESG_FROMID=>0,
MESG_TO=>"",
MESG_TOSESSION=>"",
MESG_TOID=>0,
MESG_BODY=>'<font color="'.$registered_colors[$default_color][1].'">'.$message_text.'</font>');
my_log('Writing ANSWER)');
unlink($answer);
include($engine_path."messages_put.php");
sleep($quiz_config['smoke_timeout']);
            /* Back:) */
            $messages_to_show = array(); /* Clear variable */
            $messages_to_show[] = array(MESG_TIME=>my_time(),
                                        MESG_ROOM=>$room_id,
                                        MESG_FROM=>$bot_htmlnick,
                                        MESG_FROMWOTAGS=>$bot_nick,
                                        MESG_FROMSESSION=>0,
                                        MESG_FROMAVATAR=>"",
                                        MESG_FROMID=>0,
                                        MESG_TO=>"",
                                        MESG_TOSESSION=>"",
                                        MESG_TOID=>0,
                                        MESG_BODY=>'<font color="'.$registered_colors[$default_color][1].'">'.$w_quiz_smoke_back.'</font>');
            my_log('I am back :)');
            include($engine_path."messages_put.php");
            sleep(5);
        } else {
            /* Nobody answered. */
            
            $answer_text = trim(file_get_contents($answer));
$tip = ' <i>'.$answer_text.' </i> ';
$t_text = $w_quiz_answer.' '.$answer_text;
$message_text = str_replace(array('<{SEC}>','<{ANSWER}>'), array($quiz_config['unanswered_pause'],$t_text), $w_quiz_unanswered);
$messages_to_show = array(); // Clear variable
$messages_to_show[] = array(MESG_TIME=>my_time(),
MESG_ROOM=>$room_id,
MESG_FROM=>$bot_htmlnick,
MESG_FROMWOTAGS=>$bot_nick,
MESG_FROMSESSION=>0,
MESG_FROMAVATAR=>"",
MESG_FROMID=>0,
MESG_TO=>"",
MESG_TOSESSION=>"",
MESG_TOID=>0,
MESG_BODY=>'<font color="'.$registered_colors[$default_color][1].'">'.$message_text.'</font>' );
my_log('Writing ANSWER)');
unlink($answer);
include($engine_path."messages_put.php");
sleep($quiz_config['unanswered_pause']);
        }
    } else {
    	if(intval($quiz_config['unanswered_type']) == 2) $unanswered = 0;
        /* Sleep before next question if previous answered */
        sleep($quiz_config['answered_pause']);
        continue;
    }
}
/*************************************************/
/* Functions */
function get_question() {
    if (!defined('Q_COMMON')) exit('Installation error');
    global $answer, $words_count, $answer_length, $file_path;
    if (!file_exists($file_path.'quiz.php')) exit('Some system files was not found. Please reinstall quiz!');
    /* Select question */
    $sql = 'SELECT * FROM '.MYSQL_TABLE_PREFIX.'quiz ORDER BY last_use ASC LIMIT 1';
    my_log($sql);
    $res = mysql_query($sql) or die ('SQL ERROR! '.mysql_error());
    list ($id, $question, $answer_text, $last_use) = mysql_fetch_array($res, MYSQL_NUM);
    mysql_free_result($res);
    $answer_text   = trim($answer_text);
    $answer_length = strlen($answer_text);
    $words_count   = count(explode(' ', $answer_text));
    /* Update last use time */
    $sql = 'UPDATE '.MYSQL_TABLE_PREFIX.'quiz SET last_use="'.date('Y-m-d H:i:s').'" WHERE id='.intval($id);
    my_log($sql);
    mysql_query($sql);
    /* Write Answer */
    $f = fopen($answer, "w");
    flock($f, LOCK_EX);
    fwrite($f, $answer_text."\t".time());
    flock($f, LOCK_UN);
    fclose($f);
    /* Anti-google */
    $strlen = mt_rand(1, 4);
    $anti_google_string = '';
    for($i = 0; $i < $strlen; $i++) {
        $anti_google_string .= chr(mt_rand(33, 125));
    }
    $anti_google_string = str_replace(array('<', '>', '"', "'"), '', $anti_google_string);
    $question = str_replace(' ', '<span style="color:#fafafa; font-size:1px; width:1px; overflow:hidden;">'.$anti_google_string.'</span> ', $question);
    $replaces = array();
    $replaces[] = array('from' => 'А', 'to' => 'A');
    $replaces[] = array('from' => 'В', 'to' => 'B');
    $replaces[] = array('from' => 'Е', 'to' => 'E');
    $replaces[] = array('from' => 'К', 'to' => 'K');
    $replaces[] = array('from' => 'М', 'to' => 'M');
    $replaces[] = array('from' => 'О', 'to' => 'O');
    $replaces[] = array('from' => 'Р', 'to' => 'P');
    $replaces[] = array('from' => 'С', 'to' => 'C');
    $replaces[] = array('from' => 'Т', 'to' => 'T');
    $replaces[] = array('from' => 'Х', 'to' => 'X');
    $replaces[] = array('from' => 'а', 'to' => 'a');
    $replaces[] = array('from' => 'е', 'to' => 'e');
    $replaces[] = array('from' => 'о', 'to' => 'o');
    $replaces[] = array('from' => 'р', 'to' => 'p');
    $replaces[] = array('from' => 'с', 'to' => 'c');
    $replaces[] = array('from' => 'у', 'to' => 'y');
    $replaces[] = array('from' => 'х', 'to' => 'x');
    foreach($replaces as $replace) {
        $question = str_replace($replace['from'], $replace['to'], $question);
    }
    /* End Anti-google */
    return $question;
}
function my_log($str) {
    if (!$str) return false;
    $log_string = date('Y-m-d H:i:s')."\t\t".$str."\n";
    if (LOG_CONSOLE) {
        echo $log_string;
        flush();
    }
    if (LOG_FILE) {
            $f = fopen('runtime.log', 'a+');
            flock($f, LOCK_EX);
            fwrite($f, $log_string);
            fflush($f);
            flock($f, LOCK_UN);
            fclose($f);
    }
}
?>