<?php

$plugins->add_hook('parse_message', 'hidelinkreply_parser');
$plugins->add_hook('showthread_start', 'hidelinkreply_run');
$plugins->add_hook('newreply_start', 'hidelinkreply_run');
$plugins->add_hook('printthread_start', 'hidelinkreply_run');
$plugins->add_hook('portal_start', 'hidelinkreply_run_portal');

//$plugins->add_hook('newreply_end', 'hidelinkreply_newreply_quotefix');
$plugins->add_hook('xmlhttp', 'hidelinkreply_xmlhttp_hack');
$plugins->add_hook('newreply_start', 'hidelinkreply_newreply_quotefix');
$plugins->add_hook('newreply_end', 'hidelinkreply_newreply_quotefix_end');

function hidelinkreply_info()
{
	return array(
		'name'			=> 'Only Show Links to Repliers',
		'description'	=> 'Hide all links in threads to users who haven\'t replied.',
		'website'		=> 'http://mybbhacks.zingaburga.com/',
		'author'		=> 'ZiNgA BuRgA',
		'authorsite'	=> 'http://zingaburga.com/',
		'version'		=> '1.0.1'
	);
}

function hidelinkreply_activate()
{
	global $db;
	$db->insert_query(TABLE_PREFIX."settinggroups", array(
		'name' => 'hidelinkreply', 
		'title' => 'Only Show Links to Repliers Options',
		'description' => '',
		'disporder' => 200, 
		'isdefault' => MY_NO
	));
	$gid = $db->insert_id();
	$db->insert_query(TABLE_PREFIX.'settings', array(
		'name' => 'hidelinkreply_firstpost',
		'title' => 'Only hide links in first post',
		'description' => 'If yes, will only hide links in the first post of a thread.',
		'optionscode' => 'yesno',
		'value' => 'no',
		'disporder' => 1,
		'gid' => $gid
	));
	$db->insert_query(TABLE_PREFIX.'settings', array(
		'name' => 'hidelinkreply_postmsg',
		'title' => 'Link Replacement (posts, HTML)',
		'description' => 'Hidden links in posts will be replaced with this text.',
		'optionscode' => 'text',
		'value' => '<span style="color: red; font-weight: bold;">You must reply to this thread to see hidden links.</span>',
		'disporder' => 3,
		'gid' => $gid
	));
	$db->insert_query(TABLE_PREFIX.'settings', array(
		'name' => 'hidelinkreply_quotemsg',
		'title' => 'Link Replacement (quotes, MyCode)',
		'description' => 'Hidden links in quotes will be replaced with this text.',
		'optionscode' => 'text',
		'value' => '[Link Hidden]',
		'disporder' => 4,
		'gid' => $gid
	));
	/*$db->insert_query(TABLE_PREFIX.'settings', array(
		'name' => 'hidelinkreply_allowmods',
		'title' => 'Always show links to Moderators',
		'description' => 'If yes, links will never be hidden to moderators/administrators.',
		'optionscode' => 'yesno',
		'value' => 'no',
		'disporder' => 2,
		'gid' => $gid
	));*/
	rebuildsettings();
}
function hidelinkreply_deactivate()
{
	global $db;
	$gid = $db->fetch_field($db->simple_select(TABLE_PREFIX.'settinggroups', 'gid', 'name="hidelinkreply"'), 'gid');
	if($gid)
	{
		$db->delete_query(TABLE_PREFIX.'settings', 'gid='.$gid);
		$db->delete_query(TABLE_PREFIX.'settinggroups', 'gid='.$gid);
		rebuildsettings();
	}
}

function hidelinkreply_parser($message)
{
	global $hidelinks, $mybb;
	//if(strpos($message, '[hide]'))
	//	die($message);
	if($hidelinks)
		return preg_replace(array('#\<a href=".*?" target="_blank"\>.*?\</a\>#', '#\[hide\].*?\[/hide\]#si'), array($mybb->settings['hidelinkreply_postmsg'], $mybb->settings['hidelinkreply_postmsg']), $message);
	else
		return preg_replace('#\[hide\](.*?)\[/hide\]#si', '$1', $message);
}

function hidelinkreply_run()
{
	global $mybb, $plugins;
	hidelinkreply_run_portal();
	if($mybb->settings['hidelinkreply_firstpost'] == 'yes')
	{
		$plugins->add_hook('postbit', 'hidelinkreply_unhide');
		$plugins->add_hook('printthread_post', 'hidelinkreply_unhide');
	}
}
function hidelinkreply_unhide()
{
	global $hidelinks;
	$hidelinks = false;
}
function hidelinkreply_run_portal()
{
	global $hidelinks, $db, $mybb, $tid, $fid, $thread, $forum, $foruminfo;
	//if($mybb->settings['hidelinkreply_allowmods'] == 'yes')
	//{
		if(!$fid)
		{
			if($thread['fid']) $fid = $thread['fid'];
			if($forum['fid']) $fid = $forum['fid'];
			if($foruminfo['fid']) $fid = $foruminfo['fid'];
		}
		if(is_moderator($fid) == 'yes')
			return;
	//}
	// check if user has posted in thread
	$posttest = $db->fetch_array($db->simple_select(TABLE_PREFIX.'posts', 'pid', 'uid='.$mybb->user['uid'].' AND tid='.intval($tid)));
	if(!$posttest)
		$hidelinks = true;
	
}

function hidelinkreply_newreply_quotefix()
{
	/*global $hidelinks, $message;
	if(!$hidelinks) return;
	
	$message = hidelinkreply_remove_quoted_links($message);*/
	global $mybb, $reply_errors, $external_quotes, $multiquote_external, $db, $templates, $tid, $parser, $plugins, $ourmessage, $lang;
	if($mybb->input['previewpost'] || $reply_errors || $mybb->input['action'] == "editdraft") return;
	$message = '';
	$quoted_posts = array();
	// Handle multiquote
	if($_COOKIE['multiquote'] && $mybb->settings['multiquote'] != "off")
	{
		$multiquoted = explode("|", $_COOKIE['multiquote']);
		foreach($multiquoted as $post)
		{
			$quoted_posts[$post] = intval($post);
		}
	}
	// Handle incoming 'quote' button
	if($mybb->input['pid'])
	{
		$quoted_posts[$mybb->input['pid']] = $mybb->input['pid'];
	}

	// Quoting more than one post - fetch them
	if(count($quoted_posts) > 0)
	{
		$external_quotes = 0;
		$quoted_posts = implode(",", $quoted_posts);
		$unviewable_forums = get_unviewable_forums();
		if($unviewable_forums)
		{
			$unviewable_forums = "AND t.fid NOT IN ({$unviewable_forums})";
		}
		if(is_moderator($fid) == "yes")
		{
			$visible_where = "AND p.visible != 2";
		}
		else
		{
			$visible_where = "AND p.visible > 0";
		}
		$query = $db->query("
			SELECT p.subject, p.message, p.pid, p.tid, p.username, u.username AS userusername, t.fid, t.firstpost
			FROM ".TABLE_PREFIX."posts p
			LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
			LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
			WHERE p.pid IN ($quoted_posts) {$unviewable_forums} {$visible_where}
		");
		$quoted_posts = array();
		$tids = array();
		while($quoted_post = $db->fetch_array($query))
		{
			$quoted_posts[$quoted_post['pid']] = $quoted_post;
				$tids[$quoted_post['tid']] = $quoted_post['tid'];
		}
		// check participation
		$query = $db->simple_select(TABLE_PREFIX."posts", "DISTINCT tid", "uid='{$mybb->user['uid']}' AND tid IN (".implode(',',$tids).")");
		$tids = array();
		while($t = $db->fetch_field($query, 'tid'))
		{
			$tids[$t] = $t;
		}
		
		foreach($quoted_posts as $quoted_post)
		{
			// Only show messages for the current thread
			if($quoted_post['tid'] == $tid)
			{
				// If this post was the post for which a quote button was clicked, set the subject
				if($pid == $quoted_post['pid'])
				{
					$subject = preg_replace('#RE:\s?#i', '', $quoted_post['subject']);
					$subject = "RE: ".$subject;
				}
				if($quoted_post['userusername'])
				{
					$quoted_post['username'] = $quoted_post['userusername'];
				}
				$quoted_post['message'] = preg_replace('#(^|\r|\n)/me ([^\r\n<]*)#i', "\\1* {$quoted_post['username']} \\2", $quoted_post['message']);
				$quoted_post['message'] = preg_replace('#(^|\r|\n)/slap ([^\r\n<]*)#i', "\\1* {$quoted_post['username']} {$lang->slaps} \\2 {$lang->with_trout}", $quoted_post['message']);
				$quoted_post['message'] = preg_replace("#\[attachment=([0-9]+?)\]#i", '', $quoted_post['message']);
				$quoted_post['message'] = $parser->parse_badwords($quoted_post['message']);
				if(is_moderator($quoted_post['fid']) != 'yes' && !isset($tids[$quoted_post['tid']]) && ($mybb->settings['hidelinkreply_firstpost'] != 'yes' || $quoted_post['firstpost'] == $quoted_post['pid']))
					$quoted_post['message'] = hidelinkreply_remove_quoted_links($quoted_post['message']);
				$message .= "[quote={$quoted_post['username']}]\n{$quoted_post['message']}\n[/quote]\n\n";
				$quoted_ids[] = $quoted_post['pid'];
			}
			// Count the rest
			else
			{
				++$external_quotes;
			}
		}
		$ourmessage = $message;
		unset($quoted_posts);
//		$plugins->add_hook('newreply_end', 'hidelinkreply_newreply_quotefix_end');
		if($external_quotes > 0)
		{
			if($external_quotes == 1)
			{
				$multiquote_text = $lang->multiquote_external_one;
				$multiquote_deselect = $lang->multiquote_external_one_deselect;
				$multiquote_quote = $lang->multiquote_external_one_quote;
			}
			else
			{
				$multiquote_text = sprintf($lang->multiquote_external, $external_quotes);
				$multiquote_deselect = $lang->multiquote_external_deselect;
				$multiquote_quote = $lang->multiquote_external_quote;
			}
			eval("\$multiquote_external = \"".$templates->get("newreply_multiquote_external")."\";");
		}
		if(count($quoted_ids) > 0)
		{
			$quoted_ids = implode("|", $quoted_ids);
		}
	}
	// turn multi-quote off
	$mybb->settings['multiquote'] = 'off';
	//unset($mybb->input['pid']);
	

}
function hidelinkreply_newreply_quotefix_end()
{
	global $message, $ourmessage;
	if($ourmessage)
		$message = $ourmessage;
}

function hidelinkreply_remove_quoted_links($message)
{
	global $mybb;
	// try to filter out links
	return preg_replace(array(
		"#\[url\]([a-z]+?://)([^\r\n\"\[<]+?)\[/url\]#i", "#\[url\]([^\r\n\"\[<]+?)\[/url\]#i",
		"#\[url=([a-z]+?://)([^\r\n\"\[<]+?)\](.+?)\[/url\]#si",
		"#([\s\(\)])(https?|ftp|news){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^\"\s\(\)<\[]*)?)#i",
		"#([\s\(\)])(www|ftp)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^\"\s\(\)<\[]*)?)#i",
		'#\[hide\].*?\[/hide\]#si'
	), array(
		$mybb->settings['hidelinkreply_quotemsg'],
		$mybb->settings['hidelinkreply_quotemsg'],
		$mybb->settings['hidelinkreply_quotemsg'],
		$mybb->settings['hidelinkreply_quotemsg'],
		$mybb->settings['hidelinkreply_quotemsg'],
		$mybb->settings['hidelinkreply_quotemsg'],
	), $message);
}
function hidelinkreply_xmlhttp_hack()
{
	global $mybb, $db, $hidelinks;
	if($mybb->input['action'] != "get_multiquoted") return;
	if($mybb->usergroup['cancp'] == 'yes' || $mybb->usergroup['issupermod'] == 'yes') return;
	// If the cookie does not exist, exit
	if(!array_key_exists("multiquote", $_COOKIE))
	{
		exit;
	}
	// Divide up the cookie using our delimeter
	$multiquoted = explode("|", $_COOKIE['multiquote']);
	
	// No values - exit
	if(!is_array($multiquoted))
	{
		exit;
	}
	
	// Loop through each post ID and sanitize it before querying
	foreach($multiquoted as $post)
	{
		$quoted_posts[$post] = intval($post);
	}

	// Join the post IDs back together
	$quoted_posts = implode(",", $quoted_posts);
	
	// Fetch unviewable forums
	$unviewable_forums = get_unviewable_forums();
	if($unviewable_forums)
	{
		$unviewable_forums = "AND t.fid NOT IN ({$unviewable_forums})";
	}
	$message = '';
	
	// Are we loading all quoted posts or only those not in the current thread?
	if(!$mybb->input['load_all'])
	{
		$from_tid = "p.tid != '".intval($mybb->input['tid'])."' AND ";
	}
	else
	{
		$from_tid = '';
	}

	require_once MYBB_ROOT."inc/class_parser.php";
	$parser = new postParser;

	// Query for any posts in the list which are not within the specified thread
	$query = $db->query("
		SELECT p.subject, p.message, p.pid, p.tid, p.username, t.fid, p.visible, u.username AS userusername, t.firstpost
		FROM ".TABLE_PREFIX."posts p
		LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
		LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
		WHERE {$from_tid}p.pid IN ($quoted_posts) {$unviewable_forums}
	");
	$quoted_posts = array();
	$tids = array();
	while($quoted_post = $db->fetch_array($query))
	{
		$quoted_posts[$quoted_post['pid']] = $quoted_post;
			$tids[$quoted_post['tid']] = $quoted_post['tid'];
	}
	// check participation
	$query = $db->simple_select(TABLE_PREFIX."posts", "DISTINCT tid", "uid='{$mybb->user['uid']}' AND tid IN (".implode(',',$tids).")");
	$tids = array();
	while($t = $db->fetch_field($query, 'tid'))
	{
		$tids[$t] = $t;
	}
	
	foreach($quoted_posts as $quoted_post)
	{	
		if(is_moderator($quoted_post['fid']) != 'yes' && $quoted_post['visible'] == 0)
		{
			continue;
		}
		
		// Swap username over if we have a registered user
		if($quoted_post['userusername'])
		{
			$quoted_post['username'] = $quoted_post['userusername'];
		}
		// Clean up the message
		$quoted_post['message'] = preg_replace('#(^|\r|\n)/me ([^\r\n<]*)#i', "\\1* {$quoted_post['username']} \\2", $quoted_post['message']);
		$quoted_post['message'] = preg_replace('#(^|\r|\n)/slap ([^\r\n<]*)#i', "\\1* {$quoted_post['username']} {$lang->slaps} \\2 {$lang->with_trout}", $quoted_post['message']);
		$quoted_post['message'] = preg_replace("#\[attachment=([0-9]+?)\]#i", '', $quoted_post['message']);
		$quoted_post['message'] = $parser->parse_badwords($quoted_post['message']);	
		if(is_moderator($quoted_post['fid']) != 'yes' && !isset($tids[$quoted_post['tid']]) && ($mybb->settings['hidelinkreply_firstpost'] != 'yes' || $quoted_post['firstpost'] == $quoted_post['pid']))
			$quoted_post['message'] = hidelinkreply_remove_quoted_links($quoted_post['message']);
		// Tack on to list of messages
		$message .= "[quote={$quoted_post['username']}]\n{$quoted_post['message']}\n[/quote]\n\n";
	}
	
	// Send our headers.
	header("Content-type: text/plain; charset={$charset}");
	echo $message;
	exit;
}
?>