<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Antispam, a plugin for DotClear.  
# Copyright (c) 2007 Alain Vagner and contributors. All rights
# reserved.
#
# Antispam is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# Antispam is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Antispam; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ***** END LICENSE BLOCK *****

class dcFilterLinksLookup extends dcSpamFilter
{
	public $name = 'Links Lookup';
	
	private $server = 'multi.surbl.org';
	
	protected function setInfo()
	{
		$this->description = __('Checks links in comments against surbl.org');
	}
	
	public function getStatusMessage($status,$comment_id)
	{
		return sprintf(__('Filtered by %1$s with server %2$s.'),$this->guiLink(),$status);
	}
	
	public function isSpam($type,$author,$email,$site,$ip,$content,$post_id,&$status)
	{
		if (!$ip || long2ip(ip2long($ip)) != $ip) {
			return;
		}
		
		$urls = $this->getLinks($content);
		array_unshift($urls,$site);
		
		foreach ($urls as $u)
		{
			$b = parse_url($u);
			if (!isset($b['host']) || !$b['host']) {
				continue;
			}
			
			$domain = preg_replace('/^(.*\.)([^.]+\.[^.]+)$/','$2',$b['host']);
			$host = $domain.'.'.$this->server;
			
			if (gethostbyname($host) != $host) {
				$status = substr($domain,0,128);
				return true;
			}
		}
	}
	
	private function getLinks($text)
	{
		$res = array();
		
		# href attribute on "a" tags
		if (preg_match_all('/<a ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
		{
			for ($i = 0; $i<count($match); $i++)
			{
				if (preg_match('/href="(http:\/\/[^"]+)"/ms', $match[$i][1], $matches)) {
					$res[] = $matches[1];
				}
			}
		}
		
		return $res;
	}
}
?>