<?php
/**
  * Version: 		    Thank you 2.5.2
  * Compatibillity: 	MyBB 1.8.x
  * Website: 		    http://www.mybb.com
  * Autor: 		        Dark Neo
*/

// Deny direct access to this file...
if(!defined("IN_MYBB"))
{
	die("This file can't be loaded directly please make sure IN_MYBB is defined.");
}

// Load postbit data from plugin
$plugins->add_hook("postbit", "thx");
// Load message changes hide tags and more to postbit, announcements, preview, only missing on pm because don't needed
$plugins->add_hook("postbit_announcement", "thx_code");
$plugins->add_hook("postbit_prev", "thx_code");
$plugins->add_hook("parse_message", "thx_code");
// Load memprofile additional info
$plugins->add_hook('member_profile_end', 'thx_memprofile');
// When quote hide tags
$plugins->add_hook("parse_quoted_message", "thx_quote");
// Do you use AJAX ? then run it on click thanks or remove thanks buttons
$plugins->add_hook("xmlhttp", "do_action");
// Don't use AJAX ? then run this on click thanks button or remove thanks button reloading page but send data to db
$plugins->add_hook("showthread_start", "direct_action");
// Do you delete some post, load new values to thanks counts.
$plugins->add_hook("class_moderation_delete_post", "deletepost_edit");
// Load admincp controls like recount thanks and enable groups to recount thanks.
$plugins->add_hook('admin_tools_action_handler', 'thx_admin_action');
$plugins->add_hook('admin_tools_menu', 'thx_admin_menu');
$plugins->add_hook('admin_tools_permissions', 'thx_admin_permissions');
$plugins->add_hook('admin_load', 'thx_admin');
// Did you need aditional info to be load like templates or additional function or any globalize it
$plugins->add_hook("global_start", "thx_global_start");
$plugins->add_hook("global_start", "thanks_list");
// Do you want to change thanks ammount per day and rep points to be earned when thanks, load this then !!!
$plugins->add_hook("admin_user_groups_edit_graph_tabs", "thx_edit_group_tabs");
$plugins->add_hook("admin_user_groups_edit_graph", "thx_edit_group");
// Send all new data to thanks count and rep points if enabled...
$plugins->add_hook("admin_user_groups_edit_commit", "thx_edit_group_do");

// Load all info about this plugin
function thx_info()
{
	global $mybb, $db, $lang;

	// Load a function to get all info about plugin installation and new improvements (Like MyAlerts)
	$thx_config_link = thx_getdata($thx_config_link);
	
	// Send array of info for this function as usually
	return array(
		'name'			=>	$db->escape_string($lang->thx_title),
		'description'	=>	$db->escape_string($lang->thx_desc) . $thx_config_link,
		'website'		=>	'http://www.mybb.com',
		'author'		=>	'Dark Neo',
		'authorsite'	=>	'http://www.soportemybb.es',
		'version'		=>	'2.5.2',
		'codename'		=>	'thankyou_mybb_system',
        'compatibility' =>	'18*'
	);
}

// Run install function
function thx_install()
{
	global $db;
	
	$db->query("CREATE TABLE IF NOT EXISTS ".TABLE_PREFIX."thx (
		txid INT UNSIGNED NOT NULL AUTO_INCREMENT, 
		uid int(10) UNSIGNED NOT NULL, 
		adduid int(10) UNSIGNED NOT NULL, 
		pid int(10) UNSIGNED NOT NULL, 
		time bigint(30) NOT NULL DEFAULT '0', 
		PRIMARY KEY (`txid`), 
		INDEX (`adduid`, `pid`, `time`) 
		);"
	);

	// Add new field to table users for thanks plugin purposes
	if(!$db->field_exists("thx", "users"))
	{
		$sq[] = "ALTER TABLE ".TABLE_PREFIX."users ADD `thx` INT NOT NULL, ADD `thxcount` INT NOT NULL, ADD `thxpost` INT NOT NULL, ADD `thx_ammount` INT NOT NULL";
	}
	elseif (!$db->field_exists("thxpost", "users"))		
	{
		$sq[] = "ALTER TABLE ".TABLE_PREFIX."users ADD `thxpost` INT NOT NULL";
	}
	elseif (!$db->field_exists("thx_ammount", "users"))		
	{
		$sq[] = "ALTER TABLE ".TABLE_PREFIX."users ADD `thx_ammount` INT NOT NULL";
	}
	
	// Set new values to enable max thanks ammount
	if(!$db->field_exists("thx_max_ammount", "usergroups"))
	{
		$sq[] = "ALTER TABLE ".TABLE_PREFIX."usergroups ADD thx_max_ammount INT NOT NULL DEFAULT '10', ADD thx_rep_points INT NOT NULL DEFAULT '1'";
	}
	
	// Set new values to posts table to load thanks per post
	if(!$db->field_exists("pthx", "posts"))
	{
		$sq[] = "ALTER TABLE ".TABLE_PREFIX."posts ADD `pthx` INT(10) NOT NULL DEFAULT '0'";
	}
	
	// Insert all data to db if available
	if(is_array($sq))
	{
		foreach($sq as $q)
		{
			$db->query($q);
		}
	}
}

// Verify if plugin is installed
function thx_is_installed()
{
	global $db;
	// If table fr thanks exist then return value, else say don't installed this plugin...
	if($db->table_exists('thx')){
		return true;
	}
	else{
		return false;
	}
}


// Run activate function and verify if exist or wont to load or not data, to prevent lose damage data...
function thx_activate()
{
	global $db, $lang, $cache, $plugins;
	
	// Lang exist, then load it !!!
	$lang->load("thx", false, true);

	// Get the information available for this plugin to use it  
    $plugin_info = thx_info();

	// Load cache data and compare if version is the same or don't
    $dnt_plugins = $cache->read('dnt_plugins');

	if($plugin_info['version'] > $dnt_plugins['thx']['version']){
		thx_load_all();
	}
	else{
		thx_update();
	}
	
}

function thx_update()
{
	global $cache;
	
	// Get the information available for this plugin to use it  
    $plugin_info = thx_info();

	// Load cache data and compare if version is the same or don't
	$dnt_plugins = $cache->read('dnt_plugins');
	$dnt_plugins['thx'] = array(
		'title' => 'Thanks',
		'version' => $plugin_info['version'],
	);
		
	// Update version on cache if exist new value, replacing with the old one
	$cache->update('dnt_plugins', $dnt_plugins);
}	
	
// Load all data on activate function, insert new templates, stylesheets, etc to db...
function thx_load_all()
{
	global $db, $lang, $cache, $plugins;
	
	// Lang exist, then load it !!!
	$lang->load("thx", false, true);
	
	thx_update();
	
	//Create stylesheet for this plugin...
	$query_tid = $db->write_query("SELECT tid FROM ".TABLE_PREFIX."themes");
	$themetid = $db->fetch_array($query_tid);
	$style = array(
			'name'         => 'thx_buttons.css',
			'tid'          => $themetid['tid'],
			'stylesheet'   => $db->escape_string('.thx_buttons{
    font-family: "PT Sans",sans-serif;
    font-size: 13px;
    color: #E4E4E4;
    background: none repeat scroll 0% 0% #35A32D;
    border-left: 1px solid #4E9D70;
    border-right: 1px solid #4E9D70;
    border-width: 1px 1px 3px;
    border-style: solid;
    border-color: #4E9D70 #4E9D70 #319D5F;
    border-radius: 3px;
    padding: 2px 4px;
}

.thx_buttons:hover,
.thx_buttons:active{
		background: #25DA17;
                transition: all 0.5s ease;
}

.thx_buttons .gracias{
		color: #FFFFFF;
		text-decoration: none;	   
}

.thx_buttons .egracias{
		color: #000000;
		text-decoration: none;
}

.bad_thx{
	color: #FFF;
	font-size: 12px;
	font-weight: bold;
	text-decoration: none;
	text-align: center;
	background: none repeat scroll 0% 0% #913434;
	box-shadow: 0px 0px 1em #B6B6B6;
	border-radius: 3px;
	padding: 3px 6px 3px 6px;
	text-align: center;
}

.neutral_thx{
	color: #ffffff;
	font-size: 12px;
	font-weight: bold;
	text-decoration: none;
	text-align: center;		
	background: none repeat scroll 0% 0% #2C2727;
	box-shadow: 0px 0px 1em rgb(182, 182, 182);
	border-radius: 3px;		
	padding: 3px 6px 3px 6px;
	text-align: center;
}

.good_thx{
	color: #ffffff;
	font-size: 12px;
	font-weight: bold;
	text-decoration: none;
	background: none repeat scroll 0% 0% #4b9134;
	box-shadow: 0px 0px 1em rgb(182, 182, 182);
	border-radius: 3px;
	padding: 3px 6px 3px 6px;
	text-align: center;
}

.good_thx a, bad_thx a{
	color: #fff;
}

.thx_avatar{
	background: transparent;
	border: 1px solid #F0F0F0;
	padding: 5px;
	border-radius: 5px;
	width: 30px;
	height: 30px;
}

.info_thx, .exito_thx, .alerta_thx, .error_thx {
	font-size:13px;
	border: 1px solid;
	margin: 10px 0px;
	padding:10px 8px 10px 50px;
	background-repeat: no-repeat;
	background-position: 10px center;
	text-align: center;
	font-weight: bold;
	border-radius: 5px;
}

.info_thx {
    color: #00529B;
    background-color: #BDE5F8;
    background-image: url(images/thx/info.png);
}

.exito_thx {
    background-color: #DFF2BF;
    background-image:url(images/thx/bien.png);
}

.alerta_thx {
    color: #9F6000;
    background-color: #FEEFB3;
    background-image: url(images/thx/alerta.png);
}

.error_thx {
    color: #D8000C;
    background-color: #FFBABA;
    background-image: url(images/thx/mal.png);
}

.thx_list{
	position: absolute;
	font-size: 10px;
	font-weight: bold;
	border: 1px solid #FFFFFF;
	border-radius: 4px;
	padding: 20px;
	margin: 5px;
	background: #FFFFFF;
	width: 350px;
    opacity: 0.8;
    text-align: center;
}

.thx_list_avatar{
	width: 20px;
	height: 20px;
	background-color: #FCFDFD;	
	border: 1px solid #F0F0F0;
	padding: 3px;
	border-radius: 5px;
}

.thx_list_username{
	padding: 5px;
	bottom: 10px;
	position: relative;
}

.thx_window{
	background: #DFF2BF !important;
	color: #000000 !important;
	border-width: 1px 1px 2px !important;
	border-style: solid !important;
	border-color: #DBF2BF !important;
	border-radius: 3px;
}

.thx_given{
	padding: 6px 8px;
	margin: 0px 10px;
	font: Tahoma 12px #ffffff;
	font-weight: bold;
	color: #ffffff;
	border-radius: 3px;
	background: none repeat scroll 0% 0% #3C3CB3;
	box-shadow: 0px 0px 1em rgb(182, 182, 182);
}

.thx_received{
	padding: 6px 8px;
	margin: 0px 10px;
	font: Tahoma 12px #ffffff;
	font-weight: bold;
	color: #ffffff;
	border-radius: 3px;
	background: none repeat scroll 0% 0% #4b9134;
	box-shadow: 0px 0px 1em rgb(182, 182, 182);
}'),
			'lastmodified' => TIME_NOW
		);
		// Insert stylesheet to db...
		$sid = $db->insert_query('themestylesheets', $style);
		$db->update_query('themestylesheets', array('cachefile' => "thx_buttons.css"), "sid='{$sid}'", 1);
		$query = $db->simple_select('themes', 'tid');
		while($theme = $db->fetch_array($query))
		{
			require_once MYBB_ADMIN_DIR.'inc/functions_themes.php';
			cache_stylesheet($style['tid'], $style['cachefile'], $style['stylesheet']);
			update_theme_stylesheet_list($theme['tid'], false, true);			
		}

	// Verify if myalerts exists and if compatible with 1.8.x then add alert type
	if(function_exists("myalerts_info")){
		// Load myalerts info into an array
		$my_alerts_info = myalerts_info();
		// Set version info to a new var
		$verify = $my_alerts_info['version'];
		// If MyAlerts 2.0 or better then do this !!!
		if($verify >= "2.0.0"){
			// Load cache data and compare if version is the same or don't
			$myalerts_plugins = $cache->read('mybbstuff_myalerts_alert_types');
			if($myalerts_plugins['thanks']['code'] != 'thanks'){
			//Adding alert type to db
			$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::createInstance($db, $cache);
				$alertType = new MybbStuff_MyAlerts_Entity_AlertType();
				$alertType->setCode('thanks');
				$alertType->setEnabled(true);
			$alertTypeManager->add($alertType);
			}
		}	
	}

	// Adding new group of templates for this plugin...  
	$templategrouparray = array(
		'prefix' => 'thanks',
		'title'  => 'DNT thanks plugin'
	);
	$db->insert_query("templategroups", $templategrouparray);

	// Adding every template needed ...
	$templatearray = array(
		'title' => 'thanks_postbit_list',
		'template' => "<div class=\"modal\">
	<div class=\"thx_list\" id=\"thx{\$post[\'pid\']}\">
		<div class=\"thead\">{\$lang->thx_latest_entries}</div>
		<br />
		<span>{\$entries}</span>
		<br />
		<span>
			<a href=\"{\$mybb->settings[\'bburl\']}/thx.php?thanked_pid={\$post[\'pid\']}&my_post_key={\$mybb->post_code}\">{\$lang->thx_latest_entries_view_all}</a>
		</span>
	</div>
</div>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);	
		$db->insert_query("templates", $templatearray);

	$templatearray = array(
		'title' => 'thanks_postbit_list_entries',
		'template' => "<a href=\"{\$thx[\'profile_link\']}\">{\$thx[\'avatar\']}<span class=\"thx_list_username\">{\$thx[\'user_name\']}</span>{\$thx[\'date\']}</a>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);	
		$db->insert_query("templates", $templatearray);
			
	$templatearray = array(
		'title' => 'thanks_memprofile',
		'template' => "<br />
<table id=\"thx_profile\" border=\"0\" cellspacing=\"{\$theme[\'borderwidth\']}\" cellpadding=\"{\$theme[\'tablespace\']}\" class=\"tborder\">
<tr>
<td class=\"thead\"><strong>{\$lang->thx_title}</strong></td>
</tr>
<tr>
<td class=\"trow1\">
{\$memprofile[\'thx_detailed_info\']}
<br />
{\$memprofile[\'thx_info\']}
<br />
{\$memprofile[\'thx_info2\']}
</td>
</tr>
</table>
<br />",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	
	
	$templatearray = array(
		'title' => 'thanks_hide_tag',
		'template' => "<div class=\"alerta_thx message\">{\$msg}</div>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	
	
	$templatearray = array(
		'title' => 'thanks_unhide_tag',
		'template' => "<div class=\"exito_thx message\">{\$msg}</div>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	$templatearray = array(
		'title' => 'thanks_guests_tag',
		'template' => "<div class=\"error_thx message\">{\$msg}</div>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	$templatearray = array(
		'title' => 'thanks_admins_tag',
		'template' => "<div class=\"info_thx message\">{\$msg}</div>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	$templatearray = array(
		'title' => 'thanks_results',
		'template' => "<tr>
	<td class=\"{\$trow}\"><div class=\"float_left\">{\$gived[\'avatar\']}{\$gived[\'username\']}</div><div class=\"float_right thanked\"><span class=\"thx_given\">{\$gived[\'thx\']}</span><span class=\"thx_received\">{\$gived[\'thxcount\']}</span></div></td>			
	<td class=\"{\$trow}\">{\$gived[\'txid\']}</td>		
	<td class=\"{\$trow}\"><a href=\"{\$gived[\'url\']}\">{\$lang->thx_details}</a></td>	
	<td class=\"{\$trow}\"><div class=\"float_left\">{\$gived[\'ugavatar\']}{\$gived[\'ugname\']}</div><div class=\"float_right thanked\"><span class=\"thx_given\">{\$gived[\'uthx\']}</span><span class=\"thx_received\">{\$gived[\'uthxcount\']}</span></div></td>
	<td class=\"{\$trow}\" align=\"center\">{\$gived[\'time\']}</td>
</tr>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	$templatearray = array(
		'title' => 'thanks_results_none',
		'template' => "<tr>
	<td class=\"trow1\" colspan=\"5\" align=\"center\">{\$lang->thx_empty}</td>
</tr>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	$templatearray = array(
		'title' => 'thanks_content',
		'template' => "<table border=\"0\" cellspacing=\"{\$theme[\'borderwidth\']}\" cellpadding=\"{\$theme[\'tablespace\']}\" class=\"tborder\" style=\"text-align: center;\">
	<tr>
		<td class=\"thead\" colspan=\"5\">
			<strong>{\$lang->thx_system_dnt}</strong>
		</td>
	</tr>
	<tr>
		<td class=\"tcat smalltext\"><strong>{\$lang->thx_user}</strong></td>
		<td class=\"tcat smalltext\"><strong>{\$lang->thx_id}</strong></td>
		<td class=\"tcat smalltext\"><strong>{\$lang->thx_details}</strong></td>
		<td class=\"tcat smalltext\"><strong>{\$lang->thx_added}</strong></td>
		<td class=\"tcat smalltext\"><strong>{\$lang->thx_date}</strong></td>
	</tr>
	{\$users_list}
</table>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	$templatearray = array(
		'title' => 'thanks_page',
		'template' => "<html>
	<head>
		<title>{\$mybb->settings[\'bbname\']} - {\$lang->thx_system_dnt}</title>
		{\$headerinclude}
	</head>
	<body>
		{\$header}
		{\$multipage}
		{\$content}
		{\$multipage}
		{\$footer}
	</body>
</html>",
		'sid' => '-2',
		'version' => '1803',
		'dateline' => TIME_NOW
		);
	$db->insert_query("templates", $templatearray);	

	// Add task to set max ammoun per day running every day...
	$thx_task = array(
		"title" => "Thanks per day",
		"description" => "Set all counters to 0 for every user on max ammount",
		"file" => "thx",
		"minute" => '0',
		"hour" => '0',
		"day" => '*',
		"month" => '*',
		"weekday" => '*',
		"nextrun" => time() + (1*24*60*60),
		"enabled" => '1',
		"logging" => '1'
	);
	$db->insert_query("tasks", $thx_task);

	// Add settings group for this plugin
	$thx_group = array(
		"name"			=> "Gracias",
		"title"			=> $db->escape_string($lang->thx_opt_title),
		"description"	=> $db->escape_string($lang->thx_opt_desc),
		"disporder"		=> "3",
		"isdefault"		=> "1"
	);	
	$db->insert_query("settinggroups", $thx_group);
	$gid = $db->insert_id();
	
	// Add every setting to be used by this plugin
	$thx[]= array(
		"name"			=> "thx_active",
		"title"			=> $db->escape_string($lang->thx_opt_enable),
		"description"	=> $db->escape_string($lang->thx_opt_enable_desc),
		"optionscode" 	=> "onoff",
		"value"			=> 1,
		"disporder"		=> 1,
		"gid"			=> (int)$gid,
	);

	$thx[] = array(
		"name"			=> "thx_hidesystem_notgid",
		"title"			=> $db->escape_string($lang->thx_ngid_title),
		"description"   => $db->escape_string($lang->thx_ngid_desc),
		"optionscode" 	=> "groupselect",
		"value"			=> '1,5,7',
		"disporder"		=> 2,
		"gid"			=> $db->escape_string($gid),
	);	
	
	$thx[] = array(
		"name"			=> "thx_count",
		"title"			=> $db->escape_string($lang->thx_count_title),
		"description"	=> $db->escape_string($lang->thx_count_desc),
		"optionscode" 	=> "onoff",
		"value"			=> 1,
		"disporder"		=> 3,
		"gid"			=> (int)$gid,
	);

	$thx[] = array(
		"name"			=> "thx_counter",
		"title"			=> $db->escape_string($lang->thx_counter_title),
		"description"	=> $db->escape_string($lang->thx_counter_desc),
		"optionscode" 	=> "onoff",
		"value"			=> 1,
		"disporder"		=> 4,
		"gid"			=> (int)$gid,
	);	
	$thx[] = array(
		"name"			=> "thx_del",
		"title"			=> $db->escape_string($lang->thx_del_title),
		"description"	=> $db->escape_string($lang->thx_del_desc),
		"optionscode" 	=> "onoff",
		"value"			=> 1,
		"disporder"		=> 5,
		"gid"			=> (int)$gid,
	);
	
	$thx[] = array(
		"name"			=> "thx_hidemode",
		"title"			=> $db->escape_string($lang->thx_date_title),
		"description"	=> $db->escape_string($lang->thx_date_desc),
		"optionscode" 	=> "onoff",
		"value"			=> 1,
		"disporder"		=> 6,
		"gid"			=> (int)$gid,
	);
	
	$thx[] = array(
		"name"			=> "thx_hidesystem",
		"title"			=> $db->escape_string($lang->thx_hide_title),
		'description'   => $db->escape_string($lang->thx_hide_desc),
		"optionscode" 	=> "yesno",
		"value"			=> 1,
		"disporder"		=> 7,
		"gid"			=> (int)$gid,
	);

	$thx[] = array(
		"name"			=> "thx_hidesystem_tag",
		"title"			=> $db->escape_string($lang->thx_hidetag_title),
		'description'   => $db->escape_string($lang->thx_hidetag_desc),
		"optionscode" 	=> "text",
		"value"			=> $db->escape_string($lang->thx_hidetag_value),
		"disporder"		=> 8,
		"gid"			=> (int)$gid,
	);	

	$thx[] = array(
		"name"			=> "thx_hidesystem_gid",
		"title"			=> $db->escape_string($lang->thx_gid_title),
		"description"   => $db->escape_string($lang->thx_gid_desc),
		"optionscode" 	=> "groupselect",
		"value"			=> 4,
		"disporder"		=> 9,
		"gid"			=> (int)$gid,
	);	

    $thx[] = array(
        'name' 			=> "thx_limit",
        'title' 		=> $db->escape_string($lang->thx_limit_title),
        'description' 	=> $db->escape_string($lang->thx_limit_desc),
        'optionscode' 	=> 'yesno',
        'value' 		=> 1,
        'disporder' 	=> 10,
		"gid"			=> (int)$gid,
    );  	
	
    $thx[] = array(
        'name' 			=> "thx_reputation",
        'title' 		=> $db->escape_string($lang->thx_rep_title),
        'description' 	=> $db->escape_string($lang->thx_rep_desc),
        'optionscode' 	=> 'select \n1='.$db->escape_string($lang->thx_rep_op1).' \n2='.$db->escape_string($lang->thx_rep_op2).' \n3='.$db->escape_string($lang->thx_rep_op3).' \n4='.$db->escape_string($lang->thx_rep_op4),
        'value' 		=> 3,
        'disporder' 	=> 11,
		"gid"			=> (int)$gid,
    );  	
	
	// Insert settings to db...
	foreach($thx as $t)
	{
		$db->insert_query("settings", $t);
	}

	// Load file to set template changes...
	require MYBB_ROOT."inc/adminfunctions_templates.php";	
	// Insert all template changes for templates that exist on MyBB...
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'signature\']}').'#', '{$post[\'signature\']}{$post[\'thx_list\']}{$post[\'thx_counter\']}{$post[\'thanks\']}');	
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'message\']}').'#', '<div id="thxpid_{$post[\'pid\']}">{$post[\'message\']}</div>');	
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'user_details\']}').'#', '{$post[\'user_details\']}<br />{$post[\'thanks_count\']}{$post[\'thanked_count\']}');
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'message\']}').'#', '<div id="thxpid_{$post[\'pid\']}">{$post[\'message\']}</div>');		
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'signature\']}').'#', '{$post[\'signature\']}{$post[\'thx_list\']}{$post[\'thx_counter\']}{$post[\'thanks\']}');		
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'user_details\']}').'#', '{$post[\'user_details\']}<br />{$post[\'thanks_count\']}{$post[\'thanked_count\']}');	
	find_replace_templatesets("showthread", "#".preg_quote('{$headerinclude}').'#','{$headerinclude}'."\n".'<script type="text/javascript" src="{$mybb->settings[\'bburl\']}/jscripts/thx.js"></script>
	<script type="text/javascript">
	var thx_msg_title = "{$lang->thx_msg_title}";	
	var thx_msg_add = "{$lang->thx_msg_add}";
	var thx_msg_remove = "{$lang->thx_msg_remove}";					
</script>');
	find_replace_templatesets('member_profile', '#{\$profilefields}#', '{\$profilefields}
{\$memprofile[\'thx_details\']}');
	find_replace_templatesets("codebuttons", "#".preg_quote('<script type="text/javascript" src="{$mybb->asset_url}/jscripts/bbcodes_sceditor.js"></script>').'#','<script type="text/javascript" src="{$mybb->asset_url}/jscripts/bbcodes_sceditor.js"></script>
<script type="text/javascript" src="{$mybb->asset_url}/jscripts/oculto.js"></script>
<script type="text/javascript">
    var hide_tag = "{$mybb->settings[\'thx_hidesystem_tag\']}";
    var hide_tag_title = "{$lang->thx_hide_tag_title}";
    var hide_tag_content = "{$lang->thx_hide_tag_content}";	
</script>');
	find_replace_templatesets("codebuttons", "#".preg_quote('|maximize').'#',',{$mybb->settings[\'thx_hidesystem_tag\']}|maximize');

	// Update cache for usergroups to set permissions of max_ammount and rep vals for every usergroup...
	$cache->update_usergroups();
	// Update forum info is not necesary but anyway update cache...
   	$cache->update_forums();
	// Update tasks values to set enabled and running everyday new task... 
	$cache->update_tasks();	

	// Rebuild settings, this load all necesary info used by this plugin (New settings used by this plugin like enabled, groups used, hide tags, an many more)...
	rebuild_settings();
}

// Verify if this plugin is activated or wont !!!
function thx_is_activated()
{
    global $cache, $plugins;

	// Read cache info about this plugin and say if this are enabled or wont
    $plugins = $cache->read('plugins');
	// Load from cache active value and set in a new var
    $activePlugins = $plugins['active'];
	//Create var to verify if active by default set value to false....
    $isActive = false;

	// Verify data exist by cache and then set value to true to mark plugin are enabled...
    if(in_array('thx', $activePlugins)) {
        $isActive = true;
    }

	// Return value and verify is installed
    return thx_is_installed() && $isActive;
}

function thx_deactivate()
{
	global $db, $cache;

	// Get the information available for this plugin to use it  
    $plugin_info = thx_info();

	// Load cache data and compare if version is the same or don't
    $dnt_plugins = $cache->read('dnt_plugins');

	if($plugin_info['version'] > $dnt_plugins['thx']['version']){

   	$db->delete_query('themestylesheets', "name='thx_buttons.css'");
	$query = $db->simple_select('themes', 'tid');
	while($theme = $db->fetch_array($query))
	{
		require_once MYBB_ADMIN_DIR.'inc/functions_themes.php';
		update_theme_stylesheet_list($theme['tid']);
	}

	$db->delete_query("settings", "name IN ('thx_active', 'thx_count', 'thx_counter', 'thx_del', 'thx_hidemode', 'thx_hidesystem', 'thx_hidesystem_tag', 'thx_hidesystem_gid', 'thx_hidesystem_notgid', 'thx_reputation', 'thx_version')");
	$db->delete_query("settinggroups", "name='Gracias'");
	$db->delete_query("templategroups", "prefix='thanks'");
	$db->delete_query("templates", "title IN('thanks_postbit_list', 'thanks_postbit_list_entries', 'thanks_memprofile', 'thanks_hide_tag', 'thanks_unhide_tag', 'thanks_guests_tag', 'thanks_admins_tag', 'thanks_results', 'thanks_results_none', 'thanks_content', 'thanks_page')");
	if($db->table_exists("alert_types")){
		$alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::getInstance();
        $alertTypeManager->deleteByCode('thanks');
	}
	
	$db->delete_query('tasks', 'file=\'thx\'');

	require '../inc/adminfunctions_templates.php';
	find_replace_templatesets("postbit", '#'.preg_quote('<div id="thxpid_{$post[\'pid\']}">{$post[\'message\']}</div>').'#', '{$post[\'message\']}', 0);	
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'thx_list\']}').'#', '', 0);
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'thanks_count\']}').'#', '', 0);
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'thanked_count\']}').'#', '', 0);
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'thanks\']}').'#', '', 0);
	find_replace_templatesets("postbit", '#'.preg_quote('{$post[\'thx_counter\']}').'#', '', 0);
	find_replace_templatesets("postbit_classic", '#'.preg_quote('<div id="thxpid_{$post[\'pid\']}">{$post[\'message\']}</div>').'#', '{$post[\'message\']}', 0);	
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'thx_list\']}').'#', '', 0);
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'thanks_count\']}').'#', '', 0);
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'thanked_count\']}').'#', '', 0);	
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'thanks\']}').'#', '', 0);
	find_replace_templatesets("postbit_classic", '#'.preg_quote('{$post[\'thx_counter\']}').'#', '', 0);	
	find_replace_templatesets("showthread", "#".preg_quote('<script type="text/javascript" src="{$mybb->settings[\'bburl\']}/jscripts/thx.js"></script>').'#', '', 0);
	find_replace_templatesets("showthread", "#".preg_quote('<script type="text/javascript">
	var thx_msg_title = "{$lang->thx_msg_title}";	
	var thx_msg_add = "{$lang->thx_msg_add}";
	var thx_msg_remove = "{$lang->thx_msg_remove}";					
</script>').'#', '', 0);
	find_replace_templatesets("member_profile", "#".preg_quote('{$memprofile[\'thx_details\']}').'#', '', 0);
	find_replace_templatesets("codebuttons", "#".preg_quote('<script type="text/javascript" src="{$mybb->asset_url}/jscripts/oculto.js"></script>').'#', '', 0);
	find_replace_templatesets("codebuttons", "#".preg_quote(',{$mybb->settings[\'thx_hidesystem_tag\']}').'#','', 0);
	find_replace_templatesets("codebuttons", "#".preg_quote('<script type="text/javascript">
    var hide_tag = "{$mybb->settings[\'thx_hidesystem_tag\']}";
    var hide_tag_title = "{$lang->thx_hide_tag_title}";
    var hide_tag_content = "{$lang->thx_hide_tag_content}";	
</script>').'#','', 0);		

	$cache->update_usergroups();
   	$cache->update_forums();	
	$cache->update_tasks();	
	
	rebuild_settings();
	}
}

function thx_uninstall()
{
	global $db;

	if($db->field_exists("thx", "users"))
	{
		$db->query("ALTER TABLE ".TABLE_PREFIX."users DROP thx, DROP thxcount");
	}

	if($db->field_exists("thx_ammount", "users"))
	{
		$db->query("ALTER TABLE ".TABLE_PREFIX."users DROP thx_ammount, DROP thxpost");
	}
	
	if($db->field_exists("thx_max_ammount", "usergroups"))
	{
		$db->query("ALTER TABLE ".TABLE_PREFIX."usergroups DROP thx_max_ammount, DROP thx_rep_points");
	}
	
	if($db->field_exists("pthx", "posts"))
	{
		$db->query("ALTER TABLE ".TABLE_PREFIX."posts DROP pthx");
	}

	$db->query("DELETE FROM ".TABLE_PREFIX."datacache WHERE title='dnt_plugins'");
	
	$date = date('dmY');
	if($db->table_exists("thx"))
	{
		$db->query("RENAME TABLE ".TABLE_PREFIX."thx TO ".TABLE_PREFIX."thx_backup_{$date}");
	}
	
}

function thx_getdata(&$thx_config_link)
{
	global $mybb, $db, $lang, $thx_config_link; $alertas;

	$thx_config_link = '';

	$lang->load("thx", false, true);
	
	if ($mybb->settings['thx_active'] == 1)
	{
	$download = htmlspecialchars_uni("http://www.mediafire.com/download/abk831ajp43srh1/MyAlerts_20.zip");
		if(function_exists("myalerts_info")){
			$my_alerts_info = myalerts_info();
			$verify = $my_alerts_info['version'];
		}
		else{
			$verify = "";
		}
		$thx_config_link = '<div style="float: right;"><a href="index.php?module=config&action=change&search=Gracias" style="color:#035488; background: url(../images/thx/gear.png) no-repeat 0px 18px; padding: 21px; text-decoration: none;"> '. $db->escape_string($lang->thx_config) . '</a></div>';
		$thx_config_link .= '<br /><div><span style="color: rgba(34, 136, 3, 1); background: url(../images/thx/good.png) no-repeat 0px 18px; padding: 21px; text-decoration: none;">OK</span></div>';
		if(thx_myalerts_status() && $verify >= 2.0 && $mybb->settings['thx_reputation'] == 2 || thx_myalerts_status() && $verify >= 2.0 && $mybb->settings['thx_reputation'] == 4){
			$thx_config_link .= '<div style="float: left;"><span style="color: rgba(34, 136, 3, 1); background: url(../images/thx/good.png) no-repeat 0px 18px; padding: 21px; text-decoration: none;"> ' . $db->escape_string($lang->thx_config_alerts_thx) . '</div><br />';		
		}
		else if($verify > 1.0 && $verify <= 1.05 || $verify >= 2.0 && $mybb->settings['thx_reputation'] == 1 || $verify >= 2.0 && $mybb->settings['thx_reputation'] == 3){
			$thx_config_link .= '<div style="float: left;"><span style="color: rgba(136, 17, 3, 1); background: url(../images/icons/exclamation.png) no-repeat 0px 18px; padding: 18px; text-decoration: none;">  ' . $db->escape_string($lang->thx_config_alerts_thx_config) . '</div><br />';		
		}
		else if(!thx_myalerts_status() && $mybb->settings['thx_reputation'] == 2 || !thx_myalerts_status() && $mybb->settings['thx_reputation'] == 4){
			$thx_config_link .= '<div style="float: left;"><span style="color: rgba(136, 17, 3, 1); background: url(../images/icons/exclamation.png) no-repeat 0px 18px; padding: 18px; text-decoration: none;">  ' . $lang->sprintf($lang->thx_config_alerts_missing, $download) . '</div><br />';	
		}			
		else if($verify == ""){
			$thx_config_link .= '<div style="float: left;"><span style="color: #899611; background: url(../images/icons/information.png) no-repeat 0px 18px; padding: 18px; text-decoration: none;">  ' . $lang->sprintf($lang->thx_config_alerts_none, $download) . '</div><br />';	
		}
	}
	else if ($mybb->settings['thx_active'] == 0)
	{
		$thx_config_link = '<div style="float: right; color: rgba(136, 17, 3, 1); background: url(../images/icons/exclamation.png) no-repeat 0px 18px; padding: 21px; text-decoration: none;"> '. $db->escape_string($lang->thx_disabled) . '</div>';
	}
		
	return $thx_config_link;
}

function thx_myalerts_status()
{
	global $db, $cache;

	// Load cache data and compare if version is the same or don't
    $myalerts_plugins = $cache->read('mybbstuff_myalerts_alert_types');

	if($myalerts_plugins['thanks']['code'] == 'thanks' && $myalerts_plugins['thanks']['enabled'] == 1){
		return true;
	}
	return false;
}

function thx_global_start()
{
	global $mybb, $session, $lang, $code;

    if (!$mybb->settings['thx_active'] || !empty($session->is_spider))
    {
        return false;
    }
		
	$lang->load("thx", false, true);

	if(isset($GLOBALS['templatelist']))
	{
		if(THIS_SCRIPT == "showthread.php"){
			$GLOBALS['templatelist'] .= ",thanks_postbit_list, thanks_postbit_list_entries, thanks_hide_tag, thanks_unhide_tag, thanks_guests_tag, thanks_admins_tag";
		}
		else if(THIS_SCRIPT == "thx.php"){
			$GLOBALS['templatelist'] .= ",thanks_results, thanks_results_none, thanks_content, thanks_page";
		}
		else if(THIS_SCRIPT == "member.php"){
			$GLOBALS['templatelist'] .= ",thanks_memprofile";
		}
	}

	// Registering alert formatter
	if((function_exists('myalerts_is_activated') && myalerts_is_activated()) && $mybb->user['uid'] && ($mybb->settings['thx_reputation'] == 2 || $mybb->settings['thx_reputation'] == 4)){
		global $cache, $formatterManager;
		// Load cache data and compare if version is the same or don't
		$myalerts_plugins = $cache->read('mybbstuff_myalerts_alert_types');
	
		if($myalerts_plugins['thanks']['code'] == 'thanks' && $myalerts_plugins['thanks']['enabled'] == 1){
			if (class_exists('MybbStuff_MyAlerts_AlertFormatterManager') && class_exists('ThanksAlertFormatter')) {
				$code = 'thanks';
				$formatterManager = MybbStuff_MyAlerts_AlertFormatterManager::getInstance();
				$formatterManager->registerFormatter(new ThanksAlertFormatter($mybb, $lang, $code));
			}
		}
	}
}

function thx_code(&$message)
{
    global $db, $post, $mybb, $lang, $session, $theme, $altbg, $templates, $thx_cache, $forum, $fid, $pid, $announcement, $postrow, $hide_tag;

	$lang->load("thx", false, true);

	$url = $mybb->settings['bburl'];
    $hide_tag = $mybb->settings['thx_hidesystem_tag'];	

	if($mybb->input['highlight'] == "{$hide_tag}"){		
	   $msg = $lang->thx_hide_text; 	
 	   eval("\$caja = \"".$templates->get("thanks_guests_tag",1,0)."\";");		
	   $message = $caja;
	}			

    if ($mybb->settings['thx_active'] == 0 || $mybb->settings['thx_hidesystem'] == 0)
    {
        return false;
    }

        $thx_forum_gid = explode(',', $mybb->settings['thx_hidesystem_gid']);
		$thx_forum_notgid = explode(',', $mybb->settings['thx_hidesystem_notgid']);
		
		if(THIS_SCRIPT == "syndication.php" || THIS_SCRIPT == "search.php"){
		   $msg = $lang->thx_hide_sindycation; 
		   eval("\$caja = \"".$templates->get("thanks_guests_tag",1,0)."\";");		  
		   $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);	
		}
		
		if($forum['fid'] == 0 || $forum['fid'] == ''){$forum['fid'] = $fid;}
		
		if($post['pid'] == 0 || $post['pid'] == ''){
			switch(THIS_SCRIPT)
			{
				case "printthread.php" : $post['pid'] = $postrow['pid'];break;
				case "portal.php" : $post['pid'] = $announcement['pid'];$forum_fid = $announcement['fid'];break;
				default: $post['pid'] = $pid;
			}
		}
				
        $must_thanks = $mybb->settings['thx_hidesystem_tag'];

	$thx_add_gid =  explode(",", $mybb->user['additionalgroups']);
	foreach($thx_add_gid as $ag){
		if(in_array($ag, $thx_forum_gid)){
		  $msg = "$1";
		  eval("\$caja = \"".$templates->get("thanks_admins_tag",1,0)."\";");		  
		  $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);   				
		}
	}
    if(in_array($mybb->user['usergroup'], $thx_forum_gid))
    {
	  $msg = "$1";
	  eval("\$caja = \"".$templates->get("thanks_admins_tag",1,0)."\";");		  
      $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);      
	}
      
    else if(in_array($mybb->user['usergroup'], $thx_forum_notgid) || $mybb->user['uid'] == 0)
    {	 
	   $msg = $lang->thx_hide_register; 
	   eval("\$caja = \"".$templates->get("thanks_guests_tag",1,0)."\";");		  
	   $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);
    }
    else{

	  if ($mybb->user['uid'] == $post['uid'])
       {
		   $msg = "$1";
		   eval("\$caja = \"".$templates->get("thanks_unhide_tag",1,0)."\";");		  
		   $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);
       }

     if($mybb->user['uid'] != $post['uid'])
     {
     $thx_user = (int)$mybb->user['uid'];
	 $query=$db->query("SELECT th.txid, th.uid, th.adduid, th.pid, th.time, u.username, u.usergroup, u.displaygroup, u.avatar
		FROM ".TABLE_PREFIX."thx th
		JOIN ".TABLE_PREFIX."users u
		ON th.adduid=u.uid
		WHERE th.pid='{$post[pid]}' AND th.adduid ='{$thx_user}'
		ORDER BY th.time ASC"
	);

	while($record = $db->fetch_array($query))
	{
	if($record['adduid'] == $mybb->user['uid'])
	{
	   $msg = "$1";
	   eval("\$caja = \"".$templates->get("thanks_unhide_tag",1,0)."\";");		  
       $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);
	}
	else
	{
		$msg = $lang->thx_hide_text;  
	    eval("\$caja = \"".$templates->get("thanks_hide_tag",1,0)."\";");		 
        $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);
	}
    $done = true;
    }
		$msg = $lang->thx_hide_text;  
	    eval("\$caja = \"".$templates->get("thanks_hide_tag",1,0)."\";");		 
        $message = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is",$caja,$message);
		}
	}
}

function thx_quote(&$quoted_post)
{
    global $mybb, $session, $templates, $lang, $hide_tag;

		if ($mybb->settings['thx_active'] == '0' || $mybb->settings['thx_hidesystem'] == '0')
        {
          return false;
        }
        else if ($mybb->settings['thx_hidesystem'] == 1){
		  $hide_tag = $mybb->settings['thx_hidesystem_tag'];	
          $quoted_post['message'] = preg_replace("#\[$hide_tag\](.*?)\[/$hide_tag\]#is","", $quoted_post['message']);
        }
}

function thx(&$post)
{
	global $db, $mybb, $lang ,$session, $theme, $altbg, $templates, $thx_cache, $thx_counter , $forum, $message;
	
	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}
	
    $thx_forum_notgid = explode(',', $mybb->settings['thx_hidesystem_notgid']);
	if(in_array($mybb->user['usergroup'], $thx_forum_notgid) && THIS_SCRIPT == "showthread.php"){	
		return false;
	}

	$lang->load("thx", false, true);
	$thx_list = "";
	
	if($b = $post['pthx'])
	{
		$thx_list = build_thank($post['pid'], $b);
	}
	else
	{
		$thx_list = "You don't used thanks button !!!";
	}
		
	if($mybb->settings['thx_counter'] == 1){
	$count = (int)$post['pthx'];
	if ($count == 0){$count="<a href=\"javascript:void(0)\" onclick=\"MyBB.popupWindow('{$thx_link}?action=thanks_list&amp;pid={$post['pid']}&amp;my_post_key={$mybb->post_code}', null, true); return false;\"><span id=\"counter{$post['pid']}\"><span class=\"neutral_thx\">".$count."</span></span></a>";}
	else if ($count >= 1){$count="<a href=\"javascript:void(0)\" onclick=\"MyBB.popupWindow('{$thx_link}?action=thanks_list&amp;pid={$post['pid']}&amp;my_post_key={$mybb->post_code}', null, true); return false;\"><span id=\"counter{$post['pid']}\"><span class=\"good_thx\"> ".$count." </span></span></a>";}
	else {$count="<a href=\"javascript:void(0)\" onclick=\"MyBB.popupWindow('{$thx_link}?action=thanks_list&amp;pid={$post['pid']}&amp;my_post_key={$mybb->post_code}', null, true); return false;\"><span id=\"counter{$post['pid']}\"><span class=\"bad_thx\"> ".$count." </span></span></a>";}
	}
	else{$count="<span id=\"counter{$post['pid']}\"></span>";}
	$post['thx_counter'] = $count;
	if($mybb->user['uid'] == $post['uid']){
		$post['thanks'] = "";
	}
 	if($mybb->user['uid'] != 0 && $mybb->user['uid'] != $post['uid'])
	{
		$ammount = (int)$mybb->user['thx_ammount'];
		$max_ammount = (int)$mybb->usergroup['thx_max_ammount'];		
		if($mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
			$post['button_rep'] = "";
		}
		if(!$b){
			// Verify if AJAX enabled for MyBB
			if($mybb->settings['use_xmlhttprequest'] == 1){
				$post['thanks'] = "<a id=\"add_thx{$post['pid']}\" href=\"showthread.php?action=thank&amp;tid={$post['tid']}&amp;pid={$post['pid']}\">
			 <span class=\"thx_buttons\" id=\"sp_{$post['pid']}\"><span class=\"gracias\"> {$lang->thx_button_add}</span></span></a>";
				if($mybb->settings['thx_del'] == 1){
					$post['thanks'] .= "<a style=\"display: none;\" id=\"del_thx{$post['pid']}\" href=\"showthread.php?action=remove_thank&amp;tid={$post['tid']}&amp;pid={$post['pid']}\">					
				<span class=\"thx_buttons\" id=\"sp_{$post['pid']}\"><span class=\"egracias\"> {$lang->thx_button_del}</span></span></a>";
				}
			}
			else{
				$post['thanks'] = "<a id=\"a{$post['pid']}\" href=\"showthread.php?action=thank&amp;tid={$post['tid']}&amp;pid={$post['pid']}\">
			<span class=\"thx_buttons\" id=\"sp_{$post['pid']}\"><span class=\"gracias\"> {$lang->thx_button_add}</span></span></a>";
			}	
		}
		else if($mybb->settings['thx_del'] == 1){
			// Verify if AJAX enabled for MyBB
			if($mybb->settings['use_xmlhttprequest'] == 1){		
			$post['thanks'] = "<a id=\"del_thx{$post['pid']}\" href=\"showthread.php?action=remove_thank&amp;tid={$post['tid']}&amp;pid={$post['pid']}\">					
		<span class=\"thx_buttons\" id=\"sp_{$post['pid']}\"><span class=\"egracias\"> {$lang->thx_button_del}</span></span></a>";	 		
			$post['thanks'] .= "<a style=\"display: none;\" id=\"add_thx{$post['pid']}\" href=\"showthread.php?action=thank&amp;tid={$post['tid']}&amp;pid={$post['pid']}\">
		 <span class=\"thx_buttons\" id=\"sp_{$post['pid']}\"><span class=\"gracias\"> {$lang->thx_button_add}</span></span></a>";		
			}
			else{
			$post['thanks'] = "<a id=\"a{$post['pid']}\" href=\"showthread.php?action=remove_thank&amp;tid={$post['tid']}&amp;pid={$post['pid']}\">
		<span class=\"thx_buttons\" id=\"sp_{$post['pid']}\"><span class=\"egracias\"> {$lang->thx_button_del}</span></span></a>";	 
			}			
		}		
		else{
			$post['thanks'] = "";
		}
		if($mybb->settings['thx_limit'] == 1){
			if($ammount > $max_ammount){		
				$post['thanks'] = "<img src=\"images/thx/mal.png\" width=\"20\" height=\"20\" alt=\"thx per day exceed\" />";
			}
		}			
	}

	$thx_pid = $post['pid'];
	
	if($mybb->settings['thx_count'] == "1")
	{
		$protect = "&my_post_key={$mybb->post_code}";	
		$post['thanks_count'] = $lang->sprintf($lang->thx_thank_count, $post['thx'], $post['uid'].$protect, $post['pid']) . "<br />";
		$post['thanked_count'] = $lang->sprintf($lang->thx_thanked_count, $post['thxcount'], $post['uid'].$protect, $post['pid']) . "<br />";
	}
	else if ($mybb->settings['thx_count'] == "0"){
		$post['thanks_count'] = "<span id=\"thx_thanked_{$post['pid']}\" style=\"display:none\"></span>";
		$post['thanked_count'] = "<span id=\"thx_thanks_{$post['pid']}\" style=\"display:none\"></span>";
	}
}

function thx_memprofile()
{
	global $db, $mybb, $lang, $session, $memprofile, $cache, $templates, $ammount, $max_ammount;
	
    if ($mybb->settings['thx_active'] == 0 || !empty($session->is_spider))
    {
        return false;
    }

    $thx_forum_notgid = explode(',', $mybb->settings['thx_hidesystem_notgid']);
	if(in_array($mybb->user['usergroup'], $thx_forum_notgid)){	
		return false;
	}
		$lang->load("thx", false, true);
	
		$memprofile['thx_info2'] = "";
		$protect = "&my_post_key={$mybb->post_code}";	
		$memprofile['thanks_count'] = $lang->sprintf($lang->thx_thank_count, $memprofile['thx'], $memprofile['uid'].$protect, $memprofile['pid']);
		$memprofile['thanked_count'] = $lang->sprintf($lang->thx_thanked_count, $memprofile['thxcount'], $memprofile['uid'].$protect, $memprofile['pid']);
		$memprofile['thx_info'] = "<br />" .$memprofile['thanks_count'] . "<br />" . $memprofile['thanked_count'];
		$memprofile['thx_detailed_info'] = $lang->sprintf($lang->thx_thank_details, $memprofile['thxcount'], $memprofile['thxpost'],$memprofile['thx']);	
		$ammount = (int)$mybb->user['thx_ammount'];
		$max_ammount = (int)$mybb->usergroup['thx_max_ammount'];		
		if($mybb->settings['thx_limit'] == 1 && $memprofile['uid'] == $mybb->user['uid']){
		$memprofile['thx_info2'] = $lang->sprintf($lang->thx_thank_details_extra, $ammount, $max_ammount);
		}		
		eval("\$memprofile['thx_details'] .= \"".$templates->get("thanks_memprofile")."\";");		
		
}

// Sending the alert to db
function thx_recordAlertThanks()
{
	global $db, $mybb, $alert, $post;
	if(!$mybb->settings['thx_reputation'] == 2 || !$mybb->settings['thx_reputation'] == 4 || !$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}

	$uid = (int)$post['uid'];
	$tid = (int)$post['tid'];
	$pid = (int)$post['pid'];
	$subject = htmlspecialchars_uni($post['subject']);
	$fid = (int)$post['fid'];

    $alertType = MybbStuff_MyAlerts_AlertTypeManager::getInstance()->getByCode('thanks');
	
    if(isset($alertType) && $alertType->getEnabled()){
		$alert = new MybbStuff_MyAlerts_Entity_Alert($uid, $alertType, $pid, $mybb->user['uid']);
			$alert->setExtraDetails(
			array(
				'tid' 		=> $tid,
				'pid'		=> $pid,
				't_subject' => $subject,
				'fid'		=> $fid
			)); 
			MybbStuff_MyAlerts_AlertManager::getInstance()->addAlert($alert);
	}
}

 // Alert formatter for my custom alerts.
if(class_exists("MybbStuff_MyAlerts_Formatter_AbstractFormatter")){
	global $mybb;
	if($mybb->settings['thx_reputation'] == 2 || $mybb->settings['thx_reputation'] == 4){
	class ThanksAlertFormatter extends MybbStuff_MyAlerts_Formatter_AbstractFormatter{
		public function formatAlert(MybbStuff_MyAlerts_Entity_Alert $alert, array $outputAlert)
		{
        $alertContent = $alert->getExtraDetails();
        $postLink = $this->buildShowLink($alert);
		
			return $this->lang->sprintf(
				$this->lang->thanks_alert,
				$outputAlert['from_user'],
				htmlspecialchars_uni($alertContent['t_subject'])
			);
		}

		public function init()
		{
			if (!$this->lang->thx) {
				$this->lang->load('thx');
			}
		}

		public function buildShowLink(MybbStuff_MyAlerts_Entity_Alert $alert)
		{
        $alertContent = $alert->getExtraDetails();
        $postLink = $this->mybb->settings['bburl'] . '/' . get_post_link((int)$alertContent['pid'], (int)$alertContent['tid']).'#pid'.(int)$alertContent['pid'];              

        return $postLink;
		}
	}
	}
}	

function do_action()
{
	global $mybb, $db, $lang, $theme, $templates, $count, $forum, $thread, $post, $attachcache, $parser, $pid,$tid,$ammount, $max_ammount;

	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}

	if(($mybb->input['action'] != "thankyou"  &&  $mybb->input['action'] != "remove_thankyou") || $mybb->request_method != "post")
	{
		return false;
	}
	
    $thx_forum_notgid = explode(',', $mybb->settings['thx_hidesystem_notgid']);
	if(in_array($mybb->user['usergroup'], $thx_forum_notgid) && THIS_SCRIPT == "showthread.php"){
		return false;
	}
	
	$lang->load("thx", false, true);	
	
	$ammount = (int)$mybb->user['thx_ammount'];
	$max_ammount = (int)$mybb->usergroup['thx_max_ammount'];	
	if($mybb->settings['thx_limit'] == 1){	
		// if you get max thanks per day get an error...
		if($ammount > $max_ammount){
			$error = $lang->sprintf($lang->thx_exceed, $max_ammount);
			xmlhttp_error($error);
			exit;
		}
	}
	
	// Fetch the post from the database.
	$post = get_post($mybb->get_input('pid', 1));

	// No result, die.
	if(!$post)
	{
		xmlhttp_error($lang->post_doesnt_exist);
		exit;		
	}

	$pid = (int)$mybb->input['pid'];
	$tid = (int)$mybb->input['tid'];
	
    if(!verify_post_check($mybb->input['my_post_key'])){
		xmlhttp_error($lang>thx_cant_thank);
		exit;
	}
	
	if ($mybb->input['action'] == "thankyou")
	{
		do_thank($pid);
		if($mybb->settings['thx_counter'] == "1"){
			$count = (int)$post['pthx'] + 1;
		}
		if($mybb->settings['thx_reputation'] == 2 || $mybb->settings['thx_reputation'] == 4){
			thx_recordAlertThanks();
		}
	}
	else if($mybb->settings['thx_del'] == "1")
	{
		del_thank($pid);
		if($mybb->settings['thx_counter'] == "1"){
			$count = (int)$post['pthx'] - 1;
		}
	}	

		if($mybb->settings['thx_count'] == 1){
			$query = $db->query("
				SELECT uid, thxcount
				FROM ".TABLE_PREFIX."users
				WHERE uid='".(int)$post['uid']."'
				LIMIT 1");
			while($thx = $db->fetch_array($query))
			{
				$thxcount = (int)$thx['thxcount'];
			}	
		}
		else if($mybb->settings['thx_count'] == "0"){
			$thxcount = "";
		}
		
	$nonead = 0;
	if($mybb->settings['thx_counter'] == "1"){
		if ($count == 0){
			$count="<span class=\"neutral_thx\">".$count."</span>";
		}
		else if ($count >= 1){
			$count="<span class=\"good_thx\">".$count."</span>";
		}
		else if ($count > 0){
			$count="<span class=\"bad_thx\">".$count."</span>";
		}
	}
	else{
		$count="<span id=\"counter{$post['pid']}\"></span>";
	}
	
	$post['thx_counter'] = $count;
	
	require_once MYBB_ROOT."inc/class_parser.php";
	$parser = new postParser;

	$parser_options = array(
		"allow_html" => 0,
		"allow_mycode" => 1,
		"allow_smilies" => 1,
		"allow_imgcode" => 1,
		"allow_videocode" => 1,
		"me_username" => $post['username'],
		"filter_badwords" => 1
	);

	if($post['smilieoff'] == 1)
	{
		$parser_options['allow_smilies'] = 0;
	}

	if($mybb->user['showimages'] != 1 && $mybb->user['uid'] != 0 || $mybb->settings['guestimages'] != 1 && $mybb->user['uid'] == 0)
	{
		$parser_options['allow_imgcode'] = 0;
	}

	if($mybb->user['showvideos'] != 1 && $mybb->user['uid'] != 0 || $mybb->settings['guestvideos'] != 1 && $mybb->user['uid'] == 0)
	{
		$parser_options['allow_videocode'] = 0;
	}
	
	$post['message'] = $parser->parse_message($post['message'], $parser_options);	
	$post = $post['message'];	

	if($mybb->settings['enableattachments'] != 0)
	{
		$query = $db->simple_select("attachments", "*", "pid='{$post['pid']}'");
		while($attachment = $db->fetch_array($query))
		{
			$attachcache[$attachment['pid']][$attachment['aid']] = $attachment;
		}
			require_once MYBB_ROOT."inc/functions_post.php";
			get_post_attachments($post['pid'], $post);
	}
	
	header("Content-type: text/xml; charset={$charset}");

	if(!$mybb->settings['thx_del']){
	$output = "<thankyou>
				<list><![CDATA[{$list}]]></list>
				<thxcount><![CDATA[{$thxcount}]]></thxcount>				
				<count><![CDATA[{$count}]]></count>
				<button><![CDATA[";	
	if($mybb->input['action'] == "thankyou")
	{
		$output .= "";
	}
	else if($mybb->settings['thx_del'] == "1")
	{
		$output .= "<span class=\"gracias\">{$lang->thx_button_add}</span>";
	}	
	$output .= "]]></button>
			    <post><![CDATA[{$post}]]></post>	
				<del>{$mybb->settings['thx_del']}</del>	
			 </thankyou>";
	echo $output;	
	}
	else{
	$output = "<thankyou>
				<list><![CDATA[{$list}]]></list>
				<thxcount><![CDATA[{$thxcount}]]></thxcount>								
				<count><![CDATA[{$count}]]></count>				
				<button><![CDATA[";	
	if($mybb->input['action'] == "thankyou")
	{
		$output .= "<span class=\"egracias\">{$lang->thx_button_del}</span>";
	}
	else if($mybb->settings['thx_del'] == "1")
	{
		$output .= "<span class=\"gracias\">{$lang->thx_button_add}</span>";
	}	
	$output .= "]]></button>
			    <post><![CDATA[{$post}]]></post>	
				<del>{$mybb->settings['thx_del']}</del>	
			 </thankyou>";
	echo $output;
	}
}

function direct_action()
{
	global $mybb, $lang, $tid, $pid;

	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}
	
	if($mybb->input['action'] != "thank"  &&  $mybb->input['action'] != "remove_thank")
	{
		return false;
	}

    $thx_forum_notgid = explode(',', $mybb->settings['thx_hidesystem_notgid']);
	if(in_array($mybb->user['usergroup'], $thx_forum_notgid) && THIS_SCRIPT == "showthread.php"){	
		return false;
	}
	
	$lang->load("thx", false, true);	
	
	$pid = (int)$mybb->input['pid'];
	
	if($mybb->input['action'] == "thank" )
	{
		do_thank($pid);
		if($mybb->settings['thx_reputation'] == 2 || $mybb->settings['thx_reputation'] == 4){
			thx_recordAlertThanks();
		}
	}
	else if($mybb->settings['thx_del'] == "1")
	{
		del_thank($pid);
	}
	
	redirect(get_post_link($pid, $tid)."#pid{$pid}");

}

function build_thank(&$pid, &$is_thx)
{
	global $db, $mybb, $lang;

	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}

	$pid = (int)$pid; 
	$uid = (int)$mybb->user['uid'];
	$is_thx = 0;
	if ($pid == 0 || $pid == ''){$pid == (int)$mybb->input['pid'];}

	$lang->load("thx", false, true);
	
	$query = $db->simple_select("thx", "*", "pid='{$pid}' AND adduid='{$uid}'", array("limit"=>1));
	if($db->num_rows($query) == 1)
	{
		$is_thx = 1;	
		return true;
		exit;
	}
	$db->free_result($query);
	return false;
	exit;
}

// Build thanks list via Modal Boxes
function thanks_list()
{
	global $db, $mybb, $lang, $templates, $entries, $thx_list;

	if(!$mybb->settings['thx_active'] || !empty($session->is_spider) || !$mybb->input['action'] == "thanks_list")
	{
		return false;
	}

	$thx_list = "";	
	
	if($mybb->input['action'] == "thanks_list"){
	
	$pid = (int)$mybb->input['pid']; 
	$post = get_post($pid);
	$lang->load("thx", false, true);	
	$thx_total = 0;
	
	$query = $db->query("SELECT th.txid, th.uid, th.adduid, th.pid, th.time, u.username, u.usergroup, u.displaygroup, u.avatar
		FROM ".TABLE_PREFIX."thx th
		JOIN ".TABLE_PREFIX."users u
		ON th.adduid=u.uid
		WHERE th.pid='{$pid}'
		ORDER BY th.time DESC
		LIMIT 0, 10"
	);

	while($thx = $db->fetch_array($query))
	{
		if(isset($thx['username']))
		{
			$thx['profile_link'] = get_profile_link($thx['adduid']);
			$thx['user_name'] = format_name($thx['username'], $thx['usergroup'], $thx['displaygroup']);
            $thx['avatar'] = htmlspecialchars_uni($thx['avatar']);
            if($thx['avatar'] != '')
            {
				$thx['avatar'] = "<img src=\"{$thx['avatar']}\" class=\"thx_list_avatar\" alt=\"Avatar\">";
            }
            else
            {
				$thx['avatar'] = "<img src=\"images/default_avatar.png\" class=\"thx_list_avatar\" alt=\"Avatar\">";
            }
			if($mybb->settings['thx_hidemode'])
			{			
				$thx['date'] = "&nbsp;";
			}
			else
			{
				$thx['date'] = "<span class=\"smalltext\">(" . my_date($mybb->settings['dateformat'].' '.$mybb->settings['timeformat'], $thx['time']) . ")</span>";
			}
			$thx_total++;
				eval("\$entries .= \"".$templates->get("thanks_postbit_list_entries")."\";");			
		}
		
	}
	$lang->thx_latest_entries = $lang->sprintf($lang->thx_latest_entries,$thx_total);
	eval("\$thx_list = \"".$templates->get("thanks_postbit_list", 1, 0)."\";");	
	echo $thx_list;
	exit;	
	}
}

function do_thank(&$pid)
{
	global $db, $mybb, $lang;
	
	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}
		
	$pid = (int)$pid;
	$lang->load("thx", false, true);	

	$check_query = $db->simple_select("thx", "count(*) as c" ,"adduid='{$mybb->user['uid']}' AND pid='{$pid}'", array("limit"=>"1"));
			
	$tmp=$db->fetch_array($check_query);
	if($tmp['c'] != 0)
	{
		return false;
	}
		
	$check_query = $db->simple_select("posts", "uid", "pid='{$pid}'", array("limit"=>1));
	if($db->num_rows($check_query) == 1)
	{
		
		$tmp=$db->fetch_array($check_query);
		
		if($tmp['uid'] == $mybb->user['uid'])
		{
			return false;
		}		
			
		$database = array (
			"uid" => (int)$tmp['uid'],
			"adduid" => (int)$mybb->user['uid'],
			"pid" => (int)$pid,
			"time" => time()
		);
		$thx_rep = $db->escape_string((int)$mybb->usergroup['thx_rep_points']);
		$time = time();
		$lang->thx_thankyou = $db->escape_string(htmlspecialchars_uni($lang->thx_thankyou));
		$mybb->user['uid'] = (int)$mybb->user['uid'];
		if($mybb->settings['thx_reputation'] == 1 || $mybb->settings['thx_reputation'] == 2){
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx_ammount=thx_ammount+1,thx=thx+1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount+1,thxpost=CASE( SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost+1 ELSE thxpost END WHERE uid='{$database['uid']}' LIMIT 1",					
	        "UPDATE ".TABLE_PREFIX."posts SET pthx=pthx+1 WHERE pid='{$pid}' LIMIT 1",
			);
		}else if($mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx_ammount=thx_ammount+1,thx=thx+1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount+1, reputation = reputation+{$thx_rep},thxpost=CASE( SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost+1 ELSE thxpost END WHERE uid='{$database['uid']}' LIMIT 1",					
	        "UPDATE ".TABLE_PREFIX."posts SET pthx=pthx+1 WHERE pid='{$pid}' LIMIT 1",
            "INSERT INTO ".TABLE_PREFIX."reputation (uid, adduid, pid, reputation, dateline, comments) VALUES ('{$tmp['uid']}', '{$mybb->user['uid']}', '{$pid}', '{$thx_rep}', '{$time}', '{$lang->thx_thankyou}')"
			);
		}else{
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx_ammount=thx_ammount+1,thx=thx+1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount+1, thxpost=CASE( SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost+1 ELSE thxpost END WHERE uid='{$database['uid']}' LIMIT 1",					
	        "UPDATE ".TABLE_PREFIX."posts SET pthx=pthx+1 WHERE pid='{$pid}' LIMIT 1"
			);		
		}				
		
	    unset($tmp);
				  
		foreach($sq as $q)
		{
			$db->query($q);
		}
		$db->insert_query("thx", $database);
	}	
}

function del_thank(&$pid)
{
	global $mybb, $db;

	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}
		
	$pid = (int)$pid;
	if($mybb->settings['thx_del'] != "1")
	{
		return false;
	}

	$check_query = $db->simple_select("thx", "`uid`, `txid`" ,"adduid='{$mybb->user['uid']}' AND pid='$pid'", array("limit"=>"1"));		
	
	if($db->num_rows($check_query))
	{
		$data = $db->fetch_array($check_query);
		$uid = (int)$data['uid'];
		$thxid = (int)$data['txid'];
		unset($data);
		
		$time = time();
		$thx_rep = (int)$mybb->usergroup['thx_rep_points'];
		$mybb->user['uid'] = (int)$mybb->user['uid'];
		
		if($mybb->settings['thx_reputation'] == 1){
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx=thx-1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount-1, thxpost=CASE(SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost-1 ELSE thxpost END WHERE uid='{$uid}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."posts SET pthx=pthx-1 WHERE pid='{$pid}' LIMIT 1"
		);
		$db->delete_query("thx", "txid='{$thxid}'", "1");
	    }else if($mybb->settings['thx_reputation'] == 2){
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx=thx-1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount-1, thxpost=CASE(SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost-1 ELSE thxpost END WHERE uid='{$uid}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."posts SET pthx=pthx-1 WHERE pid='{$pid}' LIMIT 1",
			"DELETE FROM ".TABLE_PREFIX."alerts WHERE from_user_id={$mybb->user['uid']} AND object_id='{$pid}' AND unread=1 LIMIT 1"			
		);
		$db->delete_query("thx", "txid='{$thxid}'", "1");		
	    }else if($mybb->settings['thx_reputation'] == 3){
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx=thx-1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount-1, reputation=reputation-{$thx_rep}, thxpost=CASE(SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost-1 ELSE thxpost END WHERE uid='{$uid}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."posts SET pthx=pthx-1 WHERE pid='{$pid}' LIMIT 1"
		);
		$db->delete_query("reputation", "adduid='{$mybb->user['uid']}' AND pid='{$pid}'");
		$db->delete_query("thx", "txid='{$thxid}'", "1");		
	    }else if($mybb->settings['thx_reputation'] == 4){
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx=thx-1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount-1, reputation=reputation-{$thx_rep}, thxpost=CASE(SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost-1 ELSE thxpost END WHERE uid='{$uid}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."posts SET pthx=pthx-1 WHERE pid='{$pid}' LIMIT 1",
			"DELETE FROM ".TABLE_PREFIX."alerts WHERE from_user_id={$mybb->user['uid']} AND object_id='{$pid}' AND unread=1 LIMIT 1"			
		);
		$db->delete_query("reputation", "adduid='{$mybb->user['uid']}' AND pid='{$pid}'");
		$db->delete_query("thx", "txid='{$thxid}'", "1");		
	    }else{
		$sq = array (
			"UPDATE ".TABLE_PREFIX."users SET thx=thx-1 WHERE uid='{$mybb->user['uid']}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount-1, thxpost=CASE(SELECT COUNT(*) FROM ".TABLE_PREFIX."thx WHERE pid='{$pid}' LIMIT 1) WHEN 0 THEN thxpost-1 ELSE thxpost END WHERE uid='{$uid}' LIMIT 1",
			"UPDATE ".TABLE_PREFIX."posts SET pthx=pthx-1 WHERE pid='{$pid}' LIMIT 1"
		);
		$db->delete_query("thx", "txid='{$thxid}'", "1");
		}
		
		foreach($sq as $q)
		{
			$db->query($q);
		}
	}
}

function deletepost_edit($pid)
{
	global $db;

	if(!$mybb->settings['thx_active'] || !empty($session->is_spider))
	{
		return false;
	}
		
	$pid = (int)$pid;
	$q = $db->simple_select("thx", "uid, adduid", "pid='{$pid}'");
	
	$postnum = $db->num_rows($q);
	if($postnum <= 0)
	{
		return false;
	}
	
	$adduids = array();
	
	while($r = $db->fetch_array($q))
	{
		$uid = (int)$r['uid'];
		$adduids[] = (int)$r['adduid'];
	}
	
	$adduids = implode(", ", $adduids);
	
	$sq = array();
	$sq[] = "UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount-1, thxpost=thxpost-1 WHERE uid='{$uid}'";
	$sq[] = "UPDATE ".TABLE_PREFIX."users SET thx=thx-1 WHERE uid IN ({$adduids})";
	
	foreach($sq as $q)
	{
		$db->query($q);
	}
	
	$db->delete_query("thx", "pid={$pid}", $postnum);	
}

function thx_admin_action(&$action)
{
	$action['recount_thanks'] = array ('active'=>'recount_thanks');
}

function thx_admin_menu(&$sub_menu)
{
    global $db, $lang;
	$lang->load("thx", false, true);	
	
	$sub_menu['45'] = array	(
		'id'	=> 'recount_thanks',
		'title'	=> $db->escape_string($lang->thx_recount),
		'link'	=> 'index.php?module=tools/recount_thanks'
	);
}

function thx_admin_permissions(&$admin_permissions)
{
    global $db,$lang;
	$lang->load("thx", false, true);	
	
	$admin_permissions['recount_thanks'] = $db->escape_string($lang->thx_can_recount);
}

function thx_admin()
{
	global $mybb, $page, $db, $lang;
	require_once MYBB_ROOT.'inc/functions_rebuild.php';
	if($page->active_action != 'recount_thanks')
	{
		return false;
	}

	$lang->load("thx", false, true);	
	
	if($mybb->request_method == "post")
	{
		if(!isset($mybb->input['page']) || (int)$mybb->input['page'] < 1)
		{
			$mybb->input['page'] = 1;
		}
		if(isset($mybb->input['do_recountthanks']))
		{
			if(!(int)$mybb->input['thx_chunk_size'])
			{
				$mybb->input['thx_chunk_size'] = 500;
			}

			do_recount();
		}
		else if(isset($mybb->input['do_recountposts']))
		{
			if(!(int)$mybb->input['post_chunk_size'])
			{
				$mybb->input['post_chunk_size'] = 500;
			}

			do_recount_post();
		}
	}

	$page->add_breadcrumb_item($db->escape_string($lang->thx_recount), "index.php?module=tools/recount_thanks");
	$page->output_header($db->escape_string($lang->thx_recount));

	$sub_tabs['thankyoulike_recount'] = array(
		'title'			=> $db->escape_string($lang->thx_recount_do),
		'link'			=> "index.php?module=tools/recount_thanks",
		'description'	=> $db->escape_string($lang->thx_upgrade_do)
	);

	$page->output_nav_tabs($sub_tabs, 'thankyoulike_recount');

	$form = new Form("index.php?module=tools/recount_thanks", "post");

	$form_container = new FormContainer($db->escape_string($lang->thx_recount));
	$form_container->output_row_header($db->escape_string($lang->thx_recount_task_desc));
	$form_container->output_row_header($db->escape_string($lang->thx_recount_send), array('width' => 50));
	$form_container->output_row_header("&nbsp;");

	$form_container->output_cell("<label>".$db->escape_string($lang->thx_recount_update)."</label>
	<div class=\"description\">".$db->escape_string($lang->thx_recount_update_desc)."</div>");
	$form_container->output_cell($form->generate_text_box("thx_chunk_size", 100, array('style' => 'width: 150px;')));
	$form_container->output_cell($form->generate_submit_button($db->escape_string($lang->thx_recount_update_button), array("name" => "do_recountthanks")));
	$form_container->construct_row();

	$form_container->output_cell("<label>".$db->escape_string($lang->thx_counter_update)."</label>
	<div class=\"description\">".$db->escape_string($lang->thx_counter_update_desc).".</div>");
	$form_container->output_cell($form->generate_text_box("post_chunk_size", 500, array('style' => 'width: 150px;')));
	$form_container->output_cell($form->generate_submit_button($db->escape_string($lang->thx_recount_update_button), array("name" => "do_recountposts")));
	$form_container->construct_row();

	$form_container->end();

	$form->end();

	$page->output_footer();

	exit;
}

function do_recount()
{
	global $db, $mybb, $lang;

	$lang->load("thx", false, true);	
	
	$cur_page = (int)$mybb->input['page'];
	$per_page = (int)$mybb->input['thx_chunk_size'];
	$start = ($cur_page-1) * $per_page;
	$end = $start + $per_page;

	if ($cur_page == 1)
	{
		$db->write_query("UPDATE ".TABLE_PREFIX."users SET thx='0', thxcount='0'");
		$db->write_query("UPDATE ".TABLE_PREFIX."posts SET pthx='0'");
	}

	$query = $db->simple_select("thx", "COUNT(txid) AS thx_count");
	$thx_count = $db->fetch_field($query, 'thx_count');

	$query = $db->query("
		SELECT uid, adduid, pid
		FROM ".TABLE_PREFIX."thx
		ORDER BY time ASC
		LIMIT $start, $per_page
	");

	$post_thx = array();
	$user_thx = array();
	$user_thx_to = array();

	while($thx = $db->fetch_array($query))
	{
		if($post_thx[$thx['pid']])
		{
			$post_thx[$thx['pid']]++;
		}
		else
		{
			$post_thx[$thx['pid']] = 1;
		}
		if($user_thx[$thx['adduid']])
		{
			$user_thx[$thx['adduid']]++;
		}
		else
		{
			$user_thx[$thx['adduid']] = 1;
		}
		if($user_thx_to[$thx['uid']])
		{
			$user_thx_to[$thx['uid']]++;
		}
		else
		{
			$user_thx_to[$thx['uid']] = 1;
		}
	}

	if(is_array($post_thx))
	{
		foreach($post_thx as $pid => $change)
		{
			$db->write_query("UPDATE ".TABLE_PREFIX."posts SET pthx=pthx+$change WHERE pid='$pid'");
		}
	}
	if(is_array($user_thx))
	{
		foreach($user_thx as $adduid => $change)
		{
			$db->write_query("UPDATE ".TABLE_PREFIX."users SET thx=thx+$change WHERE uid='$adduid'");
		}
	}
	if(is_array($user_thx_to))
	{
		foreach($user_thx_to as $uid => $change)
		{
			$db->write_query("UPDATE ".TABLE_PREFIX."users SET thxcount=thxcount+$change WHERE uid='$uid'");
		}
	}
	my_check_proceed($thx_count, $end, $cur_page+1, $per_page, "thx_chunk_size", "do_recountthanks", $db->escape_string($lang->thx_update_psuccess));
}

function do_recount_post()
{
	global $db, $mybb, $lang;

	$cur_page = (int)$mybb->input['page'];
	$per_page = (int)$mybb->input['post_chunk_size'];
	$start = ($cur_page-1) * $per_page;
	$end = $start + $per_page;
	$lang->load("thx", false, true);
	
	if ($cur_page == 1)
	{
		$db->write_query("UPDATE ".TABLE_PREFIX."users SET thxpost='0'");
	}

	$query = $db->simple_select("thx", "COUNT(distinct pid) AS post_count");
	$post_count = $db->fetch_field($query, 'post_count');

	$query = $db->query("
		SELECT uid, pid
		FROM ".TABLE_PREFIX."thx
		GROUP BY pid
		ORDER BY pid ASC
		LIMIT $start, $per_page
	");

	while($thx = $db->fetch_array($query))
	{
		$db->write_query("UPDATE ".TABLE_PREFIX."users SET thxpost=thxpost+1 WHERE uid='{$thx['uid']}'");
	}

	my_check_proceed($post_count, $end, $cur_page+1, $per_page, "post_chunk_size", "do_recountposts", $db->escape_string($lang->thx_update_tsuccess));
}

function my_check_proceed($current, $finish, $next_page, $per_page, $name_chunk, $name_submit, $message)
{
	global $db, $page, $lang;
	
	$lang->load("thx", false, true);	

	if($finish >= $current)
	{
		flash_message($message, 'success');
		admin_redirect("index.php?module=tools/recount_thanks");
	}
	else
	{
		$page->output_header();

		$form = new Form("index.php?module=tools/recount_thanks", 'post');
        $total = $current - $finish;
		echo $form->generate_hidden_field("page", $next_page);
		echo $form->generate_hidden_field($name_chunk, $per_page);
		echo $form->generate_hidden_field($name_submit, "Actualizar");
		echo "<div class=\"confirm_action\">\n";
		echo $db->escape_string($lang->thx_confirm_next);
		echo "<br />\n";
		echo "<br />\n";
		echo "<p class=\"buttons\">\n";
		echo $form->generate_submit_button($db->escape_string($lang->thx_confirm_button), array('class' => 'button_yes'));
		echo "</p>\n";
		echo "<div style=\"float: right; color: #424242;\">".$db->escape_string($lang->thx_confirm_page)." {$next_page}\n";
		echo "<br />\n";
		echo $db->escape_string($lang->thx_confirm_elements)." {$total}</div>";
		echo "<br />\n";
	    echo "<br />\n";
		echo "</div>\n";		
		$form->end();
		$page->output_footer();
		exit;
	}
}
function thx_edit_group_tabs(&$tabs)
{
	global $tabs, $mybb, $lang;
	$lang->load("thx", false, true);	
	if($mybb->settings['thx_limit'] == 1 || $mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
		$tabs['thanks'] = $lang->thx_title;
	}
}

function thx_edit_group()
{
	global $run_module, $form_container, $form, $table, $mybb, $lang;
		$lang->load("thx", false, true);	
		if($mybb->settings['thx_limit'] == 1 || $mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
	
	echo "<div id=\"tab_thanks\">";		
		$form_container = new FormContainer($lang->thx_admin_thx_group);
		$thx_options = array();
		if($mybb->settings['thx_limit'] == 1){
				$thx_options[] = $lang->thx_admin_thx_group_opt1 . $form->generate_numeric_field('thx_max_ammount', $mybb->input['thx_max_ammount'], array('id' => 'max_thx_ammount', 'class' => 'field50'));
		}
		if($mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
				$thx_options[] = $lang->thx_admin_thx_group_opt2 . $form->generate_numeric_field('thx_rep_points', $mybb->input['thx_rep_points'], array('id' => 'rep_thx_points', 'class' => 'field50'));		
		}
		$form_container->output_row($lang->thx_system_dnt, '', '<div class="group_settings_bit">'.implode('</div><div class="group_settings_bit">', $thx_options).'</div>');
		$form_container->end();
	echo "</div>";
		}
		
		else{
			return false;
		}

}

function thx_edit_group_do()
{
	global $db, $updated_group, $mybb;
	if($mybb->settings['thx_limit'] == 1 || $mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
		if($mybb->input['gid'] != 1)
		{
			if($mybb->settings['thx_limit'] == 1){
				$updated_group['thx_max_ammount'] = $db->escape_string((int)$mybb->input['thx_max_ammount']);
			}
			if($mybb->settings['thx_reputation'] == 3 || $mybb->settings['thx_reputation'] == 4){
				$updated_group['thx_rep_points'] = $db->escape_string((int)$mybb->input['thx_rep_points']);	
			}
		}
	}
	else{
		return false;
	}	
}

?>
