<?php
/*
Plugin Name: Quick Chat
Plugin URI: http://www.techytalk.info/wordpress-plugins/quick-chat/
Description: Self hosted WordPress chat plugin with support for private chat, live translation, chat rooms, avatars, user list, words filtering, smilies and more.
Author: Marko Martinović
Version: 3.50
Author URI: http://www.techytalk.info
License: GPL2

Copyright 2011.  Marko Martinović  (email : marko AT techytalk.info)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

global $quick_chat_version;
$quick_chat_version = '3.50';

global $quick_chat_quick_flag_version_minimum;
$quick_chat_quick_flag_version_minimum = '1.11';

global $quick_chat_default_db_version;
$quick_chat_default_db_version = '24';

global $quick_chat_default_badwords_list;
global $quick_chat_default_disallow_usernames_list;
global $quick_chat_default_name;
global $quick_chat_default_guest_num_digits;
global $quick_chat_default_timeout_refresh_users;
global $quick_chat_default_timeout_refresh_messages;
global $quick_chat_default_manual_gmt_offset;
global $quick_chat_default_message_maximum_number_chars;
global $quick_chat_default_avatar_size;
global $quick_chat_default_ip_blocklist;
global $quick_chat_default_adsense_content;
global $quick_chat_default_clean_target;
global $quick_chat_default_bing_appid;
global $quick_chat_default_inactivity_timeout;

global $quick_chat_options;
global $quick_chat_db_version;
global $quick_chat_url;
global $quick_chat_path;
global $quick_chat_is_embedded_array;
global $quick_chat_smile_array;
global $quick_chat_date_format;
global $quick_chat_time_format;
global $quick_chat_gmt_offset;
global $quick_chat_preselected_langcode;
global $quick_chat_user_ip;
global $quick_chat_user_id;
global $quick_chat_user_status;
global $quick_chat_user_name;
global $quick_chat_no_participation;
global $quick_chat_ip_blocked;
global $quick_chat_must_login;


$quick_chat_default_badwords_list = '4r5e, 5h1t, 5hit, a55, anal, anus, ar5e, arrse, arse, ass, ass-fucker, asses, assfucker, assfukka, asshole, assholes, asswhole, a_s_s, b!tch, b00bs, b17ch, b1tch, ballbag, balls, ballsack, bastard, beastial, beastiality, bellend, bestial, bestiality, bi+ch, biatch, bitch, bitcher, bitchers, bitches, bitchin, bitching, bloody, blow job, blowjob, blowjobs, boiolas, bollock, bollok, boner, boob, boobs, booobs, boooobs, booooobs, booooooobs, breasts, buceta, bugger, bum, bunny fucker, butt, butthole, buttmuch, buttplug, c0ck, c0cksucker, carpet muncher, cawk, chink, cipa, cl1t, clit, clitoris, clits, cnut, cock, cock-sucker, cockface, cockhead, cockmunch, cockmuncher, cocks, cocksuck , cocksucked , cocksucker, cocksucking, cocksucks , cocksuka, cocksukka, cok, cokmuncher, coksucka, coon, cox, crap, cum, cummer, cumming, cums, cumshot, cunilingus, cunillingus, cunnilingus, cunt, cuntlick , cuntlicker , cuntlicking , cunts, cyalis, cyberfuc, cyberfuck , cyberfucked , cyberfucker, cyberfuckers, cyberfucking , d1ck, damn, dick, dickhead, dildo, dildos, dink, dinks, dirsa, dlck, dog-fucker, doggin, dogging, donkeyribber, doosh, duche, dyke, ejaculate, ejaculated, ejaculates , ejaculating , ejaculatings, ejaculation, ejakulate, f u c k, f u c k e r, f4nny, fag, fagging, faggitt, faggot, faggs, fagot, fagots, fags, fanny, fannyflaps, fannyfucker, fanyy, fatass, fcuk, fcuker, fcuking, feck, fecker, felching, fellate, fellatio, fingerfuck , fingerfucked , fingerfucker , fingerfuckers, fingerfucking , fingerfucks , fistfuck, fistfucked , fistfucker , fistfuckers , fistfucking , fistfuckings , fistfucks , flange, fook, fooker, fuck, fucka, fucked, fucker, fuckers, fuckhead, fuckheads, fuckin, fucking, fuckings, fuckingshitmotherfucker, fuckme , fucks, fuckwhit, fuckwit, fudge packer, fudgepacker, fuk, fuker, fukker, fukkin, fuks, fukwhit, fukwit, fux, fux0r, f_u_c_k, gangbang, gangbanged , gangbangs , gaylord, gaysex, goatse, God, god-dam, god-damned, goddamn, goddamned, hardcoresex , hell, heshe, hoar, hoare, hoer, homo, hore, horniest, horny, hotsex, jack-off , jackoff, jap, jerk-off , jism, jiz , jizm , jizz, kawk, knob, knobead, knobed, knobend, knobhead, knobjocky, knobjokey, kock, kondum, kondums, kum, kummer, kumming, kums, kunilingus, l3i+ch, l3itch, labia, lmfao, lust, lusting, m0f0, m0fo, m45terbate, ma5terb8, ma5terbate, masochist, master-bate, masterb8, masterbat*, masterbat3, masterbate, masterbation, masterbations, masturbate, mo-fo, mof0, mofo, mothafuck, mothafucka, mothafuckas, mothafuckaz, mothafucked , mothafucker, mothafuckers, mothafuckin, mothafucking , mothafuckings, mothafucks, mother fucker, motherfuck, motherfucked, motherfucker, motherfuckers, motherfuckin, motherfucking, motherfuckings, motherfuckka, motherfucks, muff, mutha, muthafecker, muthafuckker, muther, mutherfucker, n1gga, n1gger, nazi, nigg3r, nigg4h, nigga, niggah, niggas, niggaz, nigger, niggers , nob, nob jokey, nobhead, nobjocky, nobjokey, numbnuts, nutsack, orgasim , orgasims , orgasm, orgasms , p0rn, pawn, pecker, penis, penisfucker, phonesex, phuck, phuk, phuked, phuking, phukked, phukking, phuks, phuq, pigfucker, pimpis, piss, pissed, pisser, pissers, pisses , pissflaps, pissin , pissing, pissoff , poop, porn, porno, pornography, pornos, prick, pricks , pron, pube, pusse, pussi, pussies, pussy, pussys , rectum, retard, rimjaw, rimming, s hit, s.o.b., sadist, schlong, screwing, scroat, scrote, scrotum, semen, sex, sh!+, sh!t, sh1t, shag, shagger, shaggin, shagging, shemale, shi+, shit, shitdick, shite, shited, shitey, shitfuck, shitfull, shithead, shiting, shitings, shits, shitted, shitter, shitters , shitting, shittings, shitty , skank, slut, sluts, smegma, smut, snatch, son-of-a-bitch, spac, spunk, s_h_i_t, t1tt1e5, t1tties, teets, teez, testical, testicle, tit, titfuck, tits, titt, tittie5, tittiefucker, titties, tittyfuck, tittywank, titwank, tosser, turd, tw4t, twat, twathead, twatty, twunt, twunter, v14gra, v1gra, vagina, viagra, vulva, w00se, wang, wank, wanker, wanky, whoar, whore, willies, willy, xrated, xxx';
$quick_chat_default_ip_blocklist = '';
$quick_chat_default_adsense_content = '';
$quick_chat_default_disallow_usernames_list = 'admin, moderator';
$quick_chat_default_name = __('Guest_','quick-chat');
$quick_chat_default_guest_num_digits = '3';
$quick_chat_default_timeout_refresh_users = '30';
$quick_chat_default_timeout_refresh_messages = '2';
$quick_chat_default_manual_gmt_offset = '0';
$quick_chat_default_message_maximum_number_chars = '400';
$quick_chat_default_avatar_size = '32';
$quick_chat_default_clean_target = '300';
$quick_chat_default_bing_appid = '';
$quick_chat_default_inactivity_timeout = '1800';

$quick_chat_options = get_option('quick_chat_options');
$quick_chat_preselected_langcode = 'en';
$quick_chat_db_version = get_option('quick_chat_db_version');
$quick_chat_url = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));
$quick_chat_path = WP_PLUGIN_DIR.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));
$quick_chat_is_embedded_array = array();
$quick_chat_user_ip = (isset($_SERVER['HTTP_X_FORWARD_FOR'])) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
$quick_chat_date_format = get_option('date_format');
$quick_chat_time_format = get_option('time_format');
$quick_chat_gmt_offset = ($quick_chat_options['manual_gmt_offset'] + get_option('gmt_offset'))*3600;

$quick_chat_smile_array = array(
               ':)' => 'smile',
		':(' => 'sad',
		';)' => 'wink',
		':P' =>'razz',
		':D' =>'grin',
		':|' => 'plain',
		':O' => 'surprise',
		':?' => 'confused',
		'8)' => 'glasses',
		'8o' => 'eek',
		'B)' => 'cool',
		':-)' => 'smile-big',
		':-(' => 'crying',
		':-*' => 'kiss',
		'O:-D' => 'angel',
		'&gt;:-D' => 'devilish',
		':o)' => 'monkey',
		':idea:' =>'idea',
		':important:' => 'important',
		':help:' => 'help',
		':error:' => 'error',
		':warning:' => 'warning',
		':favorite:' => 'favorite'
                );

function quick_chat_init(){
    global $quick_chat_user_status;
    global $quick_chat_ip_blocked;
    global $quick_chat_options;
    global $quick_chat_user_ip;
    global $quick_chat_user_name;
    global $quick_chat_user_id;
    global $quick_chat_no_participation;
    global $quick_chat_gmt_offset;
    global $quick_chat_must_login;

    $plugin_path = dirname(plugin_basename(__FILE__));
    load_plugin_textdomain('quick-chat', false, $plugin_path.'/languages/');

    $quick_chat_gmt_offset += $quick_chat_options['manual_gmt_offset'];

    if(is_user_logged_in()){
        if(current_user_can('manage_options')){
            $quick_chat_user_status = 0;
        }else{
            $quick_chat_user_status = 1;
        }

        global $current_user;
        get_currentuserinfo();

        if(isset($_COOKIE['quick_chat_alias_'.$current_user->ID])){
            $quick_chat_user_name =  stripslashes($_COOKIE['quick_chat_alias_'.$current_user->ID]);
        } else{
            setcookie('quick_chat_alias_'.$current_user->ID, $current_user->user_login, 0, COOKIEPATH, COOKIE_DOMAIN);
            $quick_chat_user_name =  $current_user->user_login;
        }

        $quick_chat_user_id = $current_user->ID;
    } else{
        $quick_chat_user_status = 2;

        if(isset($_COOKIE['quick_chat_alias'])){
            $quick_chat_user_name = stripslashes($_COOKIE['quick_chat_alias']);
        } else{
            $maxNumWidthNumDigits = '';
            $numDigits = $quick_chat_options['guest_num_digits'];
            for($i=0; $i<$numDigits; $i++){
                $maxNumWidthNumDigits .= '9';
            }
            $quick_chat_user_name = __($quick_chat_options['default_name'],'quick-chat').mt_rand(0, $maxNumWidthNumDigits);
            setcookie('quick_chat_alias', $quick_chat_user_name, 0, COOKIEPATH, COOKIE_DOMAIN);
        }
        $quick_chat_user_id = 0;
    }

    $quick_chat_no_participation = 0;


    $quick_chat_ip_blocked = 0;
    if( isset($quick_chat_options['ip_blocklist'])
        &&
        $quick_chat_user_status != 0
        &&
        strpos($quick_chat_options['ip_blocklist'], $quick_chat_user_ip) !== false){
            $quick_chat_ip_blocked = 1;
            $quick_chat_no_participation = 1;
    }

    if($quick_chat_ip_blocked == 0){
        $quick_chat_must_login = 0;
        if( isset($quick_chat_options['only_logged_in_users'])
            &&
            $quick_chat_user_status == 2){
            $quick_chat_must_login = 1;
            $quick_chat_no_participation = 1;
        }
    }
}
add_action('init','quick_chat_init');

function quick_chat_load_stylesheet() {
    global $quick_chat_url;
    global $quick_chat_path;
    global $wp_styles;

    $my_style_url = $quick_chat_url . 'css/quick-chat.css';
    $my_style_file = $quick_chat_path . 'css/quick-chat.css';

    $stupid_ie_style_url = $quick_chat_url . 'css/quick-chat-ie.css';
    $stupid_ie_style_file = $quick_chat_path . 'css/quick-chat-ie.css';

    if (file_exists($my_style_file)) {
        wp_enqueue_style('quick_chat_style_sheet', $my_style_url);
    }

    if (file_exists($stupid_ie_style_file)) {
        wp_enqueue_style('quick_chat_ie_style_sheet', $stupid_ie_style_url, array('quick_chat_style_sheet'));
        $wp_styles->add_data('quick_chat_ie_style_sheet', 'conditional', 'lt IE 8');
    }
}
add_action('wp_print_styles', 'quick_chat_load_stylesheet');
add_action('admin_print_styles', 'quick_chat_load_stylesheet');

function quick_chat_filter($text, $replace_inside_words){
    global $quick_chat_options;

    if(isset($quick_chat_options['badwords_list']) && ($quick_chat_options['badwords_list'] != '')){
        $strings = explode(',', $quick_chat_options['badwords_list']);
        foreach($strings as $word){
            $word = trim($word);

            $replacement = str_repeat('*', strlen($word));

            if($replace_inside_words){
                $text = str_ireplace($word, $replacement, $text);
            }
            else{
                $text = preg_replace('/\b'.$word.'\b/i', $replacement, $text);
            }
        }
    }
    return $text;
}

function quick_chat_install() {
    global $wpdb;
    global $quick_chat_default_badwords_list;
    global $quick_chat_default_disallow_usernames_list;
    global $quick_chat_default_db_version;
    global $quick_chat_default_name;
    global $quick_chat_default_guest_num_digits;
    global $quick_chat_options;
    global $quick_chat_db_version;
    global $quick_chat_default_ip_blocklist;
    global $quick_chat_default_timeout_refresh_users;
    global $quick_chat_default_adsense_content;
    global $quick_chat_default_timeout_refresh_messages;
    global $quick_chat_default_manual_gmt_offset;
    global $quick_chat_default_message_maximum_number_chars;
    global $quick_chat_default_avatar_size;
    global $quick_chat_default_clean_target;
    global $quick_chat_default_bing_appid;
    global $quick_chat_default_inactivity_timeout;

    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';
    $quick_chat_users_table_name = $wpdb->prefix . 'quick_chat_users';

    if($quick_chat_db_version < 12){
        // Quick Chat cannot be upgraded from 1.x to 2.x
        $quick_chat_messages_uninstall_table_name = $wpdb->prefix . 'quick_chat';
        $quick_chat_options = get_option('quick_chat_options');
        $query = $wpdb->query('DROP TABLE IF EXISTS '.$quick_chat_messages_uninstall_table_name.';');
    }

    if ($quick_chat_db_version < 15){
        // This is upgrade from v14 database to v15 database, added id auto increment to users table, impossible to do alter, nuke it (QC v2.30)
        $query = $wpdb->query('DROP TABLE IF EXISTS '.$quick_chat_users_table_name.';');
    }

    $messages_table_exists = ($wpdb->get_var('SHOW TABLES LIKE \''.$quick_chat_messages_table_name.'\';') == $quick_chat_messages_table_name) ? 1: 0;
    $users_table_exists = ($wpdb->get_var('SHOW TABLES LIKE \''.$quick_chat_users_table_name.'\';') == $quick_chat_users_table_name) ? 1: 0;

    if($messages_table_exists == 0) {
       $sql_messages = 'CREATE TABLE '.$quick_chat_messages_table_name.' (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        wpid BIGINT(20) UNSIGNED NOT NULL DEFAULT "0",
        room VARCHAR(50) NOT NULL DEFAULT "default",
        timestamp TIMESTAMP NOT NULL,
        alias VARCHAR(100) NOT NULL DEFAULT "",
        status TINYINT(1) NOT NULL DEFAULT 2,
        ip VARCHAR(39) NOT NULL,
        message TEXT NOT NULL,
        INDEX (timestamp ASC),
        INDEX (room ASC)) ENGINE=MyISAM DEFAULT CHARACTER SET utf8, COLLATE utf8_general_ci;';

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql_messages);

   } else{
        if($quick_chat_db_version < 14){
            // This is upgrade from v13 database to v14 database, we need to alter table (QC v2.20)
            $query = $wpdb->query('ALTER TABLE '.$quick_chat_messages_table_name.' ADD COLUMN md5email CHAR(32) NOT NULL DEFAULT "" AFTER alias;');
        }

        if($quick_chat_db_version < 18){
            // This is upgrade from v16 database to v18 database, we need to alter table (QC v2.40)
            $query = $wpdb->query('ALTER TABLE '.$quick_chat_messages_table_name.' CHANGE COLUMN alias alias VARCHAR(255) NOT NULL DEFAULT "";');
        }

        if($quick_chat_db_version < 19){
            // This is upgrade from v18 database to v19 database, we need to alter table (QC v2.40)
            $query = $wpdb->query('ALTER TABLE '.$quick_chat_messages_table_name.' ADD COLUMN wpid BIGINT(20) UNSIGNED NOT NULL DEFAULT "0" AFTER id;');
            $query = $wpdb->query('ALTER TABLE '.$quick_chat_messages_table_name.' DROP md5email;');
        }
   }

    if($users_table_exists == 0) {
        $sql_users = 'CREATE TABLE '.$quick_chat_users_table_name.' (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
	status TINYINT(1) NOT NULL DEFAULT 2,
	room VARCHAR(50) NOT NULL DEFAULT "default",
	timestamp_polled TIMESTAMP NOT NULL,
        timestamp_joined TIMESTAMP NOT NULL,
	alias VARCHAR(255) NOT NULL default "",
	ip VARCHAR(39) NOT NULL DEFAULT "" ,
        ccode CHAR(2) NULL,
        cname VARCHAR(150) NULL,
	INDEX (timestamp_polled ASC, timestamp_joined ASC),
        UNIQUE KEY roomalias (room, alias)) ENGINE=MyISAM DEFAULT CHARACTER SET utf8, COLLATE utf8_general_ci;';

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql_users);

    } else{
        if($quick_chat_db_version < 23){
            $wpdb->query('ALTER TABLE '.$quick_chat_users_table_name.' ADD COLUMN ccode CHAR(2) NULL AFTER ip;');
            $wpdb->query('ALTER TABLE '.$quick_chat_users_table_name.' ADD COLUMN cname VARCHAR(150) NULL AFTER ccode;');
        }
    }

    if($quick_chat_db_version < 12){
        // Quick Chat cannot be upgraded from 1.x to 2.x
        if(get_option('quick_chat_options')) delete_option('quick_chat_options');
        if(get_option('quick_chat_db_version')) delete_option('quick_chat_db_version');
        if(get_option('widget_quick-chat-widget')) delete_option('widget_quick-chat-widget');
    }

    if($quick_chat_db_version < 13){
        if(!isset($quick_chat_options['adsense_content'])) {
            $quick_chat_options['adsense_content'] = $quick_chat_default_adsense_content;
        }
    }

    if($quick_chat_db_version < 14){
        $widget_options = get_option('widget_quick-chat-widget');
        if(isset($widget_options) && is_array($widget_options)){
            foreach($widget_options as &$option){
                if (is_array($option) && !empty($option)){
                        $option['gravatars'] = 1;
                        $option['gravatars_size'] = 32;
                }
            }
            update_option('widget_quick-chat-widget', $widget_options);
        }
    }

    if($quick_chat_db_version < 15){
        if(!isset($quick_chat_options['timeout_refresh_messages'])) {
            $quick_chat_options['timeout_refresh_messages'] = $quick_chat_default_timeout_refresh_messages;
        }

        if(isset($quick_chat_options['timeout_consider_offline'])) {
            unset($quick_chat_options['timeout_consider_offline']);
        }
    }

    if($quick_chat_db_version < 16){
        $widget_options = get_option('widget_quick-chat-widget');
        if(isset($widget_options) && is_array($widget_options)){
            foreach($widget_options as &$option){
                if (is_array($option) && !empty($option)){
                        $option['loggedin_visible'] = 1;
                        $option['guests_visible'] = 1;
                }
            }
            update_option('widget_quick-chat-widget', $widget_options);
        }
    }

    if($quick_chat_db_version < 18){
        if(!isset($quick_chat_options['manual_gmt_offset'])) {
            $quick_chat_options['manual_gmt_offset'] = $quick_chat_default_manual_gmt_offset;
        }

        // Remove few options to simplify code (server performance)
        if(isset($quick_chat_options['keep_first_last'])) {
            unset($quick_chat_options['keep_first_last']);
        }

        if(isset($quick_chat_options['allow_guests_choice'])) {
            unset($quick_chat_options['allow_guests_choice']);
        }

        if(isset($quick_chat_options['allow_logged_in_choice'])) {
            unset($quick_chat_options['allow_logged_in_choice']);
        }

        // Increase users and messages refresh times (server performance)
        if(isset($quick_chat_options['timeout_refresh_users'])) {
            $quick_chat_options['timeout_refresh_users'] = $quick_chat_default_timeout_refresh_users;
        }

        if(isset($quick_chat_options['timeout_refresh_messages'])) {
            $quick_chat_options['timeout_refresh_messages'] = $quick_chat_default_timeout_refresh_messages;
        }
    }

    if($quick_chat_db_version < 19){
        if(isset($quick_chat_options['keep_around_count'])) {
            unset($quick_chat_options['keep_around_count']);
        }

        if(!isset($quick_chat_options['message_maximum_number_chars'])) {
            $quick_chat_options['message_maximum_number_chars'] = $quick_chat_default_message_maximum_number_chars;
        }

        if(!isset($quick_chat_options['avatar_size'])) {
            $quick_chat_options['avatar_size'] = $quick_chat_default_avatar_size;
        }

        $widget_options = get_option('widget_quick-chat-widget');
        if(isset($widget_options) && is_array($widget_options)){
            foreach($widget_options as &$option){
                if (is_array($option) && !empty($option)){
                        $option['height'] = $option['widgetheight'];
                }
            }
            update_option('widget_quick-chat-widget', $widget_options);
        }
    }

    if($quick_chat_db_version < 20){
        $widget_options = get_option('widget_quick-chat-widget');
        if(isset($widget_options) && is_array($widget_options)){
            foreach($widget_options as &$option){
                if (is_array($option) && !empty($option)){
                        $option['avatars'] = 1;
                        $option['smilies'] = 1;
                }
            }
            update_option('widget_quick-chat-widget', $widget_options);
        }
    }

    if($quick_chat_db_version < 21){
        if(!isset($quick_chat_options['clean_target'])) {
            $quick_chat_options['clean_target'] = $quick_chat_default_clean_target;
        }

        if(!isset($quick_chat_options['allow_change_username'])) {
            $quick_chat_options['allow_change_username'] = 1;
        }
    }

    if($quick_chat_db_version < 22){
        if(!isset($quick_chat_options['bing_appid'])) {
            $quick_chat_options['bing_appid'] = $quick_chat_default_bing_appid;
        }
    }

    if($quick_chat_db_version < 24){
        if(!isset($quick_chat_options['inactivity_timeout'])) {
            $quick_chat_options['inactivity_timeout'] = $quick_chat_default_inactivity_timeout;
        }
    }

    if(!isset($quick_chat_options['hyperlinks'])) {
        $quick_chat_options['hyperlinks'] = '1';
    }

    if(!isset($quick_chat_options['disallow_logged_in_usernames'])) {
        $quick_chat_options['disallow_logged_in_usernames'] = '1';
    }

    if(!isset($quick_chat_options['timeout_refresh_users'])) {
        $quick_chat_options['timeout_refresh_users'] = $quick_chat_default_timeout_refresh_users;
    }

    if(!isset($quick_chat_options['default_name'])) {
        $quick_chat_options['default_name'] = $quick_chat_default_name;
    }

    if(!isset($quick_chat_options['badwords_list'])) {
        $quick_chat_options['badwords_list'] = $quick_chat_default_badwords_list;
    }

    if(!isset($quick_chat_options['guest_num_digits'])) {
        $quick_chat_options['guest_num_digits'] = $quick_chat_default_guest_num_digits;
    }

    if(!isset($quick_chat_options['ip_blocklist'])) {
        $quick_chat_options['ip_blocklist'] = $quick_chat_default_ip_blocklist;
    }

    if(!isset($quick_chat_options['disallow_usernames_list'])) {
        $quick_chat_options['disallow_usernames_list'] = $quick_chat_default_disallow_usernames_list;
    }

    update_option('quick_chat_db_version', $quick_chat_default_db_version);
    update_option('quick_chat_options', $quick_chat_options);
    quick_chat_clear_cache();
}

function quick_chat_update_db_check() {
    global $quick_chat_db_version;
    global $quick_chat_default_db_version;

    if ($quick_chat_db_version != $quick_chat_default_db_version) {
        quick_chat_install();
    }
}
add_action('plugins_loaded', 'quick_chat_update_db_check');

function quick_chat_username_check_ajax_handler(){
    global $quick_chat_options;
    global $quick_chat_user_status;
    global $quick_chat_user_name;
    global $quick_chat_no_participation;
    global $wpdb;

    if($quick_chat_no_participation == 0){
        $quick_chat_users_table_name = $wpdb->prefix . 'quick_chat_users';

        $username_invalid = 0;
        $username_bad_words = 0;
        $username_exists = 0;
        $username_blocked = 0;

        if($_POST['username_check'] != $quick_chat_user_name){
            global $current_user;
            get_currentuserinfo();
            $_POST['username_check'] = trim(stripslashes($_POST['username_check']));

            if  (
                    ($_POST['username_check'] == '')
                    ||
                    ($_POST['username_check'] == 'quick_chat')
                    ||
                    (isset($quick_chat_options['disallow_special_usernames']) && !validate_username($_POST['username_check']))
                )
                $username_invalid = 1;

            if  (   $username_invalid == 0
                    &&
                    (quick_chat_filter($_POST['username_check'], true) != $_POST['username_check'])
                )
                $username_bad_words = 1;

            global $wp_version;
            if (version_compare($wp_version, '3.1', '<')){
                require_once(ABSPATH . WPINC . '/registration.php');
            }

            if($username_bad_words == 0 && (!is_user_logged_in() || (is_user_logged_in() && strcasecmp($_POST['username_check'], $current_user->user_login) != 0))){

                if($username_exists == 0){
                    $rooms = implode('", "', $wpdb->escape((array)$_POST['quick_chat_rooms']));
                    $sql = 'SELECT * FROM '.$quick_chat_users_table_name.' WHERE room IN ("'.$rooms.'") ORDER BY alias ASC';

                    $users = $wpdb->get_results($sql);

                    if($users){
                        foreach($users as $u){
                            if(strcasecmp($u->alias, $_POST['username_check']) == 0){
                                $username_exists = 1;
                                break;
                            }
                        }
                    }
                }

                if($quick_chat_user_status != 0 && isset($quick_chat_options['disallow_logged_in_usernames'])){
                    if(username_exists($_POST['username_check']) != null){
                        $username_exists = 1;
                    }
                }

                if($username_exists == 0 && $quick_chat_user_status != 0 && isset($quick_chat_options['disallow_usernames_list']) && ($quick_chat_options['disallow_usernames_list'] != '')){
                    $blocked_usernames = explode(',', $quick_chat_options['disallow_usernames_list']);
                    foreach ($blocked_usernames as $blocked_username) {
                        if(strcasecmp($_POST['username_check'], trim($blocked_username)) == 0){
                            $username_blocked = 1;
                            break;
                        }
                    }
                }
            }

            if($username_exists == 0 && $username_blocked == 0 && $username_invalid == 0 && $username_bad_words == 0){
                if ($quick_chat_user_status == 2){
                    setcookie('quick_chat_alias', $_POST['username_check'], 0, COOKIEPATH, COOKIE_DOMAIN);
                }else{
                    setcookie('quick_chat_alias_'.$current_user->ID, $_POST['username_check'], 0, COOKIEPATH, COOKIE_DOMAIN);
                }
            }
        }

        $response = json_encode(array('no_participation' => 0, 'username' => $_POST['username_check'], 'username_exists'=> $username_exists , 'username_blocked'=> $username_blocked, 'username_invalid'=> $username_invalid, 'username_bad_words'=> $username_bad_words));
    }else{
        $response = json_encode(array('no_participation' => 1));
    }

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-username-check', 'quick_chat_username_check_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-username-check', 'quick_chat_username_check_ajax_handler' );

function quick_chat_delete_ajax_handler(){
    global $wpdb;
    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';

    $ids = implode(', ', $wpdb->escape((array) $_POST['to_delete_ids']));
    if (!empty($ids)) {
        $sql = 'DELETE FROM '.$quick_chat_messages_table_name.' WHERE id IN ('.$ids.')';
        $wpdb->query($sql);
    }

    $response = json_encode(array());

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-delete', 'quick_chat_delete_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-delete', 'quick_chat_delete_ajax_handler' );

function quick_chat_clean_ajax_handler(){
    global $wpdb;
    global $quick_chat_options;
    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';

    $wpdb->query('DELETE FROM '.$quick_chat_messages_table_name.' WHERE room ="'.$_POST['to_clean_room_name'].'" AND id <= ( '.$wpdb->get_var('SELECT max(id) FROM '.$quick_chat_messages_table_name.' WHERE room ="'.$_POST['to_clean_room_name'].'"').' - '.$quick_chat_options['clean_target'].' );');

    $response = json_encode(array());

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-clean', 'quick_chat_clean_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-clean', 'quick_chat_clean_ajax_handler' );

function quick_chat_clean_private_ajax_handler(){
    global $wpdb;
    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';

    $sql = $wpdb->prepare('DELETE FROM '.$quick_chat_messages_table_name.' WHERE room =%s AND id <= ( (SELECT max(id) FROM '.$quick_chat_messages_table_name.' WHERE room = %s ) - %d );', $_POST['to_clean_room_name'], $_POST['to_clean_room_name'], $quick_chat_options['clean_target']);

    $wpdb->query($sql);

    $response = json_encode(array('$last_query' => $wpdb->last_error));

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-clean-private', 'quick_chat_clean_private_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-clean-private', 'quick_chat_clean_private_ajax_handler' );

function quick_chat_ban_ajax_handler(){
    global $quick_chat_options;

    if($quick_chat_options['ip_blocklist'] != '')
        $ip_blocklist = array_map('trim',explode(",", $quick_chat_options['ip_blocklist']));
    else
        $ip_blocklist = array();

    foreach ($_POST['to_ban_ips'] as $ban_ip) {
        $ip_blocklist[] = $ban_ip;
    }

    $quick_chat_options['ip_blocklist'] = implode(", ", array_unique($ip_blocklist));

    update_option('quick_chat_options', $quick_chat_options);

    $response = json_encode(array());

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-ban', 'quick_chat_ban_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-ban', 'quick_chat_ban_ajax_handler' );

function quick_chat_transcript_ajax_handler(){
    global $quick_chat_path;
    global $quick_chat_url;
    global $wpdb;
    global $quick_chat_gmt_offset;
    global $quick_chat_date_format;
    global $quick_chat_time_format;

    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';

    $transcript_datetime = date_i18n('d-m-Y_H-i-s', time()+$quick_chat_gmt_offset);

    $transcript_file = $quick_chat_path.'transcripts/'.$_POST['room_name'].'_'.$transcript_datetime.'.txt';

    $transcript_url = $quick_chat_url.'transcripts/'.$_POST['room_name'].'_'.$transcript_datetime.'.txt';

    $transcript_handle = fopen($transcript_file, 'w');

    $sql = $wpdb->prepare('SELECT alias, UNIX_TIMESTAMP(timestamp) as unix_timestamp, message FROM '.$quick_chat_messages_table_name.' WHERE room = %s AND alias != "quick_chat" ORDER BY unix_timestamp ASC', $_POST['room_name']);
    $messages = $wpdb->get_results($sql);

    $transcript = '';

    foreach($messages as $v){
        $v->timestring = date_i18n($quick_chat_date_format.' - '.$quick_chat_time_format, $v->unix_timestamp+$quick_chat_gmt_offset);
        $transcript .= $v->alias.' ['.$v->timestring.']: '.$v->message."\n";
    }

    fwrite($transcript_handle, $transcript);

    fclose($transcript_handle);

    $response = json_encode(array('quick_chat_transcript_url' => $transcript_url));

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-transcript', 'quick_chat_transcript_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-transcript', 'quick_chat_transcript_ajax_handler' );

function quick_chat_new_message_ajax_handler(){
    global $wpdb;
    global $quick_chat_options;
    global $quick_chat_user_status;
    global $quick_chat_user_name;
    global $quick_chat_user_ip;
    global $quick_chat_user_id;
    global $quick_chat_no_participation;

    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';

    if($quick_chat_user_status != 0)
        $_POST['message'] = wp_kses(trim(stripslashes(substr($_POST['message'], 0, $quick_chat_options['message_maximum_number_chars']))),'');
    else
        $_POST['message'] = wp_kses(trim(stripslashes($_POST['message'])),'');

    if($quick_chat_no_participation == 0 && $_POST['message'] != ''){

        if($quick_chat_user_status != 0){
            $_POST['message'] = quick_chat_filter($_POST['message'], (isset($quick_chat_options['replace_inside_bad_words'])? true:false));
        }

        if(isset($quick_chat_options['hyperlinks'])){
            $_POST['message'] = links_add_target(make_clickable($_POST['message']));
        }

        $wpdb->query('INSERT INTO '.$quick_chat_messages_table_name.' (wpid, room, timestamp, alias, status, ip, message) VALUES ( "'.$quick_chat_user_id.'", "'.$wpdb->escape($_POST['room']).'", NOW(), "'.(($_POST['sys_mes'] == 'true') ? 'quick_chat': $wpdb->escape($quick_chat_user_name)).'", '.$quick_chat_user_status.', "'.$quick_chat_user_ip.'", "'.$wpdb->escape($_POST['message']).'");');
    }
    $response = json_encode(array('no_participation' => $quick_chat_no_participation));

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-new-message', 'quick_chat_new_message_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-new-message', 'quick_chat_new_message_ajax_handler' );

function quick_chat_update_messages_ajax_handler(){
    global $wpdb;
    global $quick_chat_options;
    global $quick_chat_date_format;
    global $quick_chat_time_format;
    global $quick_chat_gmt_offset;
    global $quick_chat_no_participation;
    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';

    ob_start();
    header( "Content-Type: application/json" );
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

    $rooms = implode('", "', $wpdb->escape((array)$_POST['quick_chat_rooms']));

    $startTime = time();
    while((time()-$startTime)<=20){
        $sql = 'SELECT id, wpid, room, timestamp, UNIX_TIMESTAMP(timestamp) AS unix_timestamp, alias, status, message FROM '
                                                .$quick_chat_messages_table_name.' WHERE room IN ("'.$rooms.'") '
						.' AND timestamp > FROM_UNIXTIME('.$wpdb->escape($_POST['quick_chat_last_timestamp']).') '
						.' ORDER BY unix_timestamp ASC';

        $messages = $wpdb->get_results($sql);
        if($messages){
            foreach($messages as $v){
                $v->timestring = date_i18n($quick_chat_date_format.' - '.$quick_chat_time_format, $v->unix_timestamp+$quick_chat_gmt_offset);

                if (function_exists('get_simple_local_avatar')) {
                    $v->avatar = get_simple_local_avatar($v->wpid, $quick_chat_options['avatar_size'], '', $v->alias);
                } else {
                     $v->avatar = get_avatar($v->wpid, $quick_chat_options['avatar_size'], '', $v->alias);
                }
            }
            $response = json_encode(array('no_participation' => $quick_chat_no_participation, 'success'=> 1,'messages'=>$messages));

            echo $response;
            ob_flush(); flush();
            exit;
        }else{
            sleep($quick_chat_options['timeout_refresh_messages']);
        }
    }

    $response = json_encode(array('no_participation' => $quick_chat_no_participation, 'success'=> 0, 'rooms' => $rooms));

    echo $response;
    ob_flush(); flush();
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-update-messages', 'quick_chat_update_messages_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-update-messages', 'quick_chat_update_messages_ajax_handler' );

function quick_chat_update_users_ajax_handler(){
    global $wpdb;
    global $quick_chat_options;
    global $quick_chat_user_name;
    global $quick_chat_user_status;
    global $quick_chat_user_ip;
    global $quick_chat_no_participation;

    $quick_chat_users_table_name = $wpdb->prefix . 'quick_chat_users';

    $wpdb->query('DELETE FROM '.$quick_chat_users_table_name.' WHERE timestamp_polled < TIMESTAMPADD(SECOND,-'.($quick_chat_options['timeout_refresh_users']*2).',NOW());');

    $rooms = $wpdb->escape((array)$_POST['quick_chat_rooms']);
    $last_room = end($rooms);

    $quick_chat_users_table_name = $wpdb->prefix . 'quick_chat_users';

    $sql_update = 'INSERT INTO '.$quick_chat_users_table_name.' (status, room, timestamp_polled, timestamp_joined, alias, ip, ccode, cname) VALUES';

    $sql_update_country_code = 'NULL';
    $sql_update_country_name = 'NULL';
    $sql_fetch_country = 'NULL as c, NULL as m';
    if(quick_chat_quick_flag_capable()){
        $sql_fetch_country = 'ccode as c, cname as m';
        if(($country_info = quick_chat_country_info($quick_chat_user_ip)) != FALSE){
            $sql_update_country_code = '"'.$wpdb->escape($country_info->code).'"';
            $sql_update_country_name = '"'.$wpdb->escape($country_info->name).'"';
        }
    }

    if($quick_chat_user_status == 0)
        $sql_fetch = 'SELECT status, alias, room, id, ip, '.$sql_fetch_country.'  FROM '.$quick_chat_users_table_name.'  WHERE (';
    else
        $sql_fetch = 'SELECT status, alias, room, '.$sql_fetch_country.'  FROM '.$quick_chat_users_table_name.'  WHERE (';

    foreach ($rooms as $room){
        $sql_fetch .= 'room = "'.$room.'"';
        $sql_update .= '('.$quick_chat_user_status.', "'.$room.'", NOW(), NOW(), "'.$quick_chat_user_name.'", "'.$quick_chat_user_ip.'", '.$sql_update_country_code.', '.$sql_update_country_name.')';
        if($room != $last_room){
             $sql_fetch .= ' OR ';
             $sql_update .= ', ';
        }
    }

    $sql_update .= ' ON DUPLICATE KEY UPDATE timestamp_polled = NOW(), ccode='.$sql_update_country_code.', cname='.$sql_update_country_name.';';

    $sql_fetch .= ') ORDER BY timestamp_joined ASC';

    if($quick_chat_no_participation == 0)
        $wpdb->query($sql_update);

    $users = $wpdb->get_results($sql_fetch);

    $response = json_encode(array('no_participation' => $quick_chat_no_participation, 'users' => $users));

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-update-users', 'quick_chat_update_users_ajax_handler' );
add_action( 'wp_ajax_quick-chat-ajax-update-users', 'quick_chat_update_users_ajax_handler' );

function quick_chat_init_handler(){
    global $quick_chat_user_status;
    global $quick_chat_ip_blocked;
    global $quick_chat_must_login;
    global $quick_chat_options;
    global $quick_chat_user_ip;
    global $quick_chat_user_name;
    global $quick_chat_user_id;
    global $quick_chat_no_participation;
    global $quick_chat_smile_array;
    global $quick_chat_preselected_langcode;
    global $quick_flag_url;

    $js_vars = array (
            'cookiepath' => COOKIEPATH,
            'cookie_domain' => COOKIE_DOMAIN,
            'smile_array' => $quick_chat_smile_array,
            'user_status' => $quick_chat_user_status,
            'user_ip' => $quick_chat_user_ip,
            'user_name' => $quick_chat_user_name,
            'user_id' => $quick_chat_user_id,
            'ip_blocked' => $quick_chat_ip_blocked,
            'must_login' => $quick_chat_must_login,
            'default_langugage_code' => $quick_chat_preselected_langcode,
            'no_participation' => $quick_chat_no_participation,
            'timeout_refresh_users' => $quick_chat_options['timeout_refresh_users'],
            'clean_target' => $quick_chat_options['clean_target'],
            'message_maximum_number_chars' => $quick_chat_options['message_maximum_number_chars'],
            'clean_target' => $quick_chat_options['clean_target'],
            'message_maximum_number_chars' => $quick_chat_options['message_maximum_number_chars'],
            'adsense_content' => $quick_chat_options['adsense_content'],
            'bing_appid' => $quick_chat_options['bing_appid'],
            'inactivity_timeout' => $quick_chat_options['inactivity_timeout'],
            'hide_linkhome' => (isset($quick_chat_options['hide_linkhome'])) ? 1 : 0,
            'audio_enable' => (isset($quick_chat_options['message_sound_default_on'])) ? 1 : 0,
            'loggedin_initiate_private' => (isset($quick_chat_options['loggedin_initiate_private'])) ? 1 : 0,
            'guests_initiate_private' => (isset($quick_chat_options['guests_initiate_private'])) ? 1 : 0,
            'allow_change_username' => (isset($quick_chat_options['allow_change_username'])) ? 1 : 0,
            'not_allowed_to_initiate_private_s' => __('Unfortunately you do not have the authority to initiate private chat','quick-chat'),
            'delete_what_s' => __('You must select at least one message','quick-chat'),
            'delete_confirm_s' => __('Are you sure you want to permanently delete selected messages?','quick-chat'),
            'clean_confirm_s' => __('Are you sure you want to permanently delete all except the latest %s messages?','quick-chat'),
            'ban_who_s' => __('You must select at least one user','quick-chat'),
            'ban_confirm_s' => __('Are you sure you want to add selected users to your Quick Chat admin options IP blocklist?','quick-chat'),
            'reply_to_s' => __('Reply to %s','quick-chat'),
            'username_exists_s' => __('Already taken!','quick-chat'),
            'username_blocked_s' => __('Not allowed!','quick-chat'),
            'username_invalid_s' => __('Illegal characters!','quick-chat'),
            'username_bad_words_s' => __('Profanity!','quick-chat'),
            'invitation_received_s' => __('%s invites you to private chat. To start private chat you can click his user name on the user list.','quick-chat'),
            'invitation_sent_s' => __('Your private chat invitation has been sent to %s.','quick-chat'),
            'private_title_s' => __('Private chat','quick-chat'),
            'notice_s' => __('Notice','quick-chat'),
            'private_with_s' => __('Start private chat with %s','quick-chat'),
            'private_close_s' => __('Close this private chat','quick-chat'),
            'private_minimize_s' => __('Minimize this private chat','quick-chat'),
            'private_restore_s' => __('Restore this private chat','quick-chat'),
            'detect_translate_s' => __('Detect source language and translate','quick-chat'),
            'translate_s' => __('Translate','quick-chat'),
            'private_invite_confirm_s' => __('You\'re about to send private chat invitation to %s. Are you sure?' ,'quick-chat'),
            'private_accept_confirm_s' => __('You\'re about to accept private chat invitation from %s. Are you sure?' ,'quick-chat'),
            'dropped_inactivity_s' => __('You\'ve been dropped out of chat due to long period of inactivity. To continue with chat please refresh this page.','quick-chat'),
            'username_check_wait_s' => __('Checking...','quick-chat'),
            'add_blocklist_s' => __('Add this user\'s IP address to your IP block list','quick-chat'),
            'ban_s' => __('Ban','quick-chat'),
            'fetch_transcript_s' => __('Fetch this chat room transcript','quick-chat'),
            'transcript_s' => __('Transcript','quick-chat'),
            'all_toggle_s' => __('Select/deselect all messages toggle','quick-chat'),
            'toggle_s' => __('Toggle','quick-chat'),
            'delete_selected_s' => __('Delete selected messages','quick-chat'),
            'delete_s' => __('Delete','quick-chat'),
            'clean_all_except_s' => __('Clean all except the latest %s messages','quick-chat'),
            'clean_s' => __('Clean','quick-chat'),
            'scroll_toggle_s' => __('Enable/disable auto scroll when new message arrives','quick-chat'),
            'scroll_s' => __('Scroll','quick-chat'),
            'sound_toggle_s' => __('Enable/disable sound notification when new message arrives','quick-chat'),
            'sound_s' => __('Sound','quick-chat'),
            'ip_banned_s' => __('Your IP address is banned from chat.','quick-chat'),
            'must_login_s' => __('You must login if you want to participate in chat.','quick-chat'),
            'send_s' => __('Send','quick-chat')
        );

    if(isset($quick_flag_url))
        $js_vars['quick_flag_url'] = $quick_flag_url;

    $response = json_encode(array('js_vars' => $js_vars));

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
add_action( 'wp_ajax_nopriv_quick-chat-ajax-init', 'quick_chat_init_handler' );
add_action( 'wp_ajax_quick-chat-ajax-init', 'quick_chat_init_handler' );

function quick_chat_js() {
    global $quick_chat_url;
    global $quick_chat_version;
    global $quick_chat_options;

    $quick_chat_script = 'min.';

    wp_enqueue_script('jquery');

    if(isset($quick_chat_options['debug_mode']))

        $quick_chat_script = '';

    wp_enqueue_script('quick-chat-cookie', ($quick_chat_url.'js/jquery.cookie.'.$quick_chat_script.'js'), array('jquery'), $quick_chat_version, true);

    wp_enqueue_script('quick-chat-load', ($quick_chat_url.'js/quick-chat-load.'.$quick_chat_script.'js'), array('jquery', 'quick-chat-cookie'), $quick_chat_version, true);

    wp_localize_script('quick-chat-load', 'quick_chat_load_js_vars', array( 'url' => $quick_chat_url, 'ajaxurl' => admin_url('admin-ajax.php'), 'version' => $quick_chat_version, 'debug_mode' => (isset($quick_chat_options['debug_mode'])) ? 1 : 0));
}
add_action('wp_enqueue_scripts', 'quick_chat_js');
add_action('admin_enqueue_scripts', 'quick_chat_js');

function quick_chat_admin_js($hook) {
    if ($hook == 'settings_page_quick-chat/quick-chat') {
        global $quick_chat_url;
        global $quick_chat_options;
        global $quick_chat_version;

        if(isset($quick_chat_options['debug_mode'])){
            wp_enqueue_script('quick-chat-admin', ($quick_chat_url."js/quick-chat-admin.js"), array('jquery'), $quick_chat_version, true);
        } else{
            wp_enqueue_script('quick-chat-admin', ($quick_chat_url."js/quick-chat-admin.min.js"), array('jquery'), $quick_chat_version, true);
        }

        wp_localize_script('quick-chat-admin', 'quick_chat_admin_js_vars', array   (
            'ajaxurl' => admin_url('admin-ajax.php'),
            'clean_private_confirm_s' => __('You\'re about to permanently delete all messages from all private chat rooms as well as old private chat invitations. Are you sure?','quick-chat'),
            'clean_private_done_s' => __('Done','quick-chat')
        ));
    }
}
add_action('admin_enqueue_scripts', 'quick_chat_admin_js');

function quick_chat_clear_cache(){
    if ( function_exists('wp_cache_clear_cache') ) {
        $GLOBALS["super_cache_enabled"]=1;
        wp_cache_clear_cache();
    }else if(function_exists('simple_cache_clear')){
        simple_cache_clear();
    }else{
        if ( function_exists('w3tc_pgcache_flush') )
            w3tc_pgcache_flush();

        if ( function_exists('w3tc_dbcache_flush') )
            w3tc_dbcache_flush();

        if ( function_exists('w3tc_minify_flush') )
            w3tc_minify_flush();

        if ( function_exists('w3tc_objectcache_flush') )
            w3tc_objectcache_flush();

        if ( function_exists('wp_cache_clear_cache') )
            wp_cache_clear_cache();
    }
}
register_activation_hook(__FILE__, 'quick_chat_clear_cache');
register_deactivation_hook(__FILE__, 'quick_chat_clear_cache');


function quick_chat_country_info($ip){
    if(isset($_COOKIE['quick_flag_info'])){
        $info = unserialize(stripslashes($_COOKIE['quick_flag_info']));
        if($info == FALSE || $info->ip == $ip)
            return $info;
    }

    $info = quick_flag_get_info($ip);
    setcookie('quick_flag_info', serialize($info), 0, COOKIEPATH, COOKIE_DOMAIN, false, true);

    return $info;
}

function quick_chat_init_fn(){
    register_setting('quick_chat_options', 'quick_chat_options', 'quick_chat_options_validate' );

    add_settings_section('donate_section', __('Donating or getting help','quick-chat'), 'quick_chat_section_donate_fn', __FILE__);
    add_settings_section('general_section', __('General options','quick-chat'), 'quick_chat_section_general_fn', __FILE__);
    add_settings_section('private_section', __('Private chat options','quick-chat'), 'quick_chat_private_general_fn', __FILE__);
    add_settings_section('filter_section', __('Filter options','quick-chat'), 'quick_chat_section_filter_fn', __FILE__);
    add_settings_section('security_section', __('Security options','quick-chat'), 'quick_chat_section_security_fn', __FILE__);
    add_settings_section('appearance_section', __('Appearance options','quick-chat'), 'quick_chat_section_appearance_fn', __FILE__);

    add_settings_field('quick_chat_debug_mode', __('Debug mode (enable only when debugging):','quick-chat'), 'quick_chat_setting_debug_mode_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_message_sound_default_on', __('Incoming message sound notification on by default:','quick-chat'), 'quick_chat_setting_message_sound_default_on_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_def_name', __('Chat name prefix for guest users:','quick-chat'), 'quick_chat_setting_defname_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_guest_num_digits', __('Maximum number of digits for random guests chat user name suffix:','quick-chat'), 'quick_chat_setting_guest_num_digits_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_timeout_refresh_users', __('Interval for refreshing list of online users (seconds):','quick-chat'), 'quick_chat_setting_timeout_refresh_users_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_timeout_refresh_messages', __('Interval for refreshing list of messages (seconds):','quick-chat'), 'quick_chat_setting_timeout_refresh_messages_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_clean_target', __('Clean button will delete messages older than following number of messages per chat room:','quick-chat'), 'quick_chat_setting_clean_target_fn', __FILE__, 'general_section');
    add_settings_field('quick_chat_bing_appid', __('Bing Translator AppID (40 character key to enable translation features, get one for free <a href="http://www.bing.com/developers/appids.aspx" target="_blank">here</a>):','quick-chat'), 'quick_chat_bing_appid_fn', __FILE__, 'general_section');

    add_settings_field('quick_chat_hyperlinks', __('Convert URLs to hyperlinks:','quick-chat'), 'quick_chat_setting_hyperlinks_fn', __FILE__, 'filter_section');
    add_settings_field('quick_chat_disallow_special_usernames', __('Disallow using special characters inside chat user names (including special locale characters):','quick-chat'), 'quick_chat_setting_disallow_special_usernames_fn', __FILE__, 'filter_section');
    add_settings_field('quick_chat_replace_inside_bad_words', __('Filter bad words contained inside other words:','quick-chat'), 'quick_chat_setting_replace_inside_bad_words_fn', __FILE__, 'filter_section');
    add_settings_field('quick_chat_bad_words', __('Bad words list (comma separated):','quick-chat'), 'quick_chat_setting_badwords_fn', __FILE__, 'filter_section');

    add_settings_field('quick_chat_loggedin_initiate_private', __('Logged in users can initiate private chat:','quick-chat'), 'quick_chat_setting_loggedin_initiate_private_fn', __FILE__, 'private_section');
    add_settings_field('quick_chat_guests_initiate_private', __('Guest users can initiate private chat:','quick-chat'), 'quick_chat_setting_guests_initiate_private_fn', __FILE__, 'private_section');
    add_settings_field('quick_chat_clean_private', __('Clean all messages from all private chat rooms as well as old private chat invitations:','quick-chat'), 'quick_chat_setting_clean_private_fn', __FILE__, 'private_section');

    add_settings_field('quick_chat_only_logged_in_users', __('Only logged in users can participate in chat:','quick-chat'), 'quick_chat_setting_only_logged_in_users_fn', __FILE__, 'security_section');
    add_settings_field('quick_chat_disallow_logged_in_usernames', __('Protect registered users user names from being used by other users:','quick-chat'), 'quick_chat_setting_disallow_logged_in_usernames_fn', __FILE__, 'security_section');
    add_settings_field('quick_chat_allow_change_username', __('Allow users to change their chat user name:','quick-chat'), 'quick_chat_setting_allow_change_username_fn', __FILE__, 'security_section');
    add_settings_field('quick_chat_inactivity_timeout', __('Timeout for disabling updates to inactive user (seconds):','quick-chat'), 'quick_chat_setting_inactivity_timeout_fn', __FILE__, 'security_section');
    add_settings_field('quick_chat_message_maximum_number_chars', __('Maximum number of characters for each message:','quick-chat'), 'quick_chat_setting_message_maximum_number_chars_fn', __FILE__, 'security_section');
    add_settings_field('quick_chat_disallow_usernames_list', __('Restricted chat user names list (comma separated):','quick-chat'), 'quick_chat_setting_disallow_usernames_list_fn', __FILE__, 'security_section');
    add_settings_field('quick_chat_ip_blocklist', __('Deny chat access to the following IP addresses (comma separated):','quick-chat'), 'quick_chat_setting_ip_blocklist_fn', __FILE__, 'security_section');

    add_settings_field('quick_chat_disable_quick_flag', __('Disable <a href="http://www.techytalk.info/wordpress-plugins/quick-flag/" target="_blank">Quick Flag</a> WordPress plugin integration (to hide country flags on user list):','quick-chat'), 'quick_chat_setting_disable_quick_flag_fn', __FILE__, 'appearance_section');
    add_settings_field('quick_chat_hide_widget_if_embedded', __('Hide Quick Chat sidebar widget on pages where same chat room is embedded using shortcode:','quick-chat'), 'quick_chat_setting_hide_widget_if_embedded_fn', __FILE__, 'appearance_section');
    add_settings_field('quick_chat_hide_linkhome', __('Hide "Powered by Quick Chat" link (big thanks for not hiding it):','quick-chat'), 'quick_chat_setting_hide_linkhome_fn', __FILE__, 'appearance_section');
    add_settings_field('quick_chat_manual_gmt_offset', __('Manual timestamp offset when displaying messages (+/- hours):','quick-chat'), 'quick_chat_manual_gmt_offset_fn', __FILE__, 'appearance_section');
    add_settings_field('quick_chat_avatar size', __('User avatar size (pixels):','quick-chat'), 'quick_chat_avatar_size_fn', __FILE__, 'appearance_section');
    add_settings_field('quick_chat_adsense_code', __('Advertisement code for your AdSense or other ads placed between chat user name input box and message text input box:','quick-chat'), 'quick_chat_setting_adsense_content_fn', __FILE__, 'appearance_section');

    add_settings_field('quick_chat_paypal', __('Donate using PayPal (sincere thank you for your help):','quick-chat'), 'quick_chat_setting_paypal_fn', __FILE__, 'donate_section');
    add_settings_field('quick_chat_version', __('Quick Chat version:','quick-chat'), 'quick_chat_setting_version_fn', __FILE__, 'donate_section');
    add_settings_field('quick_chat_faq', __('Quick Chat FAQ:','quick-chat'), 'quick_chat_setting_faq_fn', __FILE__, 'donate_section');
    add_settings_field('quick_chat_changelog', __('Quick Chat changelog:','quick-chat'), 'quick_chat_setting_changelog_fn', __FILE__, 'donate_section');
    add_settings_field('quick_chat_support_page', __('Quick Chat support page:','quick-chat'), 'quick_chat_setting_support_page_fn', __FILE__, 'donate_section');
}
add_action('admin_init', 'quick_chat_init_fn' );

function quick_chat_plugin_meta($links, $file) {
	$plugin = plugin_basename(__FILE__);
	if ($file == $plugin) {
            return array_merge(
                $links,
                array( '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CZQW2VZNHMGGN">'.__('Donate', 'quick-flag').'</a>' )
            );
	}
	return $links;
}
add_filter('plugin_row_meta', 'quick_chat_plugin_meta', 10, 2);

function quick_chat_action_links($links, $file){
    if ($file == plugin_basename(__FILE__)) {
        $settings_link = '<a href="' . get_bloginfo('wpurl') . '/wp-admin/admin.php?page=quick-chat/quick-chat.php">'.__('Settings', 'quick-chat').'</a>';
        $links[] = $settings_link;
    }

    return $links;
}

function quick_chat_add_page_fn(){
    add_options_page('Quick Chat '.__('options page','quick-chat'), 'Quick Chat ', 'manage_options', __FILE__, 'quick_chat_options_page_fn');
    add_filter('plugin_action_links', 'quick_chat_action_links', 10, 2);
}
add_action('admin_menu', 'quick_chat_add_page_fn');

function quick_chat_section_donate_fn() {
    echo '<p>';
    _e('If you find Quick Chat useful you can donate to help it\'s development. Also you can get help with Quick Chat:','quick-chat');
    echo '</p>';
}

function quick_chat_section_general_fn() {
    echo '<p>';
    _e('Here you can control all general options:','quick-chat');
    echo '</p>';
}

function quick_chat_private_general_fn() {
    echo '<p>';
    _e('Here you can control all private chat options:','quick-chat');
    echo '</p>';
}

function quick_chat_section_filter_fn() {
    echo '<p>';
    _e('Here you can control Quick Chat message and chat user names filter:','quick-chat');
    echo '</p>';
}

function quick_chat_section_security_fn() {
    echo '<p>';
    _e('In this section you can control security options:','quick-chat');
    echo '</p>';
}

function quick_chat_section_appearance_fn() {
    echo '<p>';
    _e('Here are the Quick Chat appearance options:','quick-chat');
    echo '</p>';
}

function quick_chat_setting_timeout_refresh_users_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_timeout_refresh_users" name="quick_chat_options[timeout_refresh_users]" size="10" type="text" value="'.$quick_chat_options['timeout_refresh_users'].'" />';
}

function quick_chat_setting_timeout_refresh_messages_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_timeout_refresh_messages" name="quick_chat_options[timeout_refresh_messages]" size="10" type="text" value="'.$quick_chat_options['timeout_refresh_messages'].'" />';
}

function quick_chat_setting_faq_fn() {
    echo '<a href="http://wordpress.org/extend/plugins/quick-chat/faq/" target="_blank">'.__('FAQ','quick-chat').'</a>';
}

function quick_chat_setting_version_fn() {
    global $quick_chat_version;
    echo $quick_chat_version;
}

function quick_chat_setting_changelog_fn() {
    echo '<a href="http://wordpress.org/extend/plugins/quick-chat/changelog/" target="_blank">'.__('Changelog','quick-chat').'</a>';
}

function quick_chat_setting_support_page_fn() {
    echo '<a href="http://www.techytalk.info/wordpress-plugins/quick-chat/" target="_blank">'.__('Quick Chat at TechyTalk.info','quick-chat').'</a>';
}

function quick_chat_setting_paypal_fn() {
    global $quick_chat_url;
    echo '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CZQW2VZNHMGGN" target="_blank"><img src="'.$quick_chat_url.'img/paypal.gif" /></a>';
}

function quick_chat_setting_defname_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_def_name" name="quick_chat_options[default_name]" size="10" type="text" value="'.__($quick_chat_options['default_name'],'quick-chat').'" />';
}

function quick_chat_setting_guest_num_digits_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_guest_num_digits" name="quick_chat_options[guest_num_digits]" size="10" type="text" value="'.$quick_chat_options['guest_num_digits'].'" />';
}

function quick_chat_setting_badwords_fn() {
    global $quick_chat_options;
    echo '<a class="quick_chat_show_hide" href="">'.__('Show', 'quick-chat').'</a>';
    echo '<br>';
    echo '<textarea class="quick-chat-show-hide"  id="quick_chat_bad_words" name="quick_chat_options[badwords_list]" rows="5" cols="50" >'.$quick_chat_options['badwords_list'].'</textarea>';
}

function quick_chat_setting_disallow_special_usernames_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_disallow_special_usernames" name="quick_chat_options[disallow_special_usernames]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['disallow_special_usernames'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_replace_inside_bad_words_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_replace_inside_bad_words" name="quick_chat_options[replace_inside_bad_words]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['replace_inside_bad_words'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_hyperlinks_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_hyperlinks" name="quick_chat_options[hyperlinks]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['hyperlinks'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_disable_quick_flag_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_disable_quick_flag" name="quick_chat_options[disable_quick_flag]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['disable_quick_flag'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_hide_widget_if_embedded_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_hide_widget_if_embedded" name="quick_chat_options[hide_widget_if_embedded]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['hide_widget_if_embedded'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_hide_linkhome_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_hide_linkhome" name="quick_chat_options[hide_linkhome]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['hide_linkhome'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_debug_mode_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_debug_mode" name="quick_chat_options[debug_mode]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['debug_mode'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_only_logged_in_users_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_only_logged_in_users" name="quick_chat_options[only_logged_in_users]" type="checkbox" value="1" ';
    if(isset($quick_chat_options['only_logged_in_users'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_message_sound_default_on_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_message_sound_default_on" name="quick_chat_options[message_sound_default_on]" type="checkbox" value"1" ';
    if(isset($quick_chat_options['message_sound_default_on'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_disallow_logged_in_usernames_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_disallow_logged_in_usernames" name="quick_chat_options[disallow_logged_in_usernames]" type="checkbox" value"1" ';
    if(isset($quick_chat_options['disallow_logged_in_usernames'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_disallow_usernames_list_fn() {
    global $quick_chat_options;
    echo '<a class="quick_chat_show_hide" href="">'.__('Show', 'quick-chat').'</a>';
    echo '<br>';
    echo '<textarea class="quick-chat-show-hide" id="quick_chat_disallow_usernames_list" name="quick_chat_options[disallow_usernames_list]" rows="5" cols="50">'.$quick_chat_options['disallow_usernames_list'].'</textarea>';
}

function quick_chat_setting_ip_blocklist_fn() {
    global $quick_chat_options;
    echo '<a class="quick_chat_show_hide" href="">'.__('Show', 'quick-chat').'</a>';
    echo '<br>';
    echo '<textarea class="quick-chat-show-hide" id="quick_chat_ip_blocklist" name="quick_chat_options[ip_blocklist]" rows="5" cols="50">'.$quick_chat_options['ip_blocklist'].'</textarea>';
}

function quick_chat_setting_adsense_content_fn(){
    global $quick_chat_options;
    echo '<a class="quick_chat_show_hide" href="">'.__('Show', 'quick-chat').'</a>';
    echo '<br>';
    echo '<textarea class="quick-chat-show-hide" id="quick_chat_adsense_content" name="quick_chat_options[adsense_content]" rows="5" cols="50">'.$quick_chat_options['adsense_content'].'</textarea>';
}

function quick_chat_bing_appid_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_bing_appid" name="quick_chat_options[bing_appid]" size="40" type="text" value="'.((isset($quick_chat_options['bing_appid'])) ? $quick_chat_options['bing_appid']:'').'" />';
}

function quick_chat_manual_gmt_offset_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_manual_gmt_offset" name="quick_chat_options[manual_gmt_offset]" size="10" type="text" value="'.$quick_chat_options['manual_gmt_offset'].'" />';
}

function quick_chat_setting_loggedin_initiate_private_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_loggedin_initiate_private" name="quick_chat_options[loggedin_initiate_private]" type="checkbox" value"1" ';
    if(isset($quick_chat_options['loggedin_initiate_private'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_guests_initiate_private_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_guests_initiate_private" name="quick_chat_options[guests_initiate_private]" type="checkbox" value"1" ';
    if(isset($quick_chat_options['guests_initiate_private'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_message_maximum_number_chars_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_message_maximum_number_chars" name="quick_chat_options[message_maximum_number_chars]" size="10" type="text" value="'.$quick_chat_options['message_maximum_number_chars'].'" />';
}

function quick_chat_avatar_size_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_avatar_size" name="quick_chat_options[avatar_size]" size="10" type="text" value="'.$quick_chat_options['avatar_size'].'" />';
}

function quick_chat_setting_clean_target_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_clean_target" name="quick_chat_options[clean_target]" size="10" type="text" value="'.$quick_chat_options['clean_target'].'" />';
}

function quick_chat_setting_clean_private_fn(){
     echo '<a id="quick_chat_clean_private" href="">'.__('Start').'</a>';
}


function quick_chat_setting_allow_change_username_fn(){
    global $quick_chat_options;
    echo '<input id="allow_change_username" name="quick_chat_options[allow_change_username]" type="checkbox" value"1" ';
    if(isset($quick_chat_options['allow_change_username'])) echo 'checked="checked"';
    echo '/>';
}

function quick_chat_setting_inactivity_timeout_fn() {
    global $quick_chat_options;
    echo '<input id="quick_chat_inactivity_timeout" name="quick_chat_options[inactivity_timeout]" size="10" type="text" value="'.$quick_chat_options['inactivity_timeout'].'" />';
}

function quick_chat_options_page_fn(){
?>
    <div class="wrap">
        <div class="icon32" id="icon-options-general"><br></div>
        <h2>Quick Chat</h2>
        <form action="options.php" method="post">
        <?php settings_fields('quick_chat_options'); ?>
        <?php do_settings_sections(__FILE__); ?>
        <p class="submit">
                <input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
        </p>
        </form>
    </div>
<?php
}

function quick_chat_options_validate($input) {
    global $quick_chat_default_guest_num_digits;
    global $quick_chat_default_timeout_refresh_users;
    global $quick_chat_default_timeout_refresh_messages;
    global $quick_chat_default_manual_gmt_offset;
    global $quick_chat_default_message_maximum_number_chars;
    global $quick_chat_default_avatar_size;
    global $quick_chat_default_clean_target;
    global $quick_chat_default_bing_appid;
    global $quick_chat_default_inactivity_timeout;

    if(!is_numeric($input['timeout_refresh_users']) || ($input['timeout_refresh_users'] < 1)){
        $input['timeout_refresh_users'] =  $quick_chat_default_timeout_refresh_users;
    } else{
        $input['timeout_refresh_users'] = floor($input['timeout_refresh_users']);
    }

    if(!is_numeric($input['timeout_refresh_messages']) || ($input['timeout_refresh_messages'] < 1)){
        $input['timeout_refresh_messages'] =  $quick_chat_default_timeout_refresh_messages;
    } else{
        $input['timeout_refresh_messages'] = floor($input['timeout_refresh_messages']);
    }

    $input['badwords_list'] =  wp_filter_nohtml_kses(trim($input['badwords_list']));

    $input['ip_blocklist'] =  wp_filter_nohtml_kses(trim($input['ip_blocklist']));

    $input['disallow_usernames_list'] =  wp_filter_nohtml_kses(trim($input['disallow_usernames_list']));

    if(!is_numeric($input['guest_num_digits'])){
        $input['guest_num_digits'] =  $quick_chat_default_guest_num_digits;
    } else if($input['guest_num_digits'] < 1){
        $input['guest_num_digits'] =  '1';
    } elseif($input['guest_num_digits'] > 10){
        $input['guest_num_digits'] =  '10';
    }

    if(isset($input['bing_appid']) && strlen($input['bing_appid']) != 40){
        $input['bing_appid'] = $quick_chat_default_bing_appid;
    }

    if(!is_numeric($input['manual_gmt_offset']) || $input['manual_gmt_offset'] < -12 || $input['manual_gmt_offset'] >12){
        $input['manual_gmt_offset'] =  $quick_chat_default_manual_gmt_offset;
    } else{
        $input['manual_gmt_offset'] = floor($input['manual_gmt_offset']);
    }

    if(!is_numeric($input['message_maximum_number_chars']) || $input['message_maximum_number_chars'] < 150){
        $input['message_maximum_number_chars'] =  $quick_chat_default_message_maximum_number_chars;
    } else{
        $input['message_maximum_number_chars'] = floor($input['message_maximum_number_chars']);
    }

    if(!is_numeric($input['avatar_size']) || $input['avatar_size'] < 16 || $input['avatar_size'] > 512){
        $input['avatar_size'] =  $quick_chat_default_avatar_size;
    } else{
        $input['avatar_size'] = floor($input['avatar_size']);
    }

    if(!is_numeric($input['clean_target']) || $input['clean_target'] < 1){
        $input['clean_target'] =  $quick_chat_default_clean_target;
    } else{
        $input['clean_target'] = floor($input['clean_target']);
    }

    if(!is_numeric($input['inactivity_timeout']) || $input['inactivity_timeout']  < 1){
        $input['inactivity_timeout'] =  $quick_chat_default_inactivity_timeout;
    }else if($input['inactivity_timeout'] < 2 * $input['timeout_refresh_users']){
        $input['inactivity_timeout'] = 2 * $input['timeout_refresh_users'];
    } else {
        $input['inactivity_timeout'] = floor($input['inactivity_timeout']);
    }

    quick_chat_clear_cache();

    return $input;
}

function quick_chat_quick_flag_version_notice() {
    global $current_screen;

    if (quick_chat_quick_flag_capable() == false && current_user_can('manage_options') && ($current_screen->base == 'settings_page_quick-chat/quick-chat' || $current_screen->base == 'dashboard_page_quick_chat_dashboard_subpage')) {
        global $current_user ;
        $user_id = $current_user->ID;

        if ( ! get_user_meta($user_id, 'quick_chat_quick_flag_notice_dismiss') ) {
            global $quick_chat_quick_flag_version_minimum;
            $dismiss_url = '?page=quick-chat/quick-chat.php';
            echo '<div class="updated"><p>';
            printf(__('For displaying country flags next to users name Quick Chat requires <a href="http://www.techytalk.info/wordpress-plugins/quick-flag/" target="_blank">Quick Flag</a> WordPress plugin version '.$quick_chat_quick_flag_version_minimum.' or later installed, activated and Quick Flag support in Quick Chat settings not disabled | <a href="%1$s">Dismiss</a>','quick-chat'), $dismiss_url.'&quick_chat_quick_flag_notice_dismiss=0');
            echo "</p></div>";
        }
    }
}
add_action('admin_notices', 'quick_chat_quick_flag_version_notice');

function quick_chat_quick_flag_version_notice_dismiss() {
    if(current_user_can('manage_options')){
        global $current_user;
        $user_id = $current_user->ID;

        if ( isset($_GET['quick_chat_quick_flag_notice_dismiss']) && '0' == $_GET['quick_chat_quick_flag_notice_dismiss'] ) {
             add_user_meta($user_id, 'quick_chat_quick_flag_notice_dismiss', 'true', true);
        }
    }
}
add_action('admin_init', 'quick_chat_quick_flag_version_notice_dismiss');

function quick_chat_quick_flag_capable(){
    global $quick_chat_quick_flag_version_minimum;
    global $quick_flag_version;
    global $quick_chat_options;

    if(!isset($quick_flag_version) || ($quick_flag_version < $quick_chat_quick_flag_version_minimum) || isset($quick_chat_options['disable_quick_flag']))
        return false;
    else
        return true;

}

function quick_chat_dashboard_widget_function(){
    echo quick_chat(400, 'admin_room_'.substr(md5(AUTH_SALT),0,5), 1, 'left', 0, 0, 1, 1, 1);
}

function quick_chat_dashboard_widgets() {
    global $quick_chat_user_status;
    if($quick_chat_user_status == 0)
        wp_add_dashboard_widget('quick_chat_dashboard_widget', __('Quick Chat Admin\'s Lounge','quick-chat'), 'quick_chat_dashboard_widget_function');
}
add_action('wp_dashboard_setup', 'quick_chat_dashboard_widgets' );

function quick_chat($height = 300, $room = 'default', $userlist = 1, $userlist_position = 'left', $smilies = 1, $send_button = 0, $loggedin_visible = 1, $guests_visible = 1, $avatars = 1) {
    global $quick_chat_options;
    $content = '';
    ob_start();

    echo '<div class="quick-chat-container" data-quick-chat-id="'.wp_generate_password(12, false, false).'" data-quick-chat-height="'.$height.'" data-quick-chat-room-name="'.$room.'" data-quick-chat-userlist="'.$userlist.'" data-quick-chat-userlist-position="'.$userlist_position.'" data-quick-chat-smilies="'.$smilies.'" data-quick-chat-send-button="'.$send_button.'" data-quick-chat-loggedin-visible="'.$loggedin_visible.'" data-quick-chat-guests-visible="'.$guests_visible.'" data-quick-chat-avatars="'.$avatars.'"></div>';

    if(!isset($quick_chat_options['hide_linkhome'])){
        echo '<div class="quick-chat-linkhome"><a href="http://www.techytalk.info/wordpress-plugins/quick-chat/" target="_blank">'.__('Powered by Quick Chat', 'quick-chat').'</a></div>';
    }
    $content =  ob_get_contents();
    ob_end_clean();
    return $content;
}

class Quick_Chat extends WP_Widget {
    public $name = 'Quick Chat';
    /* Widget control settings. */
    public $control_options = array(
       'width' => 250,
       'height' => 300,
       'id_base' => 'quick-chat-widget');

    public function __construct() {
        $widget_options = array(
          'classname' => __CLASS__,
          'description' => __('Quick Chat is quick and elegant WordPress chat plugin that does not waste your bandwidth.','quick-chat'));

        parent::__construct($this->control_options['id_base'], $this->name, $widget_options);
    }

    function form ($instance) {
        $defaults = array('title'=>'Quick Chat','height' => 400, 'room' => 'default','userlist' => 1, 'userlist_position' => 'Top', 'smilies' => 1, 'loggedin_visible' => 1, 'guests_visible' => 1, 'avatars' => 1);
        $instance = wp_parse_args( (array) $instance, $defaults );
        ?>
        <p>
        <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title') ?>:</label>
        <input type="text" name="<?php echo $this->get_field_name('title') ?>" id="<?php echo $this->get_field_id('title') ?> " value="<?php echo $instance['title'] ?>" size="10">
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('room'); ?>"><?php _e('Chat room name:') ?></label>
        <input type="text" name="<?php echo $this->get_field_name('room') ?>" id="<?php echo $this->get_field_id('room') ?> " value="<?php echo $instance['room'] ?>" size="10">
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('height'); ?>"><?php _e('Message container height:','quick-chat') ?></label>
        <input type="text" name="<?php echo $this->get_field_name('height') ?>" id="<?php echo $this->get_field_id('height') ?> " value="<?php echo $instance['height'] ?>" size="2">
        px
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('userlist'); ?>"><?php _e('Include user list:','quick-chat') ?></label>
        <input id="<?php echo $this->get_field_id('userlist') ?>" name="<?php echo $this->get_field_name('userlist') ?>" type="checkbox" value="1"
        <?php if(isset($instance['userlist'])) echo 'checked="checked"' ?> />
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('userlist_position'); ?>"><?php _e('User list position:','quick-chat') ?></label>
        <select id="<?php echo $this->get_field_id('userlist_position') ?>" name="<?php echo $this->get_field_name('userlist_position') ?>">
            <option <?php if(isset($instance['userlist_position']) && $instance['userlist_position'] == 'Right') echo 'selected="selected"' ?> >Right</option>
            <option <?php if(isset($instance['userlist_position']) && $instance['userlist_position'] == 'Left') echo 'selected="selected"' ?> >Left</option>
            <option <?php if(isset($instance['userlist_position']) && $instance['userlist_position'] == 'Top') echo 'selected="selected"' ?> >Top</option>
        </select>
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('loggedin_visible'); ?>"><?php _e('Visible to logged in users:','quick-chat') ?></label>
        <input id="<?php echo $this->get_field_id('loggedin_visible') ?>" name="<?php echo $this->get_field_name('loggedin_visible') ?>" type="checkbox" value="1"
        <?php if(isset($instance['loggedin_visible'])) echo 'checked="checked"' ?> />
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('guests_visible'); ?>"><?php _e('Visible to guest users:','quick-chat') ?></label>
        <input id="<?php echo $this->get_field_id('guests_visible') ?>" name="<?php echo $this->get_field_name('guests_visible') ?>" type="checkbox" value="1"
        <?php if(isset($instance['guests_visible'])) echo 'checked="checked"' ?> />
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('avatars'); ?>"><?php _e('Include avatars:','quick-chat') ?></label>
        <input id="<?php echo $this->get_field_id('avatars') ?>" name="<?php echo $this->get_field_name('avatars') ?>" type="checkbox" value="1"
        <?php if(isset($instance['avatars'])) echo 'checked="checked"' ?> />
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('smilies'); ?>"><?php _e('Include smilies container:','quick-chat') ?></label>
        <input id="<?php echo $this->get_field_id('smilies') ?>" name="<?php echo $this->get_field_name('smilies') ?>" type="checkbox" value="1"
        <?php if(isset($instance['smilies'])) echo 'checked="checked"' ?> />
        </p>

        <p>
        <label for="<?php echo $this->get_field_id('send_button'); ?>"><?php _e('Include send button:','quick-chat') ?></label>
        <input id="<?php echo $this->get_field_id('send_button') ?>" name="<?php echo $this->get_field_name('send_button') ?>" type="checkbox" value="1"
        <?php if(isset($instance['send_button'])) echo 'checked="checked"' ?> />
        </p>
        <?php
    }

    function update ($new_instance, $old_instance) {
        $instance = $old_instance;

        if(is_numeric($new_instance['height']) && $new_instance['height'] != 0){
            $instance['height'] = $new_instance['height'];
        }
        $instance['title'] = $new_instance['title'];

        $instance['avatars'] = $new_instance['avatars'];

        $instance['userlist'] = $new_instance['userlist'];

        $instance['smilies'] = $new_instance['smilies'];

        $instance['send_button'] = $new_instance['send_button'];

        $instance['loggedin_visible'] = $new_instance['loggedin_visible'];

        $instance['guests_visible'] = $new_instance['guests_visible'];

        $instance['userlist_position'] = $new_instance['userlist_position'];

        if($new_instance['room'] != ''){
            $instance['room'] = $new_instance['room'];
        }

        quick_chat_clear_cache();
        return $instance;
    }

    function widget ($args,$instance) {
        global $quick_chat_options;
        global $quick_chat_is_embedded_array;
        extract($args);
        $title = $instance['title'];
        $height = $instance['height'];
        $userlist = (isset($instance['userlist']))? 1: 0;
        $userlist_position = strtolower($instance['userlist_position']);
        $room = $instance['room'];
        $avatars = (isset($instance['avatars']))? 1: 0;
        $smilies = (isset($instance['smilies']))? 1: 0;
        $send_button = (isset($instance['send_button']))? 1: 0;
        $loggedin_visible = (isset($instance['loggedin_visible']))? 1: 0;
        $guests_visible = (isset($instance['guests_visible']))? 1: 0;

        if  (
                !isset($quick_chat_options['hide_widget_if_embedded'])
                ||
                !isset($quick_chat_is_embedded_array[$room])
            ){
            echo $before_widget;
            echo $before_title.$title.$after_title;

            echo quick_chat($height, $room, $userlist, $userlist_position, $smilies, $send_button, $loggedin_visible, $guests_visible, $avatars);

            echo $after_widget;
        }
    }
}

function quick_chat_load_widgets() {
  register_widget('Quick_Chat');
}
add_action('widgets_init', 'quick_chat_load_widgets');

function quick_chat_shortcode_handler( $atts, $content=null, $code="" ) {
    global $quick_chat_is_embedded_array;

    extract(shortcode_atts( array(	'height' => 400,
                                        'room' => 'default',
                                        'userlist' => 1,
                                        'userlist_position' => 'left',
                                        'avatars' => 1,
                                        'smilies' => 1,
                                        'send_button' => 0,
                                        'loggedin_visible' => 1,
                                        'guests_visible' => 1),
                                        $atts ));

    $quick_chat_is_embedded_array[$room] = 1;

    return quick_chat($height, $room, $userlist, $userlist_position, $smilies, $send_button, $loggedin_visible, $guests_visible, $avatars);
}
add_shortcode( 'quick-chat', 'quick_chat_shortcode_handler' );

function quick_chat_uninstall() {
    global $wpdb;
    $quick_chat_messages_table_name = $wpdb->prefix . 'quick_chat_messages';
    $quick_chat_users_table_name = $wpdb->prefix . 'quick_chat_users';

    if(get_option('quick_chat_options')) delete_option('quick_chat_options');
    if(get_option('quick_chat_db_version')) delete_option('quick_chat_db_version');
    if(get_option('widget_quick-chat-widget')) delete_option('widget_quick-chat-widget');
    $query = $wpdb->query('DROP TABLE IF EXISTS '.$quick_chat_messages_table_name.';');
    $query = $wpdb->query('DROP TABLE IF EXISTS '.$quick_chat_users_table_name.';');

    quick_chat_clear_cache();
}
register_uninstall_hook(__FILE__, 'quick_chat_uninstall');
?>
