<?php
add_action( 'bb_recount_list', 'fast_recount_list',999);

function fast_recount_list() {
	global $recount_list, $bbdb, $fast_recount, $fast_recount_query; 
	
	$fast_recount['fast-topic-posts']="posts of every topic";
	$fast_recount['fast-topic-deleted-posts']="deleted posts on every topic";
	$fast_recount['fast-forums']="topics and posts in every forum";
	// Count topics to which each user has replied.
	// Count tags for every topic.
	// Count topics for every tag.
	// DELETE tags with no topics. Only functions if the above checked.
	// REMOVE deleted topics from users' favorites.
	
	$fast_recount_query['fast-topic-posts']=array("
	INSERT INTO $bbdb->topics (topic_id, topic_posts)
	(SELECT topic_id, count(post_status) as topic_posts
	FROM $bbdb->posts WHERE post_status = '0' GROUP BY topic_id)
	ON DUPLICATE KEY UPDATE topic_posts=VALUES(topic_posts) ");

	$fast_recount_query['fast-topic-deleted-posts']=array("
	DELETE FROM $bbdb->topicmeta  WHERE meta_key = 'deleted_posts '","
	INSERT INTO $bbdb->topicmeta  (meta_key, topic_id, meta_value) 
	(SELECT 'deleted_posts', topic_id, count(post_status) as meta_value  
	FROM $bbdb->posts WHERE post_status != '0' GROUP BY topic_id) ");

	$fast_recount_query['fast-forums']=array("
	INSERT INTO $bbdb->forums (forum_id, posts)
	(SELECT forum_id, count(post_status) as posts
	FROM $bbdb->posts WHERE post_status = '0' GROUP BY forum_id)
	ON DUPLICATE KEY UPDATE posts=VALUES(posts) ","
	INSERT INTO $bbdb->forums (forum_id, topics)
	(SELECT forum_id, count(topic_status) as topics
	FROM $bbdb->topics WHERE topic_status = '0' GROUP BY forum_id)
	ON DUPLICATE KEY UPDATE topics=VALUES(topics) ");
	
	$fast_recount=array_reverse($fast_recount);
	foreach ($fast_recount as $key=>$value) {array_unshift($recount_list,array($key, __("FAST RECOUNT $value"),'fast_recount'));}
	$fast_recount=array_reverse($fast_recount);

}	

function fast_recount() {
	global $bbdb, $fast_recount, $fast_recount_query;
	if (!bb_current_user_can('administrate')) {return;}
	bb_check_admin_referer( 'do-counts' );
	
	foreach ($fast_recount as $key=>$value) {	
	 if (isset($_POST[$key]) && 1 == $_POST[$key] ) {
	 	unset($_POST[$key]);  // or we'll get called multiple times
		$status=array();
		echo "\t<li>\n";
		echo "\t\t" . __("FAST RECOUNT $value...");		
		foreach ($fast_recount_query[$key] as $query) {$status[]=$bbdb->query($query);}
		echo "\t\t (".implode(':',$status).")<br />\n";
		echo "\t\t" . __("Done fast recounting $value.");		
		echo "\n\t</li>\n";		
	}
	}
}

?>
