<?php

$db = mysql_connect($config["dbhost"], $config["dbuname"], $config["dbpass"]);
mysql_select_db($config["dbname"],$db);

function getTopcmmConfig()
{
	global $db,$topcmm_config;
	$sql = "select * from ".$topcmm_config['chat_table'];

	$rs = mysql_query($sql,$db);
	return mysql_fetch_array($rs);
}

function updateTopcmmConfig($post)
{
	global $db,$topcmm_config;

	foreach($post as $key => $value)
	{
		$value = trim($value);
		$post[$key] = mysql_escape_string($value);
	}
	if($post['hmode'] == 3)
	{
		$sql = "update ".$topcmm_config['chat_table']." set extendserver = '".$post['hmode']."',chatroomname = '".$post['chat_room_name']."'";
	}
	else if($post['hmode'] == 2)
	{
		$sql = "update ".$topcmm_config['chat_table']." set extendserver = '".$post['hmode']."',clientlocation = '".$post['client_location']."',clientswfname = '".$post['client_name']."',primaryhost = '".$post['init_host']."',primaryport = '".$post['init_port']."',chatgroup = '".$post['chat_group']."'";
	}
	else
	{
		$sql = "update ".$topcmm_config['chat_table']." set extendserver = '".$post['hmode']."',chatserverpath = '".$post['chat_server_path']."',chatdatapath = '".$post['chat_data_path']."',clientlocation = '".$post['client_location']."',clientswfname = '".$post['client_name']."',primaryhost = '".$post['init_host']."',primaryport = '".$post['init_port']."',chatgroup = '".$post['chat_group']."',apikey = '".$post['apikey']."'";
	}
	return mysql_query($sql,$db);
}

function getHostParameters($client_location)
{
	$content = @file_get_contents($client_location);
	if(!empty($content))
	{
		$pattern = '|var urlValue="(.*)"|U';
		preg_match($pattern, $content, $matches);
		if(!empty($matches[1]))
		{
			$url = $matches[1];
			$urlinfo = parse_url($url);
			return $urlinfo;
		}
		else
		{
			$pattern = '|PARAM NAME=movie VALUE="(.*)"|U';
			preg_match($pattern, $content, $matches);
			if(!empty($matches[1]))
			{
				$url = $matches[1];
				$urlinfo = parse_url($url);
				return $urlinfo;
			}
		}
		return false;
	}
}

function TopcmmPermissionError()
{
	global $smarty, $dbconn, $config, $config_admin, $lang, $auth;
	header("location: ".$config["server"]."/admin/index.php?err=You+do+not+have+admin+permission");
	echo "<script>location.href='".$config["server"]."/admin/index.php?err=You+do+not+have+admin+permission';</script>";
	exit;
}

function TopcmmLoginCheck($file){

        $u = auth_user();

        $mode =TopcmmIsFileAllowed($u[0], TopcmmGetRightModulePath($file), "chats");

	if($mode==0){
            TopcmmPermissionError();
            exit;
        }
            return;
	}


function TopcmmIsFileAllowed($id_user, $file, $lang_type=""){

	global $dbconn, $config;
	$mod_arr = array();
	$mod_arr = TopcmmGetPermissionsUser($id_user);

	$strSQL = "select id_module from ".MODULE_FILE_TABLE." where file='".$file."' ";
        
	$rs = $dbconn->Execute($strSQL);
	$id_module = $rs->fields[0];
	if(is_array($mod_arr["id"]) && in_array($id_module, $mod_arr["id"]) ){
		return "1";
	} else {
		return "0";
	}
}

function TopcmmGetPermissionsUser($id_user){
	global $dbconn;
	$strSQL = "select distinct a.id_module from ".GROUP_MODULE_TABLE." a, ".USER_GROUP_TABLE." b
					where b.id_user='".$id_user."' and b.id_group=a.id_group ";
	$rs = $dbconn->Execute($strSQL);
	$i = 0;
	while(!$rs->EOF){
		$module["id"][$i] = $rs->fields[0];
		$rs->MoveNext();
		$i++;
	}
	return $module;
}

function TopcmmGetRightModulePath($file){
	global $config;
	$file_name = substr($file, strlen($config["site_path"]));
	$file_name = str_replace("\\", "/", $file_name);
	if(substr($file_name, 0, 1) != "/") $file_name = "/".$file_name;
	return $file_name;
}

function checkSlash($path)
{
		if(substr($path,-1,1) != "/" && !empty($path)){
			$path = $path."/";
		}
		return $path;
}

function is_valid_data_path($chat_data_path)
{
			$online_file = $chat_data_path."online.txt";
			if(false === is_readable($online_file)){
				return true;
			}
			return false;
}

function is_valid_chat_server_path($chat_server_path)
{

	if(!is_dir($chat_server_path) || !is_readable($chat_server_path."server/etc/fcserver.xml") || !is_readable($chat_server_path."server/etc/groups/default/server.xml"))
	{

		return true;
	}
	return false;
}

function is_valid_host_path($client_location)
{
	$pattern = "|http://host([0-9]*).123flashchat.com/(.+)/|U";
	if(!preg_match($pattern, $client_location, $matches))
	{
		return true;
	}
	return false;
}

function getChatServerInfo($chat_server_path)
{
	$fcserverxml = $chat_server_path."server/etc/fcserver.xml";
	$doc = new DOMDocument();
	@$doc->load($fcserverxml);
	$primaryserver = @$doc->getElementsByTagName("primary-server");
	$primary = @$primaryserver->item(0);

	$serverinfo['ip'] = @$primary->getAttribute('ip');
	$serverinfo['port'] = @$primary->getAttribute('port');

	if(is_array($serverinfo))
	{
		return $serverinfo;
	}
	else
	{
		return false;
	}
}

function updateServerXml($chat_server_path, $apikey)
{
	$serverxml = $chat_server_path."server/etc/groups/default/server.xml";

	if(is_writeable($serverxml))
	{
		$doc = new DOMDocument();
		@$doc->load($serverxml);


		$doc = replacenode($doc, "integrated-other-database","URL");

		$doc = replacenode($doc, "auth-url","http://".$_SERVER['HTTP_HOST']."/topcmm_123flashchat/login_chat.php?username=%username%&amp;password=%password%","charset","UTF-8");

		$friendattr = array('url','charset','enable');
		$friendattrvalue = array("http://".$_SERVER['HTTP_HOST']."/topcmm_123flashchat/userdata.php?action=%action%&username=%username%&destusername=%destusername%&friendgroup=%friendgroup%&apikey=".$apikey,"UTF-8","On");

		$doc = replacenode($doc, "integrated-user-data", "", $friendattr,$friendattrvalue);

		@$doc->save($serverxml);
		return true;
	}
	else
	{
		return false;
	}
}


function replacenode($doc,$nodename,$nodevalue,$attr="",$attrvalue="")
{
  $parent  =   new DomDocument;
  $parent_node   =   $parent->createElement($nodename,$nodevalue);
  if(!is_array($attr) || !is_array($attrvalue))
  {
  	if(!empty($attr) && !empty($attrvalue))
  	{
  		$parent_node->setAttribute($attr, $attrvalue);
  	}
  }
  else
  {
  	foreach($attr as $key => $value)
  	{
  		$parent_node->setAttribute($value, $attrvalue[$key]);
  	}
  }
  $parent->appendChild($parent_node);

  $nodelist = $doc->getElementsByTagName($nodename);
 	$node = @$nodelist->item(0);

 	$newnode = $doc->importNode($parent->documentElement, true);
	$node->parentNode->replaceChild($newnode,$node);


  return $doc;
}

function restartApi()
{
	$rs = @file_get_contents("http://127.0.0.1:35555/restartgroup.api");
	if($rs === "0")
	{
		return true;
	}
	return false;
}

function authurlErrorMsg()
{
	return "<font color='red'>Error to configure database integration, please do it manually as below:<br>Open: ".$_POST['chat_server_path']."server/etc/groups/default/server.xml<br>Find: &lt;integrated-other-database&gt;<br>Change the value to \"URL\"<br>Find: &lt;auth-url&gt;<br>Change the value to \"http://".$_SERVER['HTTP_HOST']."/topcmm_123flashchat/login_chat.php?username=%username%&amp;amp;password=%password%\"<br>Find: &lt;integrated-friend-list&gt;<br>Change the url value to http://".$_SERVER['HTTP_HOST']."/topcmm_123flashchat/friendlist.php?action=%action%&amp;username=%username%&amp;destusername=%destusername%&amp;amp;friendgroup=%friendgroup%, set enable value to On<br></font>".restartChatServerMsg();
}

function restartErrorMsg()
{
	return "<font color='red'>Failed to restart chat server,please do it manually</font><br>".restartChatServerMsg();
}

function restartChatServerMsg()
{
	$os = judgeOS();
	if($os == "Windows")
	{
		$msg = "Restart chat server by running ".$_POST['chat_server_path']."server/restart.bat";
	}
	else
	{
			$msg = "Restart chat server by running ".$_POST['chat_server_path']."server/fcserver.sh restart";
	}
	return "<font color='red'>".$msg."</font><br><br>";
}

function judgeOS()
{
	if(PATH_SEPARATOR==':') return 'Linux';
	return  'Windows';
}

function redirectPage($id = 0)
{
	if(!empty($id))
	{
			header("location:/viewprofile.php?id=".$id);
	}
	else
	{
		header("location:/myprofile.php");
	}
}

function setApiKey()
{
	return md5(microtime());
}
?>