<?php

defined('IN_MYBB') or die('This file cannot be accessed directly.');

$plugins->add_hook('usercp_options_start', 'ignoreforum_ucp');
$plugins->add_hook('usercp_do_options_start', 'ignoreforum_ucp_do');
$plugins->add_hook('admin_user_users_edit', 'ignoreforum_acp');
//$plugins->add_hook('admin_user_users_add', 'ignoreforum_acp');

$plugins->add_hook('search_do_search_process', 'ignoreforum_search_latest');

$plugins->add_hook('latestdiscuss_before_query', 'ignoreforum_latestdiscuss'); // latestdiscuss plugin

function ignoreforum_info() {
	return array(
		'name'			=> 'Ignored Forums',
		'description'	=> 'Allows users to select which forums they don\'t want to see.',
		'website'		=> 'http://mybbhacks.zingaburga.com/',
		'author'		=> 'ZiNgA BuRgA',
		'authorsite'	=> 'http://zingaburga.com/',
		'version'		=> '1.1',
		'compatibility'	=> '14*,15*,16*,17*,18*',
		'guid'			=> ''
	);
}

function ignoreforum_install() {
	global $db;
	$db->write_query('ALTER TABLE '.$db->table_prefix.'users ADD COLUMN (
		ignoreforum text not null
	)');
}
function ignoreforum_activate() {
	require_once MYBB_ROOT.'inc/adminfunctions_templates.php';
	find_replace_templatesets('usercp_options', '~\</td\>\s*\<td width\="50%" class\="trow1" valign\="top"\>~', '$0
<fieldset class="trow2">
<legend><strong>{$lang->ignoreforum_ignored_forums}</strong></legend>
<div class="smalltext">{$lang->ignoreforum_ignored_forums_note}</div>
<select name="ignoreforum[]" multiple="multiple" size="10">
{$ignoreforumlist}
</select>
</fieldset>
<br />');
}

function ignoreforum_is_installed() {
	global $db;
	return $db->field_exists('ignoreforum', 'users');
}

function ignoreforum_deactivate() {
	require_once MYBB_ROOT.'inc/adminfunctions_templates.php';
	find_replace_templatesets('usercp_options', '~\<fieldset class\="trow2"\>\s*\<legend\>\<strong\>\{\$lang-\>ignoreforum_ignored_forums\}\</strong\>\</legend\>.*?\<br /\>\s?~si', '', 0);
}
function ignoreforum_uninstall() {
	global $db;
	$db->write_query('ALTER TABLE '.$db->table_prefix.'users DROP COLUMN ignoreforum');
}

function ignoreforum_ucp() {
	global $mybb, $lang;
	$ignoreforum = array_flip(explode(',', $mybb->user['ignoreforum']));
	
	$lang->ignoreforum_ignored_forums = 'Ignored Forums';
	$lang->ignoreforum_ignored_forums_note = 'Forums selected below will be hidden from your latest posts searches.  Hold down the CTRL key when selecting to select multiple forums.';
	$GLOBALS['ignoreforumlist'] = ignoreforum_build_list($ignoreforum);
}
function ignoreforum_ucp_do() {
	global $plugins;
	$plugins->add_hook('datahandler_user_update', 'ignoreforum_set_opts');
}
function ignoreforum_acp() {
	global $mybb, $plugins;
	if($mybb->request_method == 'post') {
		$plugins->add_hook('datahandler_user_update', 'ignoreforum_set_opts');
		//$plugins->add_hook('datahandler_user_insert', 'ignoreforum_set_opts');
	}
	$plugins->add_hook('admin_formcontainer_output_row', 'ignoreforum_acp_row');
}
function ignoreforum_acp_row(&$a) {
	global $lang, $mybb;
	if($a['title'] != $lang->forum_display_options) return;
	
	$ignoreforum = $mybb->input['ignoreforum'];
	if(empty($ignoreforum)) $ignoreforum = array();
	elseif(!is_array($ignoreforum)) $ignoreforum = explode(',', $ignoreforum);
	$ignoreforum = array_flip(array_map('intval', $ignoreforum));
	
	$lang->ignoreforum_ignored_forums = 'Ignored Forums';
	
	$GLOBALS['form_container']->output_row($lang->ignoreforum_ignored_forums, '', '<select name="ignoreforum[]" multiple="multiple" rows="5">'.ignoreforum_build_list($ignoreforum).'</select>');
}

function ignoreforum_set_opts(&$uh) {
	global $mybb;
	$ignoreforum = $mybb->input['ignoreforum'];
	//if(!isset($ignoreforum)) return;
	if(empty($ignoreforum) || !is_array($ignoreforum)) $ignoreforum = array();
	
	$ignoreforum = array_unique(array_map('intval', $ignoreforum));
	// ensure that all these forums are valid (even though strictly unnecessary, we'll do so to conserve memory (an "attacker" could always spam the notepad if they wanted to exhaust memory nonetheless))
	$forums = $GLOBALS['cache']->read('forums');
	foreach($ignoreforum as $k => $fid) {
		if(!isset($forums[$fid]))
			unset($ignoreforum[$k]);
	}
	// we now trust this list (although, for example, one could theoretically overflow the column, but this is usually impossible to do in practice)
	
	if($uh->method == 'insert')
		$data =& $uh->user_insert_data;
	else
		$data =& $uh->user_update_data;
	
	$data['ignoreforum'] = implode(',', $ignoreforum);
}

function ignoreforum_search_latest() {
	global $mybb;
	if($mybb->input['action'] != 'getnew' && $mybb->input['action'] != 'getdaily') return;
	if(!$mybb->user['ignoreforum']) return;
	
	global $db, $where_sql, $searcharray;
	$where_sql .= ' AND t.fid NOT IN ('.$mybb->user['ignoreforum'].')';
	$searcharray['querycache'] = $db->escape_string($where_sql);
}

function ignoreforum_latestdiscuss(&$a) {
	global $mybb;
	if(!$mybb->user['ignoreforum']) return;
	$a['qwhere'] .= ' AND t.fid NOT IN ('.$mybb->user['ignoreforum'].')';
}


// based off MyBB's make_searchable_forums() function
function ignoreforum_build_list(&$sel, $pid=0, $depth='') {
	global $permissioncache, $mybb;
	static $forumcache = null;
	
	if(!isset($forumcache)) {
		global $db;
		$forumcache = array();
		$query = $db->simple_select('forums', 'pid,fid,password,name', 'linkto="" AND active!=0', array('order_by' => 'pid, disporder'));
		while($forum = $db->fetch_array($query))
			$forumcache[$forum['pid']][$forum['fid']] = $forum;
	}
	if(!is_array($permissioncache))
		$permissioncache = forum_permissions();
	
	$forumlistbits = '';
	if(!empty($forumcache[$pid])) {
		foreach($forumcache[$pid] as $fid => &$forum) {
			$perms =& $permissioncache[$fid];
			if(($perms['canview'] != 1 && $mybb->settings['hideprivateforums'] != 0) || $perms['cansearch'] == 0) continue;
			
			$selected = '';
			//$pwverified = true;
			if(isset($sel[$fid]))
				$selected = ' selected="selected"';
			//if($forum['password']) // so password cannot be "0"
			//	$pwverified = ($mybb->cookies['forumpass'][$fid] == md5($mybb->user['uid'].$forum['password']));
			
			//if($pwverified)
				$forumlistbits .= '<option value="'.$fid.'"'.$selected.'>'.$depth.' '.strip_tags($forum['name']).'</option>';
			
			// move into child forums
			if(!empty($forumcache[$fid]))
				$forumlistbits .= ignoreforum_build_list($sel, $fid, $depth.'&nbsp;&nbsp;&nbsp;&nbsp;');
		}
	}
	
	return $forumlistbits;
}

