<?php

if(!defined('IN_MYBB'))
	die('This file cannot be accessed directly.');


$plugins->add_hook('newthread_start', 'topiclock_newthread');
$plugins->add_hook('newthread_do_newthread_end', 'topiclock_do_newthread');

function topiclock_info()
{
	return array(
		'name'			=> 'Thread Stater Locking',
		'description'	=> 'Allows thread creators to lock their own thread when starting a new thread (note, they cannot lock their thread afterwards).',
		'website'		=> 'http://mybbhacks.zingaburga.com/',
		'author'		=> 'ZiNgA BuRgA',
		'authorsite'	=> 'http://zingaburga.com/',
		'version'		=> '1.1',
		'compatibility'	=> '1*',
		'guid'			=> ''
	);
}


function topiclock_activate()
{
	global $db;
	$prefix = ($GLOBALS['mybb']->version_code >= 1400 ? '' : TABLE_PREFIX);
	$gid = $db->fetch_field($db->simple_select($prefix.'settinggroups', 'gid', 'name="posting"'), 'gid');
	if($gid)
	{
		$db->insert_query($prefix.'settings', array(
			'name' => 'topiclock_fids',
			'title' => 'Allow Thread Starter Locking Forums',
			'description' => 'Enter a comma separated list of Forum IDs, which allow topic creators to lock their own threads.',
			'optionscode' => 'text',
			'value' => '',
			'disporder' => 60,
			'gid' => $gid
		));
		if(function_exists('rebuild_settings')) rebuild_settings(); else rebuildsettings();
	}
}

function topiclock_deactivate()
{
	global $db;
	$prefix = ($GLOBALS['mybb']->version_code >= 1400 ? '' : TABLE_PREFIX);
	$db->delete_query($prefix.'settings', 'name="topiclock_fids"');
	if(function_exists('rebuild_settings')) rebuild_settings(); else rebuildsettings();
}

function topiclock_newthread()
{
	global $mybb, $fid, $templates;
	$yes = ($GLOBALS['mybb']->version_code >= 1400 ? '1' : 'yes');
	if(!topiclock_validfid($fid) || is_moderator($fid) == $yes) return;
	
	// pretend this user is a supermod
	$mybb->usergroup['issupermod'] = $yes;
	// remove the sticky checkbox
	$templates->cache['newreply_modoptions'] = preg_replace('~\<br /\>'."\r?\n".preg_quote('<label><input type="checkbox" class="checkbox" name="modoptions[stickthread]" value="'.$yes.'"').' ?'.preg_quote('{$stickycheck} />').'(?:&nbsp;)?'.preg_quote('{$lang->stick_thread}</label>').'~', '', $templates->cache['newreply_modoptions']);
}

function topiclock_do_newthread()
{
	global $mybb, $fid, $db, $tid;
	$yes = ($GLOBALS['mybb']->version_code >= 1400 ? '1' : 'yes');
	if(!topiclock_validfid($fid) || is_moderator($fid) == $yes) return;
	
	if($mybb->input['modoptions']['closethread'] == $yes)
	{
		$prefix = ($GLOBALS['mybb']->version_code >= 1400 ? '' : TABLE_PREFIX);
		$db->update_query($prefix.'threads', array('closed' => $yes), 'tid='.$tid);
	}
}

function topiclock_validfid($fid)
{
	global $mybb;
	$fids = array_map('intval', explode(',', str_replace(' ', '', $mybb->settings['topiclock_fids'])));
	return (in_array($fid, $fids));
}

?>