<commit_before><?php
function doCharset($db_character_set){
    global $smcFunc;
	
    if (!empty($db_character_set)) {
	    $smcFunc['db_query']('set_character_set', 
	        'SET NAMES ' . $db_character_set,
		    array()
	    );
	}	
}	
function initModSettings(){
    global $smcFunc, $modSettings;
	
    $results = $smcFunc['db_query']('', '
		SELECT variable, value
		FROM {db_prefix}settings',
		array()
	);
	$modSettings = array();
	while ($row = $smcFunc['db_fetch_row']($results)) {
		$modSettings[$row[0]] = $row[1];
	}
	$smcFunc['db_free_result']($results);
    
	return $modSettings;
}
	
function initOptions($member_id){
    global $smcFunc, $options;
	
    $results = $smcFunc['db_query']('', '
		SELECT variable, value
		FROM {db_prefix}themes
		WHERE id_member = {string:mem}',
		array(
		        'mem' => $member_id,
		)
	);
	$options = array();
	while ($row = $smcFunc['db_fetch_row']($results)) {
		
		$options[$row[0]] = $row[1];
		
	}
	$smcFunc['db_free_result']($results);
	
	return $options;
}

function initCookies(){
    global $cookiename;
	
    if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1)
	{
		list ($member_id, $password) = @unserialize($_COOKIE[$cookiename]);
		$member_id = !empty($member_id) && strlen($password) > 0 ? (int) $member_id : 0;
		
		return array($member_id, $password);
	}
	elseif (isset($_COOKIE[$cookiename]))
	{
		list ($member_id, $password) = @unserialize(stripslashes($_COOKIE[$cookiename]));
		$member_id = !empty($member_id) && strlen($password) > 0 ? (int) $member_id : 0;
		
		return array($member_id, $password);
	}
}

function initTheme(){
    global $boardurl, $boarddir;
	
    if (isset($_REQUEST['theme']) && !strstr('..', $_REQUEST['theme']) && is_file('./themes/'.$_REQUEST['theme'].'/template.php') && is_file('./themes/'.$_REQUEST['theme'].'/style.css')) {
		$themeurl = $boardurl.'/sachat/themes/'.$_REQUEST['theme'];
		$themedir = $boarddir.'/sachat/themes/'.$_REQUEST['theme'];
		$thjs = 'theme='.$_REQUEST['theme'].'&';
	} 
	else{
	    $themeurl = $boardurl.'/sachat/themes/default';
		$themedir = $boarddir.'/sachat/themes/default';
		$thjs = '';
	}
	
	return array($themeurl, $themedir, $thjs);
}

function initLang($lang){
    global $boarddir, $themedir;
    
	if (isset($lang) && is_file($themedir.'/languages/'.$lang.'.php')) {
		$langfile = $themedir.'/languages/'.$lang.'.php';
	} 
	elseif (is_file($themedir.'/languages/english.php')){
		$langfile = $themedir.'/languages/english.php';
	} 
	else {
		$langfile = $boarddir.'/sachat/themes/default/languages/english.php';
	}
	
	return $langfile;
}
	
function initJs($jsType){
    global $themedir;
    
	if(file_exists ($themedir.'/js/'.$jsType.'.js.php')){
	    require_once($themedir.'/js/'.$jsType.'.js.php');
	}
	else{
	    require_once('js/'.$jsType.'.js.php');
    }
}

function initLink(){

	global $smcFunc, $context, $member_id;

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat_barlinks
		ORDER BY ord',
		array()
	);

	if ($results){
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			if ($row['vis'] != 0 ) {
				if ($row['vis'] == 1 && $member_id || $row['vis'] == 2 && !$member_id || $row['vis'] == 3) {
					$context['gadgetslink'][] = $row;
				}
			}
		}
		$smcFunc['db_free_result']($results);
	}
}
function initGadgets(){

	global $smcFunc, $context, $member_id;

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat_gadgets
		ORDER BY ord',
		array()
	);

	if ($results){
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			if ($row['vis'] != 0 ) {
				if ($row['vis'] == 1 && $member_id || $row['vis'] == 2 && !$member_id || $row['vis'] == 3) {
					$context['gadgets'][] = $row;
				}
			}
		}
		$smcFunc['db_free_result']($results);
	}
}

function gadget(){

	global $smcFunc, $sourcedir, $modSettings, $boarddir, $context;
	
	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat_gadgets
		WHERE {db_prefix}2sichat_gadgets.id = {int:gid}
		LIMIT 1',
		array(
			'gid' => $_REQUEST['gid'],
		)
	);

	$context['gadget'] = $smcFunc['db_fetch_assoc']($results);
     $smcFunc['db_free_result']($results);
	 
	//type = php
	if($context['gadget']['type'] == 0){
	    $context['gadget']['url'] = trim($context['gadget']['url']);
		$context['gadget']['url'] = trim($context['gadget']['url'], '<?php');
		$context['gadget']['url'] = trim($context['gadget']['url'], '?>');
        ob_start();
	    $context['gadget']['url'] = eval($context['gadget']['url']);
		$context['gadget']['url'] = ob_get_contents();
        ob_end_clean();
	}
	//type = html
	if($context['gadget']['type'] == 1){
	    $context['gadget']['url'] = $context['gadget']['url'];
	}
	
    if (isset($_REQUEST['src']) && $_REQUEST['src'] == 'true') {
		$context['HTML'] = gadgetObject_template();
	} else {
		$context['JSON']['DATA'] = gadget_template();
		$context['JSON']['GID'] = $context['gadget']['id'];
	}

}

function initChatSess(){
	
	global $smcFunc, $member_id, $buddy_id, $context;

	// Now on to the messages
	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat
		WHERE ({db_prefix}2sichat.to = {int:buddy_id} AND {db_prefix}2sichat.from = {int:member_id}) OR ({db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id})
		ORDER BY id DESC',
		array(
			'member_id' => $member_id,
			'buddy_id' => $buddy_id,
		)
	);

	$lastID = 0;

	if ($results){
		mread(); // Mark messages read since we are displaying them.
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			$row['msg'] = phaseMSG($row['msg']);
          	$context['msgs'][] = $row;
          	$lastID = $row['id'];
		}
		$smcFunc['db_free_result']($results);
	}
	$context['JSON']['DATA'] = chat_window_template();
	$context['JSON']['BID'] = $buddy_id;	
	$context['JSON']['ID'] = $lastID;
}

function retmsgs(){

	global $smcFunc, $member_id, $buddy_id, $context, $modSettings;

	$reqTime = $_REQUEST['_'] - $modSettings['2sichat_cw_heart'];

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat
		WHERE ({db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id} AND {db_prefix}2sichat.rd = 0) OR ({db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id} AND {db_prefix}2sichat.rd > {float:reqTime})
		ORDER BY id DESC',
		array(
			'member_id' => $member_id,
			'buddy_id' => $buddy_id,
			'reqTime' => $reqTime,
		)
	);

	$lastID = 0;
	
	if ($results){
		mread(); // Mark messages read since we are displaying them.
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			$row['msg'] = phaseMSG($row['msg']);
         		$context['msgs'][] = $row;
         		$lastID = $row['id'];
		}
		$smcFunc['db_free_result']($results);
		$context['JSON']['DATA'] = chat_retmsg_template();
		// Muahhahaha, now finally get rid of that stupid session junk. We got JSON.
		$context['JSON']['ID'] = $lastID;
	}
}

function savemsg(){

	global $smcFunc, $member_id, $user_settings, $context, $buddy_id, $buddy_settings, $modSettings;

	// SMF ignore list, excluding group 1 & 2, which is the admin and global mod, they get to talk to who ever, ignore or not :P
	if (!in_array(1, $user_settings['groups']) && !in_array(2, $user_settings['groups'])) {
		if (strpos($buddy_settings['pm_ignore_list'], ',') && in_array($member_id, explode(',', $buddy_settings['pm_ignore_list'])) || !strpos($buddy_settings['pm_ignore_list'], ',') && $member_id == $buddy_settings['pm_ignore_list']) {
			$context['JSON']['STATUS'] = 'IGNORE';
			doOutput();
		}
	}

	// See if they have permission, maybe one day will have a message sent back.
	if (!empty($modSettings['2sichat_dis_chat'])) {
		$context['JSON']['STATUS'] = 'NO CHAT ACCESS';
		doOutput();
	}
	
     if (str_replace(' ', '', $_REQUEST['msg']) != '') {
		$smcFunc['db_insert']('',
			'{db_prefix}2sichat',
			array('to' => 'int', 'from' => 'int', 'msg' => 'string', 'sent' => 'string'),
			array($buddy_id, $member_id, htmlspecialchars(stripslashes($_REQUEST['msg']), ENT_QUOTES), date("YmdHis")),
			array()
		);

		$context['msgs'] = phaseMSG(htmlspecialchars(stripslashes($_REQUEST['msg']), ENT_QUOTES));

          if (defined('loadOpt')){
			doOptDBexp();
		}
		$context['JSON']['DATA'] = chat_savemsg_template();
	}
}

function mread(){

	global $smcFunc, $member_id, $buddy_id;

	if (isset($_REQUEST['_'])) {
		$read = $_REQUEST['_'];
	}
	if (!isset($read)) {
		$read = 1;
	}

	// Mark messages read.
	$smcFunc['db_query']('', '
		UPDATE {db_prefix}2sichat
		SET {db_prefix}2sichat.rd = {float:read}
		WHERE {db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id} AND {db_prefix}2sichat.rd = 0',
		array (
			'member_id' => $member_id,
			'buddy_id' => $buddy_id,
			'read' => $read,
		)
	);
	if (defined('loadOpt')){
		doOptDBrec();
	}
}

function initCleanup(){

	global $smcFunc, $modSettings;

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}2sichat
		WHERE {db_prefix}2sichat.rd != 0 AND {db_prefix}2sichat.sent < {int:purge}',
		array(
			'purge' => date("Ymd", strtotime('-'.$modSettings['2sichat_purge'].' days', strtotime(date("Ymd")))),
		)
	);
}

function doheart() {

    global $smcFunc, $member_id, $context;

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat
		WHERE {db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.rd = 0',
		array(
			'member_id' => $member_id,
		)
	);

	if ($results && $smcFunc['db_num_rows']($results) != 0){
		$context['JSON']['ids'] = array();
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			if (!in_array($row['from'], $context['JSON']['ids'])) {
				$context['JSON']['ids'][] = $row['from'];
			}
		}
		$smcFunc['db_free_result']($results);
	} else {
		if (defined('loadOpt')){
			doOptDBrec();
		}
		$context['JSON']['STATUS'] = 'NO RESULTS';
	}
}

function load_smiles(){

    global $smcFunc, $modSettings;

	$smiles = array();
	$results = $smcFunc['db_query']('', '
		SELECT code, filename
		FROM {db_prefix}smileys',
		array()
	);

	while ($row = $smcFunc['db_fetch_assoc']($results)){
		$smiles['code'][] = htmlspecialchars($row['code'], ENT_QUOTES);
		$smiles['file'][] = '<img src="'.$modSettings['smileys_url'].'/'.$modSettings['smiley_sets_default'].'/'.$row['filename'].'">';
	}
	$smcFunc['db_free_result']($results);

	return $smiles;
}

function censorMSG($data){
	
	$replace = '';
	$rop = '*';
    
	for ($i=1;$i<strlen($data);$i++){ 
        $replace .= $rop; 
    } 
	
    $data = substr_replace($data,  $replace,  1); 
    return $data; 
}

function phaseMSG($data){
    global $modSettings;
	
	if (!empty($modSettings['2sichat_simple_bbc'])) {
		$data = phaseBBC($data);
		$data = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$3</a>$4'", $data);
	} else {
		$data = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$3</a>$4'", $data);
	}

	// Load up the smileys
	$smiles = load_smiles();
	$data = str_replace($smiles['code'], $smiles['file'], $data);
    
	if(!empty($modSettings['2sichat_censor_words']) && !empty($modSettings['2sichat_censor'])){
	    $badwords = explode('|', $modSettings['2sichat_censor_words']);
	
	    for ($i=0; $i<count($badwords); $i++) { 
            $data = str_replace($badwords[$i],  censorMSG($badwords[$i]),  $data); 
        } 
	}
	
	return $data;
}
function phaseBBC($data){

	// If no BBC just return the data, don't do anything extra
	if ((strpos($data, "[") === false || strpos($data, "]") === false)) {
		return $data;
	}

	$codes = array (
		'/(\[[b]\])(.+)(\[\/[b]\])/',				// Bold
		'/(\[[u]\])(.+)(\[\/[u]\])/',				// Image
		'/(\[[i]\])(.+)(\[\/[i]\])/',				// Italic
		'/(\[color=)(.+)(\])(.+)(\[\/color\])/',	// Color
		'/(\[url\]http)(.+)(\[\/url\])/',			// Url no description, http
		'/(\[url\])(.+)(\[\/url\])/',				// Url no description, no http
		'/(\[url=http)(.+)(\])(.+)(\[\/url\])/',	// Url description, http
		'/(\[url=)(.+)(\])(.+)(\[\/url\])/',		// Url description, no http
//		'/(\[img\]http)(.+)(\[\/img\])/',			// Image, http
//		'/(\[img\])(.+)(\[\/img\])/'				// Image, no http
	);
	$html = array (
		'<b>\\2</b>',
		'<u>\\2</u>',
		'<i>\\2</i>',
		'<span style="color:\\2">\\4</span>',
		'<a href="\\2">\\2</a>',
		'<a href="http://\\2">\\2</a>',
		'<a href="\\2">\\4</a>',
		'<a href="http://\\2">\\4</a>',
//		'<img src="\\2" />',
//		'<img src="http://\\2" />'
	);
	$data = preg_replace($codes, $html, $data);
	return $data;
}

function loadUserSettings($id) {

	global $smcFunc, $modSettings, $themeurl, $boardurl;

	// Load $user_settings
	$results = $smcFunc['db_query']('', '
		SELECT m.*, o.session, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
		FROM {db_prefix}members AS m
		LEFT JOIN {db_prefix}log_online AS o ON o.id_member = m.id_member
		LEFT JOIN {db_prefix}attachments AS a ON a.id_member = {int:member_id}
		WHERE m.id_member = {int:member_id}
		LIMIT 1',
		array(
			'member_id' => $id,
		)
	);
	$temp = $smcFunc['db_fetch_assoc']($results);
	$smcFunc['db_free_result']($results);

	//Lets do some fusion, Fuussiioooon Ahhhhh!!!!!
	if ($temp['additional_groups']) {
		$temp['groups'] = array_merge(array($temp['id_group'], $temp['id_post_group']),explode(',', $temp['additional_groups']));
	} else {
		$temp['groups'] = array($temp['id_group'], $temp['id_post_group']);
	}

	// Fix avatar
	if (!$temp['avatar'] && $temp['id_attach']) {
		if ($temp['attachment_type'] == 0) {
			$temp['avatar'] = $boardurl.'/index.php?action=dlattach;attach='.$temp['id_attach'].';type=avatar';
		}
		if ($temp['attachment_type'] == 1) {
			$temp['avatar'] = (isset($modSettings['custom_avatar_enabled'])?$modSettings['custom_avatar_url']:$modSettings['avatar_url']).'/'.$temp['filename'];
		}
	} else if (!$temp['avatar']) {
		$temp['avatar'] = $themeurl.'/images/blankuser.png';
	}

	if (substr($temp['avatar'], 0, 4) != 'http') {
		$temp['avatar'] = $modSettings['avatar_url'].'/'.$temp['avatar'];
	} // Allot of junk to fix one avatar, SMF needs to get this right.
	return $temp;
}

function loadPermissions($data) {
	
	global $smcFunc, $context;
	
	$temp = array();
	if (is_array($data)) {
		if (in_array(1, $data)) {
			$temp['is_admin'] = 1;
		} else if (in_array(2, $data)) {
			$temp['is_mod'] = 1;
		}
		$data = implode(',',$data);
	} else {
		if ($data == 1) {
          	$temp['is_admin'] = 1;
		} else if ($data == 2) {
			$temp['is_mod'] = 1;
		}
	}

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}permissions
		WHERE FIND_IN_SET(id_group, {string:groups})',
		array(
			'groups' => $data,
		)
	);

	while ($row = $smcFunc['db_fetch_row']($results)) {
		$temp[$row[1]] = $row[2];
	}
	$smcFunc['db_free_result']($results);
	return $temp;
}

function liveOnline() {
	
	global $modSettings, $options, $context;

	if (empty($modSettings['2sichat_dis_list']))
		$context['JSON']['ONLINE'] = genMemList();
}

function genMemList() {

	global $options, $smcFunc, $user_settings, $member_id, $context;

	$results = $smcFunc['db_query']('', '
		SELECT m.buddy_list, m.id_member, m.member_name, m.real_name, t1.value AS show_cbar, t2.value AS show_cbar_buddys, o.session
		FROM {db_prefix}members AS m
		LEFT JOIN {db_prefix}log_online AS o ON o.id_member = m.id_member
		LEFT JOIN {db_prefix}themes AS t1 ON (t1.variable = {string:name1} AND t1.id_member = m.id_member)
		LEFT JOIN {db_prefix}themes AS t2 ON (t2.variable = {string:name2} AND t2.id_member = m.id_member)
		'.(!empty($options['show_cbar_buddys']) && $options['show_cbar_buddys'] == 1 ? 'WHERE FIND_IN_SET({int:member_id}, m.buddy_list) AND t2.value = 1' : 'WHERE NOT FIND_IN_SET({int:member_id}, m.pm_ignore_list) AND t2.value != 1 AND m.show_online = 1 OR FIND_IN_SET({int:member_id}, m.buddy_list) AND m.show_online = 0').'
		ORDER BY m.real_name DESC',
		array(
			'member_id' => $member_id,
			'name1' => 'show_cbar',
			'name2' => 'show_cbar_buddys',
		)
	);
    
	$buddies = explode(',', $user_settings['buddy_list']);
	$ignore = explode(',', $user_settings['pm_ignore_list']);
	
	if ($results){
	
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			
			if (in_array($row['id_member'], $buddies) || $row['show_cbar_buddys'] == 1) {
				
				if ($row['show_cbar'] == 1)
				    continue;
					
			    $context['friends'][] = $row;
			}
		    elseif (isset($row['session']) && $row['id_member'] != $member_id){
				    
				if ($row['show_cbar'] == 1)
				    continue;
	          	    
				$context['friends'][] = $row;
			}
		}
		$smcFunc['db_free_result']($results);
	}
	$data = buddy_list_template();
	return $data;
}

function genMemcount() {

	global $smcFunc, $member_id, $options, $user_settings, $context;
	
   $request = $smcFunc['db_query']('', '
		SELECT COUNT(*)
	    FROM {db_prefix}log_online AS o
		LEFT JOIN {db_prefix}members AS m ON m.id_member = o.id_member<commit_msg>dont show all users online lag!<commit_after><?php
function doCharset($db_character_set){
    global $smcFunc;
	
    if (!empty($db_character_set)) {
	    $smcFunc['db_query']('set_character_set', 
	        'SET NAMES ' . $db_character_set,
		    array()
	    );
	}	
}	
function initModSettings(){
    global $smcFunc, $modSettings;
	
    $results = $smcFunc['db_query']('', '
		SELECT variable, value
		FROM {db_prefix}settings',
		array()
	);
	$modSettings = array();
	while ($row = $smcFunc['db_fetch_row']($results)) {
		$modSettings[$row[0]] = $row[1];
	}
	$smcFunc['db_free_result']($results);
    
	return $modSettings;
}
	
function initOptions($member_id){
    global $smcFunc, $options;
	
    $results = $smcFunc['db_query']('', '
		SELECT variable, value
		FROM {db_prefix}themes
		WHERE id_member = {string:mem}',
		array(
		        'mem' => $member_id,
		)
	);
	$options = array();
	while ($row = $smcFunc['db_fetch_row']($results)) {
		
		$options[$row[0]] = $row[1];
		
	}
	$smcFunc['db_free_result']($results);
	
	return $options;
}

function initCookies(){
    global $cookiename;
	
    if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1)
	{
		list ($member_id, $password) = @unserialize($_COOKIE[$cookiename]);
		$member_id = !empty($member_id) && strlen($password) > 0 ? (int) $member_id : 0;
		
		return array($member_id, $password);
	}
	elseif (isset($_COOKIE[$cookiename]))
	{
		list ($member_id, $password) = @unserialize(stripslashes($_COOKIE[$cookiename]));
		$member_id = !empty($member_id) && strlen($password) > 0 ? (int) $member_id : 0;
		
		return array($member_id, $password);
	}
}

function initTheme(){
    global $boardurl, $boarddir;
	
    if (isset($_REQUEST['theme']) && !strstr('..', $_REQUEST['theme']) && is_file('./themes/'.$_REQUEST['theme'].'/template.php') && is_file('./themes/'.$_REQUEST['theme'].'/style.css')) {
		$themeurl = $boardurl.'/sachat/themes/'.$_REQUEST['theme'];
		$themedir = $boarddir.'/sachat/themes/'.$_REQUEST['theme'];
		$thjs = 'theme='.$_REQUEST['theme'].'&';
	} 
	else{
	    $themeurl = $boardurl.'/sachat/themes/default';
		$themedir = $boarddir.'/sachat/themes/default';
		$thjs = '';
	}
	
	return array($themeurl, $themedir, $thjs);
}

function initLang($lang){
    global $boarddir, $themedir;
    
	if (isset($lang) && is_file($themedir.'/languages/'.$lang.'.php')) {
		$langfile = $themedir.'/languages/'.$lang.'.php';
	} 
	elseif (is_file($themedir.'/languages/english.php')){
		$langfile = $themedir.'/languages/english.php';
	} 
	else {
		$langfile = $boarddir.'/sachat/themes/default/languages/english.php';
	}
	
	return $langfile;
}
	
function initJs($jsType){
    global $themedir;
    
	if(file_exists ($themedir.'/js/'.$jsType.'.js.php')){
	    require_once($themedir.'/js/'.$jsType.'.js.php');
	}
	else{
	    require_once('js/'.$jsType.'.js.php');
    }
}

function initLink(){

	global $smcFunc, $context, $member_id;

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat_barlinks
		ORDER BY ord',
		array()
	);

	if ($results){
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			if ($row['vis'] != 0 ) {
				if ($row['vis'] == 1 && $member_id || $row['vis'] == 2 && !$member_id || $row['vis'] == 3) {
					$context['gadgetslink'][] = $row;
				}
			}
		}
		$smcFunc['db_free_result']($results);
	}
}
function initGadgets(){

	global $smcFunc, $context, $member_id;

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat_gadgets
		ORDER BY ord',
		array()
	);

	if ($results){
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			if ($row['vis'] != 0 ) {
				if ($row['vis'] == 1 && $member_id || $row['vis'] == 2 && !$member_id || $row['vis'] == 3) {
					$context['gadgets'][] = $row;
				}
			}
		}
		$smcFunc['db_free_result']($results);
	}
}

function gadget(){

	global $smcFunc, $sourcedir, $modSettings, $boarddir, $context;
	
	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat_gadgets
		WHERE {db_prefix}2sichat_gadgets.id = {int:gid}
		LIMIT 1',
		array(
			'gid' => $_REQUEST['gid'],
		)
	);

	$context['gadget'] = $smcFunc['db_fetch_assoc']($results);
     $smcFunc['db_free_result']($results);
	 
	//type = php
	if($context['gadget']['type'] == 0){
	    $context['gadget']['url'] = trim($context['gadget']['url']);
		$context['gadget']['url'] = trim($context['gadget']['url'], '<?php');
		$context['gadget']['url'] = trim($context['gadget']['url'], '?>');
        ob_start();
	    $context['gadget']['url'] = eval($context['gadget']['url']);
		$context['gadget']['url'] = ob_get_contents();
        ob_end_clean();
	}
	//type = html
	if($context['gadget']['type'] == 1){
	    $context['gadget']['url'] = $context['gadget']['url'];
	}
	
    if (isset($_REQUEST['src']) && $_REQUEST['src'] == 'true') {
		$context['HTML'] = gadgetObject_template();
	} else {
		$context['JSON']['DATA'] = gadget_template();
		$context['JSON']['GID'] = $context['gadget']['id'];
	}

}

function initChatSess(){
	
	global $smcFunc, $member_id, $buddy_id, $context;

	// Now on to the messages
	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat
		WHERE ({db_prefix}2sichat.to = {int:buddy_id} AND {db_prefix}2sichat.from = {int:member_id}) OR ({db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id})
		ORDER BY id DESC',
		array(
			'member_id' => $member_id,
			'buddy_id' => $buddy_id,
		)
	);

	$lastID = 0;

	if ($results){
		mread(); // Mark messages read since we are displaying them.
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			$row['msg'] = phaseMSG($row['msg']);
          	$context['msgs'][] = $row;
          	$lastID = $row['id'];
		}
		$smcFunc['db_free_result']($results);
	}
	$context['JSON']['DATA'] = chat_window_template();
	$context['JSON']['BID'] = $buddy_id;	
	$context['JSON']['ID'] = $lastID;
}

function retmsgs(){

	global $smcFunc, $member_id, $buddy_id, $context, $modSettings;

	$reqTime = $_REQUEST['_'] - $modSettings['2sichat_cw_heart'];

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat
		WHERE ({db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id} AND {db_prefix}2sichat.rd = 0) OR ({db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id} AND {db_prefix}2sichat.rd > {float:reqTime})
		ORDER BY id DESC',
		array(
			'member_id' => $member_id,
			'buddy_id' => $buddy_id,
			'reqTime' => $reqTime,
		)
	);

	$lastID = 0;
	
	if ($results){
		mread(); // Mark messages read since we are displaying them.
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			$row['msg'] = phaseMSG($row['msg']);
         		$context['msgs'][] = $row;
         		$lastID = $row['id'];
		}
		$smcFunc['db_free_result']($results);
		$context['JSON']['DATA'] = chat_retmsg_template();
		// Muahhahaha, now finally get rid of that stupid session junk. We got JSON.
		$context['JSON']['ID'] = $lastID;
	}
}

function savemsg(){

	global $smcFunc, $member_id, $user_settings, $context, $buddy_id, $buddy_settings, $modSettings;

	// SMF ignore list, excluding group 1 & 2, which is the admin and global mod, they get to talk to who ever, ignore or not :P
	if (!in_array(1, $user_settings['groups']) && !in_array(2, $user_settings['groups'])) {
		if (strpos($buddy_settings['pm_ignore_list'], ',') && in_array($member_id, explode(',', $buddy_settings['pm_ignore_list'])) || !strpos($buddy_settings['pm_ignore_list'], ',') && $member_id == $buddy_settings['pm_ignore_list']) {
			$context['JSON']['STATUS'] = 'IGNORE';
			doOutput();
		}
	}

	// See if they have permission, maybe one day will have a message sent back.
	if (!empty($modSettings['2sichat_dis_chat'])) {
		$context['JSON']['STATUS'] = 'NO CHAT ACCESS';
		doOutput();
	}
	
     if (str_replace(' ', '', $_REQUEST['msg']) != '') {
		$smcFunc['db_insert']('',
			'{db_prefix}2sichat',
			array('to' => 'int', 'from' => 'int', 'msg' => 'string', 'sent' => 'string'),
			array($buddy_id, $member_id, htmlspecialchars(stripslashes($_REQUEST['msg']), ENT_QUOTES), date("YmdHis")),
			array()
		);

		$context['msgs'] = phaseMSG(htmlspecialchars(stripslashes($_REQUEST['msg']), ENT_QUOTES));

          if (defined('loadOpt')){
			doOptDBexp();
		}
		$context['JSON']['DATA'] = chat_savemsg_template();
	}
}

function mread(){

	global $smcFunc, $member_id, $buddy_id;

	if (isset($_REQUEST['_'])) {
		$read = $_REQUEST['_'];
	}
	if (!isset($read)) {
		$read = 1;
	}

	// Mark messages read.
	$smcFunc['db_query']('', '
		UPDATE {db_prefix}2sichat
		SET {db_prefix}2sichat.rd = {float:read}
		WHERE {db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.from = {int:buddy_id} AND {db_prefix}2sichat.rd = 0',
		array (
			'member_id' => $member_id,
			'buddy_id' => $buddy_id,
			'read' => $read,
		)
	);
	if (defined('loadOpt')){
		doOptDBrec();
	}
}

function initCleanup(){

	global $smcFunc, $modSettings;

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}2sichat
		WHERE {db_prefix}2sichat.rd != 0 AND {db_prefix}2sichat.sent < {int:purge}',
		array(
			'purge' => date("Ymd", strtotime('-'.$modSettings['2sichat_purge'].' days', strtotime(date("Ymd")))),
		)
	);
}

function doheart() {

    global $smcFunc, $member_id, $context;

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}2sichat
		WHERE {db_prefix}2sichat.to = {int:member_id} AND {db_prefix}2sichat.rd = 0',
		array(
			'member_id' => $member_id,
		)
	);

	if ($results && $smcFunc['db_num_rows']($results) != 0){
		$context['JSON']['ids'] = array();
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			if (!in_array($row['from'], $context['JSON']['ids'])) {
				$context['JSON']['ids'][] = $row['from'];
			}
		}
		$smcFunc['db_free_result']($results);
	} else {
		if (defined('loadOpt')){
			doOptDBrec();
		}
		$context['JSON']['STATUS'] = 'NO RESULTS';
	}
}

function load_smiles(){

    global $smcFunc, $modSettings;

	$smiles = array();
	$results = $smcFunc['db_query']('', '
		SELECT code, filename
		FROM {db_prefix}smileys',
		array()
	);

	while ($row = $smcFunc['db_fetch_assoc']($results)){
		$smiles['code'][] = htmlspecialchars($row['code'], ENT_QUOTES);
		$smiles['file'][] = '<img src="'.$modSettings['smileys_url'].'/'.$modSettings['smiley_sets_default'].'/'.$row['filename'].'">';
	}
	$smcFunc['db_free_result']($results);

	return $smiles;
}

function censorMSG($data){
	
	$replace = '';
	$rop = '*';
    
	for ($i=1;$i<strlen($data);$i++){ 
        $replace .= $rop; 
    } 
	
    $data = substr_replace($data,  $replace,  1); 
    return $data; 
}

function phaseMSG($data){
    global $modSettings;
	
	if (!empty($modSettings['2sichat_simple_bbc'])) {
		$data = phaseBBC($data);
		$data = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$3</a>$4'", $data);
	} else {
		$data = preg_replace("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", "'<a href=\"$1\" target=\"_blank\">$3</a>$4'", $data);
	}

	// Load up the smileys
	$smiles = load_smiles();
	$data = str_replace($smiles['code'], $smiles['file'], $data);
    
	if(!empty($modSettings['2sichat_censor_words']) && !empty($modSettings['2sichat_censor'])){
	    $badwords = explode('|', $modSettings['2sichat_censor_words']);
	
	    for ($i=0; $i<count($badwords); $i++) { 
            $data = str_replace($badwords[$i],  censorMSG($badwords[$i]),  $data); 
        } 
	}
	
	return $data;
}
function phaseBBC($data){

	// If no BBC just return the data, don't do anything extra
	if ((strpos($data, "[") === false || strpos($data, "]") === false)) {
		return $data;
	}

	$codes = array (
		'/(\[[b]\])(.+)(\[\/[b]\])/',				// Bold
		'/(\[[u]\])(.+)(\[\/[u]\])/',				// Image
		'/(\[[i]\])(.+)(\[\/[i]\])/',				// Italic
		'/(\[color=)(.+)(\])(.+)(\[\/color\])/',	// Color
		'/(\[url\]http)(.+)(\[\/url\])/',			// Url no description, http
		'/(\[url\])(.+)(\[\/url\])/',				// Url no description, no http
		'/(\[url=http)(.+)(\])(.+)(\[\/url\])/',	// Url description, http
		'/(\[url=)(.+)(\])(.+)(\[\/url\])/',		// Url description, no http
//		'/(\[img\]http)(.+)(\[\/img\])/',			// Image, http
//		'/(\[img\])(.+)(\[\/img\])/'				// Image, no http
	);
	$html = array (
		'<b>\\2</b>',
		'<u>\\2</u>',
		'<i>\\2</i>',
		'<span style="color:\\2">\\4</span>',
		'<a href="\\2">\\2</a>',
		'<a href="http://\\2">\\2</a>',
		'<a href="\\2">\\4</a>',
		'<a href="http://\\2">\\4</a>',
//		'<img src="\\2" />',
//		'<img src="http://\\2" />'
	);
	$data = preg_replace($codes, $html, $data);
	return $data;
}

function loadUserSettings($id) {

	global $smcFunc, $modSettings, $themeurl, $boardurl;

	// Load $user_settings
	$results = $smcFunc['db_query']('', '
		SELECT m.*, o.session, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
		FROM {db_prefix}members AS m
		LEFT JOIN {db_prefix}log_online AS o ON o.id_member = m.id_member
		LEFT JOIN {db_prefix}attachments AS a ON a.id_member = {int:member_id}
		WHERE m.id_member = {int:member_id}
		LIMIT 1',
		array(
			'member_id' => $id,
		)
	);
	$temp = $smcFunc['db_fetch_assoc']($results);
	$smcFunc['db_free_result']($results);

	//Lets do some fusion, Fuussiioooon Ahhhhh!!!!!
	if ($temp['additional_groups']) {
		$temp['groups'] = array_merge(array($temp['id_group'], $temp['id_post_group']),explode(',', $temp['additional_groups']));
	} else {
		$temp['groups'] = array($temp['id_group'], $temp['id_post_group']);
	}

	// Fix avatar
	if (!$temp['avatar'] && $temp['id_attach']) {
		if ($temp['attachment_type'] == 0) {
			$temp['avatar'] = $boardurl.'/index.php?action=dlattach;attach='.$temp['id_attach'].';type=avatar';
		}
		if ($temp['attachment_type'] == 1) {
			$temp['avatar'] = (isset($modSettings['custom_avatar_enabled'])?$modSettings['custom_avatar_url']:$modSettings['avatar_url']).'/'.$temp['filename'];
		}
	} else if (!$temp['avatar']) {
		$temp['avatar'] = $themeurl.'/images/blankuser.png';
	}

	if (substr($temp['avatar'], 0, 4) != 'http') {
		$temp['avatar'] = $modSettings['avatar_url'].'/'.$temp['avatar'];
	} // Allot of junk to fix one avatar, SMF needs to get this right.
	return $temp;
}

function loadPermissions($data) {
	
	global $smcFunc, $context;
	
	$temp = array();
	if (is_array($data)) {
		if (in_array(1, $data)) {
			$temp['is_admin'] = 1;
		} else if (in_array(2, $data)) {
			$temp['is_mod'] = 1;
		}
		$data = implode(',',$data);
	} else {
		if ($data == 1) {
          	$temp['is_admin'] = 1;
		} else if ($data == 2) {
			$temp['is_mod'] = 1;
		}
	}

	$results = $smcFunc['db_query']('', '
		SELECT *
		FROM {db_prefix}permissions
		WHERE FIND_IN_SET(id_group, {string:groups})',
		array(
			'groups' => $data,
		)
	);

	while ($row = $smcFunc['db_fetch_row']($results)) {
		$temp[$row[1]] = $row[2];
	}
	$smcFunc['db_free_result']($results);
	return $temp;
}

function liveOnline() {
	
	global $modSettings, $options, $context;

	if (empty($modSettings['2sichat_dis_list']))
		$context['JSON']['ONLINE'] = genMemList();
}

function genMemList() {

	global $options, $smcFunc, $user_settings, $member_id, $context;

	$results = $smcFunc['db_query']('', '
		SELECT m.buddy_list, m.id_member, m.member_name, m.real_name, t1.value AS show_cbar, t2.value AS show_cbar_buddys, o.session
		FROM {db_prefix}members AS m
		LEFT JOIN {db_prefix}log_online AS o ON o.id_member = m.id_member
		LEFT JOIN {db_prefix}themes AS t1 ON (t1.variable = {string:name1} AND t1.id_member = m.id_member)
		LEFT JOIN {db_prefix}themes AS t2 ON (t2.variable = {string:name2} AND t2.id_member = m.id_member)
		'.(!empty($options['show_cbar_buddys']) && $options['show_cbar_buddys'] == 1 ? 'WHERE FIND_IN_SET({int:member_id}, m.buddy_list) AND t2.value = 1' : 'WHERE NOT FIND_IN_SET({int:member_id}, m.pm_ignore_list) AND t2.value != 1 AND m.show_online = 1 OR FIND_IN_SET({int:member_id}, m.buddy_list) AND m.show_online = 0').'
		ORDER BY m.real_name DESC',
		array(
			'member_id' => $member_id,
			'name1' => 'show_cbar',
			'name2' => 'show_cbar_buddys',
		)
	);
    
	$buddies = explode(',', $user_settings['buddy_list']);
	$ignore = explode(',', $user_settings['pm_ignore_list']);
	
	if ($results){
	
		while ($row = $smcFunc['db_fetch_assoc']($results)) {
			
			if (in_array($row['id_member'], $buddies) || $row['show_cbar_buddys'] == 1) {
				
				if ($row['show_cbar'] == 1)
				    continue;
					
					if (isset($row['session']) && $row['id_member'] != $member_id)
			            $context['friends'][] = $row;
			}
		    elseif (isset($row['session']) && $row['id_member'] != $member_id){
				    
				if ($row['show_cbar'] == 1)
				    continue;
	          	    
				$context['friends'][] = $row;
			}
		}
		$smcFunc['db_free_result']($results);
	}
	$data = buddy_list_template();
	return $data;
}

function genMemcount() {

	global $smcFunc, $member_id, $options, $user_settings, $context;
	
   $request = $smcFunc['db_query']('', '
		SELECT COUNT(*)
	    FROM {db_prefix}log_online AS o
		LEFT JOIN {db_prefix}members AS m ON m.id_member = o.id_member
{'fraction_non_alphanumeric': 0.23996963148980902, 'fraction_numerical': 0.00887694913274543, 'mean_word_length': 4.2229678206496875, 'pattern_counts': {'":': 0, '<': 63, '<?xml version=': 0, '>': 99, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3996936', 'n_tokens_mistral': 14818, 'n_tokens_neox': 13721, 'n_words': 2278}