<?php

// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
	die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}

$plugins->add_hook("datahandler_post_insert_thread", "threadcount_add");
$plugins->add_hook("class_moderation_delete_thread", "threadcount_remove");
// recount hooks
$plugins->add_hook("admin_maintenance_rebuild", "threadcount_admin_rebuild");
$plugins->add_hook("admin_maintenance_start", "threadcount_admin_do_rebuild");

$plugins->add_hook("postbit", "threadcount_postbit");

function numtopics_info()
{
	return array(
		"name"			=> "No. Topics Started",
		"description"	=> "Displays the number of topics started by a user.",
		"website"		=> "http://endlessparadigm.com",
		"author"		=> "ZiNgA BuRgA",
		"authorsite"	=> "http://zingaburga.com",
		"version"		=> "1.0",
	);
}

define('TOPICCOUNT_PLACEHOLDER', '<!-- NUMTOPICS -->');
define('MEMBERLIST_ADD', '<td class="tcat"><span class="smalltext"><strong>Topics:</strong></span></td>');
define('MEMBERLISTROW_ADD', '<td class="trow2">{$users[\'numtopics\']}</td>');

function numtopics_activate()
{
	global $db;
	$db->query("ALTER TABLE `".TABLE_PREFIX."users` ADD `numtopics` int(10) unsigned NOT NULL default '0'");
	
	// add postbit template
	require_once MYBB_ROOT."inc/adminfunctions_templates.php";
	find_replace_templatesets('postbit_author_user', '#'.preg_quote('{$lang->postbit_posts} {$post[\'postnum\']}').'#', '{$lang->postbit_posts} {$post[\'postnum\']}'.TOPICCOUNT_PLACEHOLDER);
	find_replace_templatesets('memberlist', '#'.preg_quote('<td class="tcat"><span class="smalltext"><strong>{$lang->posts}</strong></span></td>').'#', MEMBERLIST_ADD.'<td class="tcat"><span class="smalltext"><strong>{$lang->posts}</strong></span></td>');
	find_replace_templatesets('memberlist', '#'.preg_quote(' colspan="6"').'#', ' colspan="7"');
	find_replace_templatesets('memberlist_row', '#'.preg_quote('<td class="trow2">{$users[\'postnum\']}</td>').'#', MEMBERLISTROW_ADD.'<td class="trow2">{$users[\'postnum\']}</td>');

}

function numtopics_deactivate()
{
	global $db;
	$db->query("ALTER TABLE `".TABLE_PREFIX."users` DROP `numtopics`");
	
	require_once MYBB_ROOT."inc/adminfunctions_templates.php";
	find_replace_templatesets('postbit_author_user', '#'.preg_quote(TOPICCOUNT_PLACEHOLDER).'#', '', 0);
	find_replace_templatesets('memberlist', '#'.preg_quote(MEMBERLIST_ADD).'#', '', 0);
	find_replace_templatesets('memberlist', '#'.preg_quote(' colspan="7"').'#', ' colspan="6"', 0);
	find_replace_templatesets('memberlist_row', '#'.preg_quote(MEMBERLISTROW_ADD).'#', '', 0);
}


function threadcount_add(&$posthandler)
{
	global $db, $mybb;
	$db->query('UPDATE '.TABLE_PREFIX.'users SET numtopics=numtopics+1 WHERE uid='.$mybb->user['uid']);
}

function threadcount_remove()
{
	global $db, $thread;
	if(isset($thread['uid']))
		$db->query('UPDATE '.TABLE_PREFIX.'users SET numtopics=numtopics-1 WHERE uid='.$thread['uid']);
}

function threadcount_postbit(&$post)
{
	$post['user_details'] = str_replace(TOPICCOUNT_PLACEHOLDER, '<br />Topics: '.my_number_format($post['numtopics']), $post['user_details']);
}


function threadcount_admin_rebuild()
{
	global $lang;
	// code copied from MyBB's recount AdminCP section (there's no better method unfortunately :|)
	cpheader();
	
	startform("maintenance.php", "" , "do_rebuildstats");
	starttable();
	tableheader($lang->rebuildstats);
	makelabelcode("<div align=\"center\">$lang->rebuildstats_notice</div>");
	endtable();
	endform($lang->proceed);
	
	startform("maintenance.php", "" , "do_rebuildforums");
	starttable();
	tableheader($lang->rebuild_forum_counters);
	makelabelcode("<div align=\"center\">{$lang->rebuild_forum_counters_note}</div>", '', 2);
	makeinputcode($lang->forums_per_page, 'perpage', 50);
	endtable();
	makehiddencode('page', 1);
	endform($lang->proceed);
	
	startform("maintenance.php", "" , "do_rebuildthreads");
	starttable();
	tableheader($lang->rebuild_thread_counters);
	makelabelcode("<div align=\"center\">{$lang->rebuild_thread_counters_note}</div>", '', 2);
	makeinputcode($lang->threads_per_page, 'perpage', 500);
	endtable();
	makehiddencode('page', 1);
	endform($lang->proceed);
	
	startform("maintenance.php", "" , "do_recountpostcounts");
	starttable();
	tableheader($lang->recount_user_post_counts);
	makelabelcode("<div align=\"center\">{$lang->recount_user_post_counts_note}</div>", '', 2);
	makeinputcode($lang->users_per_page, 'perpage', 500);
	endtable();
	makehiddencode('page', 1);
	endform($lang->proceed);
	
	startform("maintenance.php", "" , "do_recountthreadcounts");
	starttable();
	tableheader('Recount User Thread Counts');
	makelabelcode("<div align=\"center\">When you run this function, the thread count for each user will be updated to reflect its current live value based on the threads in the database.</div>", '', 2);
	makeinputcode($lang->users_per_page, 'perpage', 500);
	endtable();
	makehiddencode('page', 1);
	endform($lang->proceed);
	
	startform("maintenance.php", "" , "do_rebuildthumbnails");
	starttable();
	tableheader($lang->rebuild_thumbnails);
	makelabelcode("<div align=\"center\">{$lang->rebuild_thumbnails_note}</div>", '', 2);
	makeinputcode($lang->thumbnails_per_page, 'perpage', 20);
	endtable();
	makehiddencode('page', 1);
	endform($lang->proceed);
	cpfooter();
	
	exit;
}

function threadcount_admin_do_rebuild()
{
	global $mybb, $db, $lang;
	if($mybb->input['action'] != 'do_recountthreadcounts') return;
	
	
	// code copied from MyBB's post count updater
	@set_time_limit(0);
	

	$query = $db->simple_select(TABLE_PREFIX."users", "COUNT(uid) as num_users");
	$num_users = $db->fetch_field($query, 'num_users');
	
	if(!isset($mybb->input['page']) || intval($mybb->input['page']) < 1)
	{
		$mybb->input['page'] = 1;
	}
	$page = intval($mybb->input['page']);
	if(!isset($mybb->input['perpage']) || intval($mybb->input['perpage']) < 1)
	{
		$mybb->input['perpage'] = 50;
	}
	$per_page = intval($mybb->input['perpage']);
	$start = ($page-1) * $per_page;
	$end = $start + $per_page;
	
	$query = $db->simple_select(TABLE_PREFIX."users", "uid", '', array('order_by' => 'uid', 'order_dir' => 'asc', 'limit_start' => $start, 'limit' => $per_page));
	
	// we start modifying things here to be more optimized :P
	$uids = array();
	while($user = $db->fetch_array($query))
		$uids[$user['uid']] = $user['uid'];
	
	$query = $db->query('SELECT uid, COUNT(tid) AS thread_count FROM '.TABLE_PREFIX.'threads WHERE uid IN ('.implode(',',$uids).') GROUP BY uid');
	$users = array();
	while($user = $db->fetch_array($query))
		$users[$user['uid']] = array('numtopics' => $user['thread_count']);

	numtopics_db_update_rows(TABLE_PREFIX.'users', $users, 'uid');
	
	if($end >= $num_users)
	{
		cpredirect("maintenance.php?".SID."&action=rebuild", 'Thread counts updated.');
	}
	else
	{
		cpheader();
		startform("maintenance.php", "" , "do_recountthreadcounts");
		starttable();
		tableheader('Recount Thread Counts');
		makelabelcode($lang->click_next_continue, '', 2);
		makehiddencode('page', ++$page);
		makehiddencode('perpage', $per_page);
		endtable();
		endform($lang->proceed);
		cpfooter();
	}
	
	exit;
}



// Optimized UPDATE
//  copied from an older version of MyPlaza
function numtopics_db_update_rows($table, $rows, $key)
{
	global $db;
	// see if it exceeds the threshold
	if(count($rows) > 12)
	{
		// use the temporary table approach
		// add primary key to the list of fields
		$fields = array_merge(array($key), array_keys(reset($rows)));
		
		// we'll manually insert the values here, instead of using db_insert_rows() to make things a little
		// quicker
		$insertsql = '';
		foreach($rows as $rowkey => $row)
		{
			$insertsql .= '(\''.$db->escape_string($rowkey).'\',\''.implode('\',\'', $row).'\'),';
		}
		
		// generate fields list for CREATE TABLE
		$tablefields = numtopics_db_get_columns($table);
		$fieldslist = '';
		$updatelist = '';
		foreach($fields as $field)
		{
			$tablefield = &$tablefields[$field];
			if(strtoupper($tablefield['Null']) == 'NO')
				$nulltext = ' NOT NULL';
			else
				$nulltext = '';
			if($tablefield['Default'])
				$deftext = ' default \''.$tablefield['Default'].'\'';
			else
				$deftext = '';
			if($tablefield['Extra'])
				$extratext = ' '.$tablefield['Extra'];
			else
				$extratext = '';
			
			$fieldslist .= '`'.$field.'` '.$tablefield['Type']
				.$nulltext.',';
			//	.$nulltext.$deftext.$extratext.',';
			
			// also generate update list for UPDATE
			if($field != $key)
				$updatelist .= 't1.'.$field.'=t2.'.$field.',';
		}
		
		
		$db->query('DROP TABLE IF EXISTS '.TABLE_PREFIX.'plaza_temp');
		$db->query('CREATE TABLE '.TABLE_PREFIX.'plaza_temp ('.$fieldslist.' PRIMARY KEY ('.$key.')) TYPE=HEAP;');
		// remove trailing comma
		$db->query('INSERT INTO '.TABLE_PREFIX.'plaza_temp('.implode(',', $fields).')
			VALUES '.substr($insertsql, 0, strlen($insertsql)-1).';');
		$db->query('UPDATE '.$table.' t1, '.TABLE_PREFIX.'plaza_temp t2 SET '.substr($updatelist, 0, strlen($updatelist)-1).' WHERE t1.'.$key.'=t2.'.$key);
		$db->query('DROP TABLE IF EXISTS '.TABLE_PREFIX.'plaza_temp');
	}
	else
	{
		// not enough rows to be updating, so just use normal updates
		foreach($rows as $rowkey => $row)
			$db->update_query($table, $row, $key.'=\''.$db->escape_string($rowkey).'\'', 1);
	}
}

// MyPlaza's get columns code
function numtopics_db_get_columns($table)
{
	global $db, $table_columns_cache;
	if(!isset($table_columns_cache[$table]))
	{
		$fields = $db->show_fields_from($table);
		$table_columns_cache[$table] = array();
		foreach($fields as $field)
			$table_columns_cache[$table][$field['Field']] = $field;
	}
	return $table_columns_cache[$table];
}
?>
