function chat_session_moderate_user()
 {
     global $wpdb;
     if (!isset($_POST['chat_id'])) {
         die;
     }
     $chat_id = esc_attr($_POST['chat_id']);
     if ($chat_id == '') {
         die;
     }
     if (!isset($_POST['moderate_item'])) {
         die;
     }
     $moderate_item = esc_attr($_POST['moderate_item']);
     if (empty($moderate_item)) {
         die;
     }
     if (!isset($_POST['moderate_action'])) {
         die;
     }
     $moderate_action = esc_attr($_POST['moderate_action']);
     if (empty($moderate_action)) {
         die;
     }
     if (!isset($_POST['chat_session'])) {
         die;
     }
     $chat_session = $_POST['chat_session'];
     // If the user doesn't have a type
     if (!isset($this->chat_auth['type'])) {
         die;
     } else {
         if ($this->chat_auth['type'] != "wordpress") {
             die;
         }
     }
     if (!is_user_logged_in()) {
         die;
     }
     if (!wpmudev_chat_is_moderator($chat_session)) {
         die;
     }
     if ($moderate_action == "block-user") {
         $this->_chat_options['global']['blocked_users'][] = $moderate_item;
         $this->_chat_options['global']['blocked_users'] = array_unique($this->_chat_options['global']['blocked_users']);
         update_option('wpmudev-chat-global', $this->_chat_options['global']);
     } else {
         if ($moderate_action == "unblock-user") {
             $arr_idx = array_search($moderate_item, $this->_chat_options['global']['blocked_users']);
             if ($arr_idx !== false && isset($this->_chat_options['global']['blocked_users'][$arr_idx])) {
                 unset($this->_chat_options['global']['blocked_users'][$arr_idx]);
                 update_option('wpmudev-chat-global', $this->_chat_options['global']);
             }
         }
     }
     wp_send_json_success();
     die;
 }
 /**
  * Process chat requests
  *
  * Mostly copied from process.php
  *
  * @global	object	$current_user
  * @param	string	$return		Return? 'yes' or 'no'
  * @return	string			If $return is yes will return the output else echo
  */
 function process_chat_actions($return = 'no')
 {
     if (!isset($_POST['function'])) {
         die;
     }
     $function = $_POST['function'];
     switch ($function) {
         case 'chat_init':
             $reply_data = array();
             foreach ($this->chat_sessions as $chat_id => $chat_session) {
                 //echo "chat_session<pre>"; print_r($chat_session); echo "</pre>";
                 $reply_data[$chat_id] = array();
                 $reply_data[$chat_id]['html'] = $this->chat_session_build_box($chat_session);
                 // We load the box CSS via the AJAX call. This helps when bots are hitting the page.
                 $reply_data[$chat_id]['css'] = $this->chat_session_box_styles($chat_session);
             }
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_message_send':
             $reply_data = array();
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             if (!isset($_POST['chat_messages']) || !count($_POST['chat_messages'])) {
                 $reply_data['errorText'] = "chat_messages missing";
                 $reply_data['errorStatus'] = true;
                 wp_send_json($reply_data);
                 die;
             }
             // Double check the user's authentication. Seems some users can login with multiple tabs. If they log out of one tab they
             // should not be able to post via the other tab.
             if (!isset($this->chat_auth['type'])) {
                 $reply_data['errorText'] = "Unknown user type";
                 $reply_data['errorStatus'] = true;
                 wp_send_json($reply_data);
                 die;
             }
             //log_chat_message(__FUNCTION__. ": ". $function .": ------------------------------------------------------");
             foreach ($_POST['chat_messages'] as $chat_id => $chat_messages) {
                 if (!isset($this->chat_sessions[$chat_id])) {
                     continue;
                 }
                 if (!is_array($chat_messages) || !count($chat_messages)) {
                     continue;
                 }
                 $chat_session = $this->chat_sessions[$chat_id];
                 if (!isset($reply_data['chat_messages'][$chat_id])) {
                     $reply_data['chat_messages'][$chat_id] = array();
                 }
                 //log_chat_message(__FUNCTION__ .": chat_id[". $chat_id ."] chat_message[". print_r($chat_messages, true) ."]");
                 foreach ($chat_messages as $chat_message_idx => $chat_message) {
                     $reply_data['chat_messages'][$chat_id][$chat_message_idx] = false;
                     $chat_message = urldecode($chat_message);
                     $chat_message = stripslashes($chat_message);
                     // Replace the chr(10) Line feed (not the chr(13) carraige return) with a placeholder. Will be replaced with
                     // real <br /> after filtering This is done so when we convert text within [code][/code] the <br /> are not
                     // converted to entities. Because we want the code to be formatted
                     $chat_message = str_replace(chr(10), "[[CR]]", $chat_message);
                     // In case the user entered HTML <code></code> instead of [code][/code]
                     $chat_message = str_replace("<code>", "[code]", $chat_message);
                     $chat_message = str_replace("</code>", "[/code]", $chat_message);
                     // We also can accept backtick quoted text and convert to [code][/code]
                     $chat_message = preg_replace('/`(.*?)`/', '[code]$1[/code]', $chat_message);
                     // Now split out the [code][/code] sections.
                     //preg_match_all("|\[code\](.*)\[/code\]|s", $chat_message, $code_out);
                     preg_match_all("~\\[code\\](.+?)\\[/code\\]~si", $chat_message, $code_out);
                     if ($code_out && is_array($code_out) && is_array($code_out[0]) && count($code_out[0])) {
                         foreach ($code_out[0] as $code_idx => $code_str_original) {
                             if (!isset($code_out[1][$code_idx])) {
                                 continue;
                             }
                             // Here we replace our [code][/code] block or text in the message with placeholder [code-XXX] where XXX
                             // is the index (0,1,2,3, etc.) Again we do this because in the next step we will strip out all HTML not
                             // allowed. We want to protect any HTML within the code block
                             // which will be converted to HTML entities after the filtering.
                             $chat_message = str_replace($code_str_original, '[code-' . $code_idx . ']', $chat_message);
                         }
                     }
                     // First strip all the tags!
                     $allowed_protocols = array();
                     $allowed_html = array();
                     /*
                     $allowed_html = array(	'a' => array('href' => array()),
                     						'br' => array(),
                     						'em' => array(),
                     						'strong' => array(),
                     						'strike' => array(),
                     						'blockquote' => array()
                     					);
                     */
                     $chat_message = wp_kses($chat_message, $allowed_html, $allowed_protocols);
                     // If the user enters something that liiks like a link (http://, ftp://, etc) it will be made clickable
                     // in that is will be wrapped in an anchor, etc. The the link tarket will be set so clicking it will open
                     // in a new window
                     $chat_message = links_add_target(make_clickable($chat_message));
                     // Now that we can filtered the text outside the [code][/code] we want to convert the code section HTML to entities since it
                     // will be viewed that way by other users.
                     if ($code_out && is_array($code_out) && is_array($code_out[0]) && count($code_out[0])) {
                         foreach ($code_out[0] as $code_idx => $code_str_original) {
                             if (!isset($code_out[1][$code_idx])) {
                                 continue;
                             }
                             $code_str_replace = "<code>" . htmlentities2($code_out[1][$code_idx], ENT_QUOTES | ENT_XHTML) . "</code>";
                             $chat_message = str_replace('[code-' . $code_idx . ']', $code_str_replace, $chat_message);
                         }
                     }
                     // Finally convert any of our CR placeholders to HTML breaks.
                     $chat_message = str_replace("[[CR]]", '<br />', $chat_message);
                     // Just as a precaution. After processing we may end up with double breaks. So we convert to single.
                     $chat_message = str_replace("<br /><br />", '<br />', $chat_message);
                     // End message filtering
                     if ($chat_message == '') {
                         continue;
                     }
                     // Truncate the message IF the max length is set
                     if (!wpmudev_chat_is_moderator($chat_session)) {
                         if ($chat_session['row_message_input_length'] > 0 && strlen($chat_message) > $chat_session['row_message_input_length']) {
                             $chat_message = substr($chat_message, 0, $chat_session['row_message_input_length']);
                         }
                     }
                     // Process bad words
                     if ($this->_chat_options['banned']['blocked_words_active'] == "enabled" && $chat_session['blocked_words_active'] == "enabled") {
                         $chat_message = str_ireplace($this->_chat_options['banned']['blocked_words'], $this->_chat_options['banned']['blocked_words_replace'], $chat_message);
                     }
                     /*
                     // Save for later. We had a request to support latex via chat
                     if (preg_match('/\[latex\](.*)\[\/latex\]/', $chat_message, $match)) {
                     	if (isset($match[1])) {
                     		$latex_content = $match[1];
                     		$latex_content = '[latexpage] \['. $match[1] .'\]';
                     		$latex_image = quicklatex_parser($latex_content);
                     		if ($latex_image) {
                     			$latex_image = strip_tags($latex_image, '<img>');
                     			$chat_message = str_replace($match[0], $latex_image, $chat_message);
                     		}
                     	}
                     }
                     */
                     $ret = $this->chat_session_send_message($chat_message, $chat_session);
                     if (!empty($ret)) {
                         $reply_data['chat_messages'][$chat_id][$chat_message_idx] = true;
                     }
                     //$reply_data['errorText'] 	= "chat_message sent to DB wpdb[". $ret. "]";
                 }
             }
             // From wordpress-chat-2.0.2-Beta1
             // Begin message filtering
             //$chat_message = $_POST['chat_message'];
             //log_chat_message(__FUNCTION__. ": ". $function ."\r\n");
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_user_login':
             $reply_data = array();
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             if (!isset($_POST['user_info'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('missing POST user_info', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             $user_info = $_POST['user_info'];
             switch ($user_info['type']) {
                 case 'public_user':
                     if (!isset($user_info['name']) || !isset($user_info['email'])) {
                         $reply_data['errorText'] = __('Please provide valid Name and Email.', $this->translation_domain);
                         $reply_data['errorStatus'] = true;
                         wp_send_json($reply_data);
                         die;
                     }
                     $user_info['name'] = esc_attr($user_info['name']);
                     $user_info['email'] = esc_attr($user_info['email']);
                     if (empty($user_info['name']) || empty($user_info['email']) || !is_email($user_info['email'])) {
                         $reply_data['errorText'] = __('Please provide valid Name and Email.', $this->translation_domain);
                         $reply_data['errorStatus'] = true;
                         wp_send_json($reply_data);
                         die;
                     }
                     $user_name_id = username_exists($user_info['name']);
                     if ($user_name_id) {
                         $reply_data['errorText'] = __('Name already registered. Try something unique', $this->translation_domain);
                         $reply_data['errorStatus'] = true;
                         wp_send_json($reply_data);
                         die;
                     }
                     $user_name_id = email_exists($user_info['email']);
                     if ($user_name_id) {
                         $reply_data['errorText'] = __('Email already registered. Try something  unique', $this->translation_domain);
                         $reply_data['errorStatus'] = true;
                         wp_send_json($reply_data);
                         die;
                     }
                     $avatar = get_avatar($user_info['email'], 96, get_option('avatar_default'), $user_info['name']);
                     if ($avatar) {
                         $avatar_parts = array();
                         if (stristr($avatar, ' src="') !== false) {
                             preg_match('/src="([^"]*)"/i', $avatar, $avatar_parts);
                         } else {
                             if (stristr($avatar, " src='") !== false) {
                                 preg_match("/src='([^']*)'/i", $avatar, $avatar_parts);
                             }
                         }
                         if (isset($avatar_parts[1]) && !empty($avatar_parts[1])) {
                             $user_info['avatar'] = $avatar_parts[1];
                         }
                     }
                     $user_info['ip_address'] = isset($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
                     $user_info['auth_hash'] = md5($user_info['name'] . $user_info['email'] . $user_info['ip_address']);
                     $reply_data['user_info'] = $user_info;
                     break;
                 case 'facebook':
                 case 'google_plus':
                 case 'twitter':
                     $user_info['ip_address'] = isset($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
                     $user_info['auth_hash'] = md5($user_info['id'] . $user_info['ip_address']);
                     $reply_data['user_info'] = $user_info;
                     break;
                 default:
                     break;
             }
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_messages_update':
             $reply_data = array();
             //echo "_POST<pre>"; print_r($_POST); echo "</pre>";
             //log_chat_message(__FUNCTION__. ": ". $function .": ------------------------------------------------------");
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             $reply_data['sessions'] = array();
             $reply_data['invites'] = array();
             if (isset($_POST['timers'])) {
                 $timers = $_POST['timers'];
             } else {
                 $timers = array();
             }
             //log_chat_message(__FUNCTION__ .": timers". print_r($timers, true). "");
             // We first want to grab the invites for the users. This will setup the extra items in the $this->chat_sessions reference. Then later
             // in this section we will also add the rows and meta updates for the new invite box.
             if ($this->using_popup_out_template == false && isset($timers['invites']) && $timers['invites'] == 1) {
                 //log_chat_message(__FUNCTION__ .": timer invite[1]");
                 $reply_data['invites'] = $this->chat_session_get_invites_new();
             }
             //if (!isset($chat_session['since'])) $chat_session['since'] = 0;
             //if (!isset($chat_session['last_row_id'])) $chat_session['last_row_id'] = 0;
             $this->chat_auth['ip_address'] = isset($_SERVER['HTTP_X_FORWARD_FOR']) ? $_SERVER['HTTP_X_FORWARD_FOR'] : $_SERVER['REMOTE_ADDR'];
             foreach ($this->chat_sessions as $chat_id => $chat_session) {
                 // Now process the meta information. Session Status, Deleted Row IDs and Session Users
                 $reply_data['sessions'][$chat_id]['meta'] = array();
                 if (!isset($this->chat_sessions_meta[$chat_id])) {
                     $this->chat_sessions_meta[$chat_id] = $this->chat_session_get_meta($chat_session);
                 }
                 if (isset($timers['messages']) && $timers['messages'] == 1) {
                     //log_chat_message(__FUNCTION__ .": timer messages[1]");
                     if (!isset($chat_session['last_row_id'])) {
                         $chat_session['last_row_id'] = "__EMPTY__";
                     }
                     //log_chat_message(__FUNCTION__ .": last_row_id chat_session[". $chat_session['last_row_id'] ."] meta[". $this->chat_sessions_meta[$chat_id]['last_row_id'] ."]");
                     //if ($this->chat_sessions_meta[$chat_id]['last_row_id'] === "__EMPTY__") {
                     //	//log_chat_message(__FUNCTION__ .": here #1");
                     //	$reply_data['sessions'][$chat_id]['rows'] = "__EMPTY__";
                     //} else if ($chat_session['last_row_id'] != $this->chat_sessions_meta[$chat_id]['last_row_id']) {
                     $reply_data['sessions'][$chat_id]['rows'] = array();
                     $new_rows = $this->chat_session_get_message_new($chat_session);
                     //log_chat_message(__FUNCTION__ .': new_rows<pre>'. print_r($new_rows, true) .'</pre>');
                     if ($new_rows && count($new_rows)) {
                         // Init the reply last_row_id with what was sent.
                         $reply_data['sessions'][$chat_id]['last_row_id'] = $chat_session['last_row_id'];
                         $_LAST_ROW_UPDATED = false;
                         foreach ($new_rows as $row_idx => $row) {
                             if (intval($chat_session['last_row_id']) > 0 && $row->id == $chat_session['last_row_id']) {
                                 continue;
                             }
                             $reply_data['sessions'][$chat_id]['rows'][strtotime($row->timestamp) . "-" . $row->id] = $this->chat_session_build_row($row, $chat_session);
                             // Then update the last_row_id based on the higher row->id values returned
                             if ($_LAST_ROW_UPDATED == false) {
                                 $reply_data['sessions'][$chat_id]['last_row_id'] = $row->id;
                                 $_LAST_ROW_UPDATED = true;
                             }
                             //log_chat_message(__FUNCTION__ .': row_idx['. $row_idx.'] new row['. $row->id .'] message['. $row->message .']');
                         }
                         if (count($reply_data['sessions'][$chat_id]['rows'])) {
                             ksort($reply_data['sessions'][$chat_id]['rows']);
                         }
                     } else {
                         $reply_data['sessions'][$chat_id]['rows'] = "__EMPTY__";
                     }
                     //log_chat_message("\r\n");
                     //}
                     $reply_data['sessions'][$chat_id]['meta'] = $this->chat_session_update_meta_log($chat_session);
                 }
                 if (isset($timers['meta']) && $timers['meta'] == 1) {
                     //log_chat_message(__FUNCTION__ .": timer meta[1]");
                     //$reply_data['sessions'][$chat_id]['meta'] 		= $this->chat_session_update_meta_log($chat_session);
                     //log_chat_message(__FUNCTION__ .": meta". print_r($reply_data['sessions'][$chat_id]['meta'], true));
                     $reply_data['sessions'][$chat_id]['global'] = $this->chat_session_update_global_log($chat_session);
                     //log_chat_message(__FUNCTION__ .": global". print_r($reply_data['sessions'][$chat_id]['global'], true));
                 }
                 // We update the usermeta with the current tmestamp
                 if (isset($timers['users']) && $timers['users'] == 1) {
                     //log_chat_message(__FUNCTION__ .": timer users[1]");
                     $this->chat_session_users_update_polltime($chat_session);
                     $reply_data['sessions'][$chat_id]['meta']['users-active'] = $this->chat_session_get_active_users($chat_session);
                     //log_chat_message(__FUNCTION__ .": users-active". print_r($reply_data['sessions'][$chat_id]['meta']['users-active'], true));
                 }
             }
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_meta_leave_private_session':
             global $wpdb;
             $reply_data = array();
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             $reply_data['sessions'] = array();
             // Get Private chats
             if (!isset($this->chat_auth['auth_hash']) || empty($this->chat_auth['auth_hash'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid auth_hash', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             //echo "chat_sessions<pre>"; print_r($this->chat_sessions); echo "</pre>";
             //echo "chat_auth<pre>"; print_r($this->chat_auth); echo "</pre>";
             //die();
             foreach ($this->chat_sessions as $chat_id => $chat_session) {
                 //echo "chat_session<pre>"; print_r($chat_session); echo "</pre>";
                 $reply_data['sessions'][$chat_id] = $chat_id;
                 $sql_str = $wpdb->prepare("UPDATE " . WPMUDEV_Chat::tablename('message') . " SET archived=%s WHERE chat_id=%s AND session_type=%s AND auth_hash=%s LIMIT 1", 'yes', $chat_session['id'], 'invite', $this->chat_auth['auth_hash']);
                 //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                 $wpdb->query($sql_str);
                 // When the moderator leave we archive the chat.
                 if (wpmudev_chat_is_moderator($chat_session)) {
                     $this->chat_session_archive_messages($chat_session);
                 }
             }
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_messages_clear':
             global $wpdb;
             $reply_data = array();
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             // If the user doesn't have a type
             if (!isset($this->chat_auth['type'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             } else {
                 if ($this->chat_auth['type'] != "wordpress") {
                     $reply_data['errorStatus'] = true;
                     $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                     wp_send_json($reply_data);
                     die;
                 }
             }
             if (!is_user_logged_in()) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             foreach ($this->chat_sessions as $chat_id => $chat_session) {
                 if (wpmudev_chat_is_moderator($chat_session)) {
                     $sql_str = $wpdb->prepare("DELETE FROM `" . WPMUDEV_Chat::tablename('message') . "` WHERE blog_id = %d AND chat_id = %s AND archived IN ('no') AND session_type = %s;", $chat_session['blog_id'], $chat_session['id'], $chat_session['session_type']);
                     $wpdb->query($sql_str);
                     //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                     $this->chat_session_set_meta($chat_session, 'last_row_id', '__EMPTY__');
                     $this->chat_session_update_message_rows_deleted($chat_session);
                 } else {
                     $reply_data['errorStatus'] = true;
                     $reply_data['errorText'] = __('Not moderator', $this->translation_domain);
                     die;
                 }
             }
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_messages_archive':
             $reply_data = array();
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             // If the user doesn't have a type
             if (!isset($this->chat_auth['type'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             } else {
                 if ($this->chat_auth['type'] != "wordpress") {
                     $reply_data['errorStatus'] = true;
                     $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                     wp_send_json($reply_data);
                     die;
                 }
             }
             if (!is_user_logged_in()) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             foreach ($this->chat_sessions as $chat_id => $chat_session) {
                 if (wpmudev_chat_is_moderator($chat_session)) {
                     $this->chat_session_archive_messages($chat_session);
                 }
             }
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_session_moderate_status':
             $reply_data = array();
             $reply_data['errorStatus'] = false;
             $reply_data['errorText'] = '';
             $chat_id = 0;
             if (!isset($_POST['chat_session'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_session', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             $chat_session = $_POST['chat_session'];
             $chat_id = esc_attr($chat_session['id']);
             if ($chat_id == '') {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_id', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             if (!isset($_POST['chat_session_status'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_session_status', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             $chat_session_status = esc_attr($_POST['chat_session_status']);
             if ($chat_session_status != "open" && $chat_session_status != "closed") {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_session_status', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             // If the user doesn't have a type
             if (!isset($this->chat_auth['type'])) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             } else {
                 if ($this->chat_auth['type'] != "wordpress") {
                     $reply_data['errorStatus'] = true;
                     $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                     wp_send_json($reply_data);
                     die;
                 }
             }
             if (!is_user_logged_in()) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('Invalid chat_auth [type]', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             if (!wpmudev_chat_is_moderator($chat_session)) {
                 $reply_data['errorStatus'] = true;
                 $reply_data['errorText'] = __('not moderator', $this->translation_domain);
                 wp_send_json($reply_data);
                 die;
             }
             $this->chat_session_set_meta($chat_session, 'session_status', $chat_session_status);
             wp_send_json($reply_data);
             die;
             break;
         case 'chat_session_moderate_message':
             global $wpdb;
             if (!isset($_POST['chat_id'])) {
                 wp_send_json_error();
                 die;
             }
             $chat_id = $_POST['chat_id'];
             if ($chat_id == '') {
                 wp_send_json_error();
                 die;
             }
             if (!isset($_POST['row_id'])) {
                 wp_send_json_error();
                 die;
             }
             list($row_time, $row_id) = explode('-', $_POST['row_id']);
             //$row_id = intval($_POST['row_id']);
             if (empty($row_time) || empty($row_id)) {
                 wp_send_json_error();
                 die;
             }
             //log_chat_message(__FUNCTION__ .": row_time[". $row_time ."] row_id[". $row_id ."]");
             if (!isset($_POST['moderate_action'])) {
                 wp_send_json_error();
                 die;
             }
             $moderate_action = esc_attr($_POST['moderate_action']);
             if (empty($moderate_action)) {
                 wp_send_json_error();
                 die;
             }
             if (!isset($_POST['chat_session'])) {
                 wp_send_json_error();
                 die;
             }
             $chat_session = $_POST['chat_session'];
             // If the user doesn't have a type
             if (!isset($this->chat_auth['type'])) {
                 wp_send_json_error();
                 die;
             } else {
                 if ($this->chat_auth['type'] != "wordpress") {
                     wp_send_json_error();
                     die;
                 }
             }
             if (!is_user_logged_in()) {
                 wp_send_json_error();
                 die;
             }
             if (!wpmudev_chat_is_moderator($chat_session)) {
                 wp_send_json_error();
                 die;
             }
             $row_date = date('Y-m-d H:i:s', $row_time);
             $sql_str = $wpdb->prepare("SELECT id, deleted FROM `" . WPMUDEV_Chat::tablename('message') . "` WHERE id = %d AND blog_id = %d AND chat_id = %s AND timestamp = %s LIMIT 1;", $row_id, $chat_session['blog_id'], $chat_id, $row_date);
             //echo "sql_str=[". $sql_str ."]<br />";
             //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
             $chat_row = $wpdb->get_row($sql_str);
             //log_chat_message(__FUNCTION__ .": chat_row<pre>". print_r($chat_row, true) ."</pre>";
             if ($chat_row && isset($chat_row->deleted)) {
                 $chat_row_deleted_new = '';
                 if ($moderate_action == "delete") {
                     $chat_row_deleted_new = 'yes';
                 } else {
                     if ($moderate_action == "undelete") {
                         $chat_row_deleted_new = 'no';
                     }
                 }
                 if (!empty($chat_row_deleted_new)) {
                     $sql_str = $wpdb->prepare("UPDATE `" . WPMUDEV_Chat::tablename('message') . "` SET deleted=%s WHERE id=%d AND blog_id = %d AND chat_id = %s LIMIT 1;", $chat_row_deleted_new, $chat_row->id, $chat_session['blog_id'], $chat_id);
                     //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                     $wpdb->get_results($sql_str);
                     $this->chat_session_update_message_rows_deleted($chat_session);
                     //log_chat_message(__FUNCTION__ .": deleted_rows<pre>". print_r($deleted_rows, true) ."</pre>";
                     wp_send_json_success();
                     die;
                 }
             }
             break;
         case 'chat_session_moderate_ipaddress':
             global $wpdb;
             if (!isset($_POST['chat_id'])) {
                 die;
             }
             $chat_id = esc_attr($_POST['chat_id']);
             if ($chat_id == '') {
                 die;
             }
             if (!isset($_POST['ip_address'])) {
                 die;
             }
             $ip_address = esc_attr($_POST['ip_address']);
             if (empty($ip_address)) {
                 die;
             }
             if (!isset($_POST['moderate_action'])) {
                 die;
             }
             $moderate_action = esc_attr($_POST['moderate_action']);
             if (empty($moderate_action)) {
                 die;
             }
             if (!isset($_POST['chat_session'])) {
                 die;
             }
             $chat_session = $_POST['chat_session'];
             // If the user doesn't have a type
             if (!isset($this->chat_auth['type'])) {
                 die;
             } else {
                 if ($this->chat_auth['type'] != "wordpress") {
                     die;
                 }
             }
             if (!is_user_logged_in()) {
                 die;
             }
             if (!wpmudev_chat_is_moderator($chat_session)) {
                 die;
             }
             if ($this->get_option('blocked_ip_addresses_active', 'global') != "enabled") {
                 die;
             }
             if (!isset($this->_chat_options['global']['blocked_ip_addresses']) || empty($this->_chat_options['global']['blocked_ip_addresses'])) {
                 $this->_chat_options['global']['blocked_ip_addresses'] = array();
             }
             if ($moderate_action == "block-ip") {
                 $this->_chat_options['global']['blocked_ip_addresses'][] = $ip_address;
                 $this->_chat_options['global']['blocked_ip_addresses'] = array_unique($this->_chat_options['global']['blocked_ip_addresses']);
                 update_option('wpmudev-chat-global', $this->_chat_options['global']);
             } else {
                 if ($moderate_action == "unblock-ip") {
                     $arr_idx = array_search($ip_address, $this->_chat_options['global']['blocked_ip_addresses']);
                     if ($arr_idx !== false && isset($this->_chat_options['global']['blocked_ip_addresses'][$arr_idx])) {
                         unset($this->_chat_options['global']['blocked_ip_addresses'][$arr_idx]);
                         update_option('wpmudev-chat-global', $this->_chat_options['global']);
                     }
                 }
             }
             wp_send_json_success();
             die;
             break;
         case 'chat_session_moderate_user':
             global $wpdb;
             if (!isset($_POST['chat_id'])) {
                 die;
             }
             $chat_id = esc_attr($_POST['chat_id']);
             if ($chat_id == '') {
                 die;
             }
             if (!isset($_POST['moderate_item'])) {
                 die;
             }
             $moderate_item = esc_attr($_POST['moderate_item']);
             if (empty($moderate_item)) {
                 die;
             }
             if (!isset($_POST['moderate_action'])) {
                 die;
             }
             $moderate_action = esc_attr($_POST['moderate_action']);
             if (empty($moderate_action)) {
                 die;
             }
             if (!isset($_POST['chat_session'])) {
                 die;
             }
             $chat_session = $_POST['chat_session'];
             // If the user doesn't have a type
             if (!isset($this->chat_auth['type'])) {
                 die;
             } else {
                 if ($this->chat_auth['type'] != "wordpress") {
                     die;
                 }
             }
             if (!is_user_logged_in()) {
                 die;
             }
             if (!wpmudev_chat_is_moderator($chat_session)) {
                 die;
             }
             if ($moderate_action == "block-user") {
                 $this->_chat_options['global']['blocked_users'][] = $moderate_item;
                 $this->_chat_options['global']['blocked_users'] = array_unique($this->_chat_options['global']['blocked_users']);
                 update_option('wpmudev-chat-global', $this->_chat_options['global']);
             } else {
                 if ($moderate_action == "unblock-user") {
                     $arr_idx = array_search($moderate_item, $this->_chat_options['global']['blocked_users']);
                     if ($arr_idx !== false && isset($this->_chat_options['global']['blocked_users'][$arr_idx])) {
                         unset($this->_chat_options['global']['blocked_users'][$arr_idx]);
                         update_option('wpmudev-chat-global', $this->_chat_options['global']);
                     }
                 }
             }
             wp_send_json_success();
             die;
             break;
         case 'chat_session_invite_private':
             global $wpdb, $blog_id;
             //echo "_POST<pre>"; print_r($_POST); echo "</pre>";
             //die();
             // We ONLY allow logged in users to perform private invites
             if (!is_user_logged_in()) {
                 wp_send_json_error();
                 return;
             }
             if (md5(get_current_user_id()) != $this->chat_auth['auth_hash']) {
                 wp_send_json_error();
                 return;
             }
             $user_from_hash = $this->chat_auth['auth_hash'];
             if (!isset($_REQUEST['wpmudev-chat-to-user']) || empty($_REQUEST['wpmudev-chat-to-user'])) {
                 wp_send_json_error();
                 return;
             }
             $user_to_hash = esc_attr($_REQUEST['wpmudev-chat-to-user']);
             $private_invite_noonce = time();
             $chat_id = "private-" . $private_invite_noonce;
             //if (is_multisite())
             //	$blog_id = $wpdb->blogid;
             //else
             //	$blog_id = 1;
             $sql_str = $wpdb->prepare("SELECT invite_from.chat_id, invite_from.id invite_from_id, invite_to.id invite_to_id FROM " . WPMUDEV_Chat::tablename('message') . " as invite_from INNER JOIN " . WPMUDEV_Chat::tablename('message') . " as invite_to ON invite_from.chat_id=invite_to.chat_id AND invite_to.auth_hash = %s WHERE invite_from.blog_id = %d AND invite_from.session_type=%s AND invite_from.auth_hash=%s ORDER BY invite_from.timestamp ASC LIMIT 1", $user_to_hash, $blog_id, 'invite', $user_from_hash);
             //echo "sql_str[". $sql_str ."]<br />";
             $invites = $wpdb->get_row($sql_str);
             //echo "invites<pre>"; print_r($invites); echo "</pre>";
             if (!empty($invites)) {
                 $invitation = array();
                 $invitation['host'] = array();
                 $invitation['host'] = $this->chat_auth;
                 // IF we have a previous private chat we do a number of setup tasks
                 // For the user sending the invite. We update the message with the 'no' archived status and fill in the invitation.
                 if (isset($invites->invite_from_id)) {
                     $sql_str = $wpdb->prepare("UPDATE " . WPMUDEV_Chat::tablename('message') . " SET archived = %s, message = %s, moderator = %s WHERE id = %d AND blog_id = %d AND chat_id = %s AND auth_hash = %s LIMIT 1", 'no', serialize($invitation), 'no', $invites->invite_from_id, $blog_id, $invites->chat_id, $user_from_hash);
                     //echo "sql_str[". $sql_str ."]<br />";
                     $wpdb->get_results($sql_str);
                 }
                 // For the user receiving the invite. We update the message with the 'no' archived status and fill in the invitation. The invitation
                 // Contains information like who did the invite.
                 if (isset($invites->invite_to_id)) {
                     $invitation['id'] = $invites->invite_from_id;
                     $invitation['invite-status'] = 'pending';
                     $sql_str = $wpdb->prepare("UPDATE " . WPMUDEV_Chat::tablename('message') . " SET archived = %s, message = %s, moderator = %s WHERE id = %d AND blog_id = %d AND chat_id = %s AND auth_hash = %s LIMIT 1", 'no', serialize($invitation), 'no', $invites->invite_to_id, $blog_id, $invites->chat_id, $user_to_hash);
                     //echo "sql_str[". $sql_str ."]<br />";
                     $wpdb->get_results($sql_str);
                 }
                 // Then we un-archive the previous messages if any
                 $sql_str = $wpdb->prepare("UPDATE " . WPMUDEV_Chat::tablename('message') . " SET archived = %s WHERE blog_id = %d AND chat_id = %s AND session_type = %s", 'no', $blog_id, $invites->chat_id, 'private');
                 //echo "sql_str[". $sql_str ."]<br />";
                 $wpdb->get_results($sql_str);
                 // Lastly, we then unarchive the log reference.
                 $sql_str = $wpdb->prepare("UPDATE " . WPMUDEV_Chat::tablename('log') . " SET archived = %s WHERE blog_id = %d AND chat_id = %s AND session_type = %s LIMIT 1", 'no', $blog_id, $invites->chat_id, 'private');
                 //echo "sql_str[". $sql_str ."]<br />";
                 $wpdb->get_results($sql_str);
             } else {
                 if (empty($invites)) {
                     $sql_str = $wpdb->prepare("INSERT INTO " . WPMUDEV_Chat::tablename('message') . " (`blog_id`, `chat_id`, `session_type`, `timestamp`, `name`, `avatar`, `auth_hash`, `ip_address`, `message`, `moderator`, `deleted`, `archived`, `log_id`) VALUES(%d, %s, %s, NOW(), %s, %s, %s, %s, %s, %s, %s, %s, %d);", $blog_id, $chat_id, 'invite', $this->chat_auth['name'], $this->chat_auth['avatar'], $user_from_hash, $this->chat_auth['ip_address'], serialize($invitation), $user_moderator, 'no', 'no', 0);
                     //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                     $wpdb->get_results($sql_str);
                     if (intval($wpdb->insert_id)) {
                         $invitation['id'] = $wpdb->insert_id;
                         $invitation['invite-status'] = 'pending';
                         // Then add the to
                         $user_moderator = "no";
                         $sql_str = $wpdb->prepare("SELECT * FROM " . WPMUDEV_Chat::tablename('message') . " WHERE blog_id = %d AND chat_id=%s AND session_type=%s AND auth_hash=%s AND archived = %s ORDER BY timestamp ASC", $blog_id, $chat_id, 'invite', $user_to_hash, 'no');
                         //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                         $invites = $wpdb->get_results($sql_str);
                         if (empty($invites)) {
                             $sql_str = $wpdb->prepare("INSERT INTO " . WPMUDEV_Chat::tablename('message') . " (`blog_id`, `chat_id`, `session_type`, `timestamp`, `name`, `avatar`, `auth_hash`, `ip_address`, `message`, `moderator`, `deleted`, `archived`, `log_id`) VALUES(%d, %s, %s, NOW(), %s, %s, %s, %s, %s, %s, %s, %s, %d);", $blog_id, $chat_id, 'invite', $this->chat_auth['name'], $this->chat_auth['avatar'], $user_to_hash, $this->chat_auth['ip_address'], serialize($invitation), $user_moderator, 'no', 'no', 0);
                             //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                             $wpdb->get_results($sql_str);
                         }
                     }
                 }
             }
             wp_send_json_success();
             die;
             break;
         case 'chat_update_user_status':
             if (!is_user_logged_in()) {
                 return;
             }
             $user_id = get_current_user_id();
             if (md5($user_id) == $this->chat_auth['auth_hash']) {
                 if (isset($_POST['wpmudev-chat-user-status'])) {
                     $new_status = esc_attr($_POST['wpmudev-chat-user-status']);
                     if (isset($this->_chat_options['user-statuses'][$new_status])) {
                         wpmudev_chat_update_user_status($user_id, $new_status);
                         wp_send_json_success();
                     }
                 }
             }
             die;
             break;
         case 'chat_invite_update_user_status':
             $chat_id = esc_attr($_POST['chat-id']);
             if (!$chat_id) {
                 die;
             }
             if (!isset($this->chat_auth['auth_hash']) || empty($this->chat_auth['auth_hash'])) {
                 die;
             }
             $invite_status = esc_attr($_POST['invite-status']);
             if ($invite_status != 'accepted' && $invite_status != 'declined') {
                 $invite_status = 'declined';
             }
             global $wpdb;
             $sql_str = $wpdb->prepare("SELECT * FROM " . WPMUDEV_Chat::tablename('message') . " WHERE session_type=%s AND auth_hash=%s AND archived IN('no') ORDER BY timestamp ASC", 'invite', $this->chat_auth['auth_hash']);
             //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
             $invite_chats = $wpdb->get_results($sql_str);
             if (!empty($invite_chats)) {
                 foreach ($invite_chats as $invite_chat) {
                     $invite_info = unserialize($invite_chat->message);
                     $invite_info['invite-status'] = $invite_status;
                     $sql_str = $wpdb->prepare("UPDATE " . WPMUDEV_Chat::tablename('message') . " SET `message`= %s WHERE id=%d", serialize($invite_info), $invite_chat->id);
                     //log_chat_message(__FUNCTION__ .": [". $sql_str ."]");
                     $wpdb->query($sql_str);
                 }
             }
             wp_send_json_success();
             die;
             break;
     }
 }