<?php
/**
* This plugin depends on XThreads.
*
* XThreads official release thread:
*
*		http://mybbhacks.zingaburga.com/showthread.php?tid=288
*		Coded by: Yumi/ZiNgA BuRgA
*		@ http://mybbhacks.zingaburga.com
*/
if(!defined('IN_MYBB')){
	die('Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.');
}

function xt_tf_ucp_info(){
	return array(
		'name'			=> 'Load XThreads Contents In User CP',
		'description'	=> '<strong style="color: red"><em><a href="http://mybbhacks.zingaburga.com/showthread.php?tid=288">XThreads</a> is required for this plugin</em></strong><br />Load XThreads contents in User CP Latest Threads block',
		'website'		=> 'http://mybbhacks.zingaburga.com',
		'author'		=> 'XThreads Mania',
		'authorsite'	=> 'http://mybbhacks.zingaburga.com',
		'version'		=> '1.0',
		'compatibility' => '1*',
		'guid'        	=> ''
	);
}

function xt_tf_ucp_activate(){}
function xt_tf_ucp_deactivate(){}

$plugins->add_hook('usercp_start','xt_tf_ucp_run');
function xt_tf_ucp_run(){
	if(!$GLOBALS['mybb']->input['action']){
		global $threadfield_cache;
		$threadfield_cache = xthreads_gettfcache();
		if(!empty($threadfield_cache)){
			$xtfields = '';
			foreach($threadfield_cache as &$tf){
				$xtfields .= ', tf.'.$tf['field'].' AS xthreads_'.$tf['field'];
			}
			control_object($GLOBALS['db'], '
				function query($string, $hide_errors=0, $write_query=0) {
					static $done=false;
					if(!$done && !$write_query && strpos($string, \'SELECT t.*, t.username AS threadusername, u.username\') && strpos($string, \'FROM '.TABLE_PREFIX.'threads t\') && strpos($string, \'LEFT JOIN '.TABLE_PREFIX.'users u ON \')) {
						$done = true;
						$string = strtr($string, array(
							\'SELECT t.*, t.username AS threadusername, u.username\' => \'SELECT t.*, t.username AS threadusername, u.username'.$xtfields.'\',
							\'FROM '.TABLE_PREFIX.'threads t\' => \'FROM '.TABLE_PREFIX.'threads t LEFT JOIN '.TABLE_PREFIX.'threadfields_data tf ON (tf.tid=t.tid)\'
						));
					}
					return parent::query($string, $hide_errors, $write_query);
				}
			');
			control_object($GLOBALS['templates'], '
				function get($title, $eslashes=1, $htmlcomments=1){
					if($title == \'usercp_latest_threads_threads\'){
						xt_tf_ucp_load_threadfields();
					}
					return parent::get($title, $eslashes, $htmlcomments);
				}
			');
		}
	}
}

function xt_tf_ucp_load_threadfields(){
	global $thread,$threadfield_cache,$tids,$threadfields;
	$threadfields = array();
	foreach($threadfield_cache as $k => &$v) {
		xthreads_get_xta_cache($v,$tids);
		$threadfields[$k] =& $thread['xthreads_'.$k];
		xthreads_sanitize_disp($threadfields[$k],$v);
	}
}
?>