<?php

/*
+---------------------------------------------------------------------------+
| OpenX v2.7                                                                |
| ==========                                                                |
|                                                                           |
| Copyright (c) 2003-2009 OpenX Limited                                     |
| For contact details, see: http://www.openx.org/                           |
|                                                                           |
| This program 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.                                       |
|                                                                           |
| This program 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 this program; if not, write to the Free Software               |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA |
+---------------------------------------------------------------------------+
$Id: template.php 30885 2009-01-14 14:54:31Z andrew.hill $
*/

/**
 *
 * This is autogenerated merged delivery file which contains all files
 * from delivery merged into one output file.
 *
 * !!!Warning!!!
 *
 * Do not edit this file. If you need to do any changes to any delivery PHP file
 * checkout sourcecode from the svn repository, do a necessary changes inside
 * "delivery_dev" folder and regenerate delivery files using command:
 * # ant generate-delivery
 *
 * For more information on ant generator or if you want to check why we do this
 * check out the documentation wiki page:
 * https://developer.openx.org/wiki/OptimizationPractices#GenerateDeliveryAntTask
 *
 */

// Require the initialisation file
function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true)
{
// Set up the configuration .ini file path location
if (!$configPath) {
$configPath = MAX_PATH . '/var';
}
if ($configFile) {
$configFile = '.' . $configFile;
}
$host = getHostName();
$configFileName = $configPath . '/' . $host . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$realconf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
$conf = mergeConfigFiles($realconf, $conf);
}
if (!empty($conf)) {
return $conf;
} elseif ($configFile === '.plugin') {
// For plugins, if no configuration file is found, return the sane default values
$pluginType = basename($configPath);
$defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php';
$conf = @parse_ini_file($defaultConfig, $sections);
if ($conf !== false) {
// check for false here - it's possible file doesn't exist
return $conf;
}
echo "OpenX could not read the default configuration file for the {$pluginType} plugin";
exit(1);
}
// Check for a 'default.conf.php' file
$configFileName = $configPath . '/default' . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $conf;
}
// Check to ensure Max hasn't been installed
if (file_exists(MAX_PATH . '/var/INSTALLED')) {
echo "OpenX has been installed, but no configuration file was found.\n";
exit(1);
}
// Max hasn't been installed, so delivery engine can't run
echo "OpenX has not been installed yet -- please read the INSTALL.txt file.\n";
exit(1);
}
if (!function_exists('mergeConfigFiles'))
{
function mergeConfigFiles($realConfig, $fakeConfig)
{
foreach ($fakeConfig as $key => $value) {
if (is_array($value)) {
if (!isset($realConfig[$key])) {
$realConfig[$key] = array();
}
$realConfig[$key] = mergeConfigFiles($realConfig[$key], $value);
} else {
if (isset($realConfig[$key]) && is_array($realConfig[$key])) {
$realConfig[$key][0] = $value;
} else {
if (isset($realConfig) && !is_array($realConfig)) {
$temp = $realConfig;
$realConfig = array();
$realConfig[0] = $temp;
}
$realConfig[$key] = $value;
}
}
}
unset($realConfig['realConfig']);
return $realConfig;
}
}
function setupConfigVariables()
{
$GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'] = '|';
$GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'] = '__';
// Set the URL access mechanism
if (!empty($GLOBALS['_MAX']['CONF']['openads']['requireSSL'])) {
$GLOBALS['_MAX']['HTTP'] = 'https://';
} else {
if (isset($_SERVER['SERVER_PORT'])) {
if (isset($GLOBALS['_MAX']['CONF']['openads']['sslPort'])
&& $_SERVER['SERVER_PORT'] == $GLOBALS['_MAX']['CONF']['openads']['sslPort'])
{
$GLOBALS['_MAX']['HTTP'] = 'https://';
} else {
$GLOBALS['_MAX']['HTTP'] = 'http://';
}
}
}
// Maximum random number (use default if doesn't exist - eg the case when application is upgraded)
$GLOBALS['_MAX']['MAX_RAND'] = isset($GLOBALS['_MAX']['CONF']['priority']['randmax']) ?
$GLOBALS['_MAX']['CONF']['priority']['randmax'] : 2147483647;
// Always use UTC when outside the installer
if (substr($_SERVER['SCRIPT_NAME'], -11) != 'install.php') {
OA_setTimeZoneUTC();
}
}
function setupServerVariables()
{
// PHP-CGI/IIS combination does not set REQUEST_URI
if (empty($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
if (!empty($_SERVER['QUERY_STRING'])) {
$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
}
}
}
function setupDeliveryConfigVariables()
{
if (!defined('MAX_PATH')) {
define('MAX_PATH', dirname(__FILE__).'/../..');
}
if (!defined('OX_PATH')) {
define('OX_PATH', dirname(__FILE__).'/../..');
}
if (!defined('LIB_PATH')) {
define('LIB_PATH', MAX_PATH. DIRECTORY_SEPARATOR. 'lib'. DIRECTORY_SEPARATOR. 'OX');
}
// Ensure that the initialisation has not been run before
if ( !(isset($GLOBALS['_MAX']['CONF']))) {
// Parse the Max configuration file
$GLOBALS['_MAX']['CONF'] = parseDeliveryIniFile();
}
// Set up the common configuration variables
setupConfigVariables();
}
function OA_setTimeZone($timezone)
{
// Set the new time zone
date_default_timezone_set($timezone);
// Set PEAR::Date_TimeZone default as well
//
// Ideally this should be a Date_TimeZone::setDefault() call, but for optimization
// purposes, we just override the global variable
$GLOBALS['_DATE_TIMEZONE_DEFAULT'] = $timezone;
}
function OA_setTimeZoneUTC()
{
OA_setTimeZone('UTC');
}
function OA_setTimeZoneLocal()
{
$tz = !empty($GLOBALS['_MAX']['PREF']['timezone']) ? $GLOBALS['_MAX']['PREF']['timezone'] : 'GMT';
OA_setTimeZone($tz);
}
function getHostName()
{
if (!empty($_SERVER['HTTP_HOST'])) {
$host = explode(':', $_SERVER['HTTP_HOST']);
$host = $host[0];
} else if (!empty($_SERVER['SERVER_NAME'])) {
$host = explode(':', $_SERVER['SERVER_NAME']);
$host = $host[0];
}
return $host;
}
function getHostNameWithPort()
{
if (!empty($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST'];
} else if (!empty($_SERVER['SERVER_NAME'])) {
$host = $_SERVER['SERVER_NAME'];
}
return $host;
}
function setupIncludePath()
{
static $checkIfAlreadySet;
if (isset($checkIfAlreadySet)) {
return;
}
$checkIfAlreadySet = true;
$oxPearPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'pear';
$oxZendPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib';
set_include_path($oxPearPath . PATH_SEPARATOR . $oxZendPath . PATH_SEPARATOR . get_include_path());
}
function getMinimumRequiredMemory()
{
return $GLOBALS['_MAX']['REQUIRED_MEMORY']['PHP5'];
}
function increaseMemoryLimit($setMemory) {
$memory = getMemorySizeInBytes();
if ($memory == -1) {
// unlimited
return true;
}
if ($setMemory > $memory) {
if (@ini_set('memory_limit', $setMemory) === false) {
return false;
}
}
return true;
}
function getMemorySizeInBytes() {
$phpMemory = ini_get('memory_limit');
if (empty($phpMemory) || $phpMemory == -1) {
// unlimited
return -1;
}
$aSize = array(
'G' => 1073741824,
'M' => 1048576,
'K' => 1024
);
$size = $phpMemory;
foreach($aSize as $type => $multiplier) {
$pos = strpos($phpMemory, $type);
if (!$pos) {
$pos = strpos($phpMemory, strtolower($type));
}
if ($pos) {
$size = substr($phpMemory, 0, $pos) * $multiplier;
}
}
return $size;
}
setupServerVariables();
setupDeliveryConfigVariables();
$conf = $GLOBALS['_MAX']['CONF'];
$GLOBALS['_OA']['invocationType'] = array_search(basename($_SERVER['SCRIPT_FILENAME']), $conf['file']);
// Set the log file
// Disable all notices and warnings, as some PAN code still
// generates PHP warnings in places
if (!empty($conf['debug']['production'])) {
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
} else {
// show all errors when developing
error_reporting(E_ALL);
}
$file = '/lib/max/Delivery/common.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
$file = '/lib/max/Delivery/cookie.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
$GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array();
// Include the cookie storage library
if (!is_callable('MAX_cookieSet')) {
if (!empty($conf['cookie']['plugin']) && is_readable(MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php")) {
include MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php";
} else {
function MAX_cookieSet($name, $value, $expire, $path = '/', $domain = null) { return MAX_cookieClientCookieSet($name, $value, $expire, $path, $domain); }
function MAX_cookieUnset($name) { return MAX_cookieClientCookieUnset($name); }
function MAX_cookieFlush() { return MAX_cookieClientCookieFlush(); }
function MAX_cookieLoad() { return true; }
}
}
function MAX_cookieAdd($name, $value, $expire = 0)
{
if (!isset($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
$GLOBALS['_MAX']['COOKIE']['CACHE'] = array();
}
$GLOBALS['_MAX']['COOKIE']['CACHE'][$name] = array($value, $expire);
}
function MAX_cookieSetViewerIdAndRedirect($viewerId) {
$aConf = $GLOBALS['_MAX']['CONF'];
MAX_cookieAdd($aConf['var']['viewerId'], $viewerId, _getTimeYearFromNow());
MAX_cookieFlush();
// Determine if the access to OpenX was made using HTTPS
if ($_SERVER['SERVER_PORT'] == $aConf['openads']['sslPort']) {
$url = MAX_commonConstructSecureDeliveryUrl(basename($_SERVER['PHP_SELF']));
} else {
$url = MAX_commonConstructDeliveryUrl(basename($_SERVER['PHP_SELF']));
}
$url .= "?{$aConf['var']['cookieTest']}=1&" . $_SERVER['QUERY_STRING'];
MAX_header("Location: {$url}");
exit;
}
function _getTimeThirtyDaysFromNow()
{
return MAX_commonGetTimeNow() + 2592000; // 30*24*60*60;
}
function _getTimeYearFromNow()
{
return MAX_commonGetTimeNow() + 31536000; // 365*24*60*60;
}
function _getTimeYearAgo()
{
return MAX_commonGetTimeNow() - 31536000; // 365*24*60*60;
}
function MAX_cookieUnpackCapping()
{
$conf = $GLOBALS['_MAX']['CONF'];
$cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
if (!is_array($cookieNames))
return;
// For each type of cookie, unpack and add any newly set cookies to this array
foreach ($cookieNames as $cookieName) {
if (!empty($_COOKIE[$cookieName])) {
if (!is_array($_COOKIE[$cookieName])) {
$output = array();
$data = explode('_', $_COOKIE[$cookieName]);
foreach ($data as $pair) {
list($name, $value) = explode('.', $pair);
$output[$name] = $value;
}
$_COOKIE[$cookieName] = $output;
}
}
if (!empty($_COOKIE['_' . $cookieName]) && is_array($_COOKIE['_' . $cookieName])) {
foreach ($_COOKIE['_' . $cookieName] as $adId => $cookie) {
if (_isBlockCookie($cookieName)) {
$_COOKIE[$cookieName][$adId] = $cookie;
} else {
if (isset($_COOKIE[$cookieName][$adId])) {
$_COOKIE[$cookieName][$adId] += $cookie;
} else {
$_COOKIE[$cookieName][$adId] = $cookie;
}
}
// Delete the temporary capping cookie
MAX_cookieUnset("_{$cookieName}[{$adId}]");
}
}
}
}
function _isBlockCookie($cookieName)
{
return in_array($cookieName, array(
$GLOBALS['_MAX']['CONF']['var']['blockAd'],
$GLOBALS['_MAX']['CONF']['var']['blockCampaign'],
$GLOBALS['_MAX']['CONF']['var']['blockZone'],
$GLOBALS['_MAX']['CONF']['var']['lastView'],
$GLOBALS['_MAX']['CONF']['var']['lastClick'],
$GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'],
));
}
function MAX_cookieGetUniqueViewerId($create = true)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (isset($_COOKIE[$conf['var']['viewerId']])) {
$viewerId = $_COOKIE[$conf['var']['viewerId']];
} elseif ($create) {
$viewerId = md5(uniqid('', true));  // Need to find a way to generate this...
$GLOBALS['_MAX']['COOKIE']['newViewerId'] = true;
} else {
$viewerId = null;
}
return $viewerId;
}
function MAX_cookieGetCookielessViewerID()
{
if (empty($_SERVER['REMOTE_ADDR']) || empty($_SERVER['HTTP_USER_AGENT'])) {
return '';
}
$cookiePrefix = $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'];
return $cookiePrefix . substr(md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']), 0, 32-(strlen($cookiePrefix)));
}
function MAX_Delivery_cookie_cappingOnRequest()
{
// view and xmlrpc invocation types must set capping-on-request for technical reasons
if (isset($GLOBALS['_OA']['invocationType']) &&
($GLOBALS['_OA']['invocationType'] == 'xmlrpc' || $GLOBALS['_OA']['invocationType'] == 'view')
) {
return true;
}
return !$GLOBALS['_MAX']['CONF']['logging']['adImpressions'];
}
function MAX_Delivery_cookie_setCapping($type, $id, $block = 0, $cap = 0, $sessionCap = 0)
{
$conf = $GLOBALS['_MAX']['CONF'];
$setBlock = false;
if ($cap > 0) {
// This capping cookie requires a "permanent" expiration time
$expire = MAX_commonGetTimeNow() + $conf['cookie']['permCookieSeconds'];
// The unpack capping cookies function adds this value to the counter, so to reset it we add a negative number
if (!isset($_COOKIE[$conf['var']['cap' . $type]][$id])) {
$value = 1;
$setBlock = true;
} else if ($_COOKIE[$conf['var']['cap' . $type]][$id] >= $cap) {
$value = -$_COOKIE[$conf['var']['cap' . $type]][$id]+1;
// Also reset the last-seen when resetting the frequency counter
$setBlock = true;
} else {
$value = 1;
}
MAX_cookieAdd("_{$conf['var']['cap' . $type]}[{$id}]", $value, $expire);
}
if ($sessionCap > 0) {
// The unpack capping cookies function deals with imcrementing the counter
// The expiry is set to 0 to make a session cookie
// The unpack capping cookies function adds this value to the counter, so to reset it we add a negative number
if (!isset($_COOKIE[$conf['var']['sessionCap' . $type]][$id])) {
$value = 1;
$setBlock = true;
} else if ($_COOKIE[$conf['var']['sessionCap' . $type]][$id] >= $sessionCap) {
$value = -$_COOKIE[$conf['var']['sessionCap' . $type]][$id]+1;
// Also reset the last-seen when resetting the frequency counter
$setBlock = true;
} else {
$value = 1;
}
MAX_cookieAdd("_{$conf['var']['sessionCap' . $type]}[{$id}]", $value, 0);
}
if ($block > 0 || $setBlock) {
// This blocking cookie is limited to 30 days
// Store a cookie using the current time so that the system knows when
// the last time this viewer saw this ad, an ad in this campaign or an
// ad in this zone
MAX_cookieAdd("_{$conf['var']['block' . $type]}[{$id}]", MAX_commonGetTimeNow(), _getTimeThirtyDaysFromNow());
}
}
function MAX_cookieClientCookieSet($name, $value, $expire, $path = '/', $domain = null)
{
if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xml-rpc') {
if (!isset($GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'])) {
$GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'] = array();
}
$GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'][$name] = array($value, $expire);
} else {
@setcookie($name, $value, $expire, $path, $domain);
}
}
function MAX_cookieClientCookieUnset($name)
{
MAX_cookieSet($name, false, _getTimeYearAgo());
// Work around a bug in IE where the cookie name is sometimes URL-encoded
MAX_cookieSet(str_replace('_', '%5F', urlencode($name)), false, _getTimeYearAgo());
}
function MAX_cookieClientCookieFlush()
{
$conf = $GLOBALS['_MAX']['CONF'];
MAX_cookieSendP3PHeaders();
if (!empty($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
// Set cookies
reset($GLOBALS['_MAX']['COOKIE']['CACHE']);
while (list($name,$v) = each ($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
list($value, $expire) = $v;
// Treat the viewerId cookie differently, (always set in client)
if ($name == $conf['var']['viewerId']) {
MAX_cookieClientCookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
} else {
MAX_cookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
}
}
// Clear cache
$GLOBALS['_MAX']['COOKIE']['CACHE'] = array();
}
// Compact all individual cookies into packed except for any cookies for the current bannerid
// We only need to set these packed cookies if new capping data has been merged
$cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
if (!is_array($cookieNames))
return;
// For each type of cookie, repack if necessary
foreach ($cookieNames as $cookieName) {
// We only need to write out the compacted cookie if a new item is to be inserted (or updated)
if (empty($_COOKIE["_{$cookieName}"])) {
continue;
}
switch ($cookieName) {
case $conf['var']['blockAd']            :
case $conf['var']['blockCampaign']      :
case $conf['var']['blockZone']          : $expire = _getTimeThirtyDaysFromNow(); break;
case $conf['var']['capAd']              :
case $conf['var']['capCampaign']        :
case $conf['var']['capZone']            : $expire = _getTimeYearFromNow(); break;
case $conf['var']['sessionCapCampaign'] :
case $conf['var']['sessionCapAd']       :
case $conf['var']['sessionCapZone']     : $expire = 0; break;
}
if (!empty($_COOKIE[$cookieName]) && is_array($_COOKIE[$cookieName])) {
$data = array();
foreach ($_COOKIE[$cookieName] as $adId => $value) {
$data[] = "{$adId}.{$value}";
}
// RFC says that maximum cookie data length is 4096 bytes
// So we are assuming that 2048 will be valid in most browsers
// Discard oldest data until we are under the limit
while (strlen(implode('_', $data)) > 2048) {
$data = array_slice($data, 1);
}
MAX_cookieSet($cookieName, implode('_', $data), $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
}
}
}
function MAX_cookieSendP3PHeaders() {
// Send P3P headers
if ($GLOBALS['_MAX']['CONF']['p3p']['policies']) {
MAX_header("P3P: ". _generateP3PHeader());
}
}
function _generateP3PHeader()
{
$conf = $GLOBALS['_MAX']['CONF'];
$p3p_header = '';
if ($conf['p3p']['policies']) {
if ($conf['p3p']['policyLocation'] != '') {
$p3p_header .= " policyref=\"".$conf['p3p']['policyLocation']."\"";
}
if ($conf['p3p']['policyLocation'] != '' && $conf['p3p']['compactPolicy'] != '') {
$p3p_header .= ", ";
}
if ($conf['p3p']['compactPolicy'] != '') {
$p3p_header .= " CP=\"".$conf['p3p']['compactPolicy']."\"";
}
}
return $p3p_header;
}
$file = '/lib/max/Delivery/remotehost.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
function MAX_remotehostSetInfo($run = false)
{
if (empty($GLOBALS['_OA']['invocationType']) || $run || ($GLOBALS['_OA']['invocationType'] != 'xml-rpc')) {
MAX_remotehostProxyLookup();
MAX_remotehostReverseLookup();
//MAX_remotehostSetClientInfo();  // now moved into plugin
MAX_remotehostSetGeoInfo();
}
}
function MAX_remotehostProxyLookup()
{
$conf = $GLOBALS['_MAX']['CONF'];
// Should proxy lookup conversion be performed?
if ($conf['logging']['proxyLookup']) {
// Determine if the viewer has come via an HTTP proxy
$proxy = false;
if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$proxy = true;
} elseif (!empty($_SERVER['REMOTE_HOST'])) {
$aProxyHosts = array(
'proxy',
'cache',
'inktomi'
);
foreach ($aProxyHosts as $proxyName) {
if (strpos($_SERVER['REMOTE_HOST'], $proxyName) !== false) {
$proxy = true;
break;
}
}
}
// Has the viewer come via an HTTP proxy?
if ($proxy) {
// Try to find the "real" IP address the viewer has come from
$aHeaders = array(
'HTTP_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_FORWARDED_FOR',
'HTTP_CLIENT_IP'
);
foreach ($aHeaders as $header) {
if (!empty($_SERVER[$header])) {
$ip = $_SERVER[$header];
break;
}
}
if (!empty($ip)) {
// The "remote IP" may be a list, ensure that
// only the last item is used in that case
$ip = explode(',', $ip);
$ip = trim($ip[count($ip) - 1]);
// If the found address is not unknown or a private network address
if (($ip != 'unknown') && (!MAX_remotehostPrivateAddress($ip))) {
// Set the "real" remote IP address, and unset
// the remote host (as it will be wrong for the
// newly found IP address) and HTTP_VIA header
// (so that we don't accidently do this twice)
$_SERVER['REMOTE_ADDR'] = $ip;
$_SERVER['REMOTE_HOST'] = '';
$_SERVER['HTTP_VIA']    = '';
}
}
}
}
}
function MAX_remotehostReverseLookup()
{
// Is the remote host name already set?
if (empty($_SERVER['REMOTE_HOST'])) {
// Should reverse lookups be performed?
if ($GLOBALS['_MAX']['CONF']['logging']['reverseLookup']) {
$_SERVER['REMOTE_HOST'] = @gethostbyaddr($_SERVER['REMOTE_ADDR']);
} else {
$_SERVER['REMOTE_HOST'] = $_SERVER['REMOTE_ADDR'];
}
}
}
function MAX_remotehostSetGeoInfo()
{
if (!function_exists('parseDeliveryIniFile')) {
function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true)
{
// Set up the configuration .ini file path location
if (!$configPath) {
$configPath = MAX_PATH . '/var';
}
if ($configFile) {
$configFile = '.' . $configFile;
}
$host = getHostName();
$configFileName = $configPath . '/' . $host . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$realconf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
$conf = mergeConfigFiles($realconf, $conf);
}
if (!empty($conf)) {
return $conf;
} elseif ($configFile === '.plugin') {
// For plugins, if no configuration file is found, return the sane default values
$pluginType = basename($configPath);
$defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php';
$conf = @parse_ini_file($defaultConfig, $sections);
if ($conf !== false) {
// check for false here - it's possible file doesn't exist
return $conf;
}
echo "OpenX could not read the default configuration file for the {$pluginType} plugin";
exit(1);
}
// Check for a 'default.conf.php' file
$configFileName = $configPath . '/default' . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $conf;
}
// Check to ensure Max hasn't been installed
if (file_exists(MAX_PATH . '/var/INSTALLED')) {
echo "OpenX has been installed, but no configuration file was found.\n";
exit(1);
}
// Max hasn't been installed, so delivery engine can't run
echo "OpenX has not been installed yet -- please read the INSTALL.txt file.\n";
exit(1);
}
if (!function_exists('mergeConfigFiles'))
{
function mergeConfigFiles($realConfig, $fakeConfig)
{
foreach ($fakeConfig as $key => $value) {
if (is_array($value)) {
if (!isset($realConfig[$key])) {
$realConfig[$key] = array();
}
$realConfig[$key] = mergeConfigFiles($realConfig[$key], $value);
} else {
if (isset($realConfig[$key]) && is_array($realConfig[$key])) {
$realConfig[$key][0] = $value;
} else {
if (isset($realConfig) && !is_array($realConfig)) {
$temp = $realConfig;
$realConfig = array();
$realConfig[0] = $temp;
}
$realConfig[$key] = $value;
}
}
}
unset($realConfig['realConfig']);
return $realConfig;
}
}
}
$aConf = $GLOBALS['_MAX']['CONF'];
$type = (!empty($aConf['geotargeting']['type'])) ? $aConf['geotargeting']['type'] : null;
if (!is_null($type) && $type != 'none') {
$aComponent = explode(':', $aConf['geotargeting']['type']);
if (!empty($aComponent[1]) && (!empty($aConf['pluginGroupComponents'][$aComponent[1]]))) {
$GLOBALS['_MAX']['CLIENT_GEO'] = OX_Delivery_Common_hook('getGeoInfo', array(), $type);
}
}
}
function MAX_remotehostPrivateAddress($ip)
{
setupIncludePath();
require_once 'Net/IPv4.php';
// Define the private address networks, see
// http://rfc.net/rfc1918.html
$aPrivateNetworks = array(
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'127.0.0.0/24'
);
foreach ($aPrivateNetworks as $privateNetwork) {
if (Net_IPv4::ipInNetwork($ip, $privateNetwork)) {
return true;
}
}
return false;
}
$file = '/lib/max/Delivery/log.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
$file = '/lib/max/Dal/Delivery.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
function MAX_Dal_Delivery_Include()
{
static $included;
if (isset($included)) {
return;
}
$included = true;
$conf = $GLOBALS['_MAX']['CONF'];
if (isset($conf['origin']['type']) && is_readable(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php')) {
require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php');
} else {
require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['database']['type']) . '.php');
}
}
function MAX_trackerbuildJSVariablesScript($trackerid, $conversionInfo, $trackerJsCode = null)
{
$conf = $GLOBALS['_MAX']['CONF'];
$buffer = '';
$url = MAX_commonGetDeliveryUrl($conf['file']['conversionvars']);
$tracker = MAX_cacheGetTracker($trackerid);
$variables = MAX_cacheGetTrackerVariables($trackerid);
$variableQuerystring = '';
if (empty($trackerJsCode)) {
$trackerJsCode = md5(uniqid('', true));
} else {
// Appended tracker - set method to default
$tracker['variablemethod'] = 'default';
}
if (!empty($variables)) {
if ($tracker['variablemethod'] == 'dom') {
$buffer .= "
function MAX_extractTextDom(o)
{
var txt = '';
if (o.nodeType == 3) {
txt = o.data;
} else {
for (var i = 0; i < o.childNodes.length; i++) {
txt += MAX_extractTextDom(o.childNodes[i]);
}
}
return txt;
}
function MAX_TrackVarDom(id, v)
{
if (max_trv[id][v]) { return; }
var o = document.getElementById(v);
if (o) {
max_trv[id][v] = escape(o.tagName == 'INPUT' ? o.value : MAX_extractTextDom(o));
}
}";
$funcName = 'MAX_TrackVarDom';
} elseif ($tracker['variablemethod'] == 'default') {
$buffer .= "
function MAX_TrackVarDefault(id, v)
{
if (max_trv[id][v]) { return; }
if (typeof(window[v]) == undefined) { return; }
max_trv[id][v] = window[v];
}";
$funcName = 'MAX_TrackVarDefault';
} else {
$buffer .= "
function MAX_TrackVarJs(id, v, c)
{
if (max_trv[id][v]) { return; }
if (typeof(window[v]) == undefined) { return; }
if (typeof(c) != 'undefined') {
eval(c);
}
max_trv[id][v] = window[v];
}";
$funcName = 'MAX_TrackVarJs';
}
$buffer .= "
if (!max_trv) { var max_trv = new Array(); }
if (!max_trv['{$trackerJsCode}']) { max_trv['{$trackerJsCode}'] = new Array(); }";
foreach($variables as $key => $variable) {
$variableQuerystring .= "&{$variable['name']}=\"+max_trv['{$trackerJsCode}']['{$variable['name']}']+\"";
if ($tracker['variablemethod'] == 'custom') {
$buffer .= "
{$funcName}('{$trackerJsCode}', '{$variable['name']}', '".addcslashes($variable['variablecode'], "'")."');";
} else {
$buffer .= "
{$funcName}('{$trackerJsCode}', '{$variable['name']}');";
}
}
if (!empty($variableQuerystring)) {
$buffer .= "
document.write (\"<\" + \"script language='JavaScript' type='text/javascript' src='\");
document.write (\"$url?trackerid=$trackerid&server_conv_id={$conversionInfo['server_conv_id']}&server_raw_ip={$conversionInfo['server_raw_ip']}{$variableQuerystring}'\");";
$buffer .= "\n\tdocument.write (\"><\\/scr\"+\"ipt>\");";
}
}
if(!empty($tracker['appendcode'])) {
// Add the correct "inherit" parameter if a OpenX trackercode was found
$tracker['appendcode'] = preg_replace('/("\?trackerid=\d+&amp;inherit)=1/', '$1='.$trackerJsCode, $tracker['appendcode']);
$jscode = MAX_javascriptToHTML($tracker['appendcode'], "MAX_{$trackerid}_appendcode");
// Replace template style variables
$jscode = preg_replace("/\{m3_trackervariable:(.+?)\}/", "\"+max_trv['{$trackerJsCode}']['$1']+\"", $jscode);
$buffer .= "\n".preg_replace('/^/m', "\t", $jscode)."\n";
}
if (empty($buffer)) {
$buffer = "document.write(\"\");";
}
return $buffer;
}
function MAX_trackerCheckForValidAction($trackerid)
{
// Get all creatives that are linked to this tracker
$aTrackerLinkedAds = MAX_cacheGetTrackerLinkedCreatives($trackerid);
// This tracker is not linked to any creatives
if (empty($aTrackerLinkedAds)) {
return false;
}
// Note: Constants are not included n the delivery engine, the values below map to the values defined in constants.php
$aPossibleActions = _getActionTypes();
$now = MAX_commonGetTimeNow();
$aConf = $GLOBALS['_MAX']['CONF'];
$aMatchingActions = array();
// Iterate over all creatives linked to this tracker...
foreach ($aTrackerLinkedAds as $creativeId => $aLinkedInfo) {
// Iterate over all possible actions (currently only "view" and "click")
foreach ($aPossibleActions as $actionId => $action) {
// If there is both a connection window set, and this creative has been actioned
if (!empty($aLinkedInfo[$action . '_window']) && !empty($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId])) {
list($lastAction, $zoneId) = explode('-', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId]);
// Decode the base32 timestamp
$lastAction = MAX_commonUnCompressInt($lastAction);
// Calculate how long ago this action occured
$lastSeenSecondsAgo = $now - $lastAction;
// If the action occured within the window (and sanity check that it's > 0), record this as a matching action
if ($lastSeenSecondsAgo <= $aLinkedInfo[$action . '_window'] && $lastSeenSecondsAgo > 0) {
// Index the matching array against the # seconds ago that the action occured
$aMatchingActions[$lastSeenSecondsAgo] = array(
'action_type'   => $actionId,
'tracker_type'  => $aLinkedInfo['tracker_type'],
'status'        => $aLinkedInfo['status'],
'cid'           => $creativeId,
'zid'           => $zoneId,
'dt'            => $lastAction,
'window'        => $aLinkedInfo[$action . '_window'],
);
}
}
}
}
// If no actions matched, return false
if (empty($aMatchingActions)) {
return false;
}
// Sort by ascending #seconds since action
ksort($aMatchingActions);
// Return the first matching action
return array_shift($aMatchingActions);
}
function MAX_trackerDeleteActionFromCookie($aConnection)
{
$trackerTypes = _getTrackerTypes();
if ($trackerTypes[$aConnection['tracker_type']] != 'sale') {
// We only clear the cookie information for "sale" trackers
return;
}
// Haven't planned how this will be achieved yet...
// The cookie packing mechanism wasn't built to allow deleting items from the compacted array
// I'm guessing something like set _cookieName[adId] = "false", then unset from packed when recompacting
$actionTypes = _getActionTypes();
$aConf = $GLOBALS['_MAX']['CONF'];
$cookieName = '_' . $aConf['var']['last' . ucfirst($actionTypes[$aConnection['action_type']])] . "[{$aConnection['cid']}]";
MAX_cookieAdd($cookieName, 'false', _getTimeThirtyDaysFromNow());
}
function _getActionTypes()
{
return array(0 => 'view', 1 => 'click');
}
function _getTrackerTypes()
{
return array(1 => 'sale', 2 => 'lead', 3 => 'signup');
}
function MAX_Delivery_log_logAdRequest($adId, $zoneId)
{
if (_viewersHostOkayToLog()) {
// Call all registered plugins that use the "logRequest" hook
OX_Delivery_Common_hook('logRequest', array($adId, $zoneId));
}
}
function MAX_Delivery_log_logAdImpression($adId, $zoneId)
{
if (_viewersHostOkayToLog()) {
// Call all registered plugins that use the "logImpression" hook
OX_Delivery_Common_hook('logImpression', array($adId, $zoneId));
}
}
function MAX_Delivery_log_logAdClick($adId, $zoneId)
{
if (_viewersHostOkayToLog()) {
// Call all registered plugins that use the "logClick" hook
OX_Delivery_Common_hook('logClick', array($adId, $zoneId));
}
}
function MAX_Delivery_log_logConversion($trackerId, $aConversion)
{
if (_viewersHostOkayToLog()) {
// Prepare the raw database IP address, depending on if OpenX is running
// with multiple delivery servers, or just a single server
$aConf = $GLOBALS['_MAX']['CONF'];
if (empty($aConf['rawDatabase']['host'])) {
if (!empty($aConf['lb']['enabled'])) {
$aConf['rawDatabase']['host'] = $_SERVER['SERVER_ADDR'];
} else {
$aConf['rawDatabase']['host'] = 'singleDB';
}
}
if (isset($aConf['rawDatabase']['serverRawIp'])) {
$serverRawIp = $aConf['rawDatabase']['serverRawIp'];
} else {
$serverRawIp = $aConf['rawDatabase']['host'];
}
// Call all registered plugins that use the "logConversion" hook
$aConversionInfo = OX_Delivery_Common_hook('logConversion', array($trackerId, $serverRawIp, $aConversion));
// Check that the conversion was logged correctly
if (is_array($aConversionInfo)) {
// If this was a "sale" type conversion, then clear the cookie data
MAX_trackerDeleteActionFromCookie($aConnection);
// Return the result
return $aConversionInfo;
}
}
return false;
}
function MAX_Delivery_log_logVariableValues($aVariables, $trackerId, $serverConvId, $serverRawIp)
{
$aConf = $GLOBALS['_MAX']['CONF'];
// Get the variable information, including the Variable ID
foreach ($aVariables as $aVariable) {
if (isset($_GET[$aVariable['name']])) {
$value = $_GET[$aVariable['name']];
// Do not save variable if empty or if the JS engine set it to "undefined"
if (!strlen($value) || $value == 'undefined') {
unset($aVariables[$aVariable['variable_id']]);
continue;
}
// Sanitize by datatype
switch ($aVariable['type']) {
case 'int':
case 'numeric':
// Strip useless chars, such as currency
$value = preg_replace('/[^0-9.]/', '', $value);
$value = floatval($value);
break;
case 'date':
if (!empty($value)) {
$value = date('Y-m-d H:i:s', strtotime($value));
} else {
$value = '';
}
break;
}
} else {
// Do not save anything if the variable isn't set
unset($aVariables[$aVariable['variable_id']]);
continue;
}
$aVariables[$aVariable['variable_id']]['value'] = $value;
}
if (count($aVariables)) {
OX_Delivery_Common_hook('logConversionVariable', array($aVariables, $trackerId, $serverConvId, $serverRawIp));
}
}
function _viewersHostOkayToLog()
{
$aConf = $GLOBALS['_MAX']['CONF'];
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
// Check the user-agent against the list of known browsers (if set)
if (!empty($aConf['logging']['enforceUserAgents'])) {
$aKnownBrowsers = explode('|', strtolower($aConf['logging']['enforceUserAgents']));
$allowed = false;
foreach ($aKnownBrowsers as $browser) {
if (strpos($agent, $browser) !== false) {
$allowed = true;
break;
}
}
if (!$allowed) return false;
}
// Check the user-agent against the list of known bots (if set)
if (!empty($aConf['logging']['ignoreUserAgents'])) {
$aKnownBots = explode('|', strtolower($aConf['logging']['ignoreUserAgents']));
foreach ($aKnownBots as $bot) {
if (strpos($agent, $bot) !== false) {
return false;
}
}
}
// Check if this IP address has been blocked
if (!empty($aConf['logging']['ignoreHosts'])) {
$hosts = str_replace(',', '|', $aConf['logging']['ignoreHosts']);
$hosts = '#('.$hosts.')$#i';
// Format the hosts to ignore in a PCRE format
$hosts = str_replace('.', '\.', $hosts);
$hosts = str_replace('*', '[^.]+', $hosts);
// Check if the viewer's IP address is in the ignore list
if (preg_match($hosts, $_SERVER['REMOTE_ADDR'])) {
return false;
}
// Check if the viewer's hostname is in the ignore list
if (preg_match($hosts, $_SERVER['REMOTE_HOST'])) {
return false;
}
}
return true;
}
function MAX_Delivery_log_getArrGetVariable($name)
{
$varName = $GLOBALS['_MAX']['CONF']['var'][$name];
return isset($_GET[$varName]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_GET[$varName]) : array();
}
function MAX_Delivery_log_ensureIntegerSet(&$aArray, $index)
{
if (!is_array($aArray)) {
$aArray = array();
}
if (empty($aArray[$index])) {
$aArray[$index] = 0;
} else {
if (!is_integer($aArray[$index])) {
$aArray[$index] = intval($aArray[$index]);
}
}
}
function MAX_Delivery_log_setAdLimitations($index, $aAds, $aCaps)
{
_setLimitations('Ad', $index, $aAds, $aCaps);
}
function MAX_Delivery_log_setCampaignLimitations($index, $aCampaigns, $aCaps)
{
_setLimitations('Campaign', $index, $aCampaigns, $aCaps);
}
function MAX_Delivery_log_setZoneLimitations($index, $aZones, $aCaps)
{
_setLimitations('Zone', $index, $aZones, $aCaps);
}
function MAX_Delivery_log_setLastAction($index, $aAdIds, $aZoneIds, $aSetLastSeen, $action = 'view')
{
$aConf = $GLOBALS['_MAX']['CONF'];
if (!empty($aSetLastSeen[$index])) {
MAX_cookieAdd("_{$aConf['var']['last' . ucfirst($action)]}[{$aAdIds[$index]}]", MAX_commonCompressInt(MAX_commonGetTimeNow()) . "-" . $aZoneIds[$index], _getTimeThirtyDaysFromNow());
}
}
function MAX_Delivery_log_setClickBlocked($index, $aAdIds)
{
$aConf = $GLOBALS['_MAX']['CONF'];
MAX_cookieAdd("_{$aConf['var']['blockLoggingClick']}[{$aAdIds[$index]}]", MAX_commonCompressInt(MAX_commonGetTimeNow()), _getTimeThirtyDaysFromNow());
}
function MAX_Delivery_log_isClickBlocked($adId, $aBlockLoggingClick)
{
if (isset($GLOBALS['conf']['logging']['blockAdClicksWindow']) && $GLOBALS['conf']['logging']['blockAdClicksWindow'] != 0) {
if (isset($aBlockLoggingClick[$adId])) {
$endBlock = MAX_commonUnCompressInt($aBlockLoggingClick[$adId]) + $GLOBALS['conf']['logging']['blockAdClicksWindow'];
if ($endBlock >= MAX_commonGetTimeNow()) {
return true;
}
}
}
return false;
}
function _setLimitations($type, $index, $aItems, $aCaps)
{
// Ensure that the capping values for this item are set
MAX_Delivery_log_ensureIntegerSet($aCaps['block'], $index);
MAX_Delivery_log_ensureIntegerSet($aCaps['capping'], $index);
MAX_Delivery_log_ensureIntegerSet($aCaps['session_capping'], $index);
// Set the capping cookies
MAX_Delivery_cookie_setCapping(
$type,
$aItems[$index],
$aCaps['block'][$index],
$aCaps['capping'][$index],
$aCaps['session_capping'][$index]
);
}
function MAX_commonGetDeliveryUrl($file = null)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) {
$url = MAX_commonConstructSecureDeliveryUrl($file);
} else {
$url = MAX_commonConstructDeliveryUrl($file);
}
return $url;
}
function MAX_commonConstructDeliveryUrl($file)
{
$conf = $GLOBALS['_MAX']['CONF'];
return 'http://' . $conf['webpath']['delivery'] . '/' . $file;
}
function MAX_commonConstructSecureDeliveryUrl($file)
{
$conf = $GLOBALS['_MAX']['CONF'];
if ($conf['openads']['sslPort'] != 443) {
// Fix the delivery host
$path = preg_replace('#/#', ':' . $conf['openads']['sslPort'] . '/', $conf['webpath']['deliverySSL'], 1);
} else {
$path = $conf['webpath']['deliverySSL'];
}
return 'https://' . $path . '/' . $file;
}
function MAX_commonConstructPartialDeliveryUrl($file, $ssl = false)
{
$conf = $GLOBALS['_MAX']['CONF'];
if ($ssl) {
return '//' . $conf['webpath']['deliverySSL'] . '/' . $file;
} else {
return '//' . $conf['webpath']['delivery'] . '/' . $file;
}
}
function MAX_commonRemoveSpecialChars(&$var)
{
static $magicQuotes;
if (!isset($magicQuotes)) {
$magicQuotes = get_magic_quotes_gpc();
}
if (isset($var)) {
if (!is_array($var)) {
if ($magicQuotes) {
$var = stripslashes($var);
}
$var = strip_tags($var);
$var = str_replace(array("\n", "\r"), array('', ''), $var);
$var = trim($var);
} else {
array_walk($var, 'MAX_commonRemoveSpecialChars');
}
}
}
function MAX_commonConvertEncoding($content, $toEncoding, $fromEncoding = 'UTF-8', $aExtensions = null) {
// Sanity check :)
if (($toEncoding == $fromEncoding) || empty($toEncoding)) {
return $content;
}
// Default extensions
if (!isset($aExtensions) || !is_array($aExtensions)) {
$aExtensions = array('iconv', 'mbstring', 'xml');
}
// Walk arrays
if (is_array($content)) {
foreach ($content as $key => $value) {
$content[$key] = MAX_commonConvertEncoding($value, $toEncoding, $fromEncoding, $aExtensions);
}
return $content;
} else {
// Uppercase charsets
$toEncoding   = strtoupper($toEncoding);
$fromEncoding = strtoupper($fromEncoding);
// Charset mapping
$aMap = array();
$aMap['mbstring']['WINDOWS-1255'] = 'ISO-8859-8'; // Best match to convert hebrew w/ mbstring
$aMap['xml']['ISO-8859-15'] = 'ISO-8859-1'; // Best match
// Start conversion
$converted = false;
foreach ($aExtensions as $extension) {
$mappedFromEncoding = isset($aMap[$extension][$fromEncoding]) ? $aMap[$extension][$fromEncoding] : $fromEncoding;
$mappedToEncoding   = isset($aMap[$extension][$toEncoding])   ? $aMap[$extension][$toEncoding]   : $toEncoding;
switch ($extension) {
case 'iconv':
if (function_exists('iconv')) {
$converted = @iconv($mappedFromEncoding, $mappedToEncoding, $content);
}
break;
case 'mbstring':
if (function_exists('mb_convert_encoding')) {
$converted = @mb_convert_encoding($content, $mappedToEncoding, $mappedFromEncoding);
}
break;
case 'xml':
if (function_exists('utf8_encode')) {
// Does this actually help us at all? it can only convert between UTF8 and ISO-8859-1
if ($mappedToEncoding == 'UTF-8' && $mappedFromEncoding == 'ISO-8859-1') {
$converted = utf8_encode($content);
} elseif ($mappedToEncoding == 'ISO-8859-1' && $mappedFromEncoding == 'UTF-8') {
$converted = utf8_decode($content);
}
}
break;
}
}
return $converted ? $converted : $content;
}
}
function MAX_commonSendContentTypeHeader($type = 'text/html', $charset = null)
{
$header = 'Content-type: ' . $type;
if (!empty($charset)) { $header .= '; charset=' . $charset; }
MAX_header($header);
}
function MAX_commonSetNoCacheHeaders()
{
MAX_header('Pragma: no-cache');
MAX_header('Cache-Control: private, max-age=0, no-cache');
MAX_header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
}
function MAX_commonAddslashesRecursive($a)
{
if (is_array($a)) {
reset($a);
while (list($k,$v) = each($a)) {
$a[$k] = MAX_commonAddslashesRecursive($v);
}
reset ($a);
return ($a);
} else {
return is_null($a) ? null : addslashes($a);
}
}
function MAX_commonRegisterGlobalsArray($args = array())
{
static $magic_quotes_gpc;
if (!isset($magic_quotes_gpc)) {
$magic_quotes_gpc = ini_get('magic_quotes_gpc');
}
$found = false;
foreach($args as $key) {
if (isset($_GET[$key])) {
$value = $_GET[$key];
$found = true;
}
if (isset($_POST[$key])) {
$value = $_POST[$key];
$found = true;
}
if ($found) {
if (!$magic_quotes_gpc) {
if (!is_array($value)) {
$value = addslashes($value);
} else {
$value = MAX_commonAddslashesRecursive($value);
}
}
$GLOBALS[$key] = $value;
$found = false;
}
}
}
function MAX_commonDeriveSource($source)
{
return MAX_commonEncrypt(trim(urldecode($source)));
}
function MAX_commonEncrypt($string)
{
$convert = '';
if (isset($string) && substr($string,1,4) != 'obfs' && $GLOBALS['_MAX']['CONF']['delivery']['obfuscate']) {
$strLen = strlen($string);
for ($i=0; $i < $strLen; $i++) {
$dec = ord(substr($string,$i,1));
if (strlen($dec) == 2) {
$dec = 0 . $dec;
}
$dec = 324 - $dec;
$convert .= $dec;
}
$convert = '{obfs:' . $convert . '}';
return ($convert);
} else {
return $string;
}
}
function MAX_commonDecrypt($string)
{
$conf = $GLOBALS['_MAX']['CONF'];
$convert = '';
if (isset($string) && substr($string,1,4) == 'obfs' && $conf['delivery']['obfuscate']) {
$strLen = strlen($string);
for ($i=6; $i < $strLen-1; $i = $i+3) {
$dec = substr($string,$i,3);
$dec = 324 - $dec;
$dec = chr($dec);
$convert .= $dec;
}
return ($convert);
} else {
return($string);
}
}
function MAX_commonInitVariables()
{
MAX_commonRegisterGlobalsArray(array('context', 'source', 'target', 'withText', 'withtext', 'ct0', 'what', 'loc', 'referer', 'zoneid', 'campaignid', 'bannerid', 'clientid', 'charset'));
global $context, $source, $target, $withText, $withtext, $ct0, $what, $loc, $referer, $zoneid, $campaignid, $bannerid, $clientid, $charset;
if (isset($withText) && !isset($withtext))  $withtext = $withText;
$withtext   = (isset($withtext) && is_numeric($withtext) ? $withtext : 0  );
$ct0        = (isset($ct0)          ? $ct0          : ''        );
$context    = (isset($context)      ? $context      : array()   );
$target     = (isset($target)  && (!empty($target))  && (!strpos($target , chr(32))) ? $target       : '_blank'  );
$charset    = (isset($charset) && (!empty($charset)) && (!strpos($charset, chr(32))) ? $charset      : 'UTF-8'  );
$bannerid   = (isset($bannerid)     && is_numeric($bannerid)    ? $bannerid     : ''        );
$campaignid = (isset($campaignid)   && is_numeric($campaignid)  ? $campaignid   : ''        );
$clientid   = (isset($clientid)     && is_numeric($clientid)    ? $clientid     : ''        );
$zoneid     = (isset($zoneid)       && is_numeric($zoneid)      ? $zoneid       : ''        );
if (!isset($what))
{
if (!empty($bannerid)) {
$what = 'bannerid:'.$bannerid;
} elseif (!empty($campaignid)) {
$what = 'campaignid:'.$campaignid;
} elseif (!empty($zoneid)) {
$what = 'zone:'.$zoneid;
} else {
$what = '';
}
}
elseif (preg_match('/^([a-z]+):(\d+)$/', $what, $matches))
{
switch ($matches[1])
{
case 'zoneid':
case 'zone':
$zoneid     = $matches[2];
break;
case 'bannerid':
$bannerid   = $matches[2];
break;
case 'campaignid':
$campaignid = $matches[2];
break;
case 'clientid':
$clientid   = $matches[2];
break;
}
}
// 2.0 backwards compatibility - clientid parameter was used to fetch a campaign
if (!isset($clientid)) $clientid = '';
if (!isset($campaignid))  $campaignid = $clientid;
$source = MAX_commonDeriveSource($source);
if (!empty($loc)) {
$loc = stripslashes($loc);
} elseif (!empty($_SERVER['HTTP_REFERER'])) {
$loc = $_SERVER['HTTP_REFERER'];
} else {
$loc = '';
}
$loc = urldecode($loc);
// Set real referer - Only valid if passed in
if (!empty($referer)) {
$_SERVER['HTTP_REFERER'] = stripslashes($referer);
} else {
if (isset($_SERVER['HTTP_REFERER'])) unset($_SERVER['HTTP_REFERER']);
}
$referer = urldecode($referer);
$GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array(
$GLOBALS['_MAX']['CONF']['var']['blockAd'],
$GLOBALS['_MAX']['CONF']['var']['capAd'],
$GLOBALS['_MAX']['CONF']['var']['sessionCapAd'],
$GLOBALS['_MAX']['CONF']['var']['blockCampaign'],
$GLOBALS['_MAX']['CONF']['var']['capCampaign'],
$GLOBALS['_MAX']['CONF']['var']['sessionCapCampaign'],
$GLOBALS['_MAX']['CONF']['var']['blockZone'],
$GLOBALS['_MAX']['CONF']['var']['capZone'],
$GLOBALS['_MAX']['CONF']['var']['sessionCapZone'],
$GLOBALS['_MAX']['CONF']['var']['lastClick'],
$GLOBALS['_MAX']['CONF']['var']['lastView'],
$GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'],
);
}
function MAX_commonDisplay1x1()
{
MAX_header('Content-Type: image/gif');
MAX_header('Content-Length: 43');
// 1 x 1 gif
echo base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==');
}
function MAX_commonGetTimeNow()
{
static $now;
if (!isset($now)) {
$now = $GLOBALS['_MAX']['NOW'] = time();
}
return $now;
}
function MAX_header($value)
{
header($value);
}
function MAX_redirect($url)
{
header('Location: '.$url);
MAX_sendStatusCode(302);
}
function MAX_sendStatusCode($iStatusCode) {
$aConf = $GLOBALS['_MAX']['CONF'];
$arr = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '[Unused]',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
if (isset($arr[$iStatusCode])) {
$text = $iStatusCode . ' ' . $arr[$iStatusCode];
// Using header('Status: foo') with CGI sapis appears to be deprecated but PHP-CGI seems to discard
// the Reason-Phrase and some webservers do not add a default one. Some bad spiders do not cope
// with that, that's why we added the cgiForceStatusHeader confgiuration directive. If enabled
// with CGI sapis, OpenX will use a "Status: NNN Reason" header, which seems to fix the behaviour
// on the tested webserver (Apache 1.3, running php-cgi)
if (!empty($aConf['delivery']['cgiForceStatusHeader']) && strpos(php_sapi_name(), 'cgi') !== 0) {
MAX_header('Status: ' . $text);
} else {
MAX_header($_SERVER["SERVER_PROTOCOL"] .' ' . $text);
}
}
}
function MAX_commonPackContext($context = array())
{
//return base64_encode(serialize($context));
$include = array();
$exclude = array();
foreach ($context as $idx => $value) {
reset($value);
list($key, $value) = each($value);
list($item,$id) = explode(':', $value);
switch ($item) {
case 'campaignid':  $value = 'c:' . $id; break;
case 'clientid':    $value = 'a:' . $id; break;
case 'bannerid':    $value = 'b:' . $id; break;
case 'companionid': $value = 'p:' . $id; break;
}
switch ($key) {
case '!=': $exclude[] = $value; break;
case '==': $include[] = $value; break;
}
}
return base64_encode(implode('#', $exclude) . '|' . implode('#', $include));
}
function MAX_commonUnpackContext($context = '')
{
//return unserialize(base64_decode($context));
list($exclude,$include) = explode('|', base64_decode($context));
return array_merge(_convertContextArray('!=', explode('#', $exclude)), _convertContextArray('==', explode('#', $include)));
}
function MAX_commonCompressInt($int)
{
return base_convert($int, 10, 36);
}
function MAX_commonUnCompressInt($string)
{
return base_convert($string, 36, 10);
}
function _convertContextArray($key, $array)
{
$unpacked = array();
foreach ($array as $value) {
if (empty($value)) { continue; }
list($item, $id) = explode(':', $value);
switch ($item) {
case 'c': $unpacked[] = array($key => 'campaignid:' . $id); break;
case 'a': $unpacked[] = array($key => 'clientid:'   . $id); break;
case 'b': $unpacked[] = array($key => 'bannerid:'   . $id); break;
case 'p': $unpacked[] = array($key => 'companionid:'.$id); break;
}
}
return $unpacked;
}
function OX_Delivery_Common_hook($hookName, $aParams = array(), $functionName = '')
{
$return = null;
// When a $functionname is passed in we use that function/component-identifier and execute the hook
if (!empty($functionName)) {
// Right now, we're allowing either a plain function to be executed, or a component-identifier
// we may remove the ability to pass a plain function in the future
$aParts = explode(':', $functionName);
if (count($aParts) === 3) {
$functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($functionName, $hookName);
}
if (function_exists($functionName)) {
$return = call_user_func_array($functionName, $aParams);
}
} else {
// When no $functionName is passed in, we execute all components which are registered for this hook
if (!empty($GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName])) {
$return = array();
$hooks = explode('|', $GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName]);
foreach ($hooks as $identifier) {
$functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hookName);
if (function_exists($functionName)) {
$return[$identifier] = call_user_func_array($functionName, $aParams);
}
}
}
}
return $return;
}
function OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hook = null)
{
$aInfo = explode(':', $identifier);
$functionName = 'Plugin_' . implode('_', $aInfo) . '_Delivery' . (!empty($hook) ? '_' . $hook : '');
if (!function_exists($functionName)) {
// Function doesn't exist, include the generic merged delivery file
_includeDeliveryPluginFile('/var/plugins/cache/mergedDeliveryFunctions.php');
if (!function_exists($functionName)) {
// Function doesn't exist, include the relevant plugin file
_includeDeliveryPluginFile($GLOBALS['_MAX']['CONF']['pluginPaths']['extensions'] . '/' . implode('/', $aInfo) . '.delivery.php');
if (!function_exists($functionName)) {
// Function or function file doesn't exist, use the "parent" function
_includeDeliveryPluginFile('/lib/OX/Extension/' . $aInfo[0] .  '/' . $aInfo[0] . 'Delivery.php');
$functionName = 'Plugin_' . $aInfo[0] . '_delivery';
if (!empty($hook) && function_exists($functionName . '_' . $hook)) {
$functionName .= '_' . $hook;
}
}
}
}
return $functionName;
}
function _includeDeliveryPluginFile($fileName)
{
if (!in_array($fileName, array_keys($GLOBALS['_MAX']['FILES']))) {
$GLOBALS['_MAX']['FILES'][$fileName] = true;
if (file_exists(MAX_PATH . $fileName)) {
include MAX_PATH . $fileName;
}
}
}
$file = '/lib/max/Delivery/cache.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
define ('OA_DELIVERY_CACHE_FUNCTION_ERROR', 'Function call returned an error');
$GLOBALS['OA_Delivery_Cache'] = array(
'prefix' => 'deliverycache_',
'host'   => getHostName(),
'expiry' => $GLOBALS['_MAX']['CONF']['delivery']['cacheExpire']
);
function OA_Delivery_Cache_fetch($name, $isHash = false, $expiryTime = null)
{
$filename = OA_Delivery_Cache_buildFileName($name, $isHash);
$aCacheVar = OX_Delivery_Common_hook(
'cacheRetrieve',
array($filename),
$GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin']
);
if ($aCacheVar !== false) {
if ($aCacheVar['cache_name'] != $name) {
return false;
}
// The method used to implement cache expiry imposes two cache writes if the cache is
// expired and the database is available, but avoid the need to check for file existence
// and modification time.
if ($expiryTime === null) {
$expiryTime = $GLOBALS['OA_Delivery_Cache']['expiry'];
}
$now = MAX_commonGetTimeNow();
if (    (isset($aCacheVar['cache_time']) && $aCacheVar['cache_time'] + $expiryTime < $now)
|| (isset($aCacheVar['cache_expire']) && $aCacheVar['cache_expire'] < $now) )
{
// Update expiry, needed to enable permanent caching if needed
OA_Delivery_Cache_store($name, $aCacheVar['cache_contents'], $isHash);
return false;
}
return $aCacheVar['cache_contents'];
}
return false;
}
function OA_Delivery_Cache_store($name, $cache, $isHash = false, $expireAt = null)
{
if ($cache === OA_DELIVERY_CACHE_FUNCTION_ERROR) {
// Don't store the result to enable permanent caching
return false;
}
$filename = OA_Delivery_Cache_buildFileName($name, $isHash);
$aCacheVar = array();
$aCacheVar['cache_contents'] = $cache;
$aCacheVar['cache_name'] = $name;
$aCacheVar['cache_time'] = MAX_commonGetTimeNow();
$aCacheVar['cache_expire'] = $expireAt;
return OX_Delivery_Common_hook(
'cacheStore',
array($filename, $aCacheVar),
$GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin']
);
}
function OA_Delivery_Cache_store_return($name, $cache, $isHash = false, $expireAt = null)
{
OX_Delivery_Common_hook(
'preCacheStore_'.OA_Delivery_Cache_getHookName($name),
array($name, &$cache)
);
if (OA_Delivery_Cache_store($name, $cache, $isHash, $expireAt)) {
return $cache;
}
$currentCache = OA_Delivery_Cache_fetch($name, $isHash);
// If cache storage is unavailable return given cache
if ($currentCache === false) {
return $cache;
}
return $currentCache;
}
function OA_Delivery_Cache_getHookName($name)
{
$pos = strpos($name, '^');
return $pos ? substr($name, 0, $pos) : substr($name, 0, strpos($name, '@'));
}
function OA_Delivery_Cache_buildFileName($name, $isHash = false)
{
if(!$isHash) {
// If not a hash yet
$name = md5($name);
}
return $GLOBALS['OA_Delivery_Cache']['prefix'].$name.'.php';
}
function OA_Delivery_Cache_getName($functionName)
{
$args = func_get_args();
$args[0] = strtolower(str_replace('MAX_cacheGet', '', $args[0]));
return join('^', $args).'@'.$GLOBALS['OA_Delivery_Cache']['host'];
}
function MAX_cacheGetAd($ad_id, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $ad_id);
if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aRows = OA_Dal_Delivery_getAd($ad_id);
$aRows = OA_Delivery_Cache_store_return($sName, $aRows);
}
return $aRows;
}
function MAX_cacheGetAccountTZs($cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__);
if (!$cached || ($aResult = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aResult = OA_Dal_Delivery_getAccountTZs();
$aResult = OA_Delivery_Cache_store_return($sName, $aResult);
}
return $aResult;
}
function MAX_cacheGetZoneLinkedAds($zoneId, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aRows = OA_Dal_Delivery_getZoneLinkedAds($zoneId);
$aRows = OA_Delivery_Cache_store_return($sName, $aRows);
}
return $aRows;
}
function MAX_cacheGetZoneInfo($zoneId, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aRows = OA_Dal_Delivery_getZoneInfo($zoneId);
$aRows = OA_Delivery_Cache_store_return($sName, $aRows);
}
return $aRows;
}
function MAX_cacheGetLinkedAds($search, $campaignid, $laspart, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart);
if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aAds = OA_Dal_Delivery_getLinkedAds($search, $campaignid, $laspart);
$aAds = OA_Delivery_Cache_store_return($sName, $aAds);
}
return $aAds;
}
function MAX_cacheGetCreative($filename, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $filename);
if (!$cached || ($aCreative = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aCreative = OA_Dal_Delivery_getCreative($filename);
$aCreative['contents'] = addslashes(serialize($aCreative['contents']));
$aCreative = OA_Delivery_Cache_store_return($sName, $aCreative);
}
$aCreative['contents'] = unserialize(stripslashes($aCreative['contents']));
return $aCreative;
}
function MAX_cacheGetTracker($trackerid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aTracker = OA_Dal_Delivery_getTracker($trackerid);
$aTracker = OA_Delivery_Cache_store_return($sName, $aTracker);
}
return $aTracker;
}
function MAX_cacheGetTrackerLinkedCreatives($trackerid = null, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aTracker = OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid);
$aTracker = OA_Delivery_Cache_store_return($sName, $aTracker, $isHash = true);
}
return $aTracker;
}
function MAX_cacheGetTrackerVariables($trackerid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
if (!$cached || ($aVariables = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aVariables = OA_Dal_Delivery_getTrackerVariables($trackerid);
$aVariables = OA_Delivery_Cache_store_return($sName, $aVariables);
}
return $aVariables;
}
function MAX_cacheCheckIfMaintenanceShouldRun($cached = true)
{
// Default delay is 5 minutes
$interval    = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] * 60;
$delay       = intval(($GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] / 12) * 60);
$now         = MAX_commonGetTimeNow();
$today       = strtotime(date('Y-m-d'), $now);
$nextRunTime = $today + (floor(($now - $today) / $interval) + 1) * $interval + $delay;
// Adding the delay could shift the time to the next operation interval,
// make sure to fix it in case it happens
if ($nextRunTime - $now > $interval) {
$nextRunTime -= $interval;
}
$cName  = OA_Delivery_Cache_getName(__FUNCTION__);
if (!$cached || ($lastRunTime = OA_Delivery_Cache_fetch($cName)) === false) {
MAX_Dal_Delivery_Include();
$lastRunTime = OA_Dal_Delivery_getMaintenanceInfo();
// Cache until the next operation interval if scheduled maintenance was run
// during the delay
if ($lastRunTime >= $nextRunTime - $delay) {
$nextRunTime += $interval;
}
OA_Delivery_Cache_store($cName, $lastRunTime, false, $nextRunTime);
}
return $lastRunTime < $nextRunTime - $interval;
}
function MAX_cacheGetChannelLimitations($channelid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $channelid);
if (!$cached || ($limitations = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$limitations = OA_Dal_Delivery_getChannelLimitations($channelid);
$limitations = OA_Delivery_Cache_store_return($sName, $limitations);
}
return $limitations;
}
function MAX_cacheGetGoogleJavaScript($cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__);
if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) {
$file = '/lib/max/Delivery/google.php';
if(!isset($GLOBALS['_MAX']['FILES'][$file])) {
include MAX_PATH . $file;
}
$output = MAX_googleGetJavaScript();
$output = OA_Delivery_Cache_store_return($sName, $output);
}
return $output;
}
function OA_cacheGetPublisherZones($affiliateid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $affiliateid);
if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$output = OA_Dal_Delivery_getPublisherZones($affiliateid);
$output = OA_Delivery_Cache_store_return($sName, $output);
}
return $output;
}
// Set the viewer's remote information used in logging
// and delivery limitation evaluation
MAX_remotehostSetInfo();
// Set common delivery parameters in the global scope
MAX_commonInitVariables();
// Load cookie data from client/plugin
MAX_cookieLoad();
// Unpack the packed capping cookies
MAX_cookieUnpackCapping();
// Required files
function MAX_limitationsCheckAcl($row, $source = '')
{
if (!empty($row['compiledlimitation'])) {
if (!isset($GLOBALS['_MAX']['FILES']['aIncludedPlugins'])) {
$GLOBALS['_MAX']['FILES']['aIncludedPlugins'] = array();
}
// Set to true in case of error in eval
$result = true;
$aConf = $GLOBALS['_MAX']['CONF'];
// Include required delivery files...
if(strlen($row['acl_plugins'])) {
$acl_plugins = explode(',', $row['acl_plugins']);
foreach ($acl_plugins as $acl_plugin) {
list($extension, $package, $name) = explode(':', $acl_plugin);
$pluginName = MAX_PATH . $aConf['pluginPaths']['extensions'] . "{$extension}/{$package}/{$name}.delivery.php";
if (!isset($GLOBALS['_MAX']['FILES']['aIncludedPlugins'][$pluginName])) {
include($pluginName);
$GLOBALS['_MAX']['FILES']['aIncludedPlugins'][$pluginName] = true;
}
}
}
// Set the ad's own timezone as preference, because some limitations require to be TZ aware
$GLOBALS['_MAX']['PREF']['timezone'] = $row['timezone'];
@eval('$result = (' . $row['compiledlimitation'] . ');');
// Reset timezone
unset($GLOBALS['_MAX']['PREF']['timezone']);
return $result;
} else {
return true;
}
}
function MAX_limitationsIsAdForbidden($aAd)
{
$adId = $aAd['ad_id'];
$campaignId = $aAd['placement_id'];
return (_limitationsIsAdCapped($adId, $aAd['cap_ad'], $aAd['session_cap_ad'], $aAd['block_ad']) ||
_limitationsIsCampaignCapped($campaignId, $aAd['cap_campaign'], $aAd['session_cap_campaign'], $aAd['block_campaign']));
}
function MAX_limitationsIsZoneForbidden($zoneId, $aCapping)
{
$capZone = isset($aCapping['cap_zone']) ? $aCapping['cap_zone'] : null;
$sessionCapZone = isset($aCapping['session_cap_zone']) ? $aCapping['session_cap_zone'] : null;
$blockZone = isset($aCapping['block_zone']) ? $aCapping['block_zone'] : null;
return (_limitationsIsZoneCapped($zoneId, $capZone, $sessionCapZone, $blockZone));
}
function _limitationsIsAdCapped($adId, $cap, $sessionCap = 0, $block)
{
return _limitationsIsCapped('Ad', $adId, $cap, $sessionCap, $block);
}
function _limitationsIsCampaignCapped($campaignId, $cap, $sessionCap = 0, $block)
{
return _limitationsIsCapped('Campaign', $campaignId, $cap, $sessionCap, $block);
}
function _limitationsIsZoneCapped($zoneId, $cap, $sessionCap = 0, $block)
{
return _limitationsIsCapped('Zone', $zoneId, $cap, $sessionCap, $block);
}
function _limitationsIsCapped($type, $id, $cap, $sessionCap, $block)
{
// Always return true (capped) if cookies have been disabled by the viewer
if (_areCookiesDisabled(($cap > 0) || ($sessionCap > 0) || ($block > 0))) {
return true;
}
// Get the capping cookie name from the configuration file
$conf = $GLOBALS['_MAX']['CONF'];
$cookieName = $conf['var']['cap' . $type];
// How many times (total) has the item been by the viewer?
if (isset($_COOKIE[$cookieName][$id])) {
$totalImpressions = $_COOKIE[$cookieName][$id];
}
// Get the session capping cookie name from the configuration file
$cookieName = $conf['var']['sessionCap' . $type];
// How many times (session) has the item been by the viewer?
if (isset($_COOKIE[$cookieName][$id])) {
$sessionImpressions = $_COOKIE[$cookieName][$id];
}
// When was the ad last seen
$cookieName = $conf['var']['block' . $type];
if (isset($_COOKIE[$cookieName][$id])) {
$lastSeen = $_COOKIE[$cookieName][$id];
}
// If the ad has been seen the requisite number of times...
if ((($cap > 0) && isset($totalImpressions) && ($totalImpressions >= $cap)) ||
(($sessionCap > 0) && isset($sessionImpressions) && ($sessionImpressions >= $sessionCap))) {
if ($block > 0 && MAX_commonGetTimeNow() > $lastSeen + $block) {
// This ad was last seen outside the block window, so it can now be seen again
// The log mechanism will deal with resetting the frequency counter
return false;
} else {
return true;
}
} else if ($block > 0  && ($cap == 0 && $sessionCap == 0) && MAX_commonGetTimeNow() <= $lastSeen + $block) {
return true;
} else {
return false;
}
}
function _areCookiesDisabled($filterActive = true)
{
// Since MAX_cookieGetUniqueViewerID() has to have been called by this point
return !empty($GLOBALS['_MAX']['COOKIE']['newViewerId']) && $filterActive;
}
function MAX_adRender(&$aBanner, $zoneId=0, $source='', $target='', $ct0='', $withText=false, $charset = '', $logClick=true, $logView=true, $richMedia=true, $loc='', $referer='', $context = array())
{
$conf = $GLOBALS['_MAX']['CONF'];
// Sanitize these user-inputted variables before passing to the _adRenderX calls
if (empty($target)) {
$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
}
$target = htmlspecialchars($target, ENT_QUOTES);
$source = htmlspecialchars($source, ENT_QUOTES);
$aBanner['bannerContent'] = "";
// Pre adRender hook
OX_Delivery_Common_hook('preAdRender', array(&$aBanner, &$zoneId, &$source, &$ct0, &$withText, &$logClick, &$logView, null, &$richMedia, &$loc, &$referer));
$functionName = _getAdRenderFunction($aBanner, $richMedia);
$code = OX_Delivery_Common_hook('adRender', array(&$aBanner, &$zoneId, &$source, &$ct0, &$withText, &$logClick, &$logView, null, &$richMedia, &$loc, &$referer), $functionName);
// Transform any code
// Get a timestamp
list($usec, $sec) = explode(' ', microtime());
$time = (float)$usec + (float)$sec;
// Get a random number
$random = substr(md5(uniqid($time, true)), 0, 10);
global $cookie_random;  // Temporary fix to get doubleclick tracking working (Bug # 88)
$cookie_random = $random;
// Get the click URL
$clickUrl = _adRenderBuildClickUrl($aBanner, $zoneId, $source, urlencode($ct0), $logClick, true);
// Get URL prefix, stripping the traling slash
$urlPrefix = substr(MAX_commonGetDeliveryUrl(), 0, -1);
$code = str_replace('{clickurl}', $clickUrl, $code);  // This step needs to be done separately because {clickurl} can contain {random}...
if (strpos($code, '{logurl}') !== false) {
$logUrl = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&');
$code = str_replace('{logurl}', $logUrl, $code);  // This step needs to be done separately because {logurl} does contain {random}...
}
if (strpos($code, '{logurl_enc}') !== false) {
$logUrl_enc = urlencode(_adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&'));
$code = str_replace('{logurl_enc}', $logUrl_enc, $code);  // This step needs to be done separately because {logurl} does contain {random}...
}
if (strpos($code, '{clickurlparams}')) {
$maxparams = _adRenderBuildParams($aBanner, $zoneId, $source, urlencode($ct0), $logClick, true);
$code = str_replace('{clickurlparams}', $maxparams, $code);  // This step needs to be done separately because {clickurlparams} does contain {random}...
}
$search = array('{timestamp}','{random}','{target}','{url_prefix}','{bannerid}','{zoneid}','{source}', '{pageurl}', '{width}', '{height}', '{websiteid}', '{campaignid}', '{advertiserid}');
$locReplace = isset($GLOBALS['loc']) ? $GLOBALS['loc'] : '';
$websiteid = (!empty($aBanner['affiliate_id'])) ? $aBanner['affiliate_id'] : '0';
$replace = array($time, $random, $target, $urlPrefix, $aBanner['ad_id'], $zoneId, $source, urlencode($locReplace), $aBanner['width'], $aBanner['height'], $websiteid, $aBanner['campaign_id'], $aBanner['client_id']);
preg_match_all('#{(.*?)(_enc)?}#', $code, $macros);
for ($i=0;$i<count($macros[1]);$i++) {
if (!in_array($macros[0][$i], $search) && isset($_REQUEST[$macros[1][$i]])) {
$search[] = $macros[0][$i];
$replace[] = (!empty($macros[2][$i])) ? urlencode(stripslashes($_REQUEST[$macros[1][$i]])) : stripslashes($_REQUEST[$macros[1][$i]]);
}
}
$code = str_replace($search, $replace, $code);
$clickUrl = str_replace($search, $replace, $clickUrl);
$aBanner['clickUrl'] = $clickUrl;
$logUrl = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&');
$logUrl = str_replace($search, $replace, $logUrl);
$aBanner['logUrl'] = $logUrl;
// Pass over the search / replace patterns
$aBanner['aSearch']  = $search;
$aBanner['aReplace'] = $replace;
// post adRender hook
OX_Delivery_Common_hook('postAdRender', array(&$code, $aBanner));
//    return $code;
return MAX_commonConvertEncoding($code, $charset);
}
function MAX_adRenderImageBeacon($logUrl, $beaconId = 'beacon', $userAgent = null)
{
if (!isset($userAgent) && isset($_SERVER['HTTP_USER_AGENT'])) {
$userAgent = $_SERVER['HTTP_USER_AGENT'];
}
$beaconId .= '_{random}';
// Add beacon image for logging
if (isset($userAgent) && preg_match("#Mozilla/(1|2|3|4)#", $userAgent)
&& !preg_match("#compatible#", $userAgent)) {
$div = "<layer id='{$beaconId}' width='0' height='0' border='0' visibility='hide'>";
$style = '';
$divEnd = '</layer>';
} else {
$div = "<div id='{$beaconId}' style='position: absolute; left: 0px; top: 0px; visibility: hidden;'>";
$style = " style='width: 0px; height: 0px;'";
$divEnd = '</div>';
}
$beacon = "$div<img src='".htmlspecialchars($logUrl)."' width='0' height='0' alt=''{$style} />{$divEnd}";
return $beacon;
}
function _adRenderImage(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $useAlt=false, $richMedia=true, $loc, $referer, $useAppend=true)
{
$conf = $GLOBALS['_MAX']['CONF'];
$aBanner['bannerContent'] = $imageUrl = _adRenderBuildFileUrl($aBanner, $useAlt);
if (!$richMedia) {
return _adRenderBuildFileUrl($aBanner, $useAlt);
}
$prepend = (!empty($aBanner['prepend']) && $useAppend) ? $aBanner['prepend'] : '';
$append = (!empty($aBanner['append']) && $useAppend) ? $aBanner['append'] : '';
// Create the anchor tag..
$clickUrl = _adRenderBuildClickUrl($aBanner, $zoneId, $source, $ct0, $logClick);
if (!empty($clickUrl)) {  // There is a link
$status = _adRenderBuildStatusCode($aBanner);
//$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
$clickTag = "<a href='$clickUrl' target='{target}'$status>";
$clickTagEnd = '</a>';
} else {
$clickTag = '';
$clickTagEnd = '';
}
// Create the image tag..
if (!empty($imageUrl)) {
$imgStatus = empty($clickTag) ? $status : '';
$width = !empty($aBanner['width']) ? $aBanner['width'] : 0;
$height = !empty($aBanner['height']) ? $aBanner['height'] : 0;
$alt = !empty($aBanner['alt']) ? $aBanner['alt'] : '';
$imageTag = "$clickTag<img src='$imageUrl' width='$width' height='$height' alt='$alt' title='$alt' border='0'$imgStatus />$clickTagEnd";
} else {
$imageTag = '';
}
// Get the text below the banner
$bannerText = $withText && !empty($aBanner['bannertext']) ? "<br />$clickTag{$aBanner['bannertext']}$clickTagEnd" : '';
// Get the image beacon...
$beaconTag = ($logView && $conf['logging']['adImpressions']) ? _adRenderImageBeacon($aBanner, $zoneId, $source, $loc, $referer) : '';
return $prepend . $imageTag . $bannerText . $beaconTag . $append;
}
function _adRenderFlash(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $loc, $referer)
{
$conf = $GLOBALS['_MAX']['CONF'];
$prepend = !empty($aBanner['prepend']) ? $aBanner['prepend'] : '';
$append = !empty($aBanner['append']) ? $aBanner['append'] : '';
$width = !empty($aBanner['width']) ? $aBanner['width'] : 0;
$height = !empty($aBanner['height']) ? $aBanner['height'] : 0;
$pluginVersion = !empty($aBanner['pluginversion']) ? $aBanner['pluginversion'] : '4';
// $imageUrlPrefix = ($_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) ? $conf['type_web_ssl_url'] : $conf['type_web_url'];
$altImageAdCode = !empty($aBanner['alt_filename'])
? _adRenderImage($aBanner, $zoneId, $source, $ct0, false, $logClick, false, true, true, $loc, $referer, false)
// An empty image is required because the javascript is parsed before the DOM tree
: "<img src='" . _adRenderBuildImageUrlPrefix() . '/1x1.gif' . "' alt='".$aBanner['alt']."' title='".$aBanner['alt']."' border='0' />";
// Create the anchor tag..
$clickUrl = _adRenderBuildClickUrl($aBanner, $zoneId, $source, $ct0, $logClick);
if (!empty($clickUrl)) {  // There is a link
$status = _adRenderBuildStatusCode($aBanner);
$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
$swfParams = array('clickTARGET' => $target, 'clickTAG' => $clickUrl);
$clickTag = "<a href='$clickUrl' target='$target'$status>";
$clickTagEnd = '</a>';
} else {
$swfParams = array();
$clickTag = '';
$clickTagEnd = '';
}
if (!empty($aBanner['parameters'])) {
$aAdParams = unserialize($aBanner['parameters']);
if (isset($aAdParams['swf']) && is_array($aAdParams['swf'])) {
// Converted SWF file, use paramters content
$swfParams = array();
$aBannerSwf = $aBanner;
// Set the flag to let _adRenderBuildClickUrl know that we're not using clickTAG
$aBannerSwf['noClickTag'] = true;
foreach ($aAdParams['swf'] as $iKey => $aSwf) {
$aBannerSwf['url'] = $aSwf['link'];
$swfParams["alink{$iKey}"] = _adRenderBuildClickUrl($aBannerSwf, $zoneId, $source, $ct0, $logClick);
$swfParams["atar{$iKey}"]  = $aSwf['tar'];
}
}
}
$fileUrl = _adRenderBuildFileUrl($aBanner, false);
$rnd = md5(microtime());
$swfId = (!empty($aBanner['alt']) ? $aBanner['alt'] : 'Advertisement');
$code = "
<div id='ox_$rnd' style='display: inline;'>$altImageAdCode</div>
<script type='text/javascript'><!--/"."/ <![CDATA[
var ox_swf = new FlashObject('{$fileUrl}', '{$swfId}', '{$width}', '{$height}', '{$pluginVersion}');\n";
foreach ($swfParams as $key => $value) {
// URL encode the value, but leave any Openads "magic macros" unescaped to allow substitution
$code .= "    ox_swf.addVariable('{$key}', '" . preg_replace('#%7B(.*?)%7D#', '{$1}', urlencode($value)) . "');\n";
}
if (!empty($aBanner['transparent'])) {
$code .= "\n   ox_swf.addParam('wmode','transparent');";
}
$code .= "
ox_swf.addParam('allowScriptAccess','always');
ox_swf.write('ox_$rnd');
/"."/ ]]> --></script>";
$bannerText = $withText && !empty($aBanner['bannertext']) ? "<br />{$clickTag}{$aBanner['bannertext']}{$clickTagEnd}" : '';
$beaconTag = ($logView && $conf['logging']['adImpressions']) ? _adRenderImageBeacon($aBanner, $zoneId, $source, $loc, $referer) : '';
return $prepend . $code . $bannerText . $beaconTag . $append;
}
function _adRenderQuicktime(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $loc, $referer)
{
$conf = $GLOBALS['_MAX']['CONF'];
$prepend = !empty($aBanner['prepend']) ? $aBanner['prepend'] : '';
$append = !empty($aBanner['append']) ? $aBanner['append'] : '';
$width = !empty($aBanner['width']) ? $aBanner['width'] : 0;
$height = !empty($aBanner['height']) ? $aBanner['height'] : 0;
$pluginVersion = !empty($aBanner['pluginversion']) ? $aBanner['pluginversion'] : '4';
// $imageUrlPrefix = ($_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) ? $conf['type_web_ssl_url'] : $conf['type_web_url'];
$fileName = !empty($aBanner['filename']) ? $aBanner['filename'] : '';
$altImageBannercode = _adRenderImage($aBanner, $zoneId, $source, $ct0, false, $logClick, false, true, true, $loc, $referer);
// Create the anchor tag..
$clickTag = _adRenderBuildClickUrl($aBanner, $source, $ct0, $logClick);
if (!empty($clickTag)) {  // There is a link
$status = _adRenderBuildStatusCode($aBanner);
$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
$swfParams = 'clickTAG=' . $clickTag;
$anchor = "<a href='$clickTag' target='$target'$status>";
$anchorEnd = '</a>';
} else {
$swfParams = '';
$anchor = '';
$anchorEnd = '';
}
$clickTag = _adRenderBuildFileUrl($aBanner, $source, $ct0, $logClick);
$fileUrl = _adRenderBuildFileUrl($aBanner, false, $swfParams);
$code = "
<object classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab' width='$width' height='$height'>
<param name='src' value='$fileUrl'>
<param name='controller' value='false'>
<param name='autoplay' value='true'>
<embed src='$fileUrl' controller='false' autoplay='true' width='$width' height='$height' pluginspace='http://www.apple.com/quicktime/download/'></embed>
<noembed>$altImageBannercode</noembed>
</object>";
$bannerText = $withText && !empty($aBanner['bannertext']) ? "<br />{$anchor}{$aBanner['bannertext']}{$anchorEnd}" : '';
// Get the image beacon...
$beaconTag = ($logView && $conf['logging']['adImpressions']) ? _adRenderImageBeacon($aBanner, $zoneId, $source, $loc, $referer) : '';
return $prepend . $code . $bannerText . $beaconTag . $append;
}
function _adRenderHtml(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $useAlt=false, $loc, $referer)
{
// This is a wrapper to the "parent" bannerTypeHtml function
$aConf = $GLOBALS['_MAX']['CONF'];
if (!function_exists('Plugin_BannerTypeHtml_delivery_adRender')) {
@include LIB_PATH . '/Extension/bannerTypeHtml/bannerTypeHtmlDelivery.php';
}
return Plugin_BannerTypeHtml_delivery_adRender($aBanner, $zoneId, $source, $ct0, $withText, $logClick, $logView, $useAlt, $loc, $referer);
}
function _adRenderText(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $useAlt=false, $loc, $referer)
{
// This is a wrapper to the "parent" bannerTypeHtml function
$aConf = $GLOBALS['_MAX']['CONF'];
if (!function_exists('Plugin_BannerTypeText_delivery_adRender')) {
@include LIB_PATH . '/Extension/bannerTypeText/bannerTypeTextDelivery.php';
}
return Plugin_BannerTypeText_delivery_adRender($aBanner, $zoneId, $source, $ct0, $withText, $logClick, $logView, $useAlt, $loc, $referer);
}
function _adRenderReal(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $loc, $referer)
{
$conf = $GLOBALS['_MAX']['CONF'];
$prepend = !empty($aBanner['prepend']) ? $aBanner['prepend'] : '';
$append = !empty($aBanner['append']) ? $aBanner['append'] : '';
$width = !empty($aBanner['width']) ? $aBanner['width'] : 0;
$height = !empty($aBanner['height']) ? $aBanner['height'] : 0;
$pluginVersion = !empty($aBanner['pluginversion']) ? $aBanner['pluginversion'] : '4';
// $imageUrlPrefix = ($_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) ? $conf['type_web_ssl_url'] : $conf['type_web_url'];
$fileName = !empty($aBanner['filename']) ? $aBanner['filename'] : '';
$altImageBannercode = _adRenderImage($aBanner, $zoneId, $source, $ct0, false, $logClick, false, true, true, $loc, $referer);
// Create the anchor tag..
$clickTag = _adRenderBuildClickUrl($aBanner, $source, $ct0, $logClick);
if (!empty($clickTag)) {  // There is a link
$status = _adRenderBuildStatusCode($aBanner);
$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
$swfParams = 'clickTAG=' . $clickTag;
$anchor = "<a href='$clickTag' target='$target'$status>";
$anchorEnd = '</a>';
} else {
$swfParams = '';
$anchor = '';
$anchorEnd = '';
}
$clickTag = _adRenderBuildClickUrl($aBanner, $source, $ct0, $logClick);
$fileUrl = _adRenderBuildFileUrl($aBanner, false, $swfParams);
$code = "
<object classid='clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' width='$width' height='$height'>
<param name='src' value='$fileUrl'>
<param name='controls' value='ImageWindow'>
<param name='autostart' value='true'>
<embed src='$fileUrl' controls='ImageWindow' autostart='true' width='$width' height='$height' type='audio/x-pn-realaudio-plugin'></embed>
<noembed>$altImageBannercode</noembed>
</object>";
$bannerText = $withText && !empty($aBanner['bannertext']) ? "<br />{$anchor}{$aBanner['bannertext']}{$anchorEnd}" : '';
// Get the image beacon...
$beaconTag = ($logView && $conf['logging']['adImpressions']) ? _adRenderImageBeacon($aBanner, $zoneId, $source, $loc, $referer) : '';
return $prepend . $code . $bannerText . $beaconTag . $append;
}
function _adRenderBuildFileUrl($aBanner, $useAlt = false, $params = '')
{
$conf = $GLOBALS['_MAX']['CONF'];
$fileUrl = '';
if ($aBanner['type'] == 'url') {
$fileUrl = $aBanner['imageurl'];
if (!empty($params)) {
$fileUrl .= "?{$params}";
}
} else {
$fileName = $useAlt ? $aBanner['alt_filename'] : $aBanner['filename'];
$params = !empty($params) ? $params : '';
if (!empty($fileName)) {
if ($aBanner['type'] == 'web') {
$fileUrl = _adRenderBuildImageUrlPrefix() . "/{$fileName}";
if (!empty($params)) {
$fileUrl .= "?{$params}";
}
} elseif ($aBanner['type'] == 'sql') {
$fileUrl = MAX_commonGetDeliveryUrl($conf['file']['image']) . "?filename={$fileName}&contenttype={$aBanner['contenttype']}";
if (!empty($params)) {
$fileUrl .= "&{$params}";
}
}
}
}
return $fileUrl;
}
function _adRenderBuildImageUrlPrefix()
{
$conf = $GLOBALS['_MAX']['CONF'];
return (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) ?
'https://' . $conf['webpath']['imagesSSL'] :
'http://' . $conf['webpath']['images'];
}
function _adRenderBuildLogURL($aBanner, $zoneId = 0, $source = '', $loc = '', $referer = '', $amp = '&amp;')
{
$conf = $GLOBALS['_MAX']['CONF'];
// If there is an OpenX->OpenX internal redirect, log both zones information
$delimiter = $GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'];
$logLastAction = (!empty($aBanner['viewwindow']) && !empty($aBanner['tracker_status'])) ? '1' : '';
if (!empty($GLOBALS['_MAX']['adChain'])) {
foreach ($GLOBALS['_MAX']['adChain'] as $index => $ad) {
$aBanner['ad_id'] .= $delimiter . $ad['ad_id'];
$aBanner['placement_id'] .= $delimiter . $ad['placement_id'];
$zoneId .= $delimiter . $ad['zoneid'];
$aBanner['block_ad'] .= $delimiter . $ad['block_ad'];
$aBanner['cap_ad'] .= $delimiter . $ad['cap_ad'];
$aBanner['session_cap_ad'] .= $delimiter . $ad['session_cap_ad'];
$aBanner['block_campaign'] .= $delimiter . $ad['block_campaign'];
$aBanner['cap_campaign'] .= $delimiter . $ad['cap_campaign'];
$aBanner['session_cap_campaign'] .= $delimiter . $ad['session_cap_campaign'];
$aBanner['block_zone'] .= $delimiter . $ad['block_zone'];
$aBanner['cap_zone'] .= $delimiter . $ad['cap_zone'];
$aBanner['session_cap_zone'] .= $delimiter . $ad['session_cap_zone'];
$logLastAction .= $delimiter . (!empty($ad['viewwindow']) && !empty($ad['tracker_status'])) ? '1' : '0';
}
}
$url = MAX_commonGetDeliveryUrl($conf['file']['log']);
$url .= "?bannerid=" . $aBanner['ad_id'];
$url .= $amp . "campaignid=" . $aBanner['placement_id'];
$url .= $amp . "zoneid=" . $zoneId;
if (!empty($source)) $url .= $amp . "source=" . $source;
if (!empty($aBanner['block_ad'])) $url .= $amp . $conf['var']['blockAd'] . "=" . $aBanner['block_ad'];
if (!empty($aBanner['cap_ad'])) $url .= $amp . $conf['var']['capAd'] . "=" . $aBanner['cap_ad'];
if (!empty($aBanner['session_cap_ad'])) $url .= $amp . $conf['var']['sessionCapAd'] . "=" . $aBanner['session_cap_ad'];
if (!empty($aBanner['block_campaign'])) $url .= $amp . $conf['var']['blockCampaign'] . "=" . $aBanner['block_campaign'];
if (!empty($aBanner['cap_campaign'])) $url .= $amp . $conf['var']['capCampaign'] . "=" . $aBanner['cap_campaign'];
if (!empty($aBanner['session_cap_campaign'])) $url .= $amp . $conf['var']['sessionCapCampaign'] . "=" . $aBanner['session_cap_campaign'];
if (!empty($aBanner['block_zone'])) $url .= $amp . $conf['var']['blockZone'] . "=" . $aBanner['block_zone'];
if (!empty($aBanner['cap_zone'])) $url .= $amp . $conf['var']['capZone'] . "=" . $aBanner['cap_zone'];
if (!empty($aBanner['session_cap_zone'])) $url .= $amp . $conf['var']['sessionCapZone'] . "=" . $aBanner['session_cap_zone'];
if (!empty($logLastAction)) $url .= $amp . $conf['var']['lastView'] . "=" . $logLastAction;
if (!empty($loc)) $url .= $amp . "loc=" . urlencode($loc);
if (!empty($referer)) $url .= $amp . "referer=" . urlencode($referer);
$url .= $amp . "cb={random}";
return $url;
}
function _adRenderImageBeacon($aBanner, $zoneId = 0, $source = '', $loc = '', $referer = '', $logUrl = '')
{
if (empty($logUrl)) {
$logUrl = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&');
}
return MAX_adRenderImageBeacon($logUrl);
}
function _adRenderBuildParams($aBanner, $zoneId=0, $source='', $ct0='', $logClick=true, $overrideDest=false)
{
// HACK - sometimes $aBanner has the banner ID as bannerid, and others it is ad_id.  This needs
//  to be sorted in all parts of the application to reference ad_id rather than bannerid.
if (isset($aBanner['ad_id']) && empty($aBanner['bannerid'])) {
$aBanner['bannerid'] = $aBanner['ad_id'];
}
$conf = $GLOBALS['_MAX']['CONF'];
$delimiter = $GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'];
$logLastClick = (!empty($aBanner['clickwindow'])) ? '1' : '';
// If there is an OpenX->OpenX internal redirect, log both zones information
if (!empty($GLOBALS['_MAX']['adChain'])) {
foreach ($GLOBALS['_MAX']['adChain'] as $index => $ad) {
$aBanner['bannerid'] .= $delimiter . $ad['bannerid'];
$aBanner['placement_id'] .= $delimiter . $ad['placement_id'];
$zoneId .= $delimiter . $ad['zoneid'];
$logLastClick .= (!empty($aBanner['clickwindow'])) ? '1' : '0';
}
}
$maxparams = '';
if (!empty($aBanner['url']) || $overrideDest) {
// There is a link
$del = $conf['delivery']['ctDelimiter'];
$delnum = strlen($del);
$random = "{$del}{$conf['var']['cacheBuster']}={random}";
$bannerId = !empty($aBanner['bannerid']) ? "{$del}{$conf['var']['adId']}={$aBanner['bannerid']}" : '';
$zoneId = "{$del}{$conf['var']['zoneId']}={$zoneId}";
$source = !empty($source) ? "{$del}source=" . urlencode($source) : '';
$log = $logClick ? '' : "{$del}{$conf['var']['logClick']}=no";
// Determine the destination
$dest = !empty($aBanner['url']) ? $aBanner['url'] : '';
// If the passed in a ct0= value that is not a valid URL (simple checking), then ignore it
$ct0 = (empty($ct0) || strtolower(substr($ct0, 0, 4)) != 'http') ? '' : htmlspecialchars($ct0, ENT_QUOTES);
if ($aBanner['contenttype'] == "swf" && empty($aBanner['noClickTag'])) {
// Strip maxdest with SWF banners using clickTAG
$maxdest = '';
} else {
$maxdest = "{$del}{$conf['var']['dest']}={$ct0}{$dest}";
}
$log .= (!empty($logLastClick)) ? $del . $conf['var']['lastClick'] . '=' . $logLastClick : '';
$maxparams = "{$delnum}{$bannerId}{$zoneId}{$source}{$log}{$random}{$maxdest}";
}
return $maxparams;
}
function _adRenderBuildClickUrl($aBanner, $zoneId=0, $source='', $ct0='', $logClick=true, $overrideDest=false)
{
$conf = $GLOBALS['_MAX']['CONF'];
$clickUrl = '';
if (is_string($logClick)) {
$clickUrl = $logClick;
} elseif (!empty($aBanner['url']) || $overrideDest) {
$clickUrl = MAX_commonGetDeliveryUrl($conf['file']['click']) . '?' . $conf['var']['params'] . '=' . _adRenderBuildParams($aBanner, $zoneId, $source, $ct0, $logClick, true);
}
return $clickUrl;
}
function _adRenderBuildStatusCode($aBanner)
{
return !empty($aBanner['status']) ? " onmouseover=\"self.status='" . addslashes($aBanner['status']) . "'; return true;\" onmouseout=\"self.status=''; return true;\"" : '';
}
function _getAdRenderFunction($aBanner, $richMedia = true)
{
$functionName = false;
if (!empty($aBanner['ext_bannertype'])) {
return OX_Delivery_Common_getFunctionFromComponentIdentifier($aBanner['ext_bannertype'], 'adRender');
} else {
switch ($aBanner['contenttype']) {
case 'gif'  :
case 'jpeg' :
case 'png'  :
$functionName = '_adRenderImage';
break;
case 'swf'  :
if ($richMedia) {
$functionName = '_adRenderFlash';
} else {
$functionName = '_adRenderImage';
}
break;
case 'txt'  :
$functionName = '_adRenderText';
break;
case 'mov'  :
$functionName = '_adRenderQuicktime';
break;
default :
switch ($aBanner['type']) {
case 'html' :
$functionName = '_adRenderHtml';
break;
case 'url' : // External banner without a recognised content type - assume image...
$functionName = '_adRenderImage';
break;
case 'txt' :
$functionName = '_adRenderText';
break;
default:
$functionName = '_adRenderHtml';
break;
}
break;
}
}
return $functionName;
}
function MAX_adSelect($what, $campaignid = '', $target = '', $source = '', $withtext = 0, $charset = '', $context = array(), $richmedia = true, $ct0 = '', $loc = '', $referer = '')
{
$conf = $GLOBALS['_MAX']['CONF'];
// For local mode and XML-RPC calls the some parameters are not set in the global scope
// So we need to override the empty globals with the values passed into this function.
if (empty($GLOBALS['source'])) {
$GLOBALS['source'] = $source;
}
if (empty($GLOBALS['loc'])) {
$GLOBALS['loc'] = $loc;
}
// Store the original zone, campaign or banner IDs for later use
if (strpos($what,'zone:') === 0) {
$originalZoneId = intval(substr($what,5));
} elseif (strpos($what,'campaignid:') === 0) {
$originalCampaignId = intval(substr($what,11));
} elseif (strpos($what, 'bannerid:') === 0) {
$originalBannerId = intval(substr($what,9));
}
$userid = MAX_cookieGetUniqueViewerID();
MAX_cookieSet($conf['var']['viewerId'], $userid, _getTimeYearFromNow());
$outputbuffer = '';
// Set flag
$found = false;
// Reset followed zone chain
$GLOBALS['_MAX']['followedChain'] = array();
$GLOBALS['_MAX']['adChain'] = array();
$first = true;
global $g_append, $g_prepend;
$g_append = '';
$g_prepend = '';
while ($first || ($what != '' && $found == false)) {
$first = false;
// Get first part, store second part
$ix = strpos($what, '|');
if ($ix === false) {
$remaining = '';
} else {
$remaining = substr($what, $ix+1);
$what = substr($what, 0, $ix);
}
if (strpos($what, 'zone:') === 0) {
$zoneId  = intval(substr($what,5));
$row = _adSelectZone($zoneId, $context, $source, $richmedia);
} else {
// Expand paths to regular statements
if (strpos($what, '/') > 0) {
if (strpos($what, '@') > 0) {
list ($what, $append) = explode ('@', $what);
} else {
$append = '';
}
$separate  = explode ('/', $what);
$expanded  = '';
$collected = array();
reset($separate);
while (list(,$v) = each($separate)) {
$expanded .= ($expanded != '' ? ',+' : '') . $v;
$collected[] = $expanded . ($append != '' ? ',+'.$append : '');
}
$what = strtok(implode('|', array_reverse ($collected)), '|');
$remaining = strtok('').($remaining != '' ? '|'.$remaining : '');
}
$row = _adSelectDirect($what, $campaignid, $context, $source, $richmedia, $remaining == '');
}
if (is_array($row) && empty($row['default'])) {
// Log the ad request
MAX_Delivery_log_logAdRequest($row['bannerid'], $row['zoneid']);
if (($row['adserver'] == 'max' || $row['adserver'] == '3rdPartyServers:ox3rdPartyServers:max')
&& preg_match("#{$conf['webpath']['delivery']}.*zoneid=([0-9]+)#", $row['htmltemplate'], $matches) && !stristr($row['htmltemplate'], $conf['file']['popup'])) {
// The ad selected was an OpenX HTML ad on the same server... do internal redirecty stuff
$GLOBALS['_MAX']['adChain'][] = $row;
$found = false;
$what = "zone:{$matches[1]}";
} else {
$found = true;
}
} else {
$what  = $remaining;
}
}
// Return the banner information
if ($found) {
$zoneId = empty($row['zoneid']) ? 0 : $row['zoneid'];
// For internal redirected creatives, make sure that any appended code in the adChain is appended
if (!empty($GLOBALS['_MAX']['adChain'])) {
foreach ($GLOBALS['_MAX']['adChain'] as $index => $ad) {
if (($ad['ad_id'] != $row['ad_id']) && !empty($ad['append'])) {
$row['append'] .= $ad['append'];
}
}
}
$outputbuffer = MAX_adRender($row, $zoneId, $source, $target, $ct0, $withtext, $charset, true, true, $richmedia, $loc, $referer, $context);
$output = array(
'html'          => $outputbuffer,
'bannerid'      => $row['bannerid'],
'contenttype'   => $row['contenttype'],
'alt'           => $row['alt'],
'width'         => $row['width'],
'height'        => $row['height'],
'url'           => $row['url'],
'campaignid'    => $row['campaignid'],
'clickUrl'      => $row['clickUrl'],
'logUrl'        => $row['logUrl'],
'aSearch'       => $row['aSearch'],
'aReplace'      => $row['aReplace'],
'bannerContent' => $row['bannerContent'],
'context'       => _adSelectBuildContext($row, $context)
);
// If ad-logging is disabled, the log beacon won't be sent, so set the capping at request
if (MAX_Delivery_cookie_cappingOnRequest()) {
if ($row['block_ad'] > 0 || $row['cap_ad'] > 0 || $row['session_cap_ad'] > 0) {
MAX_Delivery_cookie_setCapping('Ad', $row['bannerid'], $row['block_ad'], $row['cap_ad'], $row['session_cap_ad']);
}
if ($row['block_campaign'] > 0 || $row['cap_campaign'] > 0 || $row['session_cap_campaign'] > 0) {
MAX_Delivery_cookie_setCapping('Campaign', $row['campaign_id'], $row['block_campaign'], $row['cap_campaign'], $row['session_cap_campaign']);
}
if ($row['block_zone'] > 0 || $row['cap_zone'] > 0 || $row['session_cap_zone'] > 0) {
MAX_Delivery_cookie_setCapping('Zone', $row['zoneid'], $row['block_zone'], $row['cap_zone'], $row['session_cap_zone']);
}
// Store the last view action event om the cookie as well (if required)
MAX_Delivery_log_setLastAction(0, array($row['bannerid']), array($zoneId), array($row['viewwindow']));
}
return $output;
} else {
// No banner found
if (!empty($row['default'])) {
// Return the default banner
if (empty($target)) {
$target = '_blank';  // Default
}
$outputbuffer = $g_prepend . '<a href=\'' . $row['default_banner_destination_url'] . '\' target=\'' .
$target . '\'><img src=\'' . $row['default_banner_image_url'] .
'\' border=\'0\' alt=\'\'></a>' . $g_append;
return array('html' => $outputbuffer, 'bannerid' => '', 'default_banner_image_url' => $row['default_banner_image_url'] );
} else {
// No default banner was returned, return no banner
$outputbuffer = $g_prepend . $g_append;
return array('html' => $outputbuffer, 'bannerid' => '' );
}
}
}
function _adSelectDirect($what, $campaignid = '', $context = array(), $source = '', $richMedia = true, $lastpart = true)
{
$aDirectLinkedAds = MAX_cacheGetLinkedAds($what, $campaignid, $lastpart);
$aLinkedAd = _adSelectCommon($aDirectLinkedAds, $context, $source, $richMedia);
if (is_array($aLinkedAd)) {
$aLinkedAd['zoneid'] = 0;
$aLinkedAd['bannerid'] = $aLinkedAd['ad_id'];
$aLinkedAd['storagetype'] = $aLinkedAd['type'];
$aLinkedAd['campaignid'] = $aLinkedAd['placement_id'];
$aLinkedAd['prepend'] = '';
return $aLinkedAd;
}
if (!empty($aDirectLinkedAds['default_banner_image_url'])) {
return array(
'default'                        => true,
'default_banner_image_url'       => $aZoneLinkedAds['default_banner_image_url'],
'default_banner_destination_url' => $aZoneLinkedAds['default_banner_destination_url']
);
}
return false;
}
function _getNextZone($zoneId, $arrZone)
{
if (!empty($arrZone['chain']) && (substr($arrZone['chain'],0,5) == 'zone:')) {
return intval(substr($arrZone['chain'],5));
}
else {
return $zoneId;
}
}
function _adSelectZone($zoneId, $context = array(), $source = '', $richMedia = true)
{
global $g_append, $g_prepend;
while (!in_array($zoneId, $GLOBALS['_MAX']['followedChain'])) {
$GLOBALS['_MAX']['followedChain'][] = $zoneId;
$appendedThisZone = false;
// Get all ads which are linked to the zone
$aZoneLinkedAds = MAX_cacheGetZoneLinkedAds($zoneId);
if ($zoneId != 0 && MAX_limitationsIsZoneForbidden($zoneId, $aZoneLinkedAds)) {
$zoneId = _getNextZone($zoneId, $aZoneLinkedAds);
continue;
}
if (is_array($aZoneLinkedAds)) {
if (isset($aZoneLinkedAds['forceappend']) && $aZoneLinkedAds['forceappend'] == 't') {
$g_prepend .= $aZoneLinkedAds['prepend'];
$g_append = $aZoneLinkedAds['append'] . $g_append;
$appendedThisZone = true;
}
$aLinkedAd = _adSelectCommon($aZoneLinkedAds, $context, $source, $richMedia);
if (is_array($aLinkedAd)) {
$aLinkedAd['zoneid'] = $zoneId;
$aLinkedAd['bannerid'] = $aLinkedAd['ad_id'];
$aLinkedAd['storagetype'] = $aLinkedAd['type'];
$aLinkedAd['campaignid'] = $aLinkedAd['placement_id'];
$aLinkedAd['zone_companion'] = $aZoneLinkedAds['zone_companion'];
$aLinkedAd['block_zone'] = $aZoneLinkedAds['block_zone'];
$aLinkedAd['cap_zone'] = $aZoneLinkedAds['cap_zone'];
$aLinkedAd['session_cap_zone'] = $aZoneLinkedAds['session_cap_zone'];
if (!$appendedThisZone) {
$aLinkedAd['append'] .= $aZoneLinkedAds['append'] . $g_append;
$aLinkedAd['prepend'] = $g_prepend . $aZoneLinkedAds['prepend'];
} else {
$aLinkedAd['append'] .= $g_append;
$aLinkedAd['prepend'] = $g_prepend;
}
return ($aLinkedAd);
}
$zoneId = _getNextZone($zoneId, $aZoneLinkedAds);
}
}
if (!empty($aZoneLinkedAds['default_banner_image_url'])) {
return array(
'default'                        => true,
'default_banner_image_url'       => $aZoneLinkedAds['default_banner_image_url'],
'default_banner_destination_url' => $aZoneLinkedAds['default_banner_destination_url']
);
}
return false;
}
function _adSelectCommon($aAds, $context, $source, $richMedia)
{
// Are there any ads linked?
if (!empty($aAds['count_active'])) {
// Get an ad from the any exclusive campaigns first...
$aLinkedAd = _adSelect($aAds, $context, $source, $richMedia, 'xAds');
// If no ad selected, and a previous ad on the page has set that companion ads should be selected...
if (!is_array($aLinkedAd) && isset($aAds['zone_companion']) && is_array($aAds['zone_companion']) && !empty($context)) {
// The companion paid ads are now grouped by campaign-priority so we need to iterate over the
for ($i=10;$i>0;$i--) {
if (!empty($aAds['cAds'][$i])) {
$aLinkedAd = _adSelect($aAds, $context, $source, $richMedia, 'cAds', $i);
// Did we pick an ad from this campaign-priority level?
if (is_array($aLinkedAd)) { break; }
}
}
// If still no ad selected...
if (!is_array($aLinkedAd)) {
// Select one of the low-priority companion ads
$aLinkedAd = _adSelect($aAds, $context, $source, $richMedia, 'clAds');
}
}
// If still no ad selected...
if (!is_array($aLinkedAd)) {
// Select one of the normal ads
// The normal ads are now grouped by campaign-priority so we need to iterate over the
for ($i=10;$i>0;$i--) {
if (!empty($aAds['ads'][$i])) {
$aLinkedAd = _adSelect($aAds, $context, $source, $richMedia, 'ads', $i);
// Did we pick an ad from this campaign-priority level?
if (is_array($aLinkedAd)) { break; }
}
}
}
// If still no ad selected...
if (!is_array($aLinkedAd)) {
// Select one of the low-priority ads
$aLinkedAd = _adSelect($aAds, $context, $source, $richMedia, 'lAds');
}
if (is_array($aLinkedAd)) {
return $aLinkedAd;
}
}
return false;
}
function _adSelect(&$aLinkedAds, $context, $source, $richMedia, $adArrayVar = 'ads', $cp = null)
{
// If there are no linked ads, we can return
if (!is_array($aLinkedAds)) { return; }
if (!is_null($cp) && isset($aLinkedAds[$adArrayVar][$cp])) {
$aAds = $aLinkedAds[$adArrayVar][$cp];
} elseif (isset($aLinkedAds[$adArrayVar])) {
$aAds = $aLinkedAds[$adArrayVar];
} else {
$aAds = array();
}
// If there are no linked ads of the specified type, we can return
if (count($aAds) == 0) { return; }
// Build preconditions
$aContext = _adSelectBuildContextArray($aAds, $adArrayVar, $context);
// New delivery algorithm: discard all invalid ads before iterating over them
$aAds = _adSelectDiscardNonMatchingAds($aAds, $aContext, $source, $richMedia);
// If there are no linked ads of the specified type, we can return
if (count($aAds) == 0) { return; }
if (!is_null($cp)) {
// Scale priorities
$total_priority = 0;
foreach ($aAds as $ad) {
$total_priority += $ad['priority'] * $ad['priority_factor'];
}
if ($total_priority) {
foreach ($aAds as $key => $ad) {
$aAds[$key]['priority'] = $ad['priority'] * $ad['priority_factor'] *
$aLinkedAds['priority'][$adArrayVar][$cp] / $total_priority;
}
}
}
// Seed the random number generator
global $n;
mt_srand(floor((isset($n) && strlen($n) > 5 ? hexdec($n[0].$n[2].$n[3].$n[4].$n[5]): 1000000) * (double)microtime()));
$conf = $GLOBALS['_MAX']['CONF'];
$paidAds = ($adArrayVar == 'ads') || ($adArrayVar == 'cAds');
if ($paidAds) {
// Paid campaigns have a sum of priorities of unity, so pick
// a float random number between 0 and 1, inclusive.
$ranweight = (mt_rand(0, $GLOBALS['_MAX']['MAX_RAND']) / $GLOBALS['_MAX']['MAX_RAND']);
} else {
// All other campaigns have integer-based priority values, so
// select an integer random number between 0 and the sum of all the
// priority values
$prioritysum = 0;
foreach ($aAds as $aAd) {
$prioritysum += $aAd['priority'];
}
if (!$prioritysum) {
// No priority, exit!
return;
}
$ranweight = ($prioritysum > 1) ? mt_rand(0, $prioritysum - 1) : 0;
}
// Perform selection of an ad, based on the random number
$low = 0;
$high = 0;
foreach($aAds as $aLinkedAd) {
if (is_array($aLinkedAd)) {
$low = $high;
$high += $aLinkedAd['priority'];
if ($high > $ranweight && $low <= $ranweight) {
return $aLinkedAd;
}
}
}
return;
}
function _adSelectCheckCriteria($aAd, $aContext, $source, $richMedia)
{
$conf = $GLOBALS['_MAX']['CONF'];
// Excludelist banners
if (isset($aContext['banner']['exclude'][$aAd['ad_id']])) {
return false;
}
if (isset($aContext['campaign']['exclude'][$aAd['placement_id']])) {
// Excludelist campaigns
return false;
}
if (isset($aContext['client']['exclude'][$aAd['client_id']])) {
// Excludelist clients
return false;
}
if (sizeof($aContext['banner']['include']) && !isset($aContext['banner']['include'][$aAd['ad_id']])) {
// Includelist banners
return false;
}
if (sizeof($aContext['campaign']['include']) && !isset($aContext['campaign']['include'][$aAd['placement_id']])) {
// Includelist campaigns
return false;
}
if (   // Exclude richmedia banners if no alt image is specified
$richMedia == false &&
$aAd['alt_filename'] == '' &&
!($aAd['contenttype'] == 'jpeg' || $aAd['contenttype'] == 'gif' || $aAd['contenttype'] == 'png') &&
!($aAd['type'] == 'url' && $aAd['contenttype'] == '')
) {
return false;
}
if (MAX_limitationsIsAdForbidden($aAd)) {
// Capping & blocking
return false;
}
if ($_SERVER['SERVER_PORT'] == 443 && $aAd['type'] == 'html' &&
(($aAd['adserver'] != 'max' && $aAd['adserver'] != '3rdPartyServers:ox3rdPartyServers:max') || preg_match("#src\s?=\s?['\"]http:#", $aAd['htmlcache']))) {
// HTML Banners that contain 'http:' on SSL
return false;
}
if ($_SERVER['SERVER_PORT'] == 443 && $aAd['type'] == 'url' && (substr($aAd['imageurl'], 0, 5) == 'http:')) {
// It only matters if the initial call is to non-SSL (it can/could contain http:)
return false;
}
if ($conf['delivery']['acls'] && !MAX_limitationsCheckAcl($aAd, $source)) {
// Delivery limitations
return false;
}
// If any of the above failed, this function will have already returned false
// So to get this far means that the ad was valid
return true;
}
function _adSelectBuildContextArray(&$aLinkedAds, $adArrayVar, $context)
{
$aContext = array(
'campaign' => array('exclude' => array(), 'include' => array()),
'banner'   => array('exclude' => array(), 'include' => array()),
'client'   => array('exclude' => array(), 'include' => array()),
);
if (is_array($context) && !empty($context)) {
$cContext = count($context);
for ($i=0; $i < $cContext; $i++) {
reset($context[$i]);
list ($key, $value) = each($context[$i]);
$valueArray = explode(':', $value);
if (count($valueArray) == 1) {
list($value) = $valueArray;
$type = "";
} else {
list($type, $value) = $valueArray;
}
switch($type) {
case 'campaignid':
switch ($key) {
case '!=': $aContext['campaign']['exclude'][$value] = true; break;
case '==': $aContext['campaign']['include'][$value] = true; break;
}
break;
case 'clientid':
switch ($key) {
case '!=': $aContext['client']['exclude'][$value] = true; break;
case '==': $aContext['client']['include'][$value] = true; break;
}
break;
case 'companionid':
switch ($key) {
case '!=': $aContext['campaign']['exclude'][$value]   = true; break;
case '==': $aContext['campaign']['include'][$value] = true; break;
}
break;
default:
switch ($key) {
case '!=': $aContext['banner']['exclude'][$value] = true; break;
case '==': $aContext['banner']['include'][$value] = true; break;
}
}
}
}
return $aContext;
}
function _adSelectBuildContext($aBanner, $context = array()) {
if (!empty($aBanner['zone_companion'])) {
// This zone call has companion banners linked to it.
// So pass into the next call that we would like a banner from this campaign, and not from the other companion linked campaigns;
foreach ($aBanner['zone_companion'] AS $companionCampaign) {
$key = ($aBanner['placement_id'] == $companionCampaign) ? '==' : '!=';
$context[] = array($key => "companionid:$companionCampaign");
}
}
if (isset($aBanner['advertiser_limitation']) && $aBanner['advertiser_limitation'] == '1') {
$context[] = array('!=' => 'clientid:' . $aBanner['client_id']);
}
return $context;
}
function _adSelectDiscardNonMatchingAds($aAds, $aContext, $source, $richMedia)
{
foreach ($aAds as $adId => $aAd) {
if (!_adSelectCheckCriteria($aAd, $aContext, $source, $richMedia)) {
unset($aAds[$adId]);
} else {
}
}
return $aAds;
}
function MAX_flashGetFlashObjectExternal()
{
$conf = $GLOBALS['_MAX']['CONF'];
if (substr($conf['file']['flash'], 0, 4) == 'http') {
$url = $conf['file']['flash'];
} else {
$url = MAX_commonGetDeliveryUrl($conf['file']['flash']);
}
return "<script type='text/javascript' src='{$url}'></script>";
}
function MAX_flashGetFlashObjectInline()
{
$conf = $GLOBALS['_MAX']['CONF'];
// If a full URL is specified for the flashObject code
if (substr($conf['file']['flash'], 0, 4) == 'http') {
// Try to find the local copy (faster)
if (file_exists(MAX_PATH . '/www/delivery/' . basename($conf['file']['flash']))) {
return file_get_contents(MAX_PATH . '/www/delivery/' . basename($conf['file']['flash']));
} else {
// Last ditch - Try to read the file from the full URL
return @file_get_contents($conf['file']['flash']);
}
} elseif (file_exists(MAX_PATH . '/www/delivery/' . $conf['file']['flash'])) {
return file_get_contents(MAX_PATH . '/www/delivery/' . $conf['file']['flash']);
}
}
function MAX_javascriptToHTML($string, $varName, $output = true, $localScope = true)
{
$jsLines = array();
$search[] = "\\"; $replace[] = "\\\\";
$search[] = "\r"; $replace[] = '';
$search[] = '"'; $replace[] = '\"';
$search[] = "'";  $replace[] = "\\'";
$search[] = '<';  $replace[] = '<"+"';
$lines = explode("\n", $string);
foreach ($lines AS $line) {
if(trim($line) != '') {
$jsLines[] = $varName . ' += "' . trim(str_replace($search, $replace, $line)) . '\n";';
}
}
$buffer = (($localScope) ? 'var ' : '') . $varName ." = '';\n";
$buffer .= implode("\n", $jsLines);
if ($output == true) {
$buffer .= "\ndocument.write({$varName});\n";
}
return $buffer;
}
function MAX_javascriptEncodeJsonField($string)
{
$string = addcslashes($string, "\\/\"\n\r\t");
$string = str_replace("\x08", "\\b", $string);
$string = str_replace("\x0C", "\\f", $string);
return '"'.$string.'"';
}
// No Caching
MAX_commonSetNoCacheHeaders();
//Register any script specific input variables
MAX_commonRegisterGlobalsArray(array('layerstyle'));
if (!isset($layerstyle) || empty($layerstyle)) $layerstyle = 'geocities';
// Include layerstyle
if (file_exists(MAX_PATH . $conf['pluginPaths']['extensions'] . 'invocationTags/oxInvocationTags/layerstyles/'.$layerstyle.'/layerstyle.inc.php')) {
include MAX_PATH . $conf['pluginPaths']['extensions'] . 'invocationTags/oxInvocationTags/layerstyles/'.$layerstyle.'/layerstyle.inc.php';
} else {
// Don't generate output when plugin layerstyleisn't available,just send javascript comment on fail
echo '// Cannot load required layerstyle file. Check if openXInvocationTags plugin is installed';
exit(1);
}
//Register any script specific input variables
MAX_commonRegisterGlobalsArray(array('block', 'blockcampaign', 'exclude', 'mmm_fo', 'q'));
if (isset($context) && !is_array($context)) {
$context = MAX_commonUnpackContext($context);
}
if (!is_array($context)) {
$context = array();
}
$limitations = MAX_layerGetLimitations();
MAX_commonSendContentTypeHeader("application/x-javascript", $charset);
if ($limitations['compatible']) {
$output = MAX_adSelect($what, $campaignid, $target, $source, $withtext, $charset, $context, $limitations['richmedia'], $GLOBALS['ct0'], $GLOBALS['loc'], $GLOBALS['referer']);
MAX_cookieFlush();
// Exit if no matching banner was found
if (empty($output['html'])) {
exit;
}
$uniqid = substr(md5(uniqid('', 1)), 0, 8);
// Block this banner for next invocation
if (!empty($block) && !empty($output['bannerid'])) {
$output['context'][] = array('!=' => 'bannerid:' . $output['bannerid']);
}
// Block this campaign for next invocation
if (!empty($blockcampaign) && !empty($output['campaignid'])) {
$output['context'][] = array('!=' => 'campaignid:' . $output['campaignid']);
}
// Block this campaign for next invocation
if (!empty($blockcampaign) && !empty($output['campaignid'])) {
$output['context'][] = array('!=' => 'campaignid:' . $output['campaignid']);
}
// Append any data to the context array
if (!empty($output['context'])) {
foreach ($output['context'] as $id => $contextArray) {
if (!in_array($contextArray, $context)) {
$context[] = $contextArray;
}
}
}
// Include the FlashObject script if required
if ($output['contenttype'] == 'swf') {
echo MAX_flashGetFlashObjectInline();
}
// Set document.context, if required
$output['html'] .= (!empty($context)) ? "<script type='text/javascript'>document.context='".MAX_commonPackContext($context)."'; </script>" : '';
echo MAX_javascriptToHTML(MAX_layerGetHtml($output, $uniqid), "MAX_{$uniqid}");
MAX_layerPutJs($output, $uniqid);
ob_flush();
}


?>