/*

  	Playerinfo a plugin for Half-Life modifications
	Copyright (C) 2006  Christer Johansson

		This file is part of Playerinfo.

	Playerinfo is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	Playerinfo 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 Playerinfo; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
	
	Changelog
	- v1.0 Initial realese
	- v1.1 Fixed - spelling error on pi_roundend_save.
	- v1.2 Added - The users ip is updated in the database everytime they connect
	- v1.3 Added - option to choose between print_chat and hud message for advertising /myinfo and when players join
	       Fixed - Some code optimization and a few small fixed
	- v1.4 Removed some global variables
	
	Webfiles changelog
	       Added - extra cvar in config.php to set how many uses that needs to be on a nick before it show in the info page
*/

#include <amxmodx>
#include <amxmisc>
#include <sqlx>

new AUTH[] = "Gizmo"
new PLUGIN_NAME[] = "Playerinfo"
new VERSION[] = "1.4"

new Handle:g_SqlX
new g_table[32]
new g_table2[32]

new g_menuPosition[33]
new g_menuPlayers[33][32]
new g_menuPlayersNum[33]
new g_coloredMenus

new MyMsgSync

// pcvar globals
new pi_hudmsg
new pi_show_who
new pi_joinmsg
new pi_prunedb
new pi_prune_days
new pi_myinfo
new pi_roundend_save
new pi_debug

public plugin_init()
{
	register_plugin(PLUGIN_NAME, VERSION, AUTH)
	register_cvar(PLUGIN_NAME, VERSION, FCVAR_SERVER | FCVAR_SPONLY)

	// MySql settings
	register_cvar("pi_sql_host", "127.0.0.1")
	register_cvar("pi_sql_user", "root")
	register_cvar("pi_sql_pass", "")
	register_cvar("pi_sql_db", "amx")
	register_cvar("pi_sql_table1", "playerinfo_1")
	register_cvar("pi_sql_table2", "playerinfo_2")

	// url to playerinfo.php
	register_cvar("playerinfo_url", "http://www.yourhost.com/playerinfo/playerinfo.php?authid=%s")

	// Pruning of database, 1 = pruning on, 0 = pruning off
	pi_prunedb = register_cvar("pi_prunedb", "0")

	// How many days before old entries in the database is deleted, default is 30
	pi_prune_days = register_cvar("pi_days_before_delete", "30")
	
	// If set to 1 joinmessage is on, 0 = off
	pi_joinmsg = register_cvar("pi_joinmsg", "1")
	
	// If set to 1 only admins see joinmessages, 0 = everyone see joinmessages
	pi_show_who = register_cvar("pi_show_who_joinmsg", "1")
	
	// Set if joinmessages should print in chat or as hud message, 0 = client print, 1 = hud message
	pi_hudmsg = register_cvar("pi_hud_joinmsg", "0")
	
	// Set if player can say /myinfo to se info on themself, 0 = off, 1 = on
	pi_myinfo = register_cvar("pi_myinfo", "1")
	
	// Set this to 1 to enable debug printing
	pi_debug = register_cvar("pi_debug", "0")

	// Menu stuff
	register_concmd("pi_menu", "cmdPlayerinfomenu", ADMIN_MENU, "- Displays playerinfo menu")
	register_menucmd(register_menuid("Playerinfo Menu") , 1023, "actionPlayerinfoMenu")

	g_coloredMenus = colored_menus()
	MyMsgSync = CreateHudSyncObj()

	// Saycommand
	register_clcmd("say /myinfo", "showmotd")
	register_clcmd("say_team /myinfo", "showmotd")

	// Language files
	register_dictionary("playerinfo.txt")
	register_dictionary("common.txt")
	
	// Check what mod the server is running
	pi_roundend_save = register_cvar("pi_roundend_save", "0")
	new modname[32]
	get_modname(modname,31)
	
	if(equali("cstrike", modname) || equali("ns", modname) || equali("dod", modname))
	{
		set_pcvar_num(pi_roundend_save, 1)
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("Mod %s setting cvar pi_roundend_save to %d", modname, get_pcvar_num(pi_roundend_save))

		// Register event if the mod is cstrike
		if(equali("cstrike", modname))
		{
			register_logevent("RoundEnd", 2, "0=World triggered", "1=Round_End")
		}
		
		// Register event if the mod is ns
		else if(equali("ns", modname))
		{
			register_event("GameStatus", "RoundEnd", "ab", "1=2")
		}
		
		// Register event if the mod is dod
		else if(equali("dod", modname))
		{
			register_event("RoundState","RoundEnd","a","1=3","1=4")
		}
	}

	// Execute configfile for playerinfo
	new configsDir[64]
	get_configsdir(configsDir, 63)

	server_cmd("exec %s/playerinfo.cfg", configsDir)
	server_exec()
}

public plugin_cfg()
{
	new host[64], user[64], pass[64], db[64]

	get_cvar_string("pi_sql_host", host, 63)
	get_cvar_string("pi_sql_user", user, 63)
	get_cvar_string("pi_sql_pass", pass, 63)
	get_cvar_string("pi_sql_db", db, 63)

	g_SqlX = SQL_MakeDbTuple(host, user, pass, db)

	set_task(0.1, "create_table")
}

////////////////////////////////////////////////////////////////
//
//  Creates the tables where playerdata is stored
//

public create_table()
{
	new errnum, error[255]

	get_cvar_string("pi_sql_table1", g_table, 31)
	get_cvar_string("pi_sql_table2", g_table2, 31)

	new Handle:db = SQL_Connect(g_SqlX, errnum, error, 254)
	if (!db)
	{
		log_amx("%L", LANG_SERVER, "CONNECTION_FAILED", errnum, error)
		return
	}

	new Handle:query = SQL_PrepareQuery(db, "CREATE TABLE IF NOT EXISTS `%s` (`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `authid` VARCHAR(32) NOT NULL DEFAULT '0', `nick` VARCHAR(32) NOT NULL DEFAULT 'Unknown', `date` timestamp NOT NULL on update CURRENT_TIMESTAMP default CURRENT_TIMESTAMP , `uses` INT(10) UNSIGNED NOT NULL DEFAULT '0', `ip` VARCHAR(100) NOT NULL DEFAULT '0') ENGINE = MYISAM", g_table)
	if (!SQL_Execute(query))
	{
		errnum = SQL_QueryError(query, error, 254)
		log_amx("%L", LANG_SERVER, "QUERY_FAILED", errnum, error)
		SQL_FreeHandle(query)
		SQL_FreeHandle(db)
		return
	}
	
	new Handle:query2 = SQL_PrepareQuery(db, "CREATE TABLE IF NOT EXISTS `%s` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `authid` VARCHAR(32) NOT NULL DEFAULT '0' , `time` INT(20) UNSIGNED NOT NULL DEFAULT '0' , `connects` INT(10) UNSIGNED NOT NULL DEFAULT '0' , `rounds` INT(10) UNSIGNED NOT NULL DEFAULT '0' , `date` timestamp NOT NULL on update CURRENT_TIMESTAMP default CURRENT_TIMESTAMP ) ENGINE = MYISAM" , g_table2)
	if (!SQL_Execute(query2))
	{
		errnum = SQL_QueryError(query2, error, 254)
		log_amx("%L", LANG_SERVER, "QUERY_FAILED", errnum, error)
		SQL_FreeHandle(query2)
		SQL_FreeHandle(db)
		return
	}
	SQL_FreeHandle(query)
	SQL_FreeHandle(query2)
	SQL_FreeHandle(db)
}

////////////////////////////////////////////////////////////////
//
//   Start client_putinserver querys for both tables
//

public client_putinserver(id)
{
	new steamid[32]
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[Putinserver]Steamid: %s", steamid)

	if(containi(steamid,"BOT") != -1)
	{
		return PLUGIN_HANDLED
	}

	if(containi(steamid,"STEAM_ID_PENDING") != -1)
	{
		client_cmd(id, "reconnect")
	}

	if(get_pcvar_num(pi_myinfo) == 1)
	{
		set_task(6.0, "myinfo", id)
	}

	join_msg(id)
	client_putinserver_1a(id)
	client_putinserver_2a(id)
	client_putinserver_3a(id)
	return PLUGIN_CONTINUE
}

public myinfo(id)
{
	if(get_pcvar_num(pi_hudmsg) == 0)
	{
		client_print(id, print_chat, "%L", LANG_PLAYER, "MYINFO")
	}
	else
	{
		new name[32]
		get_user_name(id, name, 31)
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("[myinfo]Name: %s", name)

		new message[192]
		format(message, 191, "%L", id, "MYINFO", name)
		set_hudmessage(0, 255, 0, 0.05, 0.30, 0, 6.0, 5.0 , 0.5, 0.15, -1)
		ShowSyncHudMsg(id, MyMsgSync, "%s", message)
	}
	return PLUGIN_HANDLED
}

////////////////////////////////////////////////////////////////
//
//   Save client_putinserver querys for table 1
//

public client_putinserver_1a(id)
{
	new steamid[32], name[32]
	get_user_name(id, name, 31)
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[cp 1a]Steamid: %s, Name: %s", steamid, name)
	
	new query[512]
	format(query, 511, "SELECT nick FROM `%s` WHERE `authid` = '%s' AND `nick` = '%s'", g_table, steamid, name)
	
	new data[1]
	data[0] = id
	SQL_ThreadQuery(g_SqlX, "client_putinserver_1b", query, data, 1)
	return
}

public client_putinserver_1b(failstate, Handle:query, error[], errnum, data[], size)
{
	new id = data[0]
	
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError( szQuery, error, errnum, failstate, 1 )
	}
	else
	{
		new steamid[32], ip[32], name[32]
		get_user_name(id, name, 31)
		get_user_authid(id, steamid, 31)
		get_user_ip(id, ip, 31, 1)
		
		replaceall(name, 31, "'", "")
		replaceall(name, 31, "\", "")
		replaceall(name, 31, "<", "(")
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("[cp 1b]Steamid: %s, Name: %s, ip: %s", steamid, name, ip)

		if(equal(steamid, ""))
		{
			if(get_pcvar_num(pi_debug) == 1)
				log_amx("no steamid on user %s", name)
			
			return PLUGIN_HANDLED
		}
		
		if(!SQL_NumResults(query))
		{
			new query[512], data[1]

			format(query, 511, "INSERT INTO `%s` ( `id` , `authid` , `nick` , `date` , `uses` , `ip`) VALUES ( NULL , '%s', '%s', CURRENT_TIMESTAMP , '1', '%s')", g_table, steamid, name, ip)

			data[0] = id
			SQL_ThreadQuery(g_SqlX, "client_putinserver_1_insert", query, data, 1)
		}
		else
		{
			new query[512], data[1]

			format(query, 511, "UPDATE `%s` SET `uses`=`uses`+1 WHERE `nick`='%s' AND `authid`='%s'", g_table, name, steamid)

			data[0] = id
			SQL_ThreadQuery(g_SqlX, "client_putinserver_1_update", query, data, 1)
		}
	}
	return PLUGIN_HANDLED
}

public client_putinserver_1_insert(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 2)
	}
}

public client_putinserver_1_update(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 3)
	}
}


////////////////////////////////////////////////////////////////
//
//  Save client_putinserver querys for table 2
//

public client_putinserver_2a(id)
{
	new steamid[32]
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[cp 2a]Steamid: %s", steamid)
	
	new query[512]
	format(query, 511, "SELECT authid FROM `%s` WHERE `authid` = '%s'", g_table2, steamid)
	
	new data[1]
	data[0] = id

	SQL_ThreadQuery(g_SqlX, "client_putinserver_2b", query, data, 1)
	return
}

public client_putinserver_2b(failstate, Handle:query, error[], errnum, data[], size)
{
	new id = data[0]

	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 4)
	}
	else
	{	
		new steamid[32]
		get_user_authid(id, steamid, 31)
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("[cp 2b]Steamid: %s", steamid)

		if(!SQL_NumResults(query))
		{
			new query[512], data[1]

			format(query, 511, "INSERT INTO `%s` ( `authid` , `time` , `connects` , `rounds`) VALUES ( '%s', '0', '1' , '0' )", g_table2, steamid)

			data[0] = id
			SQL_ThreadQuery(g_SqlX, "client_putinserver_2_insert", query, data, 1)
		}
		else
		{
			new query[512], data[1]

			format(query, 511, "UPDATE `%s` SET `connects`=connects+1 WHERE `authid`='%s'", g_table2, steamid)

			data[0] = id
			SQL_ThreadQuery(g_SqlX, "client_putinserver_2_update", query, data, 1)
		}
	}
}

public client_putinserver_2_insert(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 5)
	}
}

public client_putinserver_2_update(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 6)
	}
}

////////////////////////////////////////////////////////////////
//
//  Updates ip on clients when they connect if their ip is diffrent from last time
//

public client_putinserver_3a(id)
{
	new steamid[32], name[32]
	get_user_name(id, name, 31)
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[cp 3a]Steamid: %s, Name: %s", steamid, name)

	new query[512]
	format(query, 511, "SELECT ip FROM `%s` WHERE `authid` = '%s' AND `nick` = '%s'", g_table, steamid, name)
	
	new data[1]
	data[0] = id
	
	SQL_ThreadQuery(g_SqlX, "client_putinserver_3b", query, data, 1)
	return
}

public client_putinserver_3b(failstate, Handle:query, error[], errnum, data[], size)
{
	new id = data[0]
	
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError( szQuery, error, errnum, failstate, 12 )
	}
	else
	{
		new steamid[32], ip[32]
		get_user_authid(id, steamid, 31)
		get_user_ip(id, ip, 31, 1)
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("[cp 3b]Steamid: %s, ip: %s", steamid, ip)

		if(!SQL_NumResults(query))
		{
			return PLUGIN_HANDLED
		}
		else
		{
			new query_ip[32]
			SQL_ReadResult(query, 0, query_ip, 31)
			if(equali(query_ip, ip))
			{
				return PLUGIN_HANDLED
			}
			else
			{
				new query[512], data[1]

				format(query, 511, "UPDATE `%s` SET `ip`='%s' WHERE `authid`='%s'", g_table, ip, steamid)
	
				data[0] = id
				SQL_ThreadQuery(g_SqlX, "client_putinserver_3_update", query, data, 1)
			}
		}
	}
	return PLUGIN_CONTINUE
}

public client_putinserver_3_update(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 3)
	}
}


////////////////////////////////////////////////////////////////
//
//  Saves number of rounds the players has played
//

public RoundEnd()
{
	if(get_pcvar_num(pi_roundend_save) == 0)
		return PLUGIN_HANDLED

	new Player[32]
	new playerCount, i
	get_players(Player, playerCount)
	for (i = 0; i < playerCount; i++)
	{
		new id = Player[i]
		if(is_user_connected(id))
		{
			EndofRound_1(id)
		}
	}
	return PLUGIN_CONTINUE
}

public EndofRound_1(id)
{
	new query[512], data[1], steamid[32]
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[Endround save]Steamid: %s", steamid)

	format(query, 511, "UPDATE `%s` SET `rounds`=rounds+1 WHERE `authid`='%s'", g_table2, steamid)

	data[0] = id
	SQL_ThreadQuery(g_SqlX, "EndofRound_2", query, data, 1)
}

public EndofRound_2(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 7)
	}
}

////////////////////////////////////////////////////////////////
//
//  Adds or updates data when player change name
//

public client_infochanged(id)
{
	if(is_user_connected(id))
	{
		new oldname[32], newname[32], steamid[32]
		get_user_info(id, "name", newname, 31)
		get_user_name(id, oldname, 31)
		get_user_authid(id, steamid, 31)
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("[infochanged]Steamid: %s, Oldname: %s, Newname: %s", steamid, oldname, newname)

		if(!equal(oldname, newname))
		{
			if(containi(steamid, "BOT") != -1)
				return PLUGIN_HANDLED

			client_infochanged_1(id, newname)
		}
	}
	return PLUGIN_CONTINUE
}

public client_infochanged_1(id, newname[])
{
	new steamid[32]
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[ci 1]Steamid: %s, Newname: %s", steamid, newname)

	new query[512]
	format(query, 511, "SELECT nick FROM `%s` WHERE `authid` = '%s' AND `nick` = '%s'", g_table, steamid, newname)
	
	new data[2]
	data[0] = id
	
	SQL_ThreadQuery(g_SqlX, "client_infochanged_2", query, data, 1)
	return
}

public client_infochanged_2(failstate, Handle:query, error[], errnum, data[], size)
{
	new id = data[0]
	new name[32]
	get_user_name(id, name, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[ci 2(1)]Newname: %s", name)
	
	new steamid[32], ip[32]
	get_user_authid(id, steamid, 31)
	get_user_ip(id, ip, 31, 1)

	replaceall(name, 31, "'", "")
	replaceall(name, 31, "\", "")
	replaceall(name, 31, "<", "(")
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[ci 2(2)]Steamid: %s, newname: %s, ip: %s", steamid, name, ip)

	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 8)
	}
	else
	{
		new result = SQL_NumResults(query)
		if(result == 0)
		{
			new query[512], data[1]
			format(query, 511, "INSERT INTO `%s` ( `id` , `authid` , `nick` , `date` , `uses` , `ip` ) VALUES ( NULL , '%s', '%s', CURRENT_TIMESTAMP , '1', '%s')", g_table, steamid, name, ip)

			data[0] = id
			SQL_ThreadQuery(g_SqlX, "client_infochanged_insert", query, data, 1)
		}
		else
		{
			new query[512], data[1]
			format(query, 511, "UPDATE `%s` SET `uses`=`uses`+1 WHERE `nick`='%s' AND `authid`='%s'", g_table, name, steamid)
			
			data[0] = id
			SQL_ThreadQuery(g_SqlX, "client_infochanged_update", query, data, 1)
		}
	}
}

public client_infochanged_insert(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 9)
	}
}

public client_infochanged_update(failstate, Handle:query, error[], errnum, data[], size)
{
	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 10)
	}
}



////////////////////////////////////////////////////////////////
//
//    Prints join message in chat when player gets steamid
//

public join_msg(id)
{
	if(get_pcvar_num(pi_joinmsg) == 0)
	{
		return PLUGIN_HANDLED
	}
	new steamid[32]
	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[joinmsg]Steamid: %s", steamid)

	new query[512]
	format(query, 511, "SELECT nick FROM `%s` WHERE `authid`='%s' ORDER BY uses DESC LIMIT 1", g_table, steamid)
	
	new data[1]
	data[0] = id

	SQL_ThreadQuery(g_SqlX, "_join_msg", query, data, 1)
	return PLUGIN_CONTINUE
}

public _join_msg(failstate, Handle:query, error[], errnum, data[], size)
{
	new id = data[0]

	if (failstate)
	{
		new szQuery[256]
		MySqlX_ThreadError(szQuery, error, errnum, failstate, 11)
	}
	else
	{
		new name[32]
		get_user_name(id, name, 31)
		
		if(get_pcvar_num(pi_debug) == 1)
			log_amx("[joinmsg 2]Name: %s",name)

		if(!SQL_NumResults(query))
		{
			if(get_pcvar_num(pi_show_who) == 1)
			{
				new players[32], playersnum
				get_players(players, playersnum, "ch")
				for(new i = 0; i < playersnum; i++)
				{
					new player = players[i]
					if(is_user_admin(player))
					{
						if(get_pcvar_num(pi_hudmsg) == 0)
						{
							client_print(player, print_chat, "%L", LANG_PLAYER, "JOIN_MSG", name)
						}
						else
						{
							new message[192]
							format(message, 191, "%L", LANG_PLAYER, "JOIN_MSG", name)
							set_hudmessage(0, 255, 0, 0.05, 0.30, 0, 6.0, 5.0 , 0.5, 0.15, -1)
							ShowSyncHudMsg(player, MyMsgSync, "%s", message)
						}
					}
				}
			}
			else
			{
				if(get_pcvar_num(pi_hudmsg) == 0)
				{
					client_print(0, print_chat, "%L", LANG_PLAYER, "JOIN_MSG", name)
				}
				else
				{
					new message[192]
					format(message, 191, "%L", LANG_PLAYER, "JOIN_MSG", name)
					set_hudmessage(0, 255, 0, 0.05, 0.30, 0, 6.0, 5.0 , 0.5, 0.15, -1)
					ShowSyncHudMsg(0, MyMsgSync, "%s", message)
				}
			}
		}
		else
		{
			new str[32]
			SQL_ReadResult(query, 0, str, 31)
	
			if(get_pcvar_num(pi_show_who) == 1)
			{
				new players[32], playersnum
				get_players(players, playersnum, "ch")
				for(new i = 0; i < playersnum; i++)
				{
					new player = players[i]
					if(is_user_admin(player))
					{
						if(get_pcvar_num(pi_hudmsg) == 0)
						{
							client_print(player, print_chat, "%L", LANG_PLAYER, "JOIN_MSG", name)
							client_print(player, print_chat, "%L", LANG_PLAYER, "JOIN_MSG2", str)
						}
						else
						{
							new message[192]
							format(message, 191, "%L", LANG_PLAYER, "JOIN_HUDMSG", name , str)
							set_hudmessage(0, 255, 0, 0.05, 0.30, 0, 6.0, 5.0 , 0.5, 0.15, -1)
							ShowSyncHudMsg(player, MyMsgSync, "%s", message)
						}
					}
				}
			}
			else
			{
				if(get_pcvar_num(pi_hudmsg) == 0)
				{
					client_print(0, print_chat, "%L", LANG_PLAYER, "JOIN_MSG", name)
					client_print(0, print_chat, "%L", LANG_PLAYER, "JOIN_MSG2", str)
				}
				else
				{
					new message[192]
					format(message, 191, "%L", LANG_PLAYER, "JOIN_HUDMSG", name, str)
					set_hudmessage(0, 255, 0, 0.05, 0.30, 0, 6.0, 5.0 , 0.5, 0.15, -1)
					ShowSyncHudMsg(0, MyMsgSync, "%s", message)
				}
			}
		}
	}
	return PLUGIN_HANDLED
}

////////////////////////////////////////////////////////////////
//
//  Save the amount of time the players has played on the server
//

public client_disconnect(id)
{
	new steamid[32], errnum, error[255]
	new playtime = get_user_time(id)

	get_user_authid(id, steamid, 31)
	
	if(get_pcvar_num(pi_debug) == 1)
		log_amx("[cd]Steamid: %s", steamid)

	new Handle:db = SQL_Connect(g_SqlX, errnum, error, 254)
	if (!db)
	{
		server_print("Connection failed [%d] %s", errnum, error)
		return
	}

	new Handle:query = SQL_PrepareQuery(db, "UPDATE `%s` SET `time`=time+%i WHERE `authid`='%s'", g_table2, playtime, steamid)
	if (!SQL_Execute(query))
	{
		errnum = SQL_QueryError(query, error, 254)
		server_print("Query failed [%d] %s", errnum, error)
		SQL_FreeHandle(query)
		SQL_FreeHandle(db)
		return
	}
	SQL_FreeHandle(query)
	SQL_FreeHandle(db)
}

////////////////////////////////////////////////////////////////
//
//   Menu functions
//

public cmdPlayerinfomenu(id, level, cid)
{
	if (!cmd_access(id, level, cid, 1))
		return PLUGIN_HANDLED

	displayPlayerinfoMenu(id, g_menuPosition[id] = 0)

	return PLUGIN_HANDLED
}

displayPlayerinfoMenu(id, pos)
{
	if (pos < 0)
		return

	get_players(g_menuPlayers[id], g_menuPlayersNum[id])

	new menuBody[512]
	new b = 0
	new i
	new name[32]
	new start = pos * 7

	if (start >= g_menuPlayersNum[id])
		start = pos = g_menuPosition[id] = 0

	new len = format(menuBody, 511, g_coloredMenus ? "\y%L\R%d/%d^n\w^n" : "%L %d/%d^n^n", id, "PLAYERINFOMENU", pos + 1, (g_menuPlayersNum[id] / 7 + ((g_menuPlayersNum[id] % 7) ? 1 : 0)))
	new end = start + 7
	new keys = MENU_KEY_0|MENU_KEY_8

	if (end > g_menuPlayersNum[id])
		end = g_menuPlayersNum[id]

	for (new a = start; a < end; ++a)
	{
		i = g_menuPlayers[id][a]
		get_user_name(i, name, 31)

		if (is_user_bot(i))// || access(i, ADMIN_IMMUNITY)
		{
			++b
			
			if (g_coloredMenus)
				len += format(menuBody[len], 511-len, "\d%d. %s^n\w", b, name)
			else
				len += format(menuBody[len], 511-len, "#. %s^n", name)
		}
		else
		{
				keys |= (1<<b)
				len += format(menuBody[len], 511-len, "%d. %s^n", ++b, name)
		}
	}

	if (end != g_menuPlayersNum[id])
	{
		format(menuBody[len], 511-len, "^n9. %L...^n0. %L", id, "MORE", id, pos ? "BACK" : "EXIT")
		keys |= MENU_KEY_9
	}
	else
		format(menuBody[len], 511-len, "^n0. %L", id, pos ? "BACK" : "EXIT")

	show_menu(id, keys, menuBody, -1, "Playerinfo Menu")
}

public actionPlayerinfoMenu(id, key)
{
	switch (key)
	{
		case 8: displayPlayerinfoMenu(id, ++g_menuPosition[id])
		case 9: displayPlayerinfoMenu(id, --g_menuPosition[id])
		default:
		{
			new player = g_menuPlayers[id][g_menuPosition[id] * 7 + key]
			new Authid[32], info_url[256], msg[2048]
			get_user_authid(player, Authid, 31)
			
			get_cvar_string("playerinfo_url", info_url, 255)
			format(msg, 2047, info_url, Authid)
			show_motd(id, msg, "Playerinfo")
			
			displayPlayerinfoMenu(id, g_menuPosition[id])
		}
	}

	return PLUGIN_HANDLED
}


////////////////////////////////////////////////////////////////
//
//  Function for showing the players their own info in motd
//

public showmotd(id)
{
	if(get_pcvar_num(pi_myinfo) == 0)
	{
		client_print(id, print_chat, "%L", LANG_PLAYER, "MYINFO_DISABLED")
		return PLUGIN_HANDLED
	}
	else
	{
		new Authid[32], msg[2048], info_url[256]
		get_user_authid(id, Authid, 31)
		get_cvar_string("playerinfo_url", info_url, 255)
		format(msg, 2047, info_url, Authid)
		show_motd(id, msg, "Playerinfo")
	}
	return PLUGIN_HANDLED
}

////////////////////////////////////////////////////////////////
//
//  Delets players older than sv_days_before_delete from the database
//

prune_db()
{
	new errnum, error[255]
	new prunedb = get_pcvar_num(pi_prune_days)
	
	new Handle:db = SQL_Connect(g_SqlX, errnum, error, 254)
	if (!db)
	{
		log_amx("%L", LANG_SERVER, "CONNECTION_FAILED", errnum, error)
		return
	}

	new Handle:query = SQL_PrepareQuery(db, "DELETE FROM `%s` WHERE DATE_SUB(CURDATE(),INTERVAL %d DAY) > date", g_table, prunedb)
	
	if (!SQL_Execute(query))
	{
		errnum = SQL_QueryError(query, error, 254)
		log_amx("%L", LANG_SERVER, "QUERY_FAILED", errnum, error)
		SQL_FreeHandle(query)
		SQL_FreeHandle(db)
		return
	}
	
	new Handle:query2 = SQL_PrepareQuery(db, "DELETE FROM `%s` WHERE DATE_SUB(CURDATE(),INTERVAL %d DAY) > date", g_table2, prunedb)
	
	if (!SQL_Execute(query2))
	{
		errnum = SQL_QueryError(query, error, 254)
		log_amx("%L", LANG_SERVER, "QUERY_FAILED", errnum, error)
		SQL_FreeHandle(query2)
		SQL_FreeHandle(db)
		return
	}
	SQL_FreeHandle(query)
	SQL_FreeHandle(query2)
	SQL_FreeHandle(db)

	server_print("%L", LANG_SERVER, "PRUNE_DB", prunedb)
}

////////////////////////////////////////////////////////////////

public plugin_end()
{
	if(get_pcvar_num(pi_prunedb) == 1)
	{
		prune_db()
	}
	SQL_FreeHandle(g_SqlX)
	return
}

////////////////////////////////////////////////////////////////

MySqlX_ThreadError(szQuery[], error[], errnum, failstate, id)
{
	
	if (failstate == TQUERY_CONNECT_FAILED)
	{
		log_amx("%L", LANG_SERVER, "TCONNECTION_FAILED")
	}
	else if (failstate == TQUERY_QUERY_FAILED)
	{
		log_amx("%L", LANG_SERVER, "TQUERY_FAILED")
	}
	log_amx("%L", LANG_SERVER, "TQUERY_ERROR", id)
	log_amx("%L", LANG_SERVER, "TQUERY_MSG", error, errnum)
	log_amx("%L", LANG_SERVER, "TQUERY_STATEMENT", szQuery)
}

stock replaceall(text[], const LEN, const WHAT[], const WITH[])
{
	while (contain(text, WHAT) != -1)
	{
		replace(text, LEN, WHAT, WITH)
	}
}