<?php

$mybb = &$GLOBALS['mybb'];
if(strtolower(basename($_SERVER['PHP_SELF'])) == 'showthread.php' && $mybb->input['action'] == 'random')
{
	// we'll have to emulate global.php partially
	
	// Read the usergroups cache as well as the moderators cache
	$GLOBALS['displaygroupfields'] = array("title", "description", "namestyle", "usertitle", "stars", "starimage", "image");
	$GLOBALS['groupscache'] = $cache->read("usergroups");

	// If the groups cache doesn't exist, update it and re-read it
	if(!is_array($GLOBALS['groupscache']))
	{
		$cache->updateusergroups();
		$GLOBALS['groupscache'] = $cache->read("usergroups");
	}

	// Read forum permissions cache
	$GLOBALS['fpermissioncache'] = $cache->read("forumpermissions");

	// Send page headers
	send_page_headers();

	// Create session for this user
	require_once MYBB_ROOT."inc/class_session.php";
	$session = &$GLOBALS['session'];
	$session = new session;
	$session->init();

	// Set and load the language
	if(!isset($mybb->settings['bblanguage']))
	{
		$mybb->settings['bblanguage'] = "english";
	}

	$db = &$GLOBALS['db'];
	require MYBB_ROOT.'inc/functions_search.php';
	$us = get_unsearchable_forums();
	if($us) $us = ' AND fid NOT IN ('.$us.')';
	$where = "closed NOT LIKE 'moved|%' AND visible <> 0$us";
	$threadcount = $db->fetch_field($db->simple_select(TABLE_PREFIX.'threads', 'COUNT(*) AS threadcount', $where), 'threadcount');
	if($threadcount < 1)
		error('There are no threads on this board.');

	// select random thread
	$rndnum = mt_rand(0, $threadcount-1);
	$rndtid = $db->fetch_field($db->simple_select(TABLE_PREFIX.'threads', 'tid', $where, array('limit' => 1, 'limit_start' => $rndnum)), 'tid');
	if(!$rndtid)
		die('Internal error');
	
	header('Location: showthread.php?tid='.$rndtid);
	exit;
}


function rndthread_info()
{
	return array(
		'name'			=> 'Random Thread Link',
		'description'	=> 'Adds a link which will direct a user to a random thread.',
		'website'		=> 'http://mybbhacks.zingaburga.com/',
		'author'		=> 'ZiNgA BuRgA',
		'authorsite'	=> 'http://zingaburga.com/',
		'version'		=> '1.0.1'
	);
}

define('RNDTHREAD_ADD', '<li><a href="{$mybb->settings[\'bburl\']}/showthread.php?action=random">Random Thread</a></li>');
function rndthread_activate()
{
	require MYBB_ROOT."/inc/adminfunctions_templates.php";
	find_replace_templatesets('header', '#'.preg_quote('</ul>').'#', RNDTHREAD_ADD.'</ul>');
}

function rndthread_deactivate()
{
	require MYBB_ROOT."/inc/adminfunctions_templates.php";
	find_replace_templatesets('header', '#'.preg_quote(RNDTHREAD_ADD).'#', '', 0);
}

?>