############################################################## 
## MOD Title: Detector Bots
## MOD Author: Lex, http://www.vidon.ru 
##     Powered:  aka LonelyWalker < webmaster[at]blume.by >
## MOD Description:    This mod detect multilink messages & stop them posting 
## MOD Version:    2.0.6 [phpBB 2.0.x] 
## 
## Installation Level:   Easy
## Installation Time:    2 Minutes
## Files To Edit (3):    includes/functions_post.php
##                       language/lang_russian/lang_main.php
##                       language/lang_english/lang_main.php
## Included Files:    detector_bot.tpl
############################################################## 
## For Security Purposes, Please Check: http://www.phpbbguru.net/mods/ for the 
## latest version of this MOD. Downloading this MOD from other sites could cause malicious code 
## to enter into your phpBB Forum. As such, phpBB will not offer support for MOD's not offered 
## in our MOD-Database, located at: http://www.phpbb.com/mods/ 
############################################################## 
## Author Notes: 
## 
############################################################## 
## MOD History: 
## 
##   2006-05-02 - Version 2.0.6
##      - Added:
##        * links like <a ... href="aaa.bbb.com" ... >aaa</a> support //Stupid bots!? :)
##
##   2006-03-10 - Version 2.0.5
##      - Fixed:
##        * Translation to English (mistake in "wasn't")
##      - Added:
##        * Alternative admin e-mail usage
##
##   2006-03-01 - Version 2.0.4
##      - Added:
##        * international languages support
##
##   2006-02-28 - Version 2.0.3 Beta
##      - Fixed:
##        * Anonymous user deleting (if he posts was 1st and spam message)
##      - Added:
##        * Spam links look like e-mail detect ("searchwords@realspamsite.com" = "realspamsite.com")
##        * Message for Admin w/o BBcodes
## 
##   2006-02-27 - Version 2.0.2 Beta
##      - Fixed:
##        * Clean up Forum after post deleting
## 
##   2006-02-27 - Version 2.0.1 Beta
##      - Fixed:
##        * E-mail to Admin content (message subj & text are empty)
##        * New topic creating error (thnx Stern)
## 
##   2006-02-24 - Version 2.0.0 Beta
##      - Extended Version Release by 
##      - Kill new user if he's posting links
##      - Advanced Posts Merging 2.x MOD Support
##      - Yellow Card MOD Support
## 
##   2005-12-27 - Version 1.0.0 
##      - Initial Release by Lex
## 
############################################################## 
## Before Adding This MOD To Your Forum, You Should Back Up All Files Related To This MOD 
############################################################## 

# 
#-----[ COPY ]------------------------------------------ 
#
copy language/*.* to language/*.*

# 
#-----[ OPEN ]------------------------------------------ 
# 
includes/functions_post.php

# 
#-----[ FIND ]------------------------------------------ 
#
	if($bbcode_on && $bbcode_uid != '')
	{
		$message = bbencode_first_pass($message, $bbcode_uid);
	}

# 
#-----[ AFTER, ADD ]------------------------------------------ 
#

/* ---8<--------[Detector Bots]----------------------------------------- */
	global $unhtml_specialchars_match, $unhtml_specialchars_replace,$client_ip,$user_ip,$db,$userdata,$phpbb_root_path,$phpEx,$lang;
	$first_post_max_link = 1; //         ,     
	$newbie_max_link = 2; //   ,   1 
	$oldbie_minposts = 50; //   ,    50 
	$oldbie_max_link = 50; //   
	$use_yellowcard = false; //  .  MOD YellowCard ,  TRUE
	$APM_mod_installed = false; //   MOD Advanced Posts Merging 2.x ,  TRUE
	$send_email_to_admin = true; //   
 	$admin_email = $board_config['board_email']; //    
//	$admin_email = "vasja_pupkin_admin@mysite.ru"; //   .
	$link_count = 0; //  

	preg_match_all('#(\[url(.*?)\[\/url\])|(([\n ]href=(.*?)&gt;)|((^|[\n ])([\w]+?://|www|ftp)[^ \"\n\r\t<>]*))|((^|[\n ]|mailto:)([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+))#si', $message, $links);
	if (isset($links[1])) {$link_count += count($links[1]);}

	if ($userdata['user_level'] == ADMIN && $userdata['session_logged_in']) {$link_count=0;} // Admin can post anything

	if ($userdata['user_id'] == ANONYMOUS)
	{
		if ($link_count > $first_post_max_link)
		{
			if ($send_email_to_admin)
			{
				include($phpbb_root_path . 'includes/emailer.'.$phpEx);
				$emailer = new emailer($board_config['smtp_delivery']);
				$emailer->from($board_config['board_email']);
				$emailer->replyto($board_config['board_email']);
				$emailer->use_template('detector_bot', $board_config['default_lang']);
				$emailer->email_address($admin_email);
				$emailer->set_subject($lang['D_Bots_email_subj']);
				$emailer->assign_vars(array(
					'SITENAME' => $board_config['sitename'],
					'EMAIL_SIG' => (!empty($board_config['board_email_sig'])) ? str_replace('<br />', "\n", "-- \n" . $board_config['board_email_sig']) : '',
					'IP' => $client_ip,
					'POSTS' => '',
					'LINKS' => $link_count,
					'RESULT' => $lang['D_Bots_post_not_sent'],
					'USERNAME' => substr(preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'", $userdata['username'])), 0, 25),
					'MESSAGE' => substr(preg_replace('/\<(.*?)>/i','',preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'", bbencode_second_pass($message, $bbcode_uid)))), 0, 1000),
					'SUB' => substr(preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'",  $GLOBALS['subject'])), 0, 100)));
				$emailer->send();
				$emailer->reset();
			}
			message_die(GENERAL_MESSAGE, $lang['D_Bots_msg_guest']);
		}
	}
	elseif ($userdata['user_posts'] < ($APM_mod_installed ? 2 : 1) && $link_count > $first_post_max_link) // 1st post. 
	{
		// grrr... spammer... kill user & message! without warning...
		$sql = "DELETE FROM " . SESSIONS_TABLE . " WHERE session_ip ='$user_ip'"; 
		if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Error clearing session', '', __LINE__, __FILE__, $sql); }
		
		$sql = "SELECT group_id FROM " . USER_GROUP_TABLE . " WHERE user_id = ".$userdata['user_id'];
		if ($row = $db->sql_fetchrow($db->sql_query($sql)))
		{
			$sql = "DELETE FROM " . GROUPS_TABLE . " WHERE group_id = ".$row['group_id'];
			if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Error deleting group', '', __LINE__, __FILE__, $sql); }
		}
		
		$sql = "DELETE FROM " . USER_GROUP_TABLE . " WHERE user_id = ".$userdata['user_id'];
		if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Error deleting user to group', '', __LINE__, __FILE__, $sql); }

		$sql = "DELETE FROM " . USERS_TABLE . " WHERE user_id = ".$userdata['user_id'];
		if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Error deleting user', '', __LINE__, __FILE__, $sql); }
		
		// clean forums correctly (Advanced Posts Merging Support)
		if (isset($GLOBALS['topic_id']) && $GLOBALS['topic_id']!='' && !is_null($GLOBALS['topic_id']))
		{
//			$sql = "DELETE p.* FROM ".POSTS_TABLE." p LEFT JOIN ".USERS_TABLE." u ON p.poster_id = u.user_id WHERE (u.user_id Is Null)";
//			if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Cannot delete posts', '', __LINE__, __FILE__, $sql); }
			$sql = "SELECT p.* FROM ".POSTS_TABLE." p LEFT JOIN ".USERS_TABLE." u ON p.poster_id = u.user_id WHERE (u.user_id Is Null)";
			if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'Cannot select posts', '', __LINE__, __FILE__, $sql); }
			while ($row = $db->sql_fetchrow($result)) {
				$sql = "DELETE FROM ".POSTS_TABLE." WHERE post_id = ".$row['post_id'];
				if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Cannot delete posts', '', __LINE__, __FILE__, $sql); }
			}

//			$sql = "DELETE pt.* FROM ".POSTS_TEXT_TABLE." pt LEFT JOIN ".POSTS_TABLE." p ON p.post_id = pt.post_id WHERE (p.post_id Is Null)";
//			if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Cannot delete post texts', '', __LINE__, __FILE__, $sql); }
			$sql = "SELECT pt.* FROM ".POSTS_TEXT_TABLE." pt LEFT JOIN ".POSTS_TABLE." p ON p.post_id = pt.post_id WHERE (p.post_id Is Null)";
			if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'Cannot select post', '', __LINE__, __FILE__, $sql); }
			while ($row = $db->sql_fetchrow($result)) {
				$sql = "DELETE FROM ".POSTS_TEXT_TABLE." WHERE post_id = ".$row['post_id'];
				if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Cannot delete post text', '', __LINE__, __FILE__, $sql); }
			}

			// synchronize topics & forums
			$sql = "SELECT MIN(post_id) AS first_post, MAX(post_id) AS last_post FROM ".POSTS_TABLE." WHERE topic_id = ".$GLOBALS['topic_id'];
			if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'Could not get post ID', '', __LINE__, __FILE__, $sql);	}
			if ($row = $db->sql_fetchrow($result))
			{
				$first_post = ( $row['first_post'] ) ? $row['first_post'] : 0;
				$last_post = ( $row['last_post'] ) ? $row['last_post'] : 0;
			}
			else
			{
				$first_post = $last_post = 0;
			}
			if ($first_post!=0 && $last_post!=0)
			{
				$sql = "UPDATE ".TOPICS_TABLE." SET topic_first_post_id = $first_post, topic_last_post_id = $last_post WHERE topic_id = ".$GLOBALS['topic_id'];
				if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Could not update forum', '', __LINE__, __FILE__, $sql); }
			}
			else
			{
				// topic's empty, so kill empty topics
//				$sql = "DELETE t.* FROM ".TOPICS_TABLE." t LEFT JOIN ".POSTS_TABLE." p ON p.topic_id = t.topic_id WHERE (p.topic_id Is Null)";
//				if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Cannot delete post texts', '', __LINE__, __FILE__, $sql); }
				$sql = "SELECT t.* FROM ".TOPICS_TABLE." t LEFT JOIN ".POSTS_TABLE." p ON p.topic_id = t.topic_id WHERE (p.topic_id Is Null)";
				if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'Cannot select post', '', __LINE__, __FILE__, $sql); }
				while ($row = $db->sql_fetchrow($result)) {
					$sql = "DELETE FROM ".TOPICS_TABLE." WHERE topic_id = ".$row['topic_id'];
					if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Cannot delete topic', '', __LINE__, __FILE__, $sql); }
				}
			}
			
			$sql = "SELECT MAX(post_id) AS last_post, COUNT(post_id) AS total FROM ".POSTS_TABLE." WHERE forum_id = ".$GLOBALS['forum_id'];
			if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'Could not get post ID', '', __LINE__, __FILE__, $sql);	}
			if ($row = $db->sql_fetchrow($result))
			{
				$last_post = ( $row['last_post'] ) ? $row['last_post'] : 0;
				$total_posts = ($row['total']) ? $row['total'] : 0;
			}
			else
			{
				$last_post = $total_posts = 0;
			}

			$sql = "SELECT COUNT(topic_id) AS total FROM ".TOPICS_TABLE." WHERE forum_id = ".$GLOBALS['forum_id'];
			if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'Could not get topic count', '', __LINE__, __FILE__, $sql); }

			$total_topics = ( $row = $db->sql_fetchrow($result) ) ? ( ( $row['total'] ) ? $row['total'] : 0 ) : 0;

			$sql = "UPDATE ".FORUMS_TABLE." SET forum_last_post_id = $last_post, forum_posts = $total_posts, forum_topics = $total_topics WHERE forum_id = ".$GLOBALS['forum_id'];
			if (!$db->sql_query($sql)) { message_die(GENERAL_ERROR, 'Could not update forum', '', __LINE__, __FILE__, $sql); }
		}

		if ($send_email_to_admin)
		{
			include($phpbb_root_path . 'includes/emailer.'.$phpEx);
			$emailer = new emailer($board_config['smtp_delivery']);
			$emailer->from($board_config['board_email']);
			$emailer->replyto($board_config['board_email']);
			$emailer->use_template('detector_bot', $board_config['default_lang']);
			$emailer->email_address($admin_email);
			$emailer->set_subject($lang['D_Bots_email_subj']);
			$emailer->assign_vars(array(
				'SITENAME' => $board_config['sitename'],
				'EMAIL_SIG' => (!empty($board_config['board_email_sig'])) ? str_replace('<br />', "\n", "-- \n" . $board_config['board_email_sig']) : '',
				'IP' => $client_ip,
				'POSTS' => $userdata['user_posts'],
				'LINKS' => $link_count,
				'RESULT' => $lang['D_Bots_post_deleted'].' '.$lang['D_Bots_user_deleted'],
				'USERNAME' => substr(preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'", $userdata['username'])), 0, 25),
				'MESSAGE' => substr(preg_replace('/\<(.*?)>/i','',preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'", bbencode_second_pass($message, $bbcode_uid)))), 0, 1000),
				'SUB' => substr(preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'",  $GLOBALS['subject'])), 0, 100)));
			$emailer->send();
			$emailer->reset();
		}
		message_die(GENERAL_MESSAGE, sprintf($lang['D_Bots_msg_user_deleted'], $userdata['username']));
	}
	elseif (($userdata['user_posts'] < $oldbie_minposts && $link_count > $newbie_max_link) || ($link_count > $oldbie_max_link))
	{
		if ($use_yellowcard)
		{
			$sql = "SELECT user_warnings FROM " . USERS_TABLE . " WHERE user_id = ".$userdata['user_id'];
			if ($row = $db->sql_fetchrow($db->sql_query($sql)))
			{
				$sql = "UPDATE " . USERS_TABLE .  " SET user_warnings = ".(intval($row['user_warnings'])+1)." WHERE user_id = ".$userdata['user_id'];
				if (!($result = $db->sql_query($sql))) { message_die(GENERAL_ERROR, 'SQL Quering error', '', __LINE__, __FILE__, $sql); }
			}
			else
			{
				message_die(GENERAL_ERROR, 'SQL Quering error', '', __LINE__, __FILE__, $sql);
			}
		}
		
		if ($send_email_to_admin)
		{
			include($phpbb_root_path . 'includes/emailer.'.$phpEx);
			$emailer = new emailer($board_config['smtp_delivery']);
			$emailer->from($board_config['board_email']);
			$emailer->replyto($board_config['board_email']);
			$emailer->use_template('detector_bot', $board_config['default_lang']);
			$emailer->email_address($admin_email);
			$emailer->set_subject($lang['D_Bots_email_subj']);
			$emailer->assign_vars(array(
				'SITENAME' => $board_config['sitename'],
				'EMAIL_SIG' => (!empty($board_config['board_email_sig'])) ? str_replace('<br />', "\n", "-- \n" . $board_config['board_email_sig']) : '',
				'IP' => $client_ip,
				'POSTS' => $userdata['user_posts'],
				'LINKS' => $link_count,
				'RESULT' => $lang['D_Bots_post_not_sent'].($use_yellowcard ? ' '.sprintf($lang['D_Bots_user_mulcted'], $row['user_warnings']+1, $board_config['max_user_bancard']):''),
				'USERNAME' => substr(preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'", $userdata['username'])), 0, 25),
				'MESSAGE' => substr(preg_replace('/\<(.*?)>/i','',preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'", bbencode_second_pass($message, $bbcode_uid)))), 0, 1000),
				'SUB' => substr(preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, str_replace("\'", "'",  $GLOBALS['subject'])), 0, 100)));
			$emailer->send();
			$emailer->reset();
		}
		message_die(GENERAL_MESSAGE, sprintf($lang['D_Bots_msg_user_mulcted'], $userdata['username']));
	}
/* ---8<--------[Detector Bots]----------------------------------------- */

# 
#-----[ OPEN ]------------------------------------------ 
# 
language/lang_russian/lang_main.php

# 
#-----[ FIND ]------------------------------------------ 
#
//
// That's all Folks!
// -------------------------------------------------

# 
#-----[ BEFORE, ADD ]------------------------------------------ 
#

/* ---8<--------[Detector Bots]----------------------------------------- */
$lang['D_Bots_email_subj'] = '  ';
$lang['D_Bots_post_not_sent'] = '  .';
$lang['D_Bots_post_deleted'] = ' .';
$lang['D_Bots_user_deleted'] = ' .';
$lang['D_Bots_user_mulcted'] = ' :  %d  %d .';
$lang['D_Bots_msg_guest'] = '    .<br> ,       <a href="profile.php?mode=register"></a>.';
$lang['D_Bots_msg_user_deleted'] = '    .<br> <b>%s</b> .   ,   - ,    .';
$lang['D_Bots_msg_user_mulcted'] = '    .<br>  ,  <b>%s</b> .   ,   - ,    .';
/* ---8<--------[Detector Bots]----------------------------------------- */

# 
#-----[ OPEN ]------------------------------------------ 
# 
language/lang_english/lang_main.php

# 
#-----[ FIND ]------------------------------------------ 
#
//
// That's all Folks!
// -------------------------------------------------

# 
#-----[ BEFORE, ADD ]------------------------------------------ 
#

/* ---8<--------[Detector Bots]----------------------------------------- */
$lang['D_Bots_email_subj'] = 'Attempt of publish of advertising';
$lang['D_Bots_post_not_sent'] = 'Message wasn\'t sent.';
$lang['D_Bots_post_deleted'] = 'Message was deleted.';
$lang['D_Bots_user_deleted'] = 'User was deleted.';
$lang['D_Bots_user_mulcted'] = 'User catch Yellow Card and now has %d of %d Yellow Cards.';
$lang['D_Bots_msg_guest'] = 'Attempt of publish of advertising was detected.<br>If you want post links, you MUST <a href="profile.php?mode=register">register</a>.';
$lang['D_Bots_msg_user_deleted'] = 'Attempt of publish of advertising was detected.<br>User <b>%s</b> was deleted.';
$lang['D_Bots_msg_user_mulcted'] = 'Attempt of publish of advertising was detected.<br>Message wasn\'t sent, user <b>%s</b> catchs Yellow Card.';
/* ---8<--------[Detector Bots]----------------------------------------- */


# 
#-----[ SAVE/CLOSE ALL FILES ]------------------------------------------ 
# 
# EoM 