<?php

/*
 * $Id$
 *
 */

class it_banner
{

function it_banner($p = array())
{
	$this->p = (array)$p + array(
		'server' => "http://localhost/",
		'serverbase' => "http://localhost/getbanner.html",
		'host' => $_SERVER['HTTP_HOST'],
		'uri' => str_replace('/doc_static', '', $_SERVER['PHP_SELF']),
		'place' => "",
		'language' => "",
		'keyword' => "",
		'category' => "",
		'region' => "",
		'vars' => array(),
		'ip' => $_SERVER['REMOTE_ADDR'],
		'uid' => $_COOKIE['UID'],
		'bgcolor' => "",
		'width' => "",
		'height' => "",
		'mx1' => "",
		'mx2' => "",
		'my1' => "",
		'my2' => "",
		'z' => "",
		'target' => "_top",
		'timeout' => 5,
		'uidcookie' => 'crustulum',
		'enablephpbanners' => false,
		'addextraline' => "",
		'bannerid' => $_REQUEST["bannerid"],
		'exclude' => $_REQUEST["exclude"],
	);

	$this->p += array('loc' => $this->p['region']);	# Historical name
}

function choose()
{
	if ($GLOBALS['debug_noads'])
		return;

	$host = 'localhost';
	$port = 80;
	$url = '/';

	if (eregi('^[a-z]+://([^:/]+):([0-9]+)(.*)', $this->p['serverbase'], $regs))
	{
		$host = $regs[1];
		$port = $regs[2];
		$url = $regs[3];
	}
	else if (eregi('^[a-z]+://([^:/]+)(.*)', $this->p['serverbase'], $regs))
	{
		$host = $regs[1];
		$port = 80;
		$url = $regs[2];
	}

	if ($url == '')
		$url = '/';

	$params = array();

	foreach (array('host', 'uri', 'place', 'language', 'keyword', 'category', 'loc', 'mx1', 'mx2', 'my1', 'my2', 'z', 'ip', 'uid', 'bgcolor', 'bannerid', 'exclude') as $key)
		$params[$key] = $this->p[$key];

	$request .= it_html::U($url, $params);
	if ($GLOBALS['debug_adreq']) # can't use EDC since itools sometimes not included
		ED("http://$host$request");

	if ($fp = @fsockopen($host, $port, $errno, $errstr, $this->p['timeout']))
	{
		if ($this->p['uid'])
			$cookie = "Cookie: " . $this->p['uidcookie'] . "=" . urlencode($this->p['uid']) . "\r\n";
		else
			$cookie = '';

		fputs($fp, "GET $request HTTP/1.0\r\nHost: $host\r\n$cookie\r\n");

		$b = array();

		while (!feof($fp))
		{
			$line = fgets($fp, 10240);

			if (!trim($line))
				$emptylines++;

			if ($emptylines == 0)
				;
			else if (ereg("^data (.*)$", $line, $r))
			{
				$len = (int)$r[1];
				$b['data'] = '';

				while (!feof($fp) && (strlen($b['data']) < $len))
					$b['data'] .= fread($fp, $len - strlen($b['data']));

				if (strlen($b['data']) < $len)
					$b['data'] = ''; # Skip banners which got corrupted during transmission, very rare
			}
			else if (ereg("^([^ ]*) (.*)\n$", $line, $r))
			{
				$b[$r[1]] = $r[2];
			}
			else if (ereg("^</banner>", $line))
			{
				# Doubleclick artificially delays banners for Mozilla/Linux so we do not show them to linux users
				if (!(eregi('linux', $_SERVER['HTTP_USER_AGENT']) && eregi('\.doubleclick\.net', $b['data'])))
				{
					$this->bannersbyposition[$b['position'] ? $b['position'] : 'banner'] = $b;
					$this->banners[] = $b;
				}

				$b = array();
			}
		}

		if ($GLOBALS['debug_adreq']) # can't use EDC since itools sometimes not included
			ED($this->banners);
	}

	srand((double)microtime()*1000000);
	$this->rand = rand();
	$this->chosen = true;
}

/**
 * Show one or all banners for this banner position
 * @param $nocount Switch off impression counting of true for multiple display
 * @param $noecho Switch off automatic display of HTML snipplet with echo
 * @return HTML snipplet to insert banner(s) if $noecho is set, undefined otherwise
 */
function show($nocount = false, $noecho = false)
{
	if (!$this->chosen)
		$this->choose();

	if (!is_array($this->banners))
		return; // none found or choose() not called yet

	$count = count($this->banners);
	$number = 0;

	if ($noecho)
		ob_start();

	foreach ($this->banners as $banner)
	{
		$result .= $this->render($banner, $count, $number, $nocount);
		$number++;
	}

	if ($noecho)
	{
		$result = ob_get_contents();
		ob_end_clean();
	}

	return $result;
}

/**
 * Returns html code for a banner from a multi banner request
 * @param $position Which position to return, e.g. 'feature'
 * @param $nocount Suppress counting of this banner
 */
function showcombined($position = "banner", $nocount = false)
{
	ob_start();
	if ($this->bannersbyposition[$position])
		$this->render($this->bannersbyposition[$position], 1, 0, $nocount);
	$result = ob_get_contents();
	ob_end_clean();

	return $result;
}

/**
 * Renders a banner, to be overloaded e.g. to render sponsor banners in a table
 * @param $banner Opaque structure representing the banner
 * @param $count Total number of banners, also number of times this method gets called
 * @param $position Current banner number, from 0 to $count - 1
 */
function render($banner, $count, $number, $nocount = false)
{
	if ($number > 0)
		echo "<br /><br />";

	$this->render_banner($banner, $nocount);
}

/**
 * Render one banner
 * @param $banner Opaque banner structure to be rendered
 */
function render_banner($banner, $nocount = false)
{
	if ($banner['width'] <= 0)
		$banner['width'] = 468;
	if ($banner['height'] <= 0)
		$banner['height'] = 60;
	if ($this->p['width'])
		$banner['width'] = $this->p['width'];
	if ($this->p['height'])
		$banner['height'] = $this->p['height'];
	$l = $banner['locationid'];
	if (strlen($banner['matchingkeyword']) + strlen($banner['matchingcategory']) + strlen($banner['matchingregion']) + strlen($banner['language']) > 0)
		$l .= "|" . $banner['matchingkeyword'];
	if (strlen($banner['matchingcategory']) + strlen($banner['matchingregion']) + strlen($banner['language']) > 0)
		$l .= "|" . $banner['matchingcategory'];
	if (strlen($banner['matchingregion']) + strlen($banner['language']) > 0)
		$l .= "|" . $banner['matchingregion'];
	if (strlen($banner['language']) > 0)
		$l .= "|" . $banner['language'];
	$l = str_replace("/", "_", $l);

	$rand = $this->rand;

	$pathinfo = "/c=" . $banner['campaignid'] . ":" . urlencode($banner['campaignname']) . "/b=" . $banner['bannerid'] . ":" . urlencode($banner['bannername']) . "/l=" . urlencode($l);
	$nocountinfo = $nocount ? "/nocount=1" : "";
	$viewpre = $this->p['server'] . "view.html$pathinfo$nocountinfo/img=";
	$clickpre = $this->p['server'] . "click.html$pathinfo/url=";
	$clickpreenc = urlencode($clickpre);
	$auditurl = $viewpre . "empty.gif";

	$keyword = $this->p['keyword'];
	$keyword = preg_replace('/<country_[^>]*>/', '', $keyword);
	$keyword = ereg_replace('\]\[', ' ', $keyword);
	$keyword = ereg_replace('^\[ +', '', $keyword);
	$keyword = ereg_replace(' +\]$', '', $keyword);
	$keywordhtml = htmlentities(substr($keyword, 0, 30));
	$keywordurl = urlencode($keyword);

	extract($this->p['vars'], EXTR_SKIP);

	while (eregi("__([a-z]*)__", $banner['alttext'], $r))
		$banner['alttext'] = str_replace($r[0], ${strtolower($r[1])}, $banner['alttext']);
	while (eregi("__([a-z]*)__", $banner['extraline'], $r))
		$banner['extraline'] = str_replace($r[0], ${strtolower($r[1])}, $banner['extraline']);
	while (eregi("__([a-z]*)__", $banner['path'], $r))
		$banner['path'] = str_replace($r[0], ${strtolower($r[1])}, $banner['path']);
	while (eregi("__([a-z]*)__", $banner['url'], $r))
		$banner['url'] = str_replace($r[0], ${strtolower($r[1])}, $banner['url']);
	$viewurl = $viewpre . $banner['path'];
	$clickurl = $clickpre . $banner['url'];
	while (eregi("__([a-z]*)__", $banner['data'], $r))
		$banner['data'] = str_replace($r[0], ${strtolower($r[1])}, $banner['data']);

	switch ($banner['type'])
	{
		case 0:
			if (eregi('&', $viewurl) && !eregi('&[a-z]+;', $viewurl))
				$viewurl = htmlspecialchars($viewurl);

			if (eregi('&', $clickurl) && !eregi('&[a-z]+;', $clickurl))
				$clickurl = htmlspecialchars($clickurl);

			if($banner['url'] != 'http://')
			{
				$linkstart = "<a href=\"$clickurl\" target=\"" . urlencode($this->p['target']) . "\">";
				$linkend   = "</a>";
			}

			echo "$linkstart<img src=\"$viewurl\" alt=\"" . $banner['alttext'] . "\" width=\"" . $banner['width'] . "\" height=\"" . $banner['height'] . "\" border=\"0\" />$linkend";

			if (strlen($banner['extraline']) > 0)
				echo "<br />$linkstart" . $banner['extraline'] . $linkend;

			if (strlen($banner['extraline']) == 0 && $this->p['addextraline'])
				echo "<br />&nbsp;";
		break;
		case 1:
			echo $banner['data'];
			break;
		case 2:
			if ($this->p['enablephpbanners'])
				eval("?>" . $banner['data']);
			break;
	}
}

}
?>