<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="http://www.fustrate.com/dev/sources/Other/modification.xsl"?>
<!DOCTYPE modification SYSTEM "http://www.simplemachines.org/xml/modification">
<modification xmlns="http://www.simplemachines.org/xml/modification" xmlns:smf="http://www.simplemachines.org/">
	<id>yodaofdarkness:advrep</id>
	<version>0.1.5</version>

	<file name="$boarddir/index.php">
		<operation>
			<search position="before"><![CDATA[
		'reporttm' => array('SendTopic.php', 'ReportToModerator'),]]></search>
			<add><![CDATA[
		'reputation' => array('Karma.php', 'SendKarma'),]]></add>
		</operation>
	</file>

	<file name="$themedir/Display.template.php">
		<operation>
			<search position="before"><![CDATA[<a name="top"></a>]]></search>
			<add><![CDATA[
<span id="reputation_menu" style="visibility: hidden; display: none;">
	<table class="bordercolor" cellpadding="4" cellspacing="1" style="width: 100%;">
		<tr class="titlebg">
			<td height="22">', $txt['karma_title'], '</td>
		</tr>
		<tr class="catbg">
			<td height="22">', $txt['karma_add_to'], ': <span id="reputation_name">&nbsp;</span></td>
		</tr>
		<tr class="windowbg2">
			<td>
				<fieldset>
					<legend>', $txt['karma_your_opinion'], '</legend>
					<form id="reputation_form" name="reputation_form" action="', $scripturl, '?action=modifykarma" method="post" accept-charset="', $context['character_set'], '" class="reputation_form">
						<input type="radio" name="type" value="agree"', !$context['can_pos_rep'] ? ' disabled="disabled"' : ' checked="checked"', ' /> ', $txt['karma_agree'], '
						<input type="radio" name="type" value="disagree"', !$context['can_neg_rep'] ? ' disabled="disabled"' : !$context['can_pos_rep'] ? ' checked="checked"' : '', ' /> ', $txt['karma_disagree'], '
						<span id="reputation_fields">&nbsp;</span>
						<br />
						', $txt['comment'], ': <input type="text" name="reputation_comment" /><br />
						<br />
						<input type="submit" value="', $txt['submit'], '" />
						<input type="hidden" name="topic" value="', $context['current_topic'], '.', $context['start'], '" />
						<input type="hidden" name="sc" value="', $context['session_id'], '" />
					</form>
				</fieldset>
			</td>
		</tr>
	</table>
</span>]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
			// Is karma display enabled?  Total or +/-?
			if ($modSettings['karmaMode'] == '1')
				echo '
								<br />
								', $modSettings['karmaLabel'], ' ', $message['member']['karma']['good'] - $message['member']['karma']['bad'], '<br />';
			elseif ($modSettings['karmaMode'] == '2')
				echo '
								<br />
								', $modSettings['karmaLabel'], ' +', $message['member']['karma']['good'], '/-', $message['member']['karma']['bad'], '<br />';

			// Is this user allowed to modify this member's karma?
			if ($message['member']['karma']['allow'])
				echo '
								<a href="', $scripturl, '?action=modifykarma;sa=applaud;uid=', $message['member']['id'], ';topic=', $context['current_topic'], '.' . $context['start'], ';m=', $message['id'], ';sesc=', $context['session_id'], '">', $modSettings['karmaApplaudLabel'], '</a>
								<a href="', $scripturl, '?action=modifykarma;sa=smite;uid=', $message['member']['id'], ';topic=', $context['current_topic'], '.', $context['start'], ';m=', $message['id'], ';sesc=', $context['session_id'], '">', $modSettings['karmaSmiteLabel'], '</a><br />';]]></search>
			<add><![CDATA[
			// Is karma display enabled?
			if ($modSettings['karmaMode'] != '0'){
				echo '
								<br />
								', $txt['karma_power'], ': ', $message['member']['karma']['power'], '<br />
								<span class="repbars">
									';

				foreach($message['member']['karma']['bars'] as $karma_bar)
					echo '<img src="', $settings['images_url'], '/karma', $karma_bar['type'], '.gif" title="', $message['member']['name'], ' ', $karma_bar['desc'], '" alt="', $message['member']['name'], ' ', $karma_bar['desc'], '" />';

				echo '
								</span>
								<br />';
			}]]></add>
		</operation>

		<operation>
			<search position="after"><![CDATA[
				// Since we know this person isn't a guest, you *can* message them.
				if ($context['can_send_pm'])
					echo '
								<a href="', $scripturl, '?action=pm;sa=send;u=', $message['member']['id'], '" title="', $message['member']['online']['label'], '">', $settings['use_image_buttons'] ? '<img src="' . $settings['images_url'] . '/im_' . ($message['member']['online']['is_online'] ? 'on' : 'off') . '.gif" alt="' . $message['member']['online']['label'] . '" border="0" />' : $message['member']['online']['label'], '</a>';]]></search>
			<add><![CDATA[
				// Is this user allowed to modify this member's karma?
				if (($context['can_pos_rep'] || $context['can_neg_rep']) && $message['can_send_karma'] && ($context['user']['id'] != $message['member']['id']))
					echo '
								<span style="visibility: hidden; display: none;" id="reputation_form_', $message['id'], '">
									<input type="hidden" name="uid" value="', $message['member']['id'], '" />
									<input type="hidden" name="m" value="', $message['id'], '" />
								</span>
								<a id="repicon" onclick="reputationForm(\'reputation_form_', $message['id'], '\', \'', $message['member']['name'], '\', this, event); return false;" href="', $scripturl, '?action=reputation;uid=', $message['member']['id'], ';m=', $message['id'], ';topic=', $context['current_topic'], '.', $context['start'], ';sesc=', $context['session_id'], '"><img src="', $settings['images_url'], '/karma.gif" alt="', $txt['add_karma'], '" title="', $txt['add_karma'], '" /></a>';
]]></add>
		</operation>
	</file>

	<file name="$themedir/PersonalMessage.template.php">
		<operation>
			<search position="replace"><![CDATA[
				// Is karma display enabled? Total or +/-?
				if ($modSettings['karmaMode'] == '1')
					echo '
									<br />
									', $modSettings['karmaLabel'], ' ', $message['member']['karma']['good'] - $message['member']['karma']['bad'], '<br />';
				elseif ($modSettings['karmaMode'] == '2')
					echo '
									<br />
									', $modSettings['karmaLabel'], ' +', $message['member']['karma']['good'], '/-', $message['member']['karma']['bad'], '<br />';

				// Is this user allowed to modify this member's karma?
				if ($message['member']['karma']['allow'])
					echo '
									<a href="', $scripturl, '?action=modifykarma;sa=applaud;uid=', $message['member']['id'], ';f=', $context['folder'], ';start=', $context['start'], ';', $context['current_label_id'] != -1 ? ';l=' . $context['current_label_id'] : '', ';pm=', $message['id'], ';sesc=', $context['session_id'], '">', $modSettings['karmaApplaudLabel'], '</a> <a href="', $scripturl, '?action=modifykarma;sa=smite;uid=', $message['member']['id'], ';f=', $context['folder'], ';start=', $context['start'], ';', $context['current_label_id'] != -1 ? ';l=' . $context['current_label_id'] : '', ';pm=', $message['id'], ';sesc=', $context['session_id'], '">', $modSettings['karmaSmiteLabel'], '</a><br />';]]></search>
			<add><![CDATA[
				// Karma removed by the Advanced Reputation System - who ever though karma in PMs was a good decision?]]></add>
		</operation>
	</file>

	<file name="$themedir/Profile.template.php">
		<operation>
			<search position="replace"><![CDATA[
	// If karma enabled show the members karma.
	if ($modSettings['karmaMode'] == '1')
		echo '
				<tr>
					<td>
						<b>', $modSettings['karmaLabel'], ' </b>
					</td><td>
						', ($context['member']['karma']['good'] - $context['member']['karma']['bad']), '
					</td>
				</tr>';
	elseif ($modSettings['karmaMode'] == '2')
		echo '
				<tr>
					<td>
						<b>', $modSettings['karmaLabel'], ' </b>
					</td><td>
						+', $context['member']['karma']['good'], '/-', $context['member']['karma']['bad'], '
					</td>
				</tr>';]]></search>
			<add><![CDATA[
	// If karma enabled show the members karma.
	if ($modSettings['karmaMode'] != '0')
		echo '
				<tr>
					<td>
						<b>', $modSettings['karmaLabel'], ' </b>
					</td><td>
						', ($context['member']['karma']['good'] - $context['member']['karma']['bad']), '
					</td>
				</tr>';]]></add>
		</operation>

		<operation>
			<search position="after"><![CDATA[
	// If karma is enabled let the admin edit it...]]></search>
			<add><![CDATA[
	// Can you disable your own karma display?
	if (!empty($modSettings['karmaMode']) && $context['allow_disable_karma'])
	{
		echo '
							<tr>
								<td colspan="2"><hr width="100%" size="1" class="hrcolor" /></td>
							</tr><tr>
								<td valign="top"><b>', $txt['user_disable_karma'], '</b></td>
								<td><input type="hidden" name="karma_disabled" value="0" /><input type="checkbox" name="karma_disabled"', $context['member']['karma']['disabled'] ? ' checked="checked"' : '', ' value="1" class="check" /></td>
							</tr>';
	}
]]></add>
		</operation>

		<operation>
			<search position="end" />
			<add><![CDATA[
// Shows recent reputation actions, and allows moderators to moderate them.
function template_reputation()
{
	global $context, $settings, $options, $scripturl, $modSettings, $txt, $ID_MEMBER;

	// If they can delete karma actions, start the form
	if($context['can_delete_karma'] && !empty($context['member']['karma_actions']))
		echo '
<form action="', $scripturl, '?action=profile;u=', $ID_MEMBER, ';sa=reputation" method="post" accept-charset="', $context['character_set'], '">
<input type="hidden" name="uid" value="', $ID_MEMBER, '" />
<input type="hidden" name="sc" value="', $context['session_id'], '" />';

	echo '
<table width="80%" border="0" cellpadding="4" cellspacing="1" align="center" class="bordercolor">
	<tr class="titlebg">
		<td colspan="', $context['can_delete_karma'] ? 7 : 6, '">
			', $txt['karma_latest_title'], '
		</td>
	</tr>';

	if(empty($context['member']['karma_actions']))
				echo '
	<tr class="windowbg">
		<td colspan="', $context['can_delete_karma'] ? 7 : 6, '">
			', $txt['no_reputation_actions'], '
		</td>
	</tr>';
	else {
		echo '
	<tr class="catbg2">
		<td width="1%">
			&nbsp;
		</td>
		<td width="', $context['can_delete_karma'] ? '29' : '30', '%">
			', $txt[118], '
		</td>
		<td width="15%">
			', $txt[317], '
		</td>
		<td width="30%">
			', $txt['comment'], '
		</td>
		<td width="12%">
			', $txt[324], '
		</td>
		<td width="12%">
			', $txt[318], '
		</td>', $context['can_delete_karma'] ? '
		<td width="1%">
			<input type="checkbox" onclick="invertAll(this, this.form);" class="check" />
		</td>' : '', '
	</tr>';
		foreach($context['member']['karma_actions'] as $karma)
			echo '
	<tr class="windowbg">
		<td align="center">
			<img src="', $settings['images_url'], '/', $karma['action_type'], '_basic.gif" />
		</td>
		<td>
			<a href="', $scripturl, '?topic=', $karma['topic_href'], '">', $karma['topic_title'], '</a>
		</td>
		<td>
			', $karma['time'], '
		</td>
		<td>
			', $karma['comment'], '
		</td>
		<td>
			', $karma['target'], '
		</td>
		<td>
			', $karma['executor'], '
		</td>', $context['can_delete_karma'] ? '
		<td align="center">
			<input type="checkbox" name="deleteBoxes[]" value="' . $karma['delete_value'] . '" class="check" />
		</td>' : '', '
	</tr>';

		echo '
	<tr class="catbg2">
		<td colspan="', $context['can_delete_karma'] ? 7 : 6, '">
			', $txt[139], ': ', $context['page_index'], '
		</td>
	</tr>';
	}
	// And close off the table.
	echo '
</table>';

	// If they can delete karma actions, end the old
	if($context['can_delete_karma'] && !empty($context['member']['karma_actions']))
		echo '
<br />
<div width="100%" align="center">
	<input type="submit" name="del_selected" value="', $txt['quickmod_delete_selected'], '" style="font-weight: normal;" onclick="if (!confirm(\'', $txt['quickmod_confirm'], '\')) return false;" /></span>
</div>
</form>';
}]]></add>
		</operation>
	</file>

	<file name="$themedir/Stats.template.php">
		<operation>
			<search position="after"><![CDATA[<tr>
				<td class="catbg" colspan="2" width="50%"><b>', $txt['smf_stats_11'], '</b></td>]]></search>
			<add><![CDATA[';

	if(!empty($modSettings['karmaMode'])){
		echo '
			<tr>
				<td class="catbg" colspan="2" width="50%"><b>', $txt['smf_stats_17'], '</b></td>
				<td class="catbg" colspan="2" width="50%"><b>', $txt['smf_stats_18'], '</b></td>
			</tr><tr>
				<td class="windowbg" width="20" valign="middle" align="center"><img src="', $settings['images_url'], '/stats_posters.gif" width="20" height="20" alt="" /></td>
				<td class="windowbg2" width="50%" valign="top">
					<table border="0" cellpadding="1" cellspacing="0" width="100%">';
		if(!empty($context['reputation_best']))
			foreach ($context['reputation_best'] as $member)
				echo '
						<tr>
							<td width="60%" valign="top">', $member['link'], '</td>
							<td width="20%" align="left" valign="top"><span class="repbars">', $member['reputation_bars'], '</span></td>
							<td width="20%" align="right" valign="top" nowrap="nowrap">', $member['amount'], '</td>
						</tr>';
		echo '
					</table>
				</td>
				<td class="windowbg" width="20" valign="middle" align="center" nowrap="nowrap"><img src="', $settings['images_url'], '/stats_posters.gif" width="20" height="20" alt="" /></td>
				<td class="windowbg2" width="50%" valign="top">
					<table border="0" cellpadding="1" cellspacing="0" width="100%">';
		if(!empty($context['reputation_worst']))
			foreach ($context['reputation_worst'] as $member)
				echo '
						<tr>
							<td width="60%" valign="top">', $member['link'], '</td>
							<td width="20%" align="left" valign="top"><span class="repbars">', $member['reputation_bars'], '</span></td>
							<td width="20%" align="right" valign="top" nowrap="nowrap">', $member['amount'], '</td>
						</tr>';
		echo '
					</table>
				</td>
			</tr>';
	}

	echo '
			]]></add>
		</operation>
	</file>

	<file name="$themedir/script.js">
		<operation>
			<search position="end" />
			<add><![CDATA[

var disappeardelay = 30 * 1000; // karma box hide display time, in milliseconds
var vertical_offset = "0px"; // vertical offset of karma box from image
var horizontal_offset = "-3px"; // horizontal offset of karma box from image

function getposOffset(what, offsettype){
	var totaloffset = (offsettype=="left") ? what.offsetLeft : what.offsetTop;
	var parentEl = what.offsetParent;
	while (parentEl!=null){
		totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
		parentEl = parentEl.offsetParent;
	}
	return totaloffset;
}

function showhiderep(obj, e){
	rep_box.style.left = rep_box.style.top = -500;
	rep_box.widthobj = rep_box.style;
	rep_box.widthobj.width = '300px';
	if (obj.visibility == "visible"){
		obj.visibility = "hidden";
		obj.display = "none";
	} else {
		obj.visibility = "visible";
		obj.display = "block";
	}
}

function reputationForm(rep_contents, member_name, obj, e){
	if(window.event)
		event.cancelBubble = true;
	else if(e.stopPropagation)
		e.stopPropagation();
	clearhidebox();
	rep_box = document.getElementById("reputation_menu");
	rep_fields = document.getElementById("reputation_fields");
	rep_name = document.getElementById("reputation_name");
	setInnerHTML(rep_fields, getInnerHTML(document.getElementById(rep_contents)));
	setInnerHTML(rep_name, member_name);

	showhiderep(rep_box.style, e);
	rep_box.x = getposOffset(obj, "left");
	rep_box.y = getposOffset(obj, "top");
	rep_box.style.left = rep_box.x + "px";
	rep_box.style.top = rep_box.y + obj.offsetHeight + "px";

	delayhidebox();
}

function hidebox(e){
	if(typeof rep_box != "undefined")
		rep_box.style.visibility = "hidden";
}

function delayhidebox(){
	delayhide = setTimeout("hidebox()", disappeardelay);
}

function clearhidebox(){
	if(typeof delayhide != "undefined")
		clearTimeout(delayhide);
}]]></add>
		</operation>
	</file>

	<file name="$themedir/style.css">
		<operation>
			<search position="end" />
			<add><![CDATA[
.repbars img
{
	padding: 0 1px 0 0;
}

#reputation_menu{
	position: absolute;
	border: 1px solid black;
	z-index: 100;
}]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Admin.php">
		<operation>
			<search position="replace"><![CDATA[
		// Clear out the karma actions.
		db_query("
			DELETE FROM {$db_prefix}log_karma", __FILE__, __LINE__);]]></search>
			<add><![CDATA[
// Advanced Reputation System - Never clear out karma logs!
/*
		// Clear out the karma actions.
		db_query("
			DELETE FROM {$db_prefix}log_karma", __FILE__, __LINE__);
*/]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Display.php">
		<operation>
			<search position="before"><![CDATA[
		'can_see_ip' => allowedTo('moderate_forum') || ($message['ID_MEMBER'] == $ID_MEMBER && !empty($ID_MEMBER)),]]></search>
			<add><![CDATA[
		'can_send_karma' => empty($message['is_repped']) && ($ID_MEMBER != $message['ID_MEMBER']),]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
		$messages_request = db_query("
			SELECT
				ID_MSG, icon, subject, posterTime, posterIP, ID_MEMBER, modifiedTime, modifiedName, body,
				smileysEnabled, posterName, posterEmail,
				ID_MSG_MODIFIED < $topicinfo[new_from] AS isRead
			FROM {$db_prefix}messages
			WHERE ID_MSG IN (" . implode(',', $messages) . ")
			ORDER BY ID_MSG" . (empty($options['view_newest_first']) ? '' : ' DESC'), __FILE__, __LINE__);]]></search>
			<add><![CDATA[
		$messages_request = db_query("
			SELECT
				m.ID_MSG, m.icon, m.subject, m.posterTime, m.posterIP, m.ID_MEMBER, m.modifiedTime, m.modifiedName, m.body,
				m.smileysEnabled, m.posterName, m.posterEmail,
				m.ID_MSG_MODIFIED < $topicinfo[new_from] AS isRead, k.message AS is_repped
			FROM {$db_prefix}messages AS m
				LEFT JOIN {$db_prefix}log_karma AS k ON (k.message = m.ID_MSG AND k.ID_EXECUTOR = {$ID_MEMBER})
			WHERE m.ID_MSG IN (" . implode(',', $messages) . ")
			ORDER BY m.ID_MSG" . (empty($options['view_newest_first']) ? '' : ' DESC'), __FILE__, __LINE__);]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
	$context['can_reply'] &= empty($topicinfo['locked']) || allowedTo('moderate_board');]]></search>
			<add><![CDATA[
	$context['can_pos_rep'] = allowedTo('positive_karma');
	$context['can_neg_rep'] = allowedTo('negative_karma');]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Karma.php">
		<operation>
			<search position="end" />
			<add><![CDATA[
// Modify a user's karma, only better than the old one!
function ModifyKarma()
{
	global $modSettings, $txt, $user_info, $ID_MEMBER, $db_prefix;

	// A fix for templates that don't get edited correctly, and still show the old links.
	if(isset($_GET['sa']) && ($_GET['sa'] == 'applaud' || $_GET['sa'] == 'smite'))
		redirectexit('action=reputation;uid=' . $_GET['uid'] . ';m=' . $_GET['m'] . ';topic=' . $_GET['topic'] . ';sesc=' . $_GET[$context['session_id']]);

	// If the mod is disabled, show an error.
	if (empty($modSettings['karmaMode']))
		fatal_lang_error('feature_disabled', true);

	// These _must_ be numbers, no matter what.
	$uid = (int) $_POST['uid'];
	$message_id = (int) $_POST['m'];
	$topic_id = (int) $_POST['topic'];

	// If you're a guest or can't do this, blow you off...
	is_not_guest();
	isAllowedTo('karma_edit');

	checkSession('request');

	// If you don't have enough posts, tough luck.
	// !!! Should this be dropped in favor of post group permissions?  Should this apply to the member you are smiting/applauding?
	if ($user_info['posts'] < $modSettings['karmaMinPosts'])
		fatal_lang_error('smf60', true, array($modSettings['karmaMinPosts']));

	// And you can't modify your own, punk! (use the profile if you need to, admins!)
	if (empty($uid) || $uid == $ID_MEMBER)
		fatal_lang_error('smf61', false);

	// Find their (super)power (and their secret identity)! Can't go into negatives...
	$points = $user_info['karmaGood'] - $user_info['karmaBad'];
	$power = ($points - ($points % $modSettings['karmaBarPower'])) / $modSettings['karmaBarPower'];
	$power = (int) (($power > 0) ? $power : 0);

	// !!! Should use a modSetting for 300
	$comment = (strlen($_POST['reputation_comment']) > 300) ? substr($_POST['reputation_comment'], 0, 300) : $_POST['reputation_comment'];
	
	// I fart in your general direction!
	if (strtolower($comment) == 'your mother was a hamster and your father smelt of elderberries!')
		fatal_error('...and Saint Attila raised the hand grenade up on high, saying, "O Lord, bless this Thy hand grenade that with it Thou mayest blow Thine enemies to tiny bits, in Thy mercy." And the Lord did grin and the people did feast upon the lambs and sloths and carp and anchovies and orangutans and breakfast cereals, and fruit bats and large chu... *ahem* And the Lord spake, saying, "First shalt thou take out the Holy Pin, then shalt thou count to three, no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who being naughty in my sight, shall snuff it." Amen.', false);
	else
		$comment = mysql_real_escape_string($comment);

	//Find the time 24 hours ago... but wait... what if karmaWaitTime is greater than 24?! Bad var name, but who gives a hoot, if it works?
	$yesterday = time() - 86400;
	$longtimeago = time() - (60 * 60 * ($modSettings['karmaWaitTime']));
	$hoursAgo = ($modSettings['karmaWaitTime'] < 24) ? $yesterday : $longtimeago;

	// Applauding or smiting? Don't try to do a cheap javascript injection on me...
	switch ($_POST['type']) {
		case 'agree':
			if(!allowedTo('positive_karma'))
				fatal_lang_error('karma_cant_agree', false);
			$karma_which = 'karmaGood';
			break;
		case 'disagree':
			if(!allowedTo('negative_karma'))
				fatal_lang_error('karma_cant_disagree', false);
			$karma_which = 'karmaBad';
			break;
		default:
			// Should never get here
			fatal_lang_error('karma_choose_action', false);
	}

	// Going in order of permissions... it only gets added if it passes all of the tests!

	// Used up all of their $modSettings['karmaMaxPerDay'] ?
	if (!empty($modSettings['karmaMaxPerDay']) && ($modSettings['karmaMaxPerDay'] > 0))
	{
		// Find out if this user has done this in the past 24 hours.
		$request = db_query("
			SELECT logTime
			FROM {$db_prefix}log_karma
			WHERE ID_EXECUTOR = {$ID_MEMBER}
				AND logTime >= {$hoursAgo}", __FILE__, __LINE__);
		if (mysql_num_rows($request) >= $modSettings['karmaMaxPerDay']){ // but why would they be over?
			mysql_free_result($request);
			fatal_lang_error('karma_maxed_out', false, array($modSettings['karmaMaxPerDay']));
		}

		// They're good on this one :) Continue on to the next test!
		mysql_free_result($request);
	}

	// Haven't waited long enough?
	if (!empty($modSettings['karmaWaitTime']) && (!empty($modSettings['karmaTimeRestrictAdmins']) || !allowedTo('moderate_forum')) && $modSettings['karmaWaitTime'] > 0)
	{
		// Find out if this user has done this in the past $longenough.
		$request = db_query("
			SELECT logTime
			FROM {$db_prefix}log_karma
			WHERE ID_EXECUTOR = {$ID_MEMBER}
				AND logTime >= {$longtimeago}
			LIMIT 1", __FILE__, __LINE__);
		if (mysql_num_rows($request) > 0){
			// Give them approximate minutes until they can, to be nice ;)
			list ($logTime) = mysql_fetch_row($request);
			$logTime_wait = ($logTime + (60 * 60 * $modSettings['karmaWaitTime'])) - time(); // seconds
			$logTime_wait = ($logTime_wait - ($logTime_wait % 60)) / 60; // minutes
			mysql_free_result($request);
			fatal_lang_error('karma_please_wait', false, array($modSettings['karmaWaitTime'], $logTime_wait));
		}

		// They're good on this one :) Continue on to the next test!
		mysql_free_result($request);
	}

	// Need to spread it around a bit? No, not the flu, silly!
	if (!empty($modSettings['karmaSpreadAround']) && ($modSettings['karmaSpreadAround'] > 0))
	{
		// Grab the latest karmaSpreadAround actions - if the target is in there, throw an error!
		$request = db_query("
			SELECT ID_TARGET
			FROM {$db_prefix}log_karma
			WHERE ID_EXECUTOR = {$ID_MEMBER}
			ORDER BY logTime DESC
			LIMIT " . $modSettings['karmaSpreadAround'], __FILE__, __LINE__);
		if (mysql_num_rows($request) > 0)
			while($row = mysql_fetch_assoc($request))
				if($row['ID_TARGET'] == $uid)
					fatal_lang_error('karma_spread_around', false);

		// They're good on this one :) Continue on to the next test!
		mysql_free_result($request);
	}

	// One last test - have they already sent rep to this particular post?
	$request = db_query("
		SELECT logTime
		FROM {$db_prefix}log_karma
		WHERE ID_EXECUTOR = {$ID_MEMBER}
			AND message = {$message_id}
		LIMIT 1", __FILE__, __LINE__);

	if(mysql_num_rows($request) != 0)
		fatal_lang_error('karma_sent_twice', false);

	mysql_free_result($request);

	// Finally! Now do an update

	$request = db_query("
		UPDATE {$db_prefix}members
		SET {$karma_which} = {$karma_which} + {$power}
		WHERE ID_MEMBER = {$uid}", __FILE__, __LINE__);

	if(!$request)
		fatal_lang_error('karma_didnt_update', false);

	$action_type = ($power != 0) ? $karma_which : 'karma_disabled';

	$request = db_query("
		SELECT subject
		FROM {$db_prefix}messages
		WHERE ID_MSG = {$message_id}
		LIMIT 1", __FILE__, __LINE__);
	list ($title) = mysql_fetch_row($request);
	$title = mysql_real_escape_string($title);
	mysql_free_result($request);

	// Log this new action!
	db_query("
		REPLACE INTO {$db_prefix}log_karma
		(`action`, `ID_TARGET`, `ID_EXECUTOR`, `logTime`, `comment`, `action_type`, `message`, `topic`, `title`)
		VALUES
		({$power}, {$uid}, {$ID_MEMBER}, " . time() . ", '{$comment}', '{$action_type}', {$message_id}, {$topic_id}, '{$title}')", __FILE__, __LINE__);

	// Send them back to whence they came!
	redirectexit('topic=' . $_POST['topic'] . '#msg' . $_POST['m']);
}

// For those poor souls without javascript support :(
function SendKarma()
{
	global $modSettings, $user_info, $context, $txt, $ID_MEMBER, $db_prefix;

	// If the mod is disabled, show an error.
	if (empty($modSettings['karmaMode']))
		fatal_lang_error('feature_disabled', true);

	if(!isset($_GET['uid']) && !isset($_GET['m']) && !isset($_GET['topic']))
		return ReputationLog();

	// If you're a guest or can't do this, blow you off...
	is_not_guest();
	isAllowedTo('karma_edit');
	checkSession('request');

	// These _must_ be a number, no matter what.
	$uid = (int) $_GET['uid'];
	$message = (int) $_GET['m'];
	$topic = (int) $_GET['topic'];

	// You can't modify your own, punk! (use the profile if you need to.)
	if (empty($uid) || $uid == $ID_MEMBER)
		fatal_lang_error('smf61', false);

	// If you don't have enough posts, tough luck.
	// !!! Should this be dropped in favor of post group permissions?  Should this apply to the member you are smiting/applauding?
	if ($user_info['posts'] < $modSettings['karmaMinPosts'])
		fatal_lang_error('smf60', true, array($modSettings['karmaMinPosts']));

	$message_request = db_query("
		SELECT *
		FROM {$db_prefix}messages
		WHERE id_msg = {$message}
		LIMIT 1", __FILE__, __LINE__);

	while($row = mysql_fetch_assoc($message_request)){
		$context['message'] = $row;

		$board_request = db_query("
			SELECT *
			FROM {$db_prefix}boards
			WHERE id_board = " . $context['message']['ID_BOARD'], __FILE__, __LINE__);

		$board = mysql_fetch_assoc($board_request);

		// Load the membergroups allowed, and check permissions.
		$board_groups = $board['memberGroups'] == '' ? array() : explode(',', $board['memberGroups']);
		mysql_free_result($board_request);

		// Kick 'em out if they don't have permission to view this topic!
		if (count(array_intersect($user_info['groups'], $board_groups)) == 0 && !$user_info['is_admin'])
			fatal_lang_error('topic_gone', false);

		// Put it in quote tags to make it stand out a little... and because it's a quote.
		$context['message']['body'] = "[quote author={$context['message']['posterName']} link=topic={$context['message']['ID_TOPIC']}.msg{$context['message']['ID_MSG']}#msg{$context['message']['ID_MSG']} date={$context['message']['posterTime']}]{$context['message']['body']}[/quote]";

		// Amish girls gone wild!
		censorText($context['message']['body']);
		censorText($context['message']['subject']);

		// Run BBC interpreter on the message.
		$context['message']['body'] = parse_bbc($context['message']['body'], $context['message']['smileysEnabled'], $context['message']['ID_MSG']);
	}

	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['karma_add_to'];
	$context['topic'] = $topic;
	$context['m'] = $message;
	$context['uid'] = $uid;
	$context['can_pos_rep'] = allowedTo('positive_karma');
	$context['can_neg_rep'] = allowedTo('negative_karma');

	loadTemplate('Karma');
}

function ReputationLog()
{
	global $modSettings, $context, $txt, $db_prefix, $scripturl;

	// If the mod is disabled, show an error.
	if (empty($modSettings['karmaMode']))
		fatal_lang_error('feature_disabled', true);

	// If you're a guest or can't do this, blow you off...
	is_not_guest();
	isAllowedTo('karma_edit');

	// Set up the stuff and load the user.
	$context['page_title'] = $txt['reputation_log'];
	$context['start'] = isset($_GET['start']) ? (int) $_GET['start'] : 0;

	$context['rep_sent'] = array();

	$request = db_query("
		SELECT COUNT(*) AS count
		FROM {$db_prefix}log_karma", __FILE__, __LINE__);

	list ($num_given) = mysql_fetch_row($request);
	mysql_free_result($request);

	$request = db_query("
		SELECT k.*, r.realName AS receiver_name, s.realName AS sender_name
		FROM {$db_prefix}log_karma AS k
			LEFT JOIN {$db_prefix}members AS r ON (r.ID_MEMBER = k.ID_TARGET)
			LEFT JOIN {$db_prefix}members AS s ON (s.ID_MEMBER = k.ID_EXECUTOR)
		ORDER BY logTime DESC
		LIMIT " . $context['start'] . ", 50", __FILE__, __LINE__);

	while ($row = mysql_fetch_assoc($request)){
		parsesmileys($row['comment']);

		$context['rep_sent'][] = array(
			'action_type' => !empty($row['action_type']) ? $row['action_type'] : ($row['action'] > 0) ? 'karmaGood' : 'karmaBad',
			'executor' => array(
				'name' => $row['sender_name'],
				'id' => $row['ID_EXECUTOR'],
			),
			'target' => array(
				'name' => $row['receiver_name'],
				'id' => $row['ID_TARGET'],
			),
			'time' => timeformat($row['logTime']),
			'comment' => stripslashes($row['comment']),
			'topic_href' => $row['topic'] . '.msg' . $row['message'] . '#msg' . $row['message'],
			'topic_title' => $row['title'],
		);
	}
	mysql_free_result($request);

	loadTemplate('Karma');
	$context['sub_template'] = 'log';

	// Construct the page index
	$context['page_index'] = constructPageIndex($scripturl . '?action=reputation', $_REQUEST['start'], $num_given, 50);
}]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
// Modify a user's karma.
function ModifyKarma()
{]]></search>
			<add><![CDATA[
/******************* Disabled by Advanced Reputation System **********************
**********************************************************************************
// Modify a user's karma the old and disgusting way...
function ModifyKarma_old()
{]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
		obExit(false);
	}
}

// What's this?  I dunno, what are you talking about?  Never seen this before, nope.  No siree.
function BookOfUnknown()]]></search>
			<add><![CDATA[
		obExit(false);
	}
}
**********************************************************************************
******************** Disabled by Advanced Reputation System *********************/

// What's this?  I dunno, what are you talking about?  Never seen this before, nope.  No siree.
function BookOfUnknown()]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Load.php">
		<operation>
			<search position="before"><![CDATA[
		'time_offset' => empty($user_settings['timeOffset']) ? 0 : $user_settings['timeOffset'],]]></search>
			<add><![CDATA[
		'karmaGood' => empty($user_settings['karmaGood']) ? 0 : $user_settings['karmaGood'],
		'karmaBad' => empty($user_settings['karmaBad']) ? 0 : $user_settings['karmaBad'],]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
			mem.karmaGood, mem.ID_POST_GROUP, mem.karmaBad, mem.lngfile, mem.ID_GROUP, mem.timeOffset, mem.showOnline,]]></search>
			<add><![CDATA[
			mem.karmaGood, mem.ID_POST_GROUP, mem.karmaBad, mem.lngfile, mem.ID_GROUP, mem.timeOffset, mem.showOnline, mem.karma_disabled,]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
			mem.birthdate, mem.ICQ, mem.AIM, mem.YIM, mem.MSN, mem.posts, mem.lastLogin, mem.karmaGood,]]></search>
			<add><![CDATA[
			mem.birthdate, mem.ICQ, mem.AIM, mem.YIM, mem.MSN, mem.posts, mem.lastLogin, mem.karmaGood, mem.karma_disabled,]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
	$buddy_list = !empty($profile['buddy_list']) ? explode(',', $profile['buddy_list']) : array();]]></search>
			<add><![CDATA[

	$profile['karma_bars'] = array();

	// If they are in the positives, and want it displayed
	if(!$profile['karma_disabled'] && ($profile['karmaGood'] >= $profile['karmaBad'])){

		$points = $profile['karmaGood'] - $profile['karmaBad'];
		$power = ($points - ($points % $modSettings['karmaBarPower'])) / $modSettings['karmaBarPower'];
		$bars = ($points - ($points % $modSettings['karmaBarPoints'])) / $modSettings['karmaBarPoints'];
		$bars = $bars == 0 ? 1 : $bars;
		$bars = ($bars > $modSettings['karmaMaxBars']) ? $modSettings['karmaMaxBars'] : $bars;
		$descriptions = preg_split("/(\r)?\n/", $modSettings['karmaDescriptions']);
		$description = $descriptions[$bars - 1];

		for($i = 0; $i < $bars; $i++)
			$profile['karma_bars'][] = array(
				'type' => 'Good_basic',
				'desc' => $description
			);

		if($bars >= $modSettings['karmaSuperBar'])
			for($i = ($modSettings['karmaSuperBar'] - 1); $i < $bars; $i++)
				$profile['karma_bars'][$i]['type'] = 'Good_super';

	// If they are in the negatives and want it displayed (or don't have a choice)
	} else if(!$profile['karma_disabled']){

		$points = $profile['karmaBad'] - $profile['karmaGood'];
		$bars = ($points - ($points % $modSettings['karmaBarPoints'])) / $modSettings['karmaBarPoints'];
		$bars = $bars == 0 ? 1 : $bars;
		$bars = ($bars > $modSettings['karmaMaxBars']) ? $modSettings['karmaMaxBars'] : $bars;

		for($i = 0; $i < $bars; $i++)
			$profile['karma_bars'][] = array(
				'type' => 'Bad_basic',
				'desc' => $modSettings['karmaNegativeDescription']
			);

		$power = 0;

		if($bars >= $modSettings['karmaSuperBar'])
			for($i = ($modSettings['karmaSuperBar'] - 1); $i < $bars; $i++)
				$profile['karma_bars'][$i]['type'] = 'Bad_super';

	// They don't want it displayed!
	} else {

		$profile['karma_bars'][] = array(
			'type' => '_disabled_basic',
			'desc' => $modSettings['karmaDisabledDescription']
		);

		$power = 0;

	}]]></add>
		</operation>

		<operation>
			<search position="after"><![CDATA[
			'good' => &$profile['karmaGood'],
			'bad' => &$profile['karmaBad'],]]></search>
			<add><![CDATA[
			'total' => $profile['karmaGood'] - $profile['karmaBad'],
			'disabled' => &$profile['karma_disabled'],
			'bars' => $profile['karma_bars'],
			'power' => $power,]]></add>
		</operation>
	</file>

	<file name="$sourcedir/ManagePermissions.php">
		<operation>
			<search position="before"><![CDATA[
		'view_mlist',
		'karma_edit',]]></search>
			<add><![CDATA[
		// Advanced Reputation System Settings
		'disable_karma_display',
		'positive_karma',
		'negative_karma',
		'delete_karma',]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
				'karma_edit' => false,]]></search>
			<add><![CDATA[
				// Advanced Reputation System Settings
				'disable_karma_display' => false,
				'positive_karma' => false,
				'negative_karma' => false,
				'delete_karma' => false,]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
	$non_guest_permissions = array(]]></search>
			<add><![CDATA[
		// Advanced Reputation System Settings
		'disable_karma_display',
		'positive_karma',
		'negative_karma',
		'delete_karma',]]></add>
		</operation>
	</file>

	<file name="$sourcedir/ManageServer.php">
		<operation>
			<search position="replace"><![CDATA[
function saveDBSettings(&$config_vars)
{
	foreach ($config_vars as $var)
	{]]></search>
			<add><![CDATA[
function saveDBSettings(&$config_vars)
{
	if(isset($_POST['karmaDescriptions'])){
		// Let's set two other ones, too!
		$config_vars[] = array('int', 'karmaMaxBars');
		$config_vars[] = array('int', 'karmaSuperBar');

		$_POST['karmaDescriptions'] = trim($_POST['karmaDescriptions']);
		$descriptions = count(preg_split("/(\r)?\n/", $_POST['karmaDescriptions']));

		$_POST['karmaMaxBars'] = $descriptions;
		$_POST['karmaSuperBar'] = ($descriptions - ($descriptions % 2))/2 + 1;
	}

	foreach ($config_vars as $var)
	{]]></add>
		</operation>
	</file>

	<file name="$sourcedir/ModSettings.php">
		<operation>
			<search position="before"><![CDATA[
			array('text', 'karmaSmiteLabel'),]]></search>
			<add><![CDATA[
		'',
			// Advanced Reputation System Settings
			array('int', 'karmaValuePost'),
			array('int', 'karmaValueThread'),
			array('int', 'karmaBarPower'),
			array('int', 'karmaBarPoints'),
			array('int', 'karmaRegistration'),
			array('text', 'karmaMaxPerDay'),
			array('text', 'karmaSpreadAround'),
			array('large_text', 'karmaDescriptions'),
			array('text', 'karmaDisabledDescription'),
			array('text', 'karmaNegativeDescription'),]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Post.php">
		<operation>
			<search position="replace"><![CDATA[
		$posterIsGuest = $user_info['is_guest'];
	}

	// Posting a new topic.]]></search>
			<add><![CDATA[
		$posterIsGuest = $user_info['is_guest'];

		if(!$user_info['is_guest'] && $modSettings['karmaValuePost'] > 0){
			$request = db_query("
				UPDATE {$db_prefix}members
				SET karmaGood = karmaGood + " . $modSettings['karmaValuePost'] . "
				WHERE ID_MEMBER = {$ID_MEMBER}", __FILE__, __LINE__);
		}
	}

	// Posting a new topic.]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
		$posterIsGuest = $user_info['is_guest'];
	}

	// Modifying an existing message?]]></search>
			<add><![CDATA[
		$posterIsGuest = $user_info['is_guest'];

		if(!$user_info['is_guest'] && $modSettings['karmaValueThread'] > 0){
			$request = db_query("
				UPDATE {$db_prefix}members
				SET karmaGood = karmaGood + " . $modSettings['karmaValueThread'] . "
				WHERE ID_MEMBER = {$ID_MEMBER}", __FILE__, __LINE__);
		}
	}

	// Modifying an existing message?]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Profile.php">
		<operation>
			<search position="before"><![CDATA[
		'deleteAccount' => array(array('profile_remove_any', 'profile_remove_own'), array('profile_remove_any')),]]></search>
			<add><![CDATA[
		'reputation' => empty($modSettings['karmaMode']) ? false : array(array('moderate_forum', 'profile_view_own'), array('moderate_forum')),]]></add>
		</operation>

		<operation>
			<search position="after"><![CDATA[
		// Groups with moderator permissions can also....]]></search>
			<add><![CDATA[
		if($context['user']['is_owner'] || allowedTo('moderate_forum'))
			$context['profile_areas']['info']['areas']['reputation'] = '<a href="' . $scripturl . '?action=profile;u=' . $memID . ';sa=reputation">' . $txt['reputation'] . '</a>';
]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
	$context['allow_edit_title'] = allowedTo('profile_title_any') || (allowedTo('profile_title_own') && $context['user']['is_owner']);]]></search>
			<add><![CDATA[
	$context['allow_disable_karma'] = allowedTo('disable_karma_display');]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
			'bad' => empty($_POST['karmaBad']) ? '0' : $_POST['karmaBad'],]]></search>
			<add><![CDATA[
			'disabled' => (empty($_POST['karma_disabled']) || !allowedTo('disable_karma_display')),]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
			'bad' => empty($user_profile[$memID]['karmaBad']) ? '0' : $user_profile[$memID]['karmaBad'],]]></search>
			<add><![CDATA[
			'disabled' => (empty($user_profile[$memID]['karma_disabled']) || !allowedTo('disable_karma_display')) ? 0 : 1,]]></add>
		</operation>

		<operation>
			<search position="before"><![CDATA[
		'notify_announcements' => empty($_POST['notifyAnnouncements']) ? 0 : 1,]]></search>
			<add><![CDATA[
		'karma_disabled' => (empty($_POST['karma_disabled']) || !allowedTo('disable_karma_display')) ? 0 : 1,]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
		'notifyAnnouncements', 'notifyOnce', 'notifySendBody']]></search>
			<add><![CDATA[
		'notifyAnnouncements', 'notifyOnce', 'notifySendBody', 'karma_disabled']]></add>
		</operation>

		<operation>
			<search position="end" />
			<add><![CDATA[
// View a summary. Includes the deletion of actions.
function reputation($memID)
{
	global $context, $memberContext, $txt, $modSettings, $user_info, $user_profile, $sourcedir, $scripturl, $db_prefix;

	// If the mod is disabled, show an error.
	if (empty($modSettings['karmaMode']))
		fatal_lang_error('feature_disabled', true);

	// Attempt to load the member's profile data.
	if (!loadMemberContext($memID) || !isset($memberContext[$memID]))
		fatal_lang_error('not_a_user', false);

	// Set up the stuff and load the user.
	$context += array(
		'page_title' => $txt['reputation'] . ' - ' . $memberContext[$memID]['name'],
		'member' => &$memberContext[$memID],
		'can_delete_karma' => allowedTo('karma_delete'),
		'start' => isset($_GET['start']) ? (int) $_GET['start'] : 0,
	);

	$amount = 15;

	// Are we deleting karma entries?
	if(isset($_POST['deleteBoxes'])){
		is_not_guest();
		isAllowedTo('delete_karma');
		checkSession('request');

		foreach($_POST['deleteBoxes'] as $value)
			if(!preg_match('/[0-9]+\|[0-9]+\|[0-9]{10}/', $value))
				die("Hacker!!!");
			else
				$delete[] = explode('|', $value);

		foreach($delete as $value){
			$request = db_query("
				SELECT action, action_type
				FROM {$db_prefix}log_karma
				WHERE ID_EXECUTOR = " . $value[1] . "
				AND logTime = " . $value[2] . "
				LIMIT 1", __FILE__, __LINE__);

			// Reverse prior actions
			while($row = mysql_fetch_assoc($request)){
				loadMemberData($value[0]);
				loadMemberContext($value[0], false);

				if($row['action_type'] == 'karmaGood')
					updateMemberData($value[0], array('karmaGood' => ($memberContext[$value[0]]['karma']['good'] - ((int) $row['action']))));
				else if($row['action_type'] == 'karmaBad')
					updateMemberData($value[0], array('karmaBad' => ($memberContext[$value[0]]['karma']['bad'] - ((int) $row['action']))));
			}

			mysql_free_result($request);

			db_query("
				DELETE
				FROM {$db_prefix}log_karma
				WHERE ID_EXECUTOR = " . $value[1] . "
				AND logTime = " . $value[2], __FILE__, __LINE__);
		}
	}

	// A list of actions they've been a part of
	$request = db_query("
		SELECT *
		FROM {$db_prefix}log_karma
		WHERE ID_TARGET = {$memID}
			OR ID_EXECUTOR = {$memID}
		LIMIT " . $context['start'] . ", {$amount}", __FILE__, __LINE__);

	while ($row = mysql_fetch_assoc($request)){
		// There are two types of rows - ones you sent, and ones you received.
		if($row['ID_TARGET'] == $memID){
			loadMemberData($row['ID_EXECUTOR']);
			loadMemberContext($row['ID_EXECUTOR'], false);

			parsesmileys($row['comment']);

			$context['member']['karma_actions'][] = array(
				'action_type' => !empty($row['action_type']) ? $row['action_type'] : (($row['action'] > 0) ? 'karmaGood' : 'karmaBad'),
				'executor' => $memberContext[$row['ID_EXECUTOR']]['link'],
				'target' => $txt['reputation_you'],
				'time' => timeformat($row['logTime']),
				'comment' => stripslashes($row['comment']),
				'topic_href' => $row['topic'] . '.msg' . $row['message'] . '#msg' . $row['message'],
				'topic_title' => $row['title'],
				'delete_value' => $row['ID_TARGET'] . '|' . $row['ID_EXECUTOR'] . '|' . $row['logTime'],
			);
		} else {
			loadMemberData($row['ID_TARGET']);
			loadMemberContext($row['ID_TARGET'], false);

			parsesmileys($row['comment']);

			$context['member']['karma_actions'][] = array(
				'action_type' => !empty($row['action_type']) ? $row['action_type'] : (($row['action'] > 0) ? 'karmaGood' : 'karmaBad'),
				'executor' => $txt['reputation_you'],
				'target' => $memberContext[$row['ID_TARGET']]['link'],
				'time' => timeformat($row['logTime']),
				'comment' => stripslashes($row['comment']),
				'topic_href' => $row['topic'] . '.msg' . $row['message'] . '#msg' . $row['message'],
				'topic_title' => $row['title'],
				'delete_value' => $row['ID_TARGET'] . '|' . $row['ID_EXECUTOR'] . '|' . $row['logTime'],
			);
		}
	}
	mysql_free_result($request);

	// And let's find out where the most are...
	$request = db_query("
		SELECT COUNT(*) AS num_rows
		FROM {$db_prefix}log_karma
		WHERE ID_TARGET = {$memID}
			OR ID_EXECUTOR = {$memID}", __FILE__, __LINE__);

	list ($total_actions) = mysql_fetch_row($request);
	mysql_free_result($request);

	// Construct the page index
	$context['page_index'] = constructPageIndex($scripturl . '?action=profile;sa=reputation;u=' . $memID, $context['start'], $total_actions, $amount);
}]]></add>
		</operation>
	</file>

	<file name="$sourcedir/RemoveTopic.php">
		<operation>
			<search position="replace"><![CDATA[
	if (!empty($row['ID_MEMBER']) && $decreasePostCount && empty($row['countPosts']))
		updateMemberData($row['ID_MEMBER'], array('posts' => '-'));]]></search>
			<add><![CDATA[
	if (!empty($row['ID_MEMBER']) && $decreasePostCount && empty($row['countPosts'])){
		updateMemberData($row['ID_MEMBER'], array('posts' => '-'));
		if($modSettings['karmaValuePost'] > 0){
			db_query("
				UPDATE {$db_prefix}members
				SET karmaGood = karmaGood - " . $modSettings['karmaValuePost'] . "
				WHERE ID_MEMBER = " . $row['ID_MEMBER'], __FILE__, __LINE__);
		}
	}]]></add>
		</operation>

		<operation>
			<search position="replace"><![CDATA[
			while ($rowMembers = mysql_fetch_assoc($requestMembers))
				updateMemberData($rowMembers['ID_MEMBER'], array('posts' => 'posts - ' . $rowMembers['posts']));]]></search>
			<add><![CDATA[
			while ($rowMembers = mysql_fetch_assoc($requestMembers)){
				updateMemberData($rowMembers['ID_MEMBER'], array('posts' => 'posts - ' . $rowMembers['posts']));
				if($modSettings['karmaValueThread'] > 0){
					db_query("
						UPDATE {$db_prefix}members
						SET karmaGood = karmaGood - " . ($rowMembers['posts'] * $modSettings['karmaValueThread']) . "
						WHERE ID_MEMBER = " . $rowMembers['ID_MEMBER'], __FILE__, __LINE__);
				}
			}]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Stats.php">
		<operation>
			<search position="replace"><![CDATA[
function DisplayStats()
{
	global $txt, $scripturl, $db_prefix, $modSettings, $user_info, $context;]]></search>
			<add><![CDATA[
function DisplayStats()
{
	global $txt, $scripturl, $db_prefix, $modSettings, $user_info, $context, $settings;]]></add>
		</operation>

		<operation>
			<search position="after"><![CDATA[
	// Topic replies top 10.]]></search>
			<add><![CDATA[
	// Highest reputation, but only if reputation is enabled.
	if(!empty($modSettings['karmaMode'])){
		$descriptions = preg_split("/(\r)?\n/", $modSettings['karmaDescriptions']);

		$context['reputation_best'] = array();
		$context['reputation_worst'] = array();

		$result = db_query("
			SELECT (karmaGood - karmaBad) AS karma, ID_MEMBER, realName
			FROM {$db_prefix}members
			WHERE karmaGood > karmaBad
			ORDER BY karma DESC
			LIMIT 10", __FILE__, __LINE__);

		while($row = mysql_fetch_assoc($result)){
			$rep_bars = '';

			$points = $row['karma'];
			$bars = ($points - ($points % $modSettings['karmaBarPoints'])) / $modSettings['karmaBarPoints'];
			$bars = $bars < 1 ? 1 : (($bars > $modSettings['karmaMaxBars']) ? $modSettings['karmaMaxBars'] : $bars);
			$description = $descriptions[$bars - 1];

			for($i = 0; $i < $bars; $i++)
				$rep_bars .= '<img src="' . $settings['images_url'] . '/karmaGood_' . ($i < ($modSettings['karmaSuperBar'] - 1) ? 'basic' : 'super') . '.gif" title="' . $row['realName'] . ' ' . $description . '" alt="' . $row['realName'] . ' ' . $description . '" />';

			$context['reputation_best'][] = array(
				'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['ID_MEMBER'] . '">' . $row['realName'] . '</a>',
				'reputation_bars' => $rep_bars,
				'amount' => '+' . $row['karma'],
			);
		}

		mysql_free_result($result);

		$result = db_query("
			SELECT (karmaBad - karmaGood) AS karma, ID_MEMBER, realName
			FROM {$db_prefix}members
			WHERE karmaBad > karmaGood
			ORDER BY karma DESC
			LIMIT 10", __FILE__, __LINE__);

		while($row = mysql_fetch_assoc($result)){
			$rep_bars = '';

			$points = $row['karma'];
			$bars = ($points - ($points % $modSettings['karmaBarPoints'])) / $modSettings['karmaBarPoints'];
			$bars = $bars < 1 ? 1 : (($bars > $modSettings['karmaMaxBars']) ? $modSettings['karmaMaxBars'] : $bars);

			for($i = 0; $i < $bars; $i++)
				$rep_bars .= '<img src="' . $settings['images_url'] . '/karmaBad_' . ($i < ($modSettings['karmaSuperBar'] - 1) ? 'basic' : 'super') . '.gif" title="' . $row['realName'] . ' ' . $modSettings['karmaNegativeDescription'] . '" alt="' . $row['realName'] . ' ' . $modSettings['karmaNegativeDescription'] . '" />';

			$context['reputation_worst'][] = array(
				'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['ID_MEMBER'] . '">' . $row['realName'] . '</a>',
				'reputation_bars' => $rep_bars,
				'amount' => '-' . $row['karma'],
			);
		}

		mysql_free_result($result);
	}
]]></add>
		</operation>
	</file>

	<file name="$sourcedir/Subs-Members.php">
		<operation>
			<search position="before"><![CDATA[
		'smileySet' => "''",]]></search>
			<add><![CDATA[
		'karmaGood' => ($modSettings['karmaRegistration'] > 0) ? $modSettings['karmaRegistration'] : 0,
		'karmaBad' => 0,]]></add>
		</operation>
	</file>

</modification>
