<?php
if(!defined('IN_MYBB')){
	die('Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.');
}

function xttimg_index_info(){
	return array(
		'name'			=> 'Threads on Index',
		'description'	=> 'Displaying threads title from specified forum id(s) on forum index',
		'website'		=> 'http://mybbhacks.zingaburga.com',
		'author'		=> 'XThreads Mania',
		'authorsite'	=> 'http://mybbhacks.zingaburga.com',
		'version'		=> '1.0',
		'compatibility' => '1*',
		'guid'        	=> ''
	);
}

function xttimg_index_activate(){
	global $db;
	$db->insert_query('templates', array(
		'title'		=> 'xttimg_index_latest_threads',
		'template'	=> $db->escape_string('<br class="clear" />
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
	<tr>
		<td class="thead" colspan="3">
			<strong>Latest Threads</strong>
		</td>
	</tr>
	{$xttimg_index_latest_threads_thread}
</table>'),
		'sid'		=> -1
	));
	$db->insert_query('templates', array(
		'title'		=> 'xttimg_index_latest_threads_thread',
		'template'	=> $db->escape_string('<tr>
	<td class="{$altbg}" style="width:1px">
		{$thread[\'useravatar\']}
	</td>
	<td class="{$altbg}" style="width:1px">
		<img src="{$thread[\'xtimgurl\']}" alt="" />
	</td>
	<td class="{$altbg}">
		<div><strong><a href="{$thread[\'threadurl\']}">{$thread[\'subject\']}</a></strong></div>
		<div class="smalltext">
			<div>By: {$thread[\'profilelink\']}</div>
			<em>Posted in: <a href="{$thread[\'forumurl\']}">{$thread[\'forumname\']}</a>, {$thread[\'threaddate\']} {$thread[\'threadtime\']}</em>
		</div>
		<div class="post_body">{$thread[\'postpreview\']}</div>
		<div class="float_right smalltext">
			Replies: {$thread[\'replies\']}, Views: {$thread[\'views\']}
		</div>
	</td>
</tr>'),
		'sid'		=> -1
	));
	$db->insert_query('templates', array(
		'title'		=> 'xttimg_index_most_viewed_threads',
		'template'	=> $db->escape_string('<br class="clear" />
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
	<tr>
		<td class="thead" colspan="3">
			<strong>Most Viewed Threads</strong>
		</td>
	</tr>
	{$xttimg_index_most_viewed_threads_thread}
</table>'),
		'sid'		=> -1
	));
	$db->insert_query('templates', array(
		'title'		=> 'xttimg_index_most_viewed_threads_thread',
		'template'	=> $db->escape_string('<tr>
	<td class="{$altbg}" style="width:1px">
		{$thread[\'useravatar\']}
	</td>
	<td class="{$altbg}" style="width:1px">
		<img src="{$thread[\'xtimgurl\']}" alt="" />
	</td>
	<td class="{$altbg}">
		<div><strong><a href="{$thread[\'threadurl\']}">{$thread[\'subject\']}</a></strong></div>
		<div class="smalltext">
			<div>By: {$thread[\'profilelink\']}</div>
			<em>Posted in: <a href="{$thread[\'forumurl\']}">{$thread[\'forumname\']}</a>, {$thread[\'threaddate\']} {$thread[\'threadtime\']}</em>
		</div>
		<div class="post_body">{$thread[\'postpreview\']}</div>
		<div class="float_right smalltext">
			Replies: {$thread[\'replies\']}, Views: {$thread[\'views\']}
		</div>
	</td>
</tr>'),
		'sid'		=> -1
	));
}

function xttimg_index_deactivate(){
	global $db;
	$db->delete_query('templates', 'title IN("xttimg_index_latest_threads","xttimg_index_latest_threads_thread","xttimg_index_most_viewed_threads","xttimg_index_most_viewed_threads_thread")');
}

$plugins->add_hook('global_start','xttimg_index_tcache');
function xttimg_index_tcache(){
	if(THIS_SCRIPT == 'index.php'){
		if(isset($GLOBALS['templatelist'])){
			$GLOBALS['templatelist'] .= ',xttimg_index_latest_threads,xttimg_index_latest_threads_thread,xttimg_index_most_viewed_threads,xttimg_index_most_viewed_threads_thread';
		}
	}
}

$plugins->add_hook('index_start','xttimg_index_index');
function xttimg_index_index(){
	global $xttimg_index_latest_threads,$xttimg_index_most_viewed_threads;
	$fids = array('2','3');// Forum IDs
	$xtimgdim = array('w'=>75,'h'=>75);// XThreads image thumbnail dimension
	$avdim = array('w'=>50,'h'=>50);

	$xttimg_index_latest_threads = xttimg_threads_run($fids,5,'dateline','xttimg_index_latest_threads_thread','xttimg_index_latest_threads','timg',$xtimgdim,$avdim);
	$xttimg_index_most_viewed_threads = xttimg_threads_run($fids,5,'views','xttimg_index_most_viewed_threads_thread','xttimg_index_most_viewed_threads','timg',$xtimgdim,$avdim);
}

function xttimg_threads_run($fids=array(),$limit,$order,$cthread,$threads,$xtkey='',$xtimgdim=array(),$avmaxdim=array()){
	if(!$fids) return;
	global $db;
	$cond = '1=1';
	foreach($fids as $fid){
		$fids_array[] = intval($fid);
	}
	$cond .= ' AND t.fid IN ('.implode(',',$fids_array).')';
	$unviewable = get_unviewable_forums(true);
	if($unviewable) $cond .= ' AND t.fid NOT IN ('.$unviewable.')';
	$notactive = get_inactive_forums();
	if($notactive) $cond .= ' AND t.fid NOT IN ('.$notactive.')';
	if($xtkey){
		$xtattfields = ',a.updatetime,a.md5hash,a.uploadtime,a.aid,a.attachname,a.filename,a.thumbs';
		$xtatttable = ' LEFT JOIN '.TABLE_PREFIX.'xtattachments a ON (a.tid=t.tid)';
		$cond .= ' AND a.field="'.$db->escape_string($xtkey).'"';
	}
	if(!in_array($order,array('dateline','views','replies'))) $order = 'dateline';
	$query = $db->query('SELECT t.*,t.username AS threadusername,u.username,u.avatar,u.avatardimensions,u.usergroup,u.displaygroup'.$xtattfields.'
		FROM '.TABLE_PREFIX.'threads t'.$xtatttable.'
		LEFT JOIN '.TABLE_PREFIX.'users u ON (u.uid=t.uid)
		WHERE '.$cond.' AND t.visible=1 AND t.closed NOT LIKE "moved|%"
		ORDER BY t.'.$db->escape_string($order).' DESC
		LIMIT 0,'.intval($limit)
	);
	$threads_cache = array();
	while($thread = $db->fetch_array($query)){
		$threads_cache[$thread['tid']] = $thread;
	}
	if(!empty($threads_cache)){
		global $mybb,$theme,$parser;
		$altbg = alt_trow();
		if(!is_object($parser)){
			require_once MYBB_ROOT.'inc/class_parser.php';
			$parser = new postParser;
		}
		$$cthread = '';
		foreach($threads_cache as $thread){
			$forumpermissions[$thread['fid']] = forum_permissions($thread['fid']);
			if($forumpermissions[$thread['fid']]['canview'] == 0 || $forumpermissions[$thread['fid']]['canviewthreads'] == 0 || $forumpermissions[$thread['fid']]['canonlyviewownthreads'] == 1 && $thread['uid'] != $mybb->user['uid']){
				continue;
			}
			if(!$thread['username']){
				$thread['profilelink'] = format_name($thread['threadusername'],1);
			}else{
				$thread['formatname'] = format_name(htmlspecialchars_uni($thread['username']),$thread['usergroup'],$thread['displaygroup']);
				$thread['profilelink'] = build_profile_link($thread['formatname'],$thread['uid']);
			}
			$thread['threaddate'] = my_date($mybb->settings['dateformat'],$thread['dateline']);
			$thread['threadtime'] = my_date($mybb->settings['timeformat'],$thread['dateline']);
			$thread['replies'] = my_number_format($thread['replies']);
			$thread['views'] = my_number_format($thread['views']);
			$thread['threadurl'] = get_thread_link($thread['tid']);
			$thread['subject'] = htmlspecialchars_uni($parser->parse_badwords($thread['subject']));
			$thread['forumurl'] = get_forum_link($thread['fid']);
			$thread['forumname'] = preg_replace('#&(?!\#[0-9]+;)#si', '&amp;',$GLOBALS['forum_cache'][$thread['fid']]['name']);
			if($thread['postpreview']){
				$thread['postpreview'] = htmlspecialchars_uni($parser->parse_badwords($thread['postpreview']));
			}
			if(!empty($avmaxdim)){
				$user_avatar_img = $mybb->settings['bburl'].'/images/default_avatar.gif';
				$maxw = $avwidth = intval($avmaxdim['w']); $maxh = $avheight = intval($avmaxdim['h']);
				if($thread['avatar']){
					$user_avatar_img = htmlspecialchars_uni($thread['avatar']);
					$avdim = explode('|',$thread['avatardimensions']);
					if($avdim[0] && $avdim[1]){
						$avwidth = intval($avdim[0]); $avheight = intval($avdim[1]);
						if($avdim[0] > $maxw || $avdim[1] > $maxh){
							if(!function_exists('scale_image')) require_once MYBB_ROOT.'inc/functions_image.php';
							$scaled_dim = scale_image($avdim[0],$avdim[1],$maxw,$maxh);
							$avwidth = $scaled_dim['width']; $avheight = $scaled_dim['height'];
						}
					}
				}
				$avwh = ' width="'.$avwidth.'" height="'.$avheight.'"';
				$thread['useravatar'] = '<img src="'.$user_avatar_img.'" alt=""'.$avwh.' />';
			}
			if($xtkey){
				if($thread['thumbs']){
					$thread['thumbs'] = unserialize($thread['thumbs']);
					$thread['thumbsw'] = $thread['thumbs'][$xtimgdim['w']]['w'];
					$thread['thumbsh'] = $thread['thumbs'][$xtimgdim['h']]['h'];
				}
				$thread['xtimgurl'] = xthreads_get_xta_url($thread,$xtimgdim['w'].'x'.$xtimgdim['h']);
			}
			eval('$$cthread .= "'.$GLOBALS['templates']->get($cthread).'";');
			$altbg = alt_trow();
		}
		if($$cthread){
			eval('$$threads = "'.$GLOBALS['templates']->get($threads).'";');
			return $$threads;
		}
	}
}
?>