<?php

/*
+---------------------------------------------------------------------------+
| Revive Adserver                                                           |
| http://www.revive-adserver.com                                            |
|                                                                           |
| Copyright: See the COPYRIGHT.txt file.                                    |
| License: GPLv2 or later, see the LICENSE.txt file.                        |
+---------------------------------------------------------------------------+
*/

/**
 * This is autogenerated file which contains all files from the "delivery_dev"
 * folder of Revive Adserver merged into a single output file. On systems
 * without a PHP opcode cache that is configured to not regularly check for
 * file updates, this autogenerated file can dramatically improve the
 * performance of Revive Adserver's delivery engine.
 *
 * !!!Warning!!!
 *
 * Do not edit this file. If you need to do any changes to any delivery file,
 * check out the source code from GitHub; make the necessary changes to the
 * file(s) in the "delivery_dev" folder; and regenerate the delivery files
 * using the script located in the "scripts/delivery" directory.
 */

function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true)
{
$fixMysqli = function($conf) {
if ('mysql' === $conf['database']['type'] && !extension_loaded('mysql') && extension_loaded('mysqli')) {
$conf['database']['type'] = 'mysqli';
} elseif ('mysqli' === $conf['database']['type'] && !extension_loaded('mysqli') && extension_loaded('mysql')) {
$conf['database']['type'] = 'mysql';
}
return $conf;
};
if (!$configPath) {
$configPath = MAX_PATH . '/var';
}
if ($configFile) {
$configFile = '.' . $configFile;
}
$host = OX_getHostName();
$configFileName = $configPath . '/' . $host . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
$realconf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
$conf = mergeConfigFiles($realconf, $conf);
}
if (!empty($conf)) {
return $fixMysqli($conf);
} elseif ($configFile === '.plugin') {
$pluginType = basename($configPath);
$defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php';
$conf = @parse_ini_file($defaultConfig, $sections);
if ($conf !== false) {
return $conf;
}
echo "Revive Adserver could not read the default configuration file for the {$pluginType} plugin";
exit(1);
}
$configFileName = $configPath . '/default' . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $fixMysqli($conf);
}
if (file_exists(MAX_PATH . '/var/INSTALLED')) {
echo "Revive Adserver has been installed, but no configuration file was found.\n";
exit(1);
}
echo "Revive Adserver 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 OX_getMinimumRequiredMemory($limit = null)
{
if ($limit == 'maintenance') {
return 134217728;  }
return 134217728; }
function OX_getMemoryLimitSizeInBytes() {
$phpMemoryLimit = ini_get('memory_limit');
if (empty($phpMemoryLimit) || $phpMemoryLimit == -1) {
return -1;
}
$aSize = array(
'G' => 1073741824,
'M' => 1048576,
'K' => 1024
);
$phpMemoryLimitInBytes = $phpMemoryLimit;
foreach($aSize as $type => $multiplier) {
$pos = strpos($phpMemoryLimit, $type);
if (!$pos) {
$pos = strpos($phpMemoryLimit, strtolower($type));
}
if ($pos) {
$phpMemoryLimitInBytes = substr($phpMemoryLimit, 0, $pos) * $multiplier;
}
}
return $phpMemoryLimitInBytes;
}
function OX_checkMemoryCanBeSet()
{
$phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes();
if ($phpMemoryLimitInBytes == -1) {
return true;
}
OX_increaseMemoryLimit($phpMemoryLimitInBytes + 1);
$newPhpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes();
$memoryCanBeSet = ($phpMemoryLimitInBytes != $newPhpMemoryLimitInBytes);
@ini_set('memory_limit', $phpMemoryLimitInBytes);
return $memoryCanBeSet;
}
function OX_increaseMemoryLimit($setMemory) {
$phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes();
if ($phpMemoryLimitInBytes == -1) {
return true;
}
if ($setMemory > $phpMemoryLimitInBytes) {
if (@ini_set('memory_limit', $setMemory) === false) {
return false;
}
}
return true;
}


function setupConfigVariables()
{
$GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'] = '|';
$GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'] = '__';
$GLOBALS['_MAX']['thread_id'] = uniqid();
$GLOBALS['_MAX']['SSL_REQUEST'] = false;
if (
(!empty($_SERVER['SERVER_PORT']) && !empty($GLOBALS['_MAX']['CONF']['openads']['sslPort']) && ($_SERVER['SERVER_PORT'] == $GLOBALS['_MAX']['CONF']['openads']['sslPort'])) ||
(!empty($_SERVER['HTTPS']) && ((strtolower($_SERVER['HTTPS']) == 'on') || ($_SERVER['HTTPS'] == 1))) ||
(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) ||
(!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && (strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on')) ||
(!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && (strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) == 'on')) ||
(!empty($_SERVER['FRONT-END-HTTPS']) && (strtolower($_SERVER['FRONT-END-HTTPS']) == 'on'))
) {
$GLOBALS['_MAX']['SSL_REQUEST'] = true;
}
$GLOBALS['_MAX']['MAX_RAND'] = isset($GLOBALS['_MAX']['CONF']['priority']['randmax']) ?
$GLOBALS['_MAX']['CONF']['priority']['randmax'] : 2147483647;
list($micro_seconds, $seconds) = explode(" ", microtime());
$GLOBALS['_MAX']['NOW_ms'] = round(1000 *((float)$micro_seconds + (float)$seconds));
if (substr($_SERVER['SCRIPT_NAME'], -11) != 'install.php') {
$GLOBALS['serverTimezone'] = date_default_timezone_get();
OA_setTimeZoneUTC();
}
}
function setupServerVariables()
{
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', MAX_PATH);
}
if (!defined('RV_PATH')) {
define('RV_PATH', MAX_PATH);
}
if (!defined('LIB_PATH')) {
define('LIB_PATH', MAX_PATH. DIRECTORY_SEPARATOR. 'lib'. DIRECTORY_SEPARATOR. 'OX');
}
if ( !(isset($GLOBALS['_MAX']['CONF']))) {
$GLOBALS['_MAX']['CONF'] = parseDeliveryIniFile();
}
setupConfigVariables();
}
function OA_setTimeZone($timezone)
{
date_default_timezone_set($timezone);
$GLOBALS['_DATE_TIMEZONE_DEFAULT'] = $timezone;
}
function OA_setTimeZoneUTC()
{
OA_setTimeZone('UTC');
}
function OA_setTimeZoneLocal()
{
$tz = !empty($GLOBALS['_MAX']['PREF']['timezone']) ? $GLOBALS['_MAX']['PREF']['timezone'] : 'UTC';
OA_setTimeZone($tz);
}
function OX_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 OX_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 RV_getContainer()
{
return $GLOBALS['_MAX']['DI'];
}

OX_increaseMemoryLimit(OX_getMinimumRequiredMemory());
if (!defined('E_DEPRECATED')) {
define('E_DEPRECATED', 0);
}
setupServerVariables();
setupDeliveryConfigVariables();
$conf = $GLOBALS['_MAX']['CONF'];
include MAX_PATH.'/lib/vendor/autoload.php';
$GLOBALS['_OA']['invocationType'] = array_search(basename($_SERVER['SCRIPT_FILENAME']), $conf['file']);
if (!empty($conf['debug']['production'])) {
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING | E_DEPRECATED | E_STRICT));
} else {
error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT));
}

$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();
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'];
if (!empty($aConf['privacy']['disableViewerId'])) {
return;
}
MAX_cookieAdd($aConf['var']['viewerId'], $viewerId, _getTimeYearFromNow());
MAX_cookieFlush();
if ($GLOBALS['_MAX']['SSL_REQUEST']) {
$url = MAX_commonConstructSecureDeliveryUrl(basename($_SERVER['SCRIPT_NAME']));
} else {
$url = MAX_commonConstructDeliveryUrl(basename($_SERVER['SCRIPT_NAME']));
}
$url .= "?{$aConf['var']['cookieTest']}=1&" . $_SERVER['QUERY_STRING'];
MAX_header("Location: {$url}");
 exit;
}
function _getTimeThirtyDaysFromNow()
{
return MAX_commonGetTimeNow() + 2592000; }
function _getTimeYearFromNow()
{
return MAX_commonGetTimeNow() + 31536000; }
function _getTimeYearAgo()
{
return MAX_commonGetTimeNow() - 31536000; }
function MAX_cookieUnpackCapping()
{
$conf = $GLOBALS['_MAX']['CONF'];
$cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
if (!is_array($cookieNames))
return;
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;
}
}
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)
{
static $uniqueViewerId = null;
 if (null !== $uniqueViewerId) {
return $uniqueViewerId;
}

$conf = $GLOBALS['_MAX']['CONF'];
$privacyViewerId = empty($conf['privacy']['disableViewerId']) ? null : '01000111010001000101000001010010';
if (isset($_COOKIE[$conf['var']['viewerId']])) {
$uniqueViewerId = $privacyViewerId ?: $_COOKIE[$conf['var']['viewerId']];
} elseif ($create) {
$uniqueViewerId = $privacyViewerId ?: md5(uniqid('', true));
$GLOBALS['_MAX']['COOKIE']['newViewerId'] = true;
} else {
$uniqueViewerId = null;
}
return $uniqueViewerId;
}
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()
{
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) {
$expire = MAX_commonGetTimeNow() + $conf['cookie']['permCookieSeconds'];
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;
$setBlock = true;
} else {
$value = 1;
}
MAX_cookieAdd("_{$conf['var']['cap' . $type]}[{$id}]", $value, $expire);
}
if ($sessionCap > 0) {
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;
$setBlock = true;
} else {
$value = 1;
}
MAX_cookieAdd("_{$conf['var']['sessionCap' . $type]}[{$id}]", $value, 0);
}
if ($block > 0 || $setBlock) {
MAX_cookieAdd("_{$conf['var']['block' . $type]}[{$id}]", MAX_commonGetTimeNow(), _getTimeThirtyDaysFromNow());
}
}
function MAX_cookieClientCookieSet($name, $value, $expires, $path = '/', $domain = null, $secure = null, $httpOnly = false, $sameSite = 'none')
{
 if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xmlrpc') {
if (!isset($GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'])) {
$GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'] = array();
}
$GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'][$name] = array($value, $expires);
} else {
$secure = $secure ?? !empty($GLOBALS['_MAX']['SSL_REQUEST']);
if (PHP_VERSION_ID < 70300) {
@setcookie($name, $value, $expires, $path.'; samesite='.$sameSite, $domain, $secure, $httpOnly);
} else {
@setcookie($name, $value, [
'expires' => $expires,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $httpOnly,
'samesite' => $sameSite,
]);
}
}
}
function MAX_cookieClientCookieUnset($name)
{
$conf = $GLOBALS['_MAX']['CONF'];
$domain = (!empty($conf['cookie']['domain'])) ? $conf['cookie']['domain'] : null;
MAX_cookieSet($name, false, _getTimeYearAgo(), '/', $domain);
MAX_cookieSet(str_replace('_', '%5F', urlencode($name)), false, _getTimeYearAgo(), '/', $domain);
}
function MAX_cookieClientCookieFlush()
{
$conf = $GLOBALS['_MAX']['CONF'];
$domain = !empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null;
MAX_cookieSendP3PHeaders();
if (!empty($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
reset($GLOBALS['_MAX']['COOKIE']['CACHE']);
while (list($name,$v) = each ($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
list($value, $expire) = $v;
if ($name === $conf['var']['viewerId']) {
MAX_cookieClientCookieSet($name, $value, $expire, '/', !empty($conf['cookie']['viewerIdDomain']) ? $conf['cookie']['viewerIdDomain'] : $domain);
} else {
MAX_cookieSet($name, $value, $expire, '/', $domain);
}
}
$GLOBALS['_MAX']['COOKIE']['CACHE'] = array();
}
$cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
if (!is_array($cookieNames))
return;
$maxCookieSize = !empty($conf['cookie']['maxCookieSize']) ? $conf['cookie']['maxCookieSize'] : 2048;
foreach ($cookieNames as $cookieName) {
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']['lastClick'] :
case $conf['var']['lastView'] :
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}";
}
while (strlen(implode('_', $data)) > $maxCookieSize) {
$data = array_slice($data, 1);
}
MAX_cookieSet($cookieName, implode('_', $data), $expire, '/', $domain);
}
}
}
function MAX_cookieSendP3PHeaders() {
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'] != 'xmlrpc')) {
MAX_remotehostProxyLookup();
MAX_remotehostAnonymise();
MAX_remotehostReverseLookup();
MAX_remotehostSetGeoInfo();
}
}
function MAX_remotehostProxyLookup()
{
$conf = $GLOBALS['_MAX']['CONF'];
if ($conf['logging']['proxyLookup']) {
OX_Delivery_logMessage('checking remote host proxy', 7);
$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;
}
}
}
if ($proxy) {
OX_Delivery_logMessage('proxy detected', 7);
$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)) {
foreach (explode(',', $ip) as $ip) {
$ip = trim($ip);
if (($ip != 'unknown') && (!MAX_remotehostPrivateAddress($ip))) {
$_SERVER['REMOTE_ADDR'] = $ip;
$_SERVER['REMOTE_HOST'] = '';
$_SERVER['HTTP_VIA'] = '';
OX_Delivery_logMessage('real address set to '.$ip, 7);
break;
}
}
}
}
}
}
function MAX_remotehostReverseLookup()
{
if (empty($_SERVER['REMOTE_HOST'])) {
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')) {

}
$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_remotehostAnonymise()
{
if (!empty($GLOBALS['_MAX']['CONF']['privacy']['anonymiseIp'])) {
$_SERVER['REMOTE_ADDR'] = preg_replace('/\d+$/', '0', $_SERVER['REMOTE_ADDR']);
}
}
function MAX_remotehostPrivateAddress($ip)
{
$ip = ip2long($ip);
if (!$ip) return false;
return (MAX_remotehostMatchSubnet($ip, '10.0.0.0', 8) ||
MAX_remotehostMatchSubnet($ip, '172.16.0.0', 12) ||
MAX_remotehostMatchSubnet($ip, '192.168.0.0', 16) ||
MAX_remotehostMatchSubnet($ip, '127.0.0.0', 8)
);
}
function MAX_remotehostMatchSubnet($ip, $net, $mask)
{
$net = ip2long($net);
if (!is_integer($ip)) {
$ip = ip2long($ip);
}
if (!$ip || !$net) {
return false;
}
if (is_integer($mask)) {
if ($mask > 32 || $mask <= 0)
return false;
elseif ($mask == 32)
$mask = ~0;
else
$mask = ~((1 << (32 - $mask)) - 1);
} elseif (!($mask = ip2long($mask))) {
return false;
}
return ($ip & $mask) == ($net & $mask) ? true : false;
}


$file = '/lib/max/Delivery/log.php';
$GLOBALS['_MAX']['FILES'][$file] = true;

$file = '/lib/max/Dal/Delivery.php';
$GLOBALS['_MAX']['FILES'][$file] = true;

$file = '/lib/OA/Dal/Delivery.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
function OA_Dal_Delivery_isValidResult($result) {
return is_resource($result) || $result instanceof mysqli_result;
}
function OA_Dal_Delivery_getAccountTZs()
{
$aConf = $GLOBALS['_MAX']['CONF'];
$query = "
        SELECT
            value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['application_variable'])."
        WHERE
            name = 'admin_account_id'
    ";
$res = OA_Dal_Delivery_query($query);
if (OA_Dal_Delivery_isValidResult($res) && OA_Dal_Delivery_numRows($res)) {
$adminAccountId = (int)OA_Dal_Delivery_result($res, 0, 0);
} else {
$adminAccountId = false;
}
$query = "
        SELECT
            a.account_id AS account_id,
            apa.value AS timezone
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a JOIN
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa ON (apa.account_id = a.account_id) JOIN
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['preferences'])." AS p ON (p.preference_id = apa.preference_id)
        WHERE
            a.account_type IN ('ADMIN', 'MANAGER') AND
            p.preference_name = 'timezone'
    ";
$res = OA_Dal_Delivery_query($query);
$aResult = array(
'adminAccountId' => $adminAccountId,
'aAccounts' => array()
);
if (OA_Dal_Delivery_isValidResult($res)) {
while ($row = OA_Dal_Delivery_fetchAssoc($res)) {
$accountId = (int)$row['account_id'];
if ($accountId === $adminAccountId) {
$aResult['default'] = $row['timezone'];
} else {
$aResult['aAccounts'][$accountId] = $row['timezone'];
}
}
}
if (empty($aResult['default'])) {
$aResult['default'] = 'UTC';
}
return $aResult;
}
function OA_Dal_Delivery_getZoneInfo($zoneid) {
$aConf = $GLOBALS['_MAX']['CONF'];
$zoneid = (int)$zoneid;
$query = "
        SELECT
            z.zoneid AS zone_id,
            z.zonename AS name,
            z.delivery AS type,
            z.description AS description,
            z.width AS width,
            z.height AS height,
            z.chain AS chain,
            z.prepend AS prepend,
            z.append AS append,
            z.appendtype AS appendtype,
            z.forceappend AS forceappend,
            z.inventory_forecast_type AS inventory_forecast_type,
            z.block AS block_zone,
            z.capping AS cap_zone,
            z.session_capping AS session_cap_zone,
            z.show_capped_no_cookie AS show_capped_no_cookie_zone,
            z.ext_adselection AS ext_adselection,
            z.affiliateid AS publisher_id,
            a.agencyid AS agency_id,
            a.account_id AS trafficker_account_id,
            m.account_id AS manager_account_id
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['zones'])." AS z,
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['affiliates'])." AS a,
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['agency'])." AS m
        WHERE
            z.zoneid = {$zoneid}
          AND
            z.affiliateid = a.affiliateid
          AND
            a.agencyid = m.agencyid";
$rZoneInfo = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rZoneInfo)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
}
$aZoneInfo = OA_Dal_Delivery_fetchAssoc($rZoneInfo);
if (empty($aZoneInfo)) {
return false;
}
$query = "
        SELECT
            p.preference_id AS preference_id,
            p.preference_name AS preference_name
        FROM
            {$aConf['table']['prefix']}{$aConf['table']['preferences']} AS p
        WHERE
            p.preference_name = 'default_banner_image_url'
            OR
            p.preference_name = 'default_banner_destination_url'";
$rPreferenceInfo = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rPreferenceInfo)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
}
if (OA_Dal_Delivery_numRows($rPreferenceInfo) != 2) {
return $aZoneInfo;
}
$aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo);
$variableName = $aPreferenceInfo['preference_name'] . '_id';
$$variableName = $aPreferenceInfo['preference_id'];
$aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo);
$variableName = $aPreferenceInfo['preference_name'] . '_id';
$$variableName = $aPreferenceInfo['preference_id'];
$query = "
        SELECT
            'default_banner_destination_url_trafficker' AS item,
            apa.value AS value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
        WHERE
            apa.account_id = {$aZoneInfo['trafficker_account_id']}
            AND
            apa.preference_id = $default_banner_destination_url_id
        UNION
        SELECT
            'default_banner_destination_url_manager' AS item,
            apa.value AS value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
        WHERE
            apa.account_id = {$aZoneInfo['manager_account_id']}
            AND
            apa.preference_id = $default_banner_destination_url_id
        UNION
        SELECT
            'default_banner_image_url_trafficker' AS item,
            apa.value AS value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
        WHERE
            apa.account_id = {$aZoneInfo['trafficker_account_id']}
            AND
            apa.preference_id = $default_banner_image_url_id
        UNION
        SELECT
            'default_banner_image_url_manager' AS item,
            apa.value AS value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
        WHERE
            apa.account_id = {$aZoneInfo['manager_account_id']}
            AND
            apa.preference_id = $default_banner_image_url_id
        UNION
        SELECT
            'default_banner_image_url_admin' AS item,
            apa.value AS value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa,
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a
        WHERE
            apa.account_id = a.account_id
            AND
            a.account_type = 'ADMIN'
            AND
            apa.preference_id = $default_banner_image_url_id
        UNION
        SELECT
            'default_banner_destination_url_admin' AS item,
            apa.value AS value
        FROM
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa,
            ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a
        WHERE
            apa.account_id = a.account_id
            AND
            a.account_type = 'ADMIN'
            AND
            apa.preference_id = $default_banner_destination_url_id";
$rDefaultBannerInfo = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rDefaultBannerInfo)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
}
if (OA_Dal_Delivery_numRows($rDefaultBannerInfo) == 0) {
if ($aConf['defaultBanner']['imageUrl'] != '') {
$aZoneInfo['default_banner_image_url'] = $aConf['defaultBanner']['imageUrl'];
}
return $aZoneInfo;
}
$aDefaultImageURLs = array();
$aDefaultDestinationURLs = array();
while ($aRow = OA_Dal_Delivery_fetchAssoc($rDefaultBannerInfo)) {
if (stristr($aRow['item'], 'default_banner_image_url')) {
$aDefaultImageURLs[$aRow['item']] = $aRow['value'];
} else if (stristr($aRow['item'], 'default_banner_destination_url')) {
$aDefaultDestinationURLs[$aRow['item']] = $aRow['value'];
}
}
$aTypes = array(
0 => 'admin',
1 => 'manager',
2 => 'trafficker'
);
foreach ($aTypes as $type) {
if (isset($aDefaultImageURLs['default_banner_image_url_' . $type])) {
$aZoneInfo['default_banner_image_url'] = $aDefaultImageURLs['default_banner_image_url_' . $type];
}
if (isset($aDefaultDestinationURLs['default_banner_destination_url_' . $type])) {
$aZoneInfo['default_banner_destination_url'] = $aDefaultDestinationURLs['default_banner_destination_url_' . $type];
}
}
return $aZoneInfo;
}
function OA_Dal_Delivery_getPublisherZones($publisherid) {
$conf = $GLOBALS['_MAX']['CONF'];
$publisherid = (int)$publisherid;
$rZones = OA_Dal_Delivery_query("
    SELECT
        z.zoneid AS zone_id,
        z.affiliateid AS publisher_id,
        z.zonename AS name,
        z.delivery AS type
    FROM
        ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z
    WHERE
        z.affiliateid={$publisherid}
    ");
if (!OA_Dal_Delivery_isValidResult($rZones)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
}
while ($aZone = OA_Dal_Delivery_fetchAssoc($rZones)) {
$aZones[$aZone['zone_id']] = $aZone;
}
return ($aZones);
}
function OA_Dal_Delivery_getZoneLinkedAds($zoneid) {
$conf = $GLOBALS['_MAX']['CONF'];
$zoneid = (int)$zoneid;
$aRows = OA_Dal_Delivery_getZoneInfo($zoneid);
$aRows['xAds'] = array();
$aRows['ads'] = array();
$aRows['lAds'] = array();
$aRows['eAds'] = array();
$aRows['count_active'] = 0;
$aRows['zone_companion'] = false;
$aRows['count_active'] = 0;
$totals = array(
'xAds' => 0,
'ads' => 0,
'lAds' => 0
);
$query = "
        SELECT
            d.bannerid AS ad_id,
            d.campaignid AS placement_id,
            d.status AS status,
            d.description AS name,
            d.storagetype AS type,
            d.contenttype AS contenttype,
            d.pluginversion AS pluginversion,
            d.filename AS filename,
            d.imageurl AS imageurl,
            d.htmltemplate AS htmltemplate,
            d.htmlcache AS htmlcache,
            d.width AS width,
            d.height AS height,
            d.weight AS weight,
            d.seq AS seq,
            d.target AS target,
            d.url AS url,
            d.alt AS alt,
            d.statustext AS statustext,
            d.bannertext AS bannertext,
            d.adserver AS adserver,
            d.block AS block_ad,
            d.capping AS cap_ad,
            d.session_capping AS session_cap_ad,
            d.compiledlimitation AS compiledlimitation,
            d.acl_plugins AS acl_plugins,
            d.prepend AS prepend,
            d.append AS append,
            d.bannertype AS bannertype,
            d.alt_filename AS alt_filename,
            d.alt_imageurl AS alt_imageurl,
            d.alt_contenttype AS alt_contenttype,
            d.parameters AS parameters,
            d.transparent AS transparent,
            d.ext_bannertype AS ext_bannertype,
            d.iframe_friendly AS iframe_friendly,
            az.priority AS priority,
            az.priority_factor AS priority_factor,
            az.to_be_delivered AS to_be_delivered,
            c.campaignid AS campaign_id,
            c.campaignname AS campaign_name,
            c.priority AS campaign_priority,
            c.weight AS campaign_weight,
            c.companion AS campaign_companion,
            c.block AS block_campaign,
            c.capping AS cap_campaign,
            c.session_capping AS session_cap_campaign,
            c.show_capped_no_cookie AS show_capped_no_cookie,
            c.clientid AS client_id,
            c.expire_time AS expire_time,
            c.revenue_type AS revenue_type,
            c.ecpm_enabled AS ecpm_enabled,
            c.ecpm AS ecpm,
            c.clickwindow AS clickwindow,
            c.viewwindow AS viewwindow,
            m.advertiser_limitation AS advertiser_limitation,
            a.account_id AS account_id,
            z.affiliateid AS affiliate_id,
            a.agencyid as agency_id
        FROM
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z ON (az.zone_id = z.zoneid) JOIN
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m ON (m.clientid = c.clientid) LEFT JOIN
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = m.agencyid)
        WHERE
            az.zone_id = {$zoneid}
          AND
            d.status <= 0
          AND
            c.status <= 0
    ";
$rAds = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rAds)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
}
$aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives();
while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
$aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null;
if ($aAd['campaign_priority'] == -1) {
$aRows['xAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} elseif ($aAd['campaign_priority'] == 0) {
$aRows['lAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} elseif ($aAd['campaign_priority'] == -2) {
$aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} else {
$aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
}
if ($aAd['campaign_companion'] == 1) {
$aRows['zone_companion'][] = $aAd['placement_id'];
}
}
if (is_array($aRows['xAds'])) {
$totals['xAds'] = _setPriorityFromWeights($aRows['xAds']);
}
if (is_array($aRows['ads'])) {
$totals['ads'] = _getTotalPrioritiesByCP($aRows['ads']);
}
if (is_array($aRows['eAds'])) {
$totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']);
}
if (is_array($aRows['lAds'])) {
$totals['lAds'] = _setPriorityFromWeights($aRows['lAds']);
}
$aRows['priority'] = $totals;
return $aRows;
}
function OA_Dal_Delivery_getZoneLinkedAdInfos($zoneid) {
$conf = $GLOBALS['_MAX']['CONF'];
$zoneid = (int)$zoneid;
$aRows['xAds'] = array();
$aRows['ads'] = array();
$aRows['lAds'] = array();
$aRows['eAds'] = array();
$aRows['zone_companion'] = false;
$aRows['count_active'] = 0;
$query =
"SELECT "
."d.bannerid AS ad_id, "  ."d.campaignid AS placement_id, "  ."d.status AS status, "  ."d.width AS width, "
."d.ext_bannertype AS ext_bannertype, "
."d.height AS height, "
."d.storagetype AS type, "  ."d.contenttype AS contenttype, "  ."d.weight AS weight, "  ."d.adserver AS adserver, "  ."d.block AS block_ad, "  ."d.capping AS cap_ad, "  ."d.session_capping AS session_cap_ad, "  ."d.compiledlimitation AS compiledlimitation, "  ."d.acl_plugins AS acl_plugins, "  ."d.alt_filename AS alt_filename, "  ."az.priority AS priority, "  ."az.priority_factor AS priority_factor, "  ."az.to_be_delivered AS to_be_delivered, "  ."c.campaignid AS campaign_id, "  ."c.priority AS campaign_priority, "  ."c.weight AS campaign_weight, "  ."c.companion AS campaign_companion, "  ."c.block AS block_campaign, "  ."c.capping AS cap_campaign, "  ."c.session_capping AS session_cap_campaign, " ."c.show_capped_no_cookie AS show_capped_no_cookie, "
."c.clientid AS client_id, "  ."c.expire_time AS expire_time, "
."c.revenue_type AS revenue_type, "
."c.ecpm_enabled AS ecpm_enabled, "
."c.ecpm AS ecpm, "
."ct.status AS tracker_status, "
.OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe, "
.OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe "
."FROM "
.OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN "
.OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN "
.OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN "
.OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = c.campaignid) "
."WHERE "
."az.zone_id = {$zoneid} "
."AND "
."d.status <= 0 "
."AND "
."c.status <= 0 ";
$rAds = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rAds)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
}
while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
if ($aAd['campaign_priority'] == -1) {
$aRows['xAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} elseif ($aAd['campaign_priority'] == 0) {
$aRows['lAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} elseif ($aAd['campaign_priority'] == -2) {
$aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} else {
$aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
}
if ($aAd['campaign_companion'] == 1) {
$aRows['zone_companion'][] = $aAd['placement_id'];  }
}
return $aRows;
}
function OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid = '', $lastpart = true) {
$conf = $GLOBALS['_MAX']['CONF'];
$campaignid = (int)$campaignid;
if ($campaignid > 0) {
$precondition = " AND d.campaignid = '".$campaignid."' ";
} else {
$precondition = '';
}
$aRows['xAds'] = array();
$aRows['ads'] = array();
$aRows['lAds'] = array();
$aRows['count_active'] = 0;
$aRows['zone_companion'] = false;
$aRows['count_active'] = 0;
$totals = array(
'xAds' => 0,
'ads' => 0,
'lAds' => 0
);
$query = OA_Dal_Delivery_buildAdInfoQuery($search, $lastpart, $precondition);
$rAds = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rAds)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
}
while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
if ($aAd['campaign_priority'] == -1) {
$aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
$aRows['xAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
$totals['xAds'] += $aAd['priority'];
} elseif ($aAd['campaign_priority'] == 0) {
$aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
$aRows['lAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
$totals['lAds'] += $aAd['priority'];
} elseif ($aAd['campaign_priority'] == -2) {
$aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} else {
$aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
}
}
return $aRows;
}
function OA_Dal_Delivery_getLinkedAds($search, $campaignid = '', $lastpart = true) {
$conf = $GLOBALS['_MAX']['CONF'];
$campaignid = (int)$campaignid;
if ($campaignid > 0) {
$precondition = " AND d.campaignid = '".$campaignid."' ";
} else {
$precondition = '';
}
$aRows['xAds'] = array();
$aRows['ads'] = array();
$aRows['lAds'] = array();
$aRows['count_active'] = 0;
$aRows['zone_companion'] = false;
$aRows['count_active'] = 0;
$totals = array(
'xAds' => 0,
'ads' => 0,
'lAds' => 0
);
$query = OA_Dal_Delivery_buildQuery($search, $lastpart, $precondition);
$rAds = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rAds)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
}
$aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives();
while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
$aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null;
if ($aAd['campaign_priority'] == -1) {
$aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
$aRows['xAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
$totals['xAds'] += $aAd['priority'];
} elseif ($aAd['campaign_priority'] == 0) {
$aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
$aRows['lAds'][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
$totals['lAds'] += $aAd['priority'];
} elseif ($aAd['campaign_priority'] == -2) {
$aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
} else {
$aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
$aRows['count_active']++;
}
}
if (isset($aRows['xAds']) && is_array($aRows['xAds'])) {
$totals['xAds'] = _setPriorityFromWeights($aRows['xAds']);
}
if (isset($aRows['ads']) && is_array($aRows['ads'])) {
if (isset($aRows['lAds']) && is_array($aRows['lAds']) && count($aRows['lAds']) > 0) {
$totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], true);
} else {
$totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], false);
}
}
if (is_array($aRows['eAds'])) {
$totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']);
}
if (isset($aRows['lAds']) && is_array($aRows['lAds'])) {
$totals['lAds'] = _setPriorityFromWeights($aRows['lAds']);
}
$aRows['priority'] = $totals;
return $aRows;
}
function OA_Dal_Delivery_getAd($ad_id) {
$conf = $GLOBALS['_MAX']['CONF'];
$ad_id = (int)$ad_id;
$query = "
        SELECT
        d.bannerid AS ad_id,
        d.campaignid AS placement_id,
        d.status AS status,
        d.description AS name,
        d.storagetype AS type,
        d.contenttype AS contenttype,
        d.pluginversion AS pluginversion,
        d.filename AS filename,
        d.imageurl AS imageurl,
        d.htmltemplate AS htmltemplate,
        d.htmlcache AS htmlcache,
        d.width AS width,
        d.height AS height,
        d.weight AS weight,
        d.seq AS seq,
        d.target AS target,
        d.url AS url,
        d.alt AS alt,
        d.statustext AS statustext,
        d.bannertext AS bannertext,
        d.adserver AS adserver,
        d.block AS block_ad,
        d.capping AS cap_ad,
        d.session_capping AS session_cap_ad,
        d.compiledlimitation AS compiledlimitation,
        d.acl_plugins AS acl_plugins,
        d.prepend AS prepend,
        d.append AS append,
        d.bannertype AS bannertype,
        d.alt_filename AS alt_filename,
        d.alt_imageurl AS alt_imageurl,
        d.alt_contenttype AS alt_contenttype,
        d.parameters AS parameters,
        d.transparent AS transparent,
        d.ext_bannertype AS ext_bannertype,
        d.iframe_friendly AS iframe_friendly,
        c.campaignid AS campaign_id,
        c.block AS block_campaign,
        c.capping AS cap_campaign,
        c.session_capping AS session_cap_campaign,
        c.show_capped_no_cookie AS show_capped_no_cookie,
        m.clientid AS client_id,
        c.clickwindow AS clickwindow,
        c.viewwindow AS viewwindow,
        m.advertiser_limitation AS advertiser_limitation,
        m.agencyid AS agency_id,
        c.status AS campaign_status
    FROM
        ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d,
        ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c,
        ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m
    WHERE
        d.bannerid={$ad_id}
        AND
        d.campaignid = c.campaignid
        AND
        m.clientid = c.clientid
    ";
$rAd = OA_Dal_Delivery_query($query);
if (!OA_Dal_Delivery_isValidResult($rAd)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
} else {
return (OA_Dal_Delivery_fetchAssoc($rAd));
}
}
function OA_Dal_Delivery_getChannelLimitations($channelid) {
$conf = $GLOBALS['_MAX']['CONF'];
$channelid = (int)$channelid;
$rLimitation = OA_Dal_Delivery_query("
    SELECT
            acl_plugins,compiledlimitation
    FROM
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['channel'])."
    WHERE
            channelid={$channelid}");
if (!OA_Dal_Delivery_isValidResult($rLimitation)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
}
$limitations = OA_Dal_Delivery_fetchAssoc($rLimitation);
return $limitations;
}
function OA_Dal_Delivery_getCreative($filename)
{
$conf = $GLOBALS['_MAX']['CONF'];
$rCreative = OA_Dal_Delivery_query("
        SELECT
            contents,
            t_stamp
        FROM
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['images'])."
        WHERE
            filename = '".OX_escapeString($filename)."'
    ");
if (!OA_Dal_Delivery_isValidResult($rCreative)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
} else {
$aResult = OA_Dal_Delivery_fetchAssoc($rCreative);
$aResult['contents'] = OX_unescapeBlob($aResult['contents']);
$aResult['t_stamp'] = strtotime($aResult['t_stamp'] . ' GMT');
return ($aResult);
}
}
function OA_Dal_Delivery_getTracker($trackerid)
{
$conf = $GLOBALS['_MAX']['CONF'];
$trackerid = (int)$trackerid;
$rTracker = OA_Dal_Delivery_query("
        SELECT
            t.clientid AS advertiser_id,
            t.trackerid AS tracker_id,
            t.trackername AS name,
            t.variablemethod AS variablemethod,
            t.description AS description,
            t.viewwindow AS viewwindow,
            t.clickwindow AS clickwindow,
            t.blockwindow AS blockwindow,
            t.appendcode AS appendcode
        FROM
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['trackers'])." AS t
        WHERE
            t.trackerid={$trackerid}
    ");
if (!OA_Dal_Delivery_isValidResult($rTracker)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
} else {
return (OA_Dal_Delivery_fetchAssoc($rTracker));
}
}
function OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid = null)
{
$aConf = $GLOBALS['_MAX']['CONF'];
$trackerid = (int)$trackerid;
$rCreatives = OA_Dal_Delivery_query("
        SELECT
            b.bannerid AS ad_id,
            b.campaignid AS placement_id,
            c.viewwindow AS view_window,
            c.clickwindow AS click_window,
            ct.status AS status,
            t.type AS tracker_type
        FROM
            {$aConf['table']['prefix']}{$aConf['table']['banners']} AS b,
            {$aConf['table']['prefix']}{$aConf['table']['campaigns_trackers']} AS ct,
            {$aConf['table']['prefix']}{$aConf['table']['campaigns']} AS c,
            {$aConf['table']['prefix']}{$aConf['table']['trackers']} AS t
        WHERE
          ct.trackerid=t.trackerid
          AND c.campaignid=b.campaignid
          AND b.campaignid = ct.campaignid
          " . ((!empty($trackerid)) ? ' AND t.trackerid='.$trackerid : '') . "
    ");
if (!OA_Dal_Delivery_isValidResult($rCreatives)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
} else {
$output = array();
while ($aRow = OA_Dal_Delivery_fetchAssoc($rCreatives)) {
$output[$aRow['ad_id']] = $aRow;
}
return $output;
}
}
function OA_Dal_Delivery_getTrackerVariables($trackerid)
{
$conf = $GLOBALS['_MAX']['CONF'];
$trackerid = (int)$trackerid;
$rVariables = OA_Dal_Delivery_query("
        SELECT
            v.variableid AS variable_id,
            v.trackerid AS tracker_id,
            v.name AS name,
            v.datatype AS type,
            purpose AS purpose,
			reject_if_empty AS reject_if_empty,
			is_unique AS is_unique,
			unique_window AS unique_window,
            v.variablecode AS variablecode
        FROM
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['variables'])." AS v
        WHERE
            v.trackerid={$trackerid}
    ");
if (!OA_Dal_Delivery_isValidResult($rVariables)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
} else {
$output = array();
while ($aRow = OA_Dal_Delivery_fetchAssoc($rVariables)) {
$output[$aRow['variable_id']] = $aRow;
}
return $output;
}
}
function OA_Dal_Delivery_getMaintenanceInfo()
{
$conf = $GLOBALS['_MAX']['CONF'];
$result = OA_Dal_Delivery_query("
        SELECT
            value AS maintenance_timestamp
        FROM
            ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['application_variable'])."
        WHERE name = 'maintenance_timestamp'
    ");
if (!OA_Dal_Delivery_isValidResult($result)) {
return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
} else {
$result = OA_Dal_Delivery_fetchAssoc($result);
return $result['maintenance_timestamp'];
}
}
function OA_Dal_Delivery_buildQuery($part, $lastpart, $precondition)
{
$conf = $GLOBALS['_MAX']['CONF'];
$aColumns = array(
'd.bannerid AS ad_id',
'd.campaignid AS placement_id',
'd.status AS status',
'd.description AS name',
'd.storagetype AS type',
'd.contenttype AS contenttype',
'd.pluginversion AS pluginversion',
'd.filename AS filename',
'd.imageurl AS imageurl',
'd.htmltemplate AS htmltemplate',
'd.htmlcache AS htmlcache',
'd.width AS width',
'd.height AS height',
'd.weight AS weight',
'd.seq AS seq',
'd.target AS target',
'd.url AS url',
'd.alt AS alt',
'd.statustext AS statustext',
'd.bannertext AS bannertext',
'd.adserver AS adserver',
'd.block AS block_ad',
'd.capping AS cap_ad',
'd.session_capping AS session_cap_ad',
'd.compiledlimitation AS compiledlimitation',
'd.acl_plugins AS acl_plugins',
'd.prepend AS prepend',
'd.append AS append',
'd.bannertype AS bannertype',
'd.alt_filename AS alt_filename',
'd.alt_imageurl AS alt_imageurl',
'd.alt_contenttype AS alt_contenttype',
'd.parameters AS parameters',
'd.transparent AS transparent',
'd.ext_bannertype AS ext_bannertype',
'd.iframe_friendly AS iframe_friendly',
'az.priority AS priority',
'az.priority_factor AS priority_factor',
'az.to_be_delivered AS to_be_delivered',
'm.campaignid AS campaign_id',
'm.priority AS campaign_priority',
'm.weight AS campaign_weight',
'm.companion AS campaign_companion',
'm.block AS block_campaign',
'm.capping AS cap_campaign',
'm.session_capping AS session_cap_campaign',
'm.show_capped_no_cookie AS show_capped_no_cookie',
'm.clickwindow AS clickwindow',
'm.viewwindow AS viewwindow',
'cl.clientid AS client_id',
'm.expire_time AS expire_time',
'm.revenue_type AS revenue_type',
'm.ecpm_enabled AS ecpm_enabled',
'm.ecpm AS ecpm',
'cl.advertiser_limitation AS advertiser_limitation',
'a.account_id AS account_id',
'a.agencyid AS agency_id'
);
$aTables = array(
"".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d",
"JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (d.campaignid = m.campaignid) ",
"JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (m.clientid = cl.clientid) ",
"JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)"
);
$select = "
      az.zone_id = 0
      AND m.status <= 0
      AND d.status <= 0";
if ($precondition != '')
$select .= " $precondition ";
if ($part != '')
{
$conditions = '';
$onlykeywords = true;
$part_array = explode(',', $part);
for ($k=0; $k < count($part_array); $k++)
{
if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_')
{
$operator = 'AND';
$part_array[$k] = substr($part_array[$k], 1);
}
elseif (substr($part_array[$k], 0, 1) == '-')
{
$operator = 'NOT';
$part_array[$k] = substr($part_array[$k], 1);
}
else
$operator = 'OR';
if($part_array[$k] != '' && $part_array[$k] != ' ')
{
if(preg_match('#^(?:size:)?(\d+)x(\d+)$#', $part_array[$k], $m))
{
$width = (int)$m[1];
$height = (int)$m[2];
if ($operator == 'OR') {
$conditions .= "OR (d.width = {$width} AND d.height = {$height}) ";
} elseif ($operator == 'AND') {
$conditions .= "AND (d.width = {$width} AND d.height = {$height}) ";
} else {
$conditions .= "AND (d.width <> {$width} OR d.height <> {$height}) ";
}
$onlykeywords = false;
}
elseif (preg_match('#^width:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
{
$min = (int)$m[1];
$range = !empty($m[2]);
$max = (int)$m[3];
if (!$range && $min) {
if ($operator == 'OR') {
$conditions .= "OR d.width = {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.width = {$min} ";
} else {
$conditions .= "AND d.width <> {$min} ";
}
} else {
if (!$min) {
$min = 1;
}
if (!$max)
{
if ($operator == 'OR') {
$conditions .= "OR d.width >= {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.width >= {$min} ";
} else {
$conditions .= "AND d.width < {$min} ";
}
} else {
if ($operator == 'OR') {
$conditions .= "OR (d.width >= {$min} AND d.width <= {$max}) ";
} elseif ($operator == 'AND') {
$conditions .= "AND (d.width >= {$min} AND d.width <= {$max}) ";
} else {
$conditions .= "AND (d.width < {$min} OR d.width > {$max}) ";
}
}
}
$onlykeywords = false;
}
elseif (preg_match('#^height:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
{
$min = (int)$m[1];
$range = !empty($m[2]);
$max = (int)$m[3];
if (!$range && $min) {
if ($operator == 'OR') {
$conditions .= "OR d.height = {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.height = {$min} ";
} else {
$conditions .= "AND d.height <> {$min} ";
}
} else {
if (!$min) {
$min = 1;
}
if (!$max)
{
if ($operator == 'OR') {
$conditions .= "OR d.height >= {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.height >= {$min} ";
} else {
$conditions .= "AND d.height < {$min} ";
}
} else {
if ($operator == 'OR') {
$conditions .= "OR (d.height >= {$min} AND d.height <= {$max}) ";
} elseif ($operator == 'AND') {
$conditions .= "AND (d.height >= {$min} AND d.height <= {$max}) ";
} else {
$conditions .= "AND (d.height < {$min} OR d.height > {$max}) ";
}
}
}
$onlykeywords = false;
}
elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?(\d+)$#', $part_array[$k], $m))
{
$bannerid = (int)$m[1];
if ($bannerid)
{
if ($operator == 'OR') {
$conditions .= "OR d.bannerid = {$bannerid} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.bannerid = {$bannerid} ";
} else {
$conditions .= "AND d.bannerid <> {$bannerid} ";
}
}
$onlykeywords = false;
}
elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?(\d+)$#', $part_array[$k], $m))
{
$campaignid = (int)$m[1];
if ($campaignid)
{
if ($operator == 'OR') {
$conditions .= "OR d.campaignid = {$campaignid} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.campaignid = {$campaignid} ";
} else {
$conditions .= "AND d.campaignid <> {$campaignid} ";
}
}
$onlykeywords = false;
}
elseif (substr($part_array[$k], 0, 7) == 'format:')
{
$format = OX_escapeString(trim(stripslashes(substr($part_array[$k], 7))));
if (!empty($format))
{
if ($operator == 'OR') {
$conditions .= "OR d.contenttype = '{$format}' ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.contenttype = '{$format}' ";
} else {
$conditions .= "AND d.contenttype <> '{$format}' ";
}
}
$onlykeywords = false;
}
elseif ($part_array[$k] == 'html')
{
if ($operator == 'OR') {
$conditions .= "OR d.storagetype = 'html' ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.storagetype = 'html' ";
} else {
$conditions .= "AND d.storagetype <> 'html' ";
}
$onlykeywords = false;
}
elseif ($part_array[$k] == 'textad')
{
if ($operator == 'OR') {
$conditions .= "OR d.storagetype = 'txt' ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.storagetype = 'txt' ";
} else {
$conditions .= "AND d.storagetype <> 'txt' ";
}
$onlykeywords = false;
}
else
{
$conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]);
}
}
}
$conditions = strstr($conditions, ' ');
if ($lastpart == true && $onlykeywords == true)
$conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global');
if ($conditions != '') $select .= ' AND ('.$conditions.') ';
}
$columns = implode(",\n    ", $aColumns);
$tables = implode("\n    ", $aTables);
$leftJoin = "
            LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS c ON (c.clientid = m.clientid)
            LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = c.agencyid)
    ";
$query = "SELECT\n    " . $columns . "\nFROM\n    " . $tables . $leftJoin . "\nWHERE " . $select;
return $query;
}
function OA_Dal_Delivery_buildAdInfoQuery($part, $lastpart, $precondition)
{
$conf = $GLOBALS['_MAX']['CONF'];
$aColumns = array(
'd.bannerid AS ad_id',
'd.campaignid AS placement_id',
'd.status AS status',
'd.storagetype AS type',
'd.contenttype AS contenttype',
'd.weight AS weight',
'd.width AS width',
'd.ext_bannertype AS ext_bannertype',
'd.height AS height',
'd.adserver AS adserver',
'd.block AS block_ad',
'd.capping AS cap_ad',
'd.session_capping AS session_cap_ad',
'd.compiledlimitation AS compiledlimitation',
'd.acl_plugins AS acl_plugins',
'd.alt_filename AS alt_filename',
'az.priority AS priority',
'az.priority_factor AS priority_factor',
'az.to_be_delivered AS to_be_delivered',
'm.campaignid AS campaign_id',
'm.priority AS campaign_priority',
'm.weight AS campaign_weight',
'm.companion AS campaign_companion',
'm.block AS block_campaign',
'm.capping AS cap_campaign',
'm.session_capping AS session_cap_campaign',
'm.show_capped_no_cookie AS show_capped_no_cookie',
'cl.clientid AS client_id',
'm.expire_time AS expire_time',
'm.revenue_type AS revenue_type',
'm.ecpm_enabled AS ecpm_enabled',
'm.ecpm AS ecpm',
'ct.status AS tracker_status',
OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe",
OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe",
);
$aTables = array(
"".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d",
"JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)",
"JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (m.campaignid = d.campaignid) ",
);
$select = "
      az.zone_id = 0
      AND m.status <= 0
      AND d.status <= 0";
if ($precondition != '')
$select .= " $precondition ";
if ($part != '')
{
$conditions = '';
$onlykeywords = true;
$part_array = explode(',', $part);
for ($k=0; $k < count($part_array); $k++)
{
if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_')
{
$operator = 'AND';
$part_array[$k] = substr($part_array[$k], 1);
}
elseif (substr($part_array[$k], 0, 1) == '-')
{
$operator = 'NOT';
$part_array[$k] = substr($part_array[$k], 1);
}
else
$operator = 'OR';
if($part_array[$k] != '' && $part_array[$k] != ' ')
{
if(preg_match('#^(?:size:)?(\d+)x(\d+)$#', $part_array[$k], $m))
{
$width = (int)$m[1];
$height = (int)$m[2];
if ($operator == 'OR') {
$conditions .= "OR (d.width = {$width} AND d.height = {$height}) ";
} elseif ($operator == 'AND') {
$conditions .= "AND (d.width = {$width} AND d.height = {$height}) ";
} else {
$conditions .= "AND (d.width <> {$width} OR d.height <> {$height}) ";
}
$onlykeywords = false;
}
elseif (preg_match('#^width:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
{
$min = (int)$m[1];
$range = !empty($m[2]);
$max = (int)$m[3];
if (!$range && $min) {
if ($operator == 'OR') {
$conditions .= "OR d.width = {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.width = {$min} ";
} else {
$conditions .= "AND d.width <> {$min} ";
}
} else {
if (!$min) {
$min = 1;
}
if (!$max)
{
if ($operator == 'OR') {
$conditions .= "OR d.width >= {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.width >= {$min} ";
} else {
$conditions .= "AND d.width < {$min} ";
}
} else {
if ($operator == 'OR') {
$conditions .= "OR (d.width >= {$min} AND d.width <= {$max}) ";
} elseif ($operator == 'AND') {
$conditions .= "AND (d.width >= {$min} AND d.width <= {$max}) ";
} else {
$conditions .= "AND (d.width < {$min} OR d.width > {$max}) ";
}
}
}
$onlykeywords = false;
}
elseif (preg_match('#^height:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
{
$min = (int)$m[1];
$range = !empty($m[2]);
$max = (int)$m[3];
if (!$range && $min) {
if ($operator == 'OR') {
$conditions .= "OR d.height = {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.height = {$min} ";
} else {
$conditions .= "AND d.height <> {$min} ";
}
} else {
if (!$min) {
$min = 1;
}
if (!$max)
{
if ($operator == 'OR') {
$conditions .= "OR d.height >= {$min} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.height >= {$min} ";
} else {
$conditions .= "AND d.height < {$min} ";
}
} else {
if ($operator == 'OR') {
$conditions .= "OR (d.height >= {$min} AND d.height <= {$max}) ";
} elseif ($operator == 'AND') {
$conditions .= "AND (d.height >= {$min} AND d.height <= {$max}) ";
} else {
$conditions .= "AND (d.height < {$min} OR d.height > {$max}) ";
}
}
}
$onlykeywords = false;
}
elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?(\d+)$#', $part_array[$k], $m))
{
$bannerid = (int)$m[1];
if ($bannerid)
{
if ($operator == 'OR') {
$conditions .= "OR d.bannerid = {$bannerid} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.bannerid = {$bannerid} ";
} else {
$conditions .= "AND d.bannerid <> {$bannerid} ";
}
}
$onlykeywords = false;
}
elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?(\d+)$#', $part_array[$k], $m))
{
$campaignid = (int)$m[1];
if ($campaignid)
{
if ($operator == 'OR') {
$conditions .= "OR d.campaignid = {$campaignid} ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.campaignid = {$campaignid} ";
} else {
$conditions .= "AND d.campaignid <> {$campaignid} ";
}
}
$onlykeywords = false;
}
elseif (substr($part_array[$k], 0, 7) == 'format:')
{
$format = OX_escapeString(trim(stripslashes(substr($part_array[$k], 7))));
if (!empty($format))
{
if ($operator == 'OR') {
$conditions .= "OR d.contenttype = '{$format}' ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.contenttype = '{$format}' ";
} else {
$conditions .= "AND d.contenttype <> '{$format}' ";
}
}
$onlykeywords = false;
}
elseif ($part_array[$k] == 'html')
{
if ($operator == 'OR') {
$conditions .= "OR d.storagetype = 'html' ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.storagetype = 'html' ";
} else {
$conditions .= "AND d.storagetype <> 'html' ";
}
$onlykeywords = false;
}
elseif ($part_array[$k] == 'textad')
{
if ($operator == 'OR') {
$conditions .= "OR d.storagetype = 'txt' ";
} elseif ($operator == 'AND') {
$conditions .= "AND d.storagetype = 'txt' ";
} else {
$conditions .= "AND d.storagetype <> 'txt' ";
}
$onlykeywords = false;
}
else
{
$conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]);
}
}
}
$conditions = strstr($conditions, ' ');
if ($lastpart == true && $onlykeywords == true)
$conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global');
if ($conditions != '') $select .= ' AND ('.$conditions.') ';
}
$columns = implode(",\n    ", $aColumns);
$tables = implode("\n    ", $aTables);
$leftJoin = "
            LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = m.campaignid)
            LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (cl.clientid = m.clientid)
            LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = cl.agencyid)
    ";
$query = "SELECT\n    " . $columns . "\nFROM\n    " . $tables . $leftJoin . "\nWHERE " . $select;
return $query;
}
function _setPriorityFromWeights(&$aAds)
{
if (!count($aAds)) {
return 0;
}
$aCampaignWeights = array();
$aCampaignAdWeight = array();
foreach ($aAds as $v) {
if (!isset($aCampaignWeights[$v['placement_id']])) {
$aCampaignWeights[$v['placement_id']] = $v['campaign_weight'];
$aCampaignAdWeight[$v['placement_id']] = 0;
}
$aCampaignAdWeight[$v['placement_id']] += $v['weight'];
}
foreach ($aCampaignWeights as $k => $v) {
if ($aCampaignAdWeight[$k]) {
$aCampaignWeights[$k] /= $aCampaignAdWeight[$k];
}
}
$totalPri = 0;
foreach ($aAds as $k => $v) {
$aAds[$k]['priority'] = $aCampaignWeights[$v['placement_id']] * $v['weight'];
$totalPri += $aAds[$k]['priority'];
}
if ($totalPri) {
foreach ($aAds as $k => $v) {
$aAds[$k]['priority'] /= $totalPri;
}
return 1;
}
return 0;
}
function _getTotalPrioritiesByCP($aAdsByCP, $includeBlank = true)
{
$totals = array();
$total_priority_cp = array();
$blank_priority = 1;
foreach ($aAdsByCP as $campaign_priority => $aAds) {
$total_priority_cp[$campaign_priority] = 0;
foreach ($aAds as $key => $aAd) {
$blank_priority -= (double)$aAd['priority'];
if ($aAd['to_be_delivered']) {
$priority = $aAd['priority'] * $aAd['priority_factor'];
} else {
$priority = 0.00001;
}
$total_priority_cp[$campaign_priority] += $priority;
}
}
$total_priority = 0;
if ($includeBlank) {
$total_priority = $blank_priority <= 1e-15 ? 0 : $blank_priority;
}
ksort($total_priority_cp);
foreach($total_priority_cp as $campaign_priority => $priority) {
$total_priority += $priority;
if ($total_priority) {
$totals[$campaign_priority] = $priority / $total_priority;
} else {
$totals[$campaign_priority] = 0;
}
}
return $totals;
}

function MAX_Dal_Delivery_Include()
{
static $included;
if (isset($included)) {
return;
}
$included = true;
$conf = $GLOBALS['_MAX']['CONF'];
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 {
$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)) {
foreach ($conversionInfo as $plugin => $pluginData) {
$conversionInfoParams = array();
if (is_array($pluginData)) {
foreach ($pluginData as $key => $value) {
$conversionInfoParams[] = $key . '=' . urlencode($value);
}
}
$conversionInfoParams = '&' . implode('&', $conversionInfoParams);
$buffer .= "
    document.write (\"<\" + \"script language='JavaScript' type='text/javascript' src='\");
    document.write (\"$url?trackerid=$trackerid&plugin={$plugin}{$conversionInfoParams}{$variableQuerystring}'\");";
$buffer .= "\n\tdocument.write (\"><\\/scr\"+\"ipt>\");";
}
}
}
if(!empty($tracker['appendcode'])) {
$tracker['appendcode'] = preg_replace('/("\?trackerid=\d+&amp;inherit)=1/', '$1='.$trackerJsCode, $tracker['appendcode']);
$jscode = MAX_javascriptToHTML($tracker['appendcode'], "MAX_{$trackerid}_appendcode");
$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)
{
$aTrackerLinkedAds = MAX_cacheGetTrackerLinkedCreatives($trackerid);
if (empty($aTrackerLinkedAds)) {
return false;
}
$aPossibleActions = _getActionTypes();
$now = MAX_commonGetTimeNow();
$aConf = $GLOBALS['_MAX']['CONF'];
$aMatchingActions = array();
foreach ($aTrackerLinkedAds as $creativeId => $aLinkedInfo) {
foreach ($aPossibleActions as $actionId => $action) {
if (!empty($aLinkedInfo[$action . '_window']) && !empty($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId])) {
if (stristr($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], ' ')) {
list($value, $extra) = explode(' ', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], 2);
$_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId] = $value;
} else {
$extra = '';
}
list($lastAction, $zoneId) = explode('-', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId]);
$lastAction = MAX_commonUnCompressInt($lastAction);
$lastSeenSecondsAgo = $now - $lastAction;
if ($lastSeenSecondsAgo <= $aLinkedInfo[$action . '_window'] && $lastSeenSecondsAgo > 0) {
$aMatchingActions[$lastSeenSecondsAgo] = array(
'action_type' => $actionId,
'tracker_type' => $aLinkedInfo['tracker_type'],
'status' => $aLinkedInfo['status'],
'cid' => $creativeId,
'zid' => $zoneId,
'dt' => $lastAction,
'window' => $aLinkedInfo[$action . '_window'],
'extra' => $extra,
);
}
}
}
}
if (empty($aMatchingActions)) {
return false;
}
ksort($aMatchingActions);
return array_shift($aMatchingActions);
}
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, $aAd = array())
{
if (empty($GLOBALS['_MAX']['CONF']['logging']['adRequests'])) { return true; }
OX_Delivery_Common_hook('logRequest', array($adId, $zoneId, $aAd, _viewersHostOkayToLog($adId, $zoneId)));
}
function MAX_Delivery_log_logAdImpression($adId, $zoneId)
{
if (empty($GLOBALS['_MAX']['CONF']['logging']['adImpressions'])) { return true; }
if (MAX_commonIsAdActionBlockedBecauseInactive($adId)) {
return true;
}
OX_Delivery_Common_hook('logImpression', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId)));
}
function MAX_Delivery_log_logAdClick($adId, $zoneId)
{
if (empty($GLOBALS['_MAX']['CONF']['logging']['adClicks'])) { return true; }
OX_Delivery_Common_hook('logClick', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId)));
}
function MAX_Delivery_log_logConversion($trackerId, $aConversion)
{
if (empty($GLOBALS['_MAX']['CONF']['logging']['trackerImpressions'])) { return true; }
$aConf = $GLOBALS['_MAX']['CONF'];
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'];
}
$aConversionInfo = OX_Delivery_Common_hook('logConversion', array($trackerId, $serverRawIp, $aConversion, _viewersHostOkayToLog(null, null, $trackerId)));
if (is_array($aConversionInfo)) {
return $aConversionInfo;
}
return false;
}
function MAX_Delivery_log_logVariableValues($aVariables, $trackerId, $serverConvId, $serverRawIp, $pluginId = null)
{
$aConf = $GLOBALS['_MAX']['CONF'];
foreach ($aVariables as $aVariable) {
if (isset($_GET[$aVariable['name']])) {
$value = $_GET[$aVariable['name']];
if (!strlen($value) || $value == 'undefined') {
unset($aVariables[$aVariable['variable_id']]);
continue;
}
switch ($aVariable['type']) {
case 'int':
case 'numeric':
$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 {
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, _viewersHostOkayToLog(null, null, $trackerId)),
empty($pluginId) ? null : $pluginId.'Variable'
);
}
}
function _viewersHostOkayToLog($adId=0, $zoneId=0, $trackerId=0)
{
$aConf = $GLOBALS['_MAX']['CONF'];
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$okToLog = true;
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;
}
}
OX_Delivery_logMessage('user-agent browser : '.$agent.' is '.($allowed ? '' : 'not ').'allowed', 7);
if (!$allowed) {
$GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'enforceUserAgents';
$okToLog = false;
}
}
if (!empty($aConf['logging']['ignoreUserAgents'])) {
$aKnownBots = explode('|', strtolower($aConf['logging']['ignoreUserAgents']));
foreach ($aKnownBots as $bot) {
if (strpos($agent, $bot) !== false) {
OX_Delivery_logMessage('user-agent '.$agent.' is a known bot '.$bot, 7);
$GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreUserAgents';
$okToLog = false;
}
}
}
if (!empty($aConf['logging']['ignoreHosts'])) {
$hosts = str_replace(',', '|', $aConf['logging']['ignoreHosts']);
$hosts = '#^('.$hosts.')$#i';
$hosts = str_replace('.', '\.', $hosts);
$hosts = str_replace('*', '[^.]+', $hosts);
if (preg_match($hosts, $_SERVER['REMOTE_ADDR'])) {
OX_Delivery_logMessage('viewer\'s ip is in the ignore list '.$_SERVER['REMOTE_ADDR'], 7);
$GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_ip';
$okToLog = false;
}
if (preg_match($hosts, $_SERVER['REMOTE_HOST'])) {
OX_Delivery_logMessage('viewer\'s host is in the ignore list '.$_SERVER['REMOTE_HOST'], 7);
$GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_host';
$okToLog = false;
}
}
if ($okToLog) OX_Delivery_logMessage('viewer\'s host is OK to log', 7);
$result = OX_Delivery_Common_Hook('filterEvent', array($adId, $zoneId, $trackerId));
if (!empty($result) && is_array($result)) {
foreach ($result as $pci => $value) {
if ($value == true) {
$GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = $pci;
$okToLog = false;
}
}
}
return $okToLog;
}
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])) {
$cookieData = MAX_commonCompressInt(MAX_commonGetTimeNow()) . "-" . $aZoneIds[$index];
$conversionParams = OX_Delivery_Common_hook('addConversionParams', array(&$index, &$aAdIds, &$aZoneIds, &$aSetLastSeen, &$action, &$cookieData));
if (!empty($conversionParams) && is_array($conversionParams)) {
foreach ($conversionParams as $params) {
if (!empty($params) && is_array($params)) {
foreach ($params as $key => $value) {
$cookieData .= " {$value}";
}
}
}
}
MAX_cookieAdd("_{$aConf['var']['last' . ucfirst($action)]}[{$aAdIds[$index]}]", $cookieData, _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()) {
OX_Delivery_logMessage('adID '.$adId.' click is still blocked by block logging window ', 7);
return true;
}
}
}
return false;
}
function _setLimitations($type, $index, $aItems, $aCaps)
{
MAX_Delivery_log_ensureIntegerSet($aCaps['block'], $index);
MAX_Delivery_log_ensureIntegerSet($aCaps['capping'], $index);
MAX_Delivery_log_ensureIntegerSet($aCaps['session_capping'], $index);
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 ($GLOBALS['_MAX']['SSL_REQUEST']) {
$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) {
$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) {
if (($toEncoding == $fromEncoding) || empty($toEncoding)) {
return $content;
}
if (!isset($aExtensions) || !is_array($aExtensions)) {
$aExtensions = array('iconv', 'mbstring', 'xml');
}
if (is_array($content)) {
foreach ($content as $key => $value) {
$content[$key] = MAX_commonConvertEncoding($value, $toEncoding, $fromEncoding, $aExtensions);
}
return $content;
} else {
$toEncoding = strtoupper($toEncoding);
$fromEncoding = strtoupper($fromEncoding);
$aMap = array();
$aMap['mbstring']['WINDOWS-1255'] = 'ISO-8859-8';  $aMap['xml']['ISO-8859-15'] = 'ISO-8859-1';   $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')) {
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) && preg_match('/^[a-zA-Z0-9_-]+$/D', $charset)) {
$header .= '; charset=' . $charset;
}
MAX_header($header);
}
function MAX_commonSetNoCacheHeaders()
{
MAX_header('Pragma: no-cache');
MAX_header('Cache-Control: no-cache, no-store, must-revalidate');
MAX_header('Expires: 0');
MAX_header('Access-Control-Allow-Origin: *');
}
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 : '' );
$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;
}
}
if (!isset($clientid)) $clientid = '';
if (empty($campaignid)) $campaignid = $clientid;
$source = MAX_commonDeriveSource($source);
if (!empty($loc)) {
$loc = stripslashes($loc);
} elseif (!empty($_SERVER['HTTP_REFERER'])) {
$loc = $_SERVER['HTTP_REFERER'];
} else {
$loc = '';
}
if (!empty($referer)) {
$_SERVER['HTTP_REFERER'] = stripslashes($referer);
} else {
if (isset($_SERVER['HTTP_REFERER'])) unset($_SERVER['HTTP_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'],
);
if (strtolower($charset) == 'unicode') { $charset = 'utf-8'; }
}
function MAX_commonIsAdActionBlockedBecauseInactive($adId)
{
if (!empty($GLOBALS['_MAX']['CONF']['logging']['blockInactiveBanners'])) {
$aAdInfo = MAX_cacheGetAd($adId);
return $aAdInfo['status'] || $aAdInfo['campaign_status'];
}
return false;
}
function MAX_commonDisplay1x1()
{
MAX_header('Content-Type: image/gif');
echo "GIF89a\001\0\001\0\200\0\0\377\377\377\0\0\0!\371\004\0\0\0\0\0,\0\0\0\0\001\0\001\0\0\002\002D\001\0;";
}
function MAX_commonGetTimeNow()
{
if (!isset($GLOBALS['_MAX']['NOW'])) {
$GLOBALS['_MAX']['NOW'] = time();
}
return $GLOBALS['_MAX']['NOW'];
}
function MAX_getRandomNumber($length = 10)
{
return substr(md5(uniqid(time(), true)), 0, $length);
}
function MAX_header($value)
{
 header($value);
}
function MAX_redirect($url)
{
if (!preg_match('/^(?:javascript|data):/i', $url)) {
$host = @parse_url($url, PHP_URL_HOST);
if (function_exists('idn_to_ascii')) {
$idn = idn_to_ascii($host);
if ($host != $idn) {
$url = preg_replace('#^(.*?://)'.preg_quote($host, '#').'#', '$1'.$idn, $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];
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())
{
$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] = true; break;
case '==': $include[$value] = true; break;
}
}
$exclude = array_keys($exclude);
$include = array_keys($include);
return base64_encode(implode('#', $exclude) . '|' . implode('#', $include));
}
function MAX_commonUnpackContext($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;
if (!empty($functionName)) {
$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 {
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)) {
OX_Delivery_logMessage('calling on '.$functionName, 7);
$return[$identifier] = call_user_func_array($functionName, $aParams);
}
}
}
}
return $return;
}
function OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hook = null)
{
if (preg_match('/[^a-zA-Z0-9:]/', $identifier)) {
if (PHP_SAPI === 'cli') {
exit(1);
} else {
MAX_sendStatusCode(400);
exit;
}
}
$aInfo = explode(':', $identifier);
$functionName = 'Plugin_' . implode('_', $aInfo) . '_Delivery' . (!empty($hook) ? '_' . $hook : '');
if (!function_exists($functionName)) {
if (!empty($GLOBALS['_MAX']['CONF']['pluginSettings']['useMergedFunctions'])) _includeDeliveryPluginFile('/var/cache/' . OX_getHostName() . '_mergedDeliveryFunctions.php');
if (!function_exists($functionName)) {
_includeDeliveryPluginFile($GLOBALS['_MAX']['CONF']['pluginPaths']['plugins'] . '/' . implode('/', $aInfo) . '.delivery.php');
if (!function_exists($functionName)) {
_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;
}
}
}
function OX_Delivery_logMessage($message, $priority = 6)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (empty($conf['deliveryLog']['enabled'])) return true;
$priorityLevel = is_numeric($conf['deliveryLog']['priority']) ? $conf['deliveryLog']['priority'] : 6;
if ($priority > $priorityLevel && empty($_REQUEST[$conf['var']['trace']])) { return true; }
error_log('[' . date('r') . "] {$conf['log']['ident']}-delivery-{$GLOBALS['_MAX']['thread_id']}: {$message}\n", 3, MAX_PATH . '/var/' . $conf['deliveryLog']['name']);
OX_Delivery_Common_hook('logMessage', array($message, $priority));
return true;
}


$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' => OX_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) {
OX_Delivery_logMessage("Cache ERROR: {$name} != {$aCacheVar['cache_name']}", 7);
return false;
}
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) )
{
OA_Delivery_Cache_store($name, $aCacheVar['cache_contents'], $isHash);
OX_Delivery_logMessage("Cache EXPIRED: {$name}", 7);
return false;
}
OX_Delivery_logMessage("Cache HIT: {$name}", 7);
return $aCacheVar['cache_contents'];
}
OX_Delivery_logMessage("Cache MISS {$name}", 7);
return false;
}
function OA_Delivery_Cache_store($name, $cache, $isHash = false, $expireAt = null)
{
if ($cache === OA_DELIVERY_CACHE_FUNCTION_ERROR) {
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 ($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) {
$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_cacheGetZoneLinkedAdInfos($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_getZoneLinkedAdInfos($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_cacheGetLinkedAdInfos($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_getLinkedAdInfos($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);
}
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)
{
$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;
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();
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 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;
}

OX_Delivery_logMessage('starting delivery script: ' . basename($_SERVER['REQUEST_URI']), 7);
if (!empty($_REQUEST[$conf['var']['trace']])) {
OX_Delivery_logMessage('trace enabled: ' . $_REQUEST[$conf['var']['trace']], 7);
}
MAX_remotehostSetInfo();
MAX_commonInitVariables();
MAX_cookieLoad();
MAX_cookieUnpackCapping();
if (empty($GLOBALS['_OA']['invocationType']) || $GLOBALS['_OA']['invocationType'] != 'xmlrpc') {
OX_Delivery_Common_hook('postInit');
}

setupIncludePath();

require_once RV_PATH . '/lib/RV.php';






require_once OX_PATH . '/lib/pear/PEAR.php';

class MAX
{
public static function errorConstantToString($errorCode)
{
$aErrorCodes = array(
MAX_ERROR_INVALIDARGS => 'invalid arguments',
MAX_ERROR_INVALIDCONFIG => 'invalid config',
MAX_ERROR_NODATA => 'no data',
MAX_ERROR_NOCLASS => 'no class',
MAX_ERROR_NOMETHOD => 'no method',
MAX_ERROR_NOAFFECTEDROWS => 'no affected rows',
MAX_ERROR_NOTSUPPORTED => 'not supported',
MAX_ERROR_INVALIDCALL => 'invalid call',
MAX_ERROR_INVALIDAUTH => 'invalid auth',
MAX_ERROR_EMAILFAILURE => 'email failure',
MAX_ERROR_DBFAILURE => 'db failure',
MAX_ERROR_DBTRANSACTIONFAILURE => 'db transaction failure',
MAX_ERROR_BANNEDUSER => 'banned user',
MAX_ERROR_NOFILE => 'no file',
MAX_ERROR_INVALIDFILEPERMS => 'invalid file perms',
MAX_ERROR_INVALIDSESSION => 'invalid session',
MAX_ERROR_INVALIDPOST => 'invalid post',
MAX_ERROR_INVALIDTRANSLATION => 'invalid translation',
MAX_ERROR_FILEUNWRITABLE => 'file unwritable',
MAX_ERROR_INVALIDREQUEST => 'invalid request',
MAX_ERROR_INVALIDTYPE => 'invalid type',
);
if (in_array($errorCode, array_keys($aErrorCodes))) {
return strtoupper($aErrorCodes[$errorCode]);
} else {
return 'PEAR';
}
}
public static function errorObjToString($oError, $additionalInfo = null)
{
$aConf = $GLOBALS['_MAX']['CONF'];
$message = htmlspecialchars($oError->getMessage());
$debugInfo = htmlspecialchars($oError->getDebugInfo());
$additionalInfo = htmlspecialchars($additionalInfo);
$level = $oError->getCode();
$errorType = MAX::errorConstantToString($level);
$img = MAX::constructURL(MAX_URL_IMAGE, 'errormessage.gif');
$output = <<<EOF
<br />
<div class="errormessage">
    <img class="errormessage" src="$img" align="absmiddle">
    <span class='tab-r'>$errorType Error</span>
    <br />
    <br />$message
    <br /><pre>$debugInfo</pre>
    $additionalInfo
</div>
<br />
<br />
EOF;
return $output;
}
public static function raiseError($message, $type = null, $behaviour = null)
{
if ($behaviour == PEAR_ERROR_DIE) {
$errorType = MAX::errorConstantToString($type);
if (!is_string($message)) $message = print_r($message, true);
OA::debug($type . ' :: ' . $message, PEAR_LOG_EMERG);
exit();
}
$error = PEAR::raiseError($message, $type, $behaviour);
return $error;
}
public static function constructURL($type, $file = null)
{
$aConf = $GLOBALS['_MAX']['CONF'];
if ($type == MAX_URL_ADMIN) {
$path = $aConf['webpath']['admin'];
} elseif ($type == MAX_URL_IMAGE) {
return OX::assetPath("/images/" . $file);
} else {
return null;
}
$path .= '/';
if ($aConf['openads']['sslPort'] != 443) {
if ($GLOBALS['_MAX']['HTTP'] == 'https://') {
$path = preg_replace('#/#', ':' . $aConf['openads']['sslPort'] . '/', $path, 1);
}
}
return $GLOBALS['_MAX']['HTTP'] . $path . $file;
}
}
function pearErrorHandler($oError)
{
$aConf = $GLOBALS['_MAX']['CONF'];
$message = $oError->getMessage();
$debugInfo = $oError->getDebugInfo();
OA::debug('PEAR' . " :: $message : $debugInfo", PEAR_LOG_ERR);
$msg = '';
if (empty($aConf['debug']['production'])) {
$GLOBALS['_MAX']['ERRORS'][] = $oError;
}
if (!empty($aConf['debug']['showBacktrace'])) {
$msg .= 'PEAR backtrace: <div onClick="if (this.style.height) {this.style.height = null;this.style.width = null;} else {this.style.height = \'8px\'; this.style.width=\'8px\'}"';
$msg .= 'style="float:left; cursor: pointer; border: 1px dashed #FF0000; background-color: #EFEFEF; height: 8px; width: 8px; overflow: hidden; margin-bottom: 2px;">';
$msg .= '<pre wrap style="margin: 5px; background-color: #EFEFEF">';
ob_start();
print_r($oError->getBacktrace());
$msg .= ob_get_clean();
$msg .= '<hr></pre></div>';
$msg .= '<div style="clear:both"></div>';
}
if (defined('TEST_ENVIRONMENT_RUNNING')) {
echo nl2br("Message: $message\ndebugInfo: $debugInfo\nbackTrace: $msg");
exit(1);
} elseif (defined('OA_WEBSERVICES_API_XMLRPC')) {
$oResponse = new XML_RPC_Response('', 99999, $message);
echo $oResponse->serialize();
exit;
} else {
echo MAX::errorObjToString($oError, $msg);
}
}
$oPEAR = new PEAR();
$oPEAR->setErrorHandling(PEAR_ERROR_CALLBACK, 'pearErrorHandler');
$clientCache = array();
$campaignCache = array();
$bannerCache = array();
$zoneCache = array();
$affiliateCache = array();



function MAX_limitationsCheckAcl($row, $source = '')
{
if (!empty($row['compiledlimitation'])) {
if (!isset($GLOBALS['_MAX']['FILES']['aIncludedPlugins'])) {
$GLOBALS['_MAX']['FILES']['aIncludedPlugins'] = array();
}
$result = true;
$aConf = $GLOBALS['_MAX']['CONF'];
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']['plugins'] . "{$extension}/{$package}/{$name}.delivery.php";
if (!isset($GLOBALS['_MAX']['FILES']['aIncludedPlugins'][$pluginName])) {
if (include($pluginName)) {
$GLOBALS['_MAX']['FILES']['aIncludedPlugins'][$pluginName] = true;
} else {
return true;
}
}
}
}
@eval('$result = (' . $row['compiledlimitation'] . ');');
return $result;
} else {
return true;
}
}
function MAX_limitationsIsAdForbidden($aAd)
{
$adId = $aAd['ad_id'];
$campaignId = $aAd['placement_id'];
$showCappedNoCookie = (bool)$aAd['show_capped_no_cookie'];
return (_limitationsIsAdCapped($adId, $aAd['cap_ad'], $aAd['session_cap_ad'], $aAd['block_ad'], $showCappedNoCookie) ||
_limitationsIsCampaignCapped($campaignId, $aAd['cap_campaign'], $aAd['session_cap_campaign'], $aAd['block_campaign'], $showCappedNoCookie));
}
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;
$showCappedNoCookie = !empty($aCapping['show_capped_no_cookie_zone']);
return (_limitationsIsZoneCapped($zoneId, $capZone, $sessionCapZone, $blockZone, $showCappedNoCookie));
}
function _limitationsIsAdCapped($adId, $cap, $sessionCap = 0, $block, $showCappedNoCookie)
{
return _limitationsIsCapped('Ad', $adId, $cap, $sessionCap, $block, $showCappedNoCookie);
}
function _limitationsIsCampaignCapped($campaignId, $cap, $sessionCap = 0, $block, $showCappedNoCookie)
{
return _limitationsIsCapped('Campaign', $campaignId, $cap, $sessionCap, $block, $showCappedNoCookie);
}
function _limitationsIsZoneCapped($zoneId, $cap, $sessionCap = 0, $block, $showCappedNoCookie)
{
return _limitationsIsCapped('Zone', $zoneId, $cap, $sessionCap, $block, $showCappedNoCookie);
}
function _limitationsIsCapped($type, $id, $cap, $sessionCap, $block, $showCappedNoCookie)
{
if (_areCookiesDisabled((($cap > 0) || ($sessionCap > 0) || ($block > 0)) && !$showCappedNoCookie)) {
return true;
}
$conf = $GLOBALS['_MAX']['CONF'];
$cookieName = $conf['var']['cap' . $type];
if (isset($_COOKIE[$cookieName][$id])) {
$totalImpressions = $_COOKIE[$cookieName][$id];
}
$cookieName = $conf['var']['sessionCap' . $type];
if (isset($_COOKIE[$cookieName][$id])) {
$sessionImpressions = $_COOKIE[$cookieName][$id];
}
$cookieName = $conf['var']['block' . $type];
if (isset($_COOKIE[$cookieName][$id])) {
$lastSeen = $_COOKIE[$cookieName][$id];
}
if ((($cap > 0) && isset($totalImpressions) && ($totalImpressions >= $cap)) ||
(($sessionCap > 0) && isset($sessionImpressions) && ($sessionImpressions >= $sessionCap))) {
if ($block > 0 && MAX_commonGetTimeNow() > $lastSeen + $block) {
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)
{
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'];
if (empty($target)) {
$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
}
$target = htmlspecialchars($target, ENT_QUOTES);
$source = htmlspecialchars($source, ENT_QUOTES);
$aBanner['bannerContent'] = "";
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);
list($usec, $sec) = explode(' ', microtime());
$time = (float)$usec + (float)$sec;
$random = MAX_getRandomNumber();
global $cookie_random;  $cookie_random = $random;
$clickUrl = _adRenderBuildClickUrl($aBanner, $zoneId, $source, $ct0, $logClick, true);
$urlPrefix = rtrim(MAX_commonGetDeliveryUrl(), '/');
$imgUrlPrefix = rtrim(_adRenderBuildImageUrlPrefix(), '/');
$code = str_replace('{clickurl}', $clickUrl, $code); 
if (strpos($code, '{logurl}') !== false) {
$logUrl = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&');
$code = str_replace('{logurl}', $logUrl, $code);  }
if (strpos($code, '{logurl_enc}') !== false) {
$logUrl_enc = urlencode(_adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&'));
$code = str_replace('{logurl_enc}', $logUrl_enc, $code);  }
if (strpos($code, '{imgurl}') !== false) {
$imgUrl = _adRenderBuildImageUrlPrefix();
$code = str_replace('{imgurl}', $imgUrl, $code);  }
if (strpos($code, '{imgurl_enc}') !== false) {
$imgUrl_enc = urlencode(_adRenderBuildImageUrlPrefix());
$code = str_replace('{imgurl_enc}', $logUrl, $code);  }
if (strpos($code, '{clickurlparams}')) {
$maxparams = _adRenderBuildParams($aBanner, $zoneId, $source, urlencode($ct0), $logClick, true);
$code = str_replace('{clickurlparams}', $maxparams, $code);  }
$search = array('{timestamp}','{random}','{target}','{url_prefix}','{img_url_prefix}','{bannerid}','{zoneid}','{source}', '{pageurl}', '{width}', '{height}', '{websiteid}', '{campaignid}', '{advertiserid}', '{referer}');
$locReplace = isset($GLOBALS['loc']) ? $GLOBALS['loc'] : '';
$websiteid = (!empty($aBanner['affiliate_id'])) ? $aBanner['affiliate_id'] : '0';
$replace = array($time, $random, $target, $urlPrefix, $imgUrlPrefix, $aBanner['ad_id'], $zoneId, $source, urlencode($locReplace), $aBanner['width'], $aBanner['height'], $websiteid, $aBanner['campaign_id'], $aBanner['client_id'], $referer);
preg_match_all('#{([a-zA-Z0-9_]*?)(_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]])) : htmlspecialchars(stripslashes($_REQUEST[$macros[1][$i]]), ENT_QUOTES);
}
}
$componentParams = OX_Delivery_Common_hook('addUrlParams', array($aBanner));
if (!empty($componentParams) && is_array($componentParams)) {
foreach ($componentParams as $params) {
if (!empty($params) && is_array($params)) {
foreach ($params as $key => $value) {
$search[] = '{' . $key . '}';
$replace[] = urlencode($value);
}
}
}
}
$code = str_replace($search, $replace, $code);
$clickUrl = str_replace($search, $replace, $clickUrl);
$aBanner['clickUrl'] = $clickUrl;
if (strpos($code, '{clickurl_enc}') !== false) {
$code = str_replace('{clickurl_enc}', urlencode($clickUrl), $code);
}
$logUrl = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&');
$logUrl = str_replace($search, $replace, $logUrl);
$aBanner['logUrl'] = $logUrl;
$aBanner['aSearch'] = $search;
$aBanner['aReplace'] = $replace;
OX_Delivery_Common_hook('postAdRender', array(&$code, $aBanner, &$context));
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}';
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, ENT_QUOTES)."' width='0' height='0' alt=''{$style} />{$divEnd}";
return $beacon;
}
function MAX_adRenderBlankBeacon($zoneId, $source, $loc, $referer)
{
$logUrl = _adRenderBuildLogURL(array(
'ad_id' => 0,
'placement_id' => 0,
), $zoneId, $source, $loc, $referer, '&');
return str_replace('{random}', MAX_getRandomNumber(), MAX_adRenderImageBeacon($logUrl));
}
function _adRenderImage(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $useAlt=false, $richMedia=true, $loc='', $referer='', $context=array(), $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'] : '';
$clickUrl = _adRenderBuildClickUrl($aBanner, $zoneId, $source, $ct0, $logClick);
if (!empty($clickUrl)) {  $status = _adRenderBuildStatusCode($aBanner);
$clickTag = "<a href='".htmlspecialchars($clickUrl, ENT_QUOTES)."' target='{target}'$status>";
$clickTagEnd = '</a>';
} else {
$clickTag = '';
$clickTagEnd = '';
}
if (!empty($imageUrl)) {
$imgStatus = empty($clickTag) && !empty($status) ? $status : '';
$width = !empty($aBanner['width']) ? $aBanner['width'] : 0;
$height = !empty($aBanner['height']) ? $aBanner['height'] : 0;
$alt = !empty($aBanner['alt']) ? htmlspecialchars($aBanner['alt'], ENT_QUOTES) : '';
$imageTag = "$clickTag<img src='".htmlspecialchars($imageUrl, ENT_QUOTES)."' width='$width' height='$height' alt='$alt' title='$alt' border='0'$imgStatus />$clickTagEnd";
} else {
$imageTag = '';
}
$bannerText = $withText && !empty($aBanner['bannertext']) ? "<br />$clickTag" . htmlspecialchars($aBanner['bannertext'], ENT_QUOTES) . "$clickTagEnd" : '';
$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, $useAlt=false, $richMedia=true, $loc='', $referer='', $context=array())
{
$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']) ? _adRenderGetRealPluginVersion($aBanner['pluginversion']) : '4';
$logURL = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&');
if (!empty($aBanner['alt_filename']) || !empty($aBanner['alt_imageurl'])) {
$altImageAdCode = _adRenderImage($aBanner, $zoneId, $source, $ct0, false, $logClick, false, true, true, $loc, $referer, $context, false);
$fallBackLogURL = _adRenderBuildLogURL($aBanner, $zoneId, $source, $loc, $referer, '&', true);
} else {
$alt = !empty($aBanner['alt']) ? htmlspecialchars($aBanner['alt'], ENT_QUOTES) : '';
$altImageAdCode = "<img src='" . _adRenderBuildImageUrlPrefix() . '/1x1.gif' . "' alt='".$alt."' title='".$alt."' border='0' />";
if ($zoneId) {
$fallBackLogURL = _adRenderBuildLogURL(array(
'ad_id' => 0,
'placement_id' => 0,
), $zoneId, $source, $loc, $referer, '&', true);
} else {
$fallBackLogURL = false;
}
}
$clickUrl = _adRenderBuildClickUrl($aBanner, $zoneId, $source, $ct0, $logClick);
if (!empty($clickUrl)) {  $status = _adRenderBuildStatusCode($aBanner);
$target = !empty($aBanner['target']) ? $aBanner['target'] : '_blank';
$swfParams = array('clickTARGET' => $target, 'clickTAG' => $clickUrl);
$clickTag = "<a href='".htmlspecialchars($clickUrl, ENT_QUOTES)."' 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'])) {
$swfParams = array();
$aBannerSwf = $aBanner;
$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);
$id = 'rv_swf_{random}';
$swfId = (!empty($aBanner['alt']) ? $aBanner['alt'] : 'Advertisement');
$swfId = 'id-' . preg_replace('/[a-z0-1]+/', '', strtolower($swfId));
$code = "
<div id='{$id}' 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) {
$code .= "    ox_swf.addVariable('{$key}', '" . preg_replace('#%7B(.*?)%7D#', '{$1}', urlencode($value)) . "');\n";
}
if (!empty($aBanner['transparent'])) {
$code .= "    ox_swf.addParam('wmode','transparent');\n";
} else {
$code .= "    ox_swf.addParam('wmode','opaque');\n";
}
$code .= "    ox_swf.addParam('allowScriptAccess','always');\n";
if ($logView && $conf['logging']['adImpressions']) {
$code .= "    ox_swf.write('{$id}', ".json_encode($logURL).", ".json_encode($fallBackLogURL).");\n";
} else {
$code .= "    ox_swf.write('{$id}');\n";
}
$code .= "/"."/ ]]> --></script>";
if ($fallBackLogURL) {
$code .= '<noscript>' . _adRenderImageBeacon($aBanner, $zoneId, $source, $loc, $referer, $fallBackLogURL) . '</noscript>';
}
$bannerText = $withText && !empty($aBanner['bannertext']) ? "<br />{$clickTag}{$aBanner['bannertext']}{$clickTagEnd}" : '';
return $prepend . $code . $bannerText . $append;
}
function _adRenderHtml(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $useAlt=false, $richMedia=true, $loc='', $referer='', $context=array())
{
if (!function_exists('Plugin_BannerTypeHtml_delivery_adRender')) {
_includeDeliveryPluginFile('/lib/OX/Extension/bannerTypeHtml/bannerTypeHtmlDelivery.php');
}
return Plugin_BannerTypeHtml_delivery_adRender($aBanner, $zoneId, $source, $ct0, $withText, $logClick, $logView, $useAlt, $richMedia, $loc, $referer);
}
function _adRenderText(&$aBanner, $zoneId=0, $source='', $ct0='', $withText=false, $logClick=true, $logView=true, $useAlt=false, $richMedia=false, $loc='', $referer='', $context=array())
{
$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, $richMedia, $loc, $referer);
}
function _adRenderBuildFileUrl($aBanner, $useAlt = false, $params = '')
{
$conf = $GLOBALS['_MAX']['CONF'];
$fileUrl = '';
if ($aBanner['type'] == 'url') {
$fileUrl = $useAlt ? $aBanner['alt_imageurl'] : $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 $GLOBALS['_MAX']['SSL_REQUEST'] ? 'https://' . $conf['webpath']['imagesSSL'] : 'http://' . $conf['webpath']['images'];
}
function _adRenderBuildLogURL($aBanner, $zoneId = 0, $source = '', $loc = '', $referer = '', $amp = '&amp;', $fallBack = false)
{
$conf = $GLOBALS['_MAX']['CONF'];
$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 .= "?" . $conf['var']['adId'] . "=" . $aBanner['ad_id'];
$url .= $amp . $conf['var']['campaignId'] . "=" . $aBanner['placement_id'];
$url .= $amp . $conf['var']['zoneId'] . "=" . $zoneId;
if (!empty($source)) $url .= $amp . $conf['var']['channel'] . "=" . $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);
if (!empty($fallBack)) $url .= $amp . $conf['var']['fallBack'] . '=1';
$url .= $amp . "cb={random}";
$componentParams = OX_Delivery_Common_hook('addUrlParams', array($aBanner));
if (!empty($componentParams) && is_array($componentParams)) {
foreach ($componentParams as $params) {
if (!empty($params) && is_array($params)) {
foreach ($params as $key => $value) {
$url .= $amp . urlencode($key) . '=' . urlencode($value);
}
}
}
}
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)
{
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 (!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) {
$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";
$dest = !empty($aBanner['url']) ? $aBanner['url'] : '';
if (!empty($ct0) && strtolower(substr($ct0, 0, 4)) == 'http') {
$dest = $ct0.preg_replace('/%7B(.*?)%7D/', '{$1}', urlencode($dest));
}
$dest = preg_replace('/%7B(.*?)%7D/', '{$1}', urlencode($dest));
$maxdest = "{$del}{$conf['var']['dest']}={$dest}";
$log .= (!empty($logLastClick)) ? $del . $conf['var']['lastClick'] . '=' . $logLastClick : '';
$maxparams = $delnum . $bannerId . $zoneId . $source . $log . $random;
$componentParams = OX_Delivery_Common_hook('addUrlParams', array($aBanner));
if (!empty($componentParams) && is_array($componentParams)) {
foreach ($componentParams as $params) {
if (!empty($params) && is_array($params)) {
foreach ($params as $key => $value) {
$maxparams .= $del . urlencode($key) . '=' . urlencode($value);
}
}
}
}
$maxparams .= $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 _adRenderGetRealPluginVersion($swfVersion)
{
if ($swfVersion <= 10) {
$pluginVersion = $swfVersion;
} elseif ($swfVersion >= 23) {
$pluginVersion = $swfVersion - 11;
} elseif ($swfVersion == 11 || $swfVersion == 12) {
$pluginVersion = 10 + ($swfVersion - 9) / 10;
} elseif ($swfVersion >= 13 && $swfVersion <= 22) {
$pluginVersion = 11 + ($swfVersion - 13) / 10;
}
return (string)$pluginVersion;
}
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;
default :
switch ($aBanner['type']) {
case 'html' :
$functionName = '_adRenderHtml';
break;
case 'url' :  $functionName = '_adRenderImage';
break;
case 'txt' :
$functionName = '_adRenderText';
break;
default:
$functionName = '_adRenderHtml';
break;
}
break;
}
}
return $functionName;
}


define ("PRI_ECPM_FROM", 6);
define ("PRI_ECPM_TO", 9);
$GLOBALS['OX_adSelect_SkipOtherPriorityLevels'] = -1;
function MAX_adSelect($what, $campaignid = '', $target = '', $source = '', $withtext = 0, $charset = '', $context = array(), $richmedia = true, $ct0 = '', $loc = '', $referer = '')
{
$conf = $GLOBALS['_MAX']['CONF'];
if (empty($GLOBALS['source'])) {
$GLOBALS['source'] = $source;
}
if (empty($GLOBALS['loc'])) {
$GLOBALS['loc'] = $loc;
}
$originalZoneId = null;
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_cookieAdd($conf['var']['viewerId'], $userid, _getTimeYearFromNow());
$outputbuffer = '';
$found = false;
$GLOBALS['_MAX']['followedChain'] = array();
$GLOBALS['_MAX']['adChain'] = array();
$GLOBALS['_MAX']['considered_ads'] = array();
$first = true;
global $g_append, $g_prepend;
$g_append = '';
$g_prepend = '';
if(!empty($what)) {
while ($first || ($what != '' && $found == false)) {
$first = false;
$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 {
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'])) {
MAX_Delivery_log_logAdRequest($row['bannerid'], $row['zoneid'], $row);
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'])) {
$GLOBALS['_MAX']['adChain'][] = $row;
$found = false;
$what = "zone:{$matches[1]}";
} else {
$found = true;
}
} else {
MAX_Delivery_log_logAdRequest(null, $originalZoneId, null);
$what = $remaining;
}
}
}
if ($found) {
$zoneId = empty($row['zoneid']) ? 0 : $row['zoneid'];
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'],
'clickwindow' => $row['clickwindow'],
'aRow' => $row,
'context' => _adSelectBuildContext($row, $context),
'iframeFriendly' => (bool)$row['iframe_friendly'],
);
$row += array(
'block_ad' => 0,
'cap_ad' => 0,
'session_cap_ad' => 0,
'block_campaign' => 0,
'cap_campaign' => 0,
'session_cap_campaign' => 0,
'block_zone' => 0,
'cap_zone' => 0,
'session_cap_zone' => 0,
);
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']);
}
MAX_Delivery_log_setLastAction(0, array($row['bannerid']), array($zoneId), array($row['viewwindow']));
}
} else {
if (!empty($zoneId)) {
$g_append = MAX_adRenderBlankBeacon($zoneId, $source, $loc, $referer).$g_append;
$outputbuffer = join("\n", OX_Delivery_Common_hook('blankAdSelect', array($zoneId, $context, $source, $richmedia)) ?: []);
}
if (!empty($outputbuffer)) {
$outputbuffer = $g_prepend . $outputbuffer . $g_append;
$output = array('html' => $outputbuffer, 'bannerid' => '' );
} elseif (!empty($row['default'])) {
if (empty($target)) {
$target = '_blank';  }
$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;
$output = array('html' => $outputbuffer, 'bannerid' => '', 'default_banner_image_url' => $row['default_banner_image_url'] );
} elseif (!empty($conf['defaultBanner']['imageUrl'])) {
if (empty($target)) {
$target = '_blank';  }
$outputbuffer = "{$g_prepend}<img src='{$conf['defaultBanner']['imageUrl']}' border='0' alt=''>{$g_append}";
$output = array('html' => $outputbuffer, 'bannerid' => '', 'default_banner_image_url' => $conf['defaultBanner']['imageUrl']);
} else {
$outputbuffer = $g_prepend . $g_append;
$output = array('html' => $outputbuffer, 'bannerid' => '' );
}
}
OX_Delivery_Common_hook('postAdSelect', array(&$output));
return $output;
}
function _adSelectDirect($what, $campaignid = '', $context = array(), $source = '', $richMedia = true, $lastpart = true)
{
$aDirectLinkedAdInfos = MAX_cacheGetLinkedAdInfos($what, $campaignid, $lastpart);
$GLOBALS['_MAX']['DIRECT_SELECTION'] = true;
$aLinkedAd = _adSelectCommon($aDirectLinkedAdInfos, $context, $source, $richMedia);
if (is_array($aLinkedAd)) {
$aLinkedAd['zoneid'] = 0;
$aLinkedAd['bannerid'] = $aLinkedAd['ad_id'];
$aLinkedAd['storagetype'] = $aLinkedAd['type'];
$aLinkedAd['campaignid'] = $aLinkedAd['placement_id'];
return $aLinkedAd;
}
if (!empty($aDirectLinkedAdInfos['default_banner_image_url'])) {
return array(
'default' => true,
'default_banner_image_url' => $aDirectLinkedAdInfos['default_banner_image_url'],
'default_banner_destination_url' => $aDirectLinkedAdInfos['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)
{
if ($zoneId === 0) { return false; }
global $g_append, $g_prepend;
while (!in_array($zoneId, $GLOBALS['_MAX']['followedChain'])) {
$GLOBALS['_MAX']['followedChain'][] = $zoneId;
$appendedThisZone = false;
$aZoneInfo = MAX_cacheGetZoneInfo($zoneId);
if (empty($aZoneInfo)) {
return false;
}
if ($zoneId != 0 && MAX_limitationsIsZoneForbidden($zoneId, $aZoneInfo)) {
$zoneId = _getNextZone($zoneId, $aZoneInfo);
continue;
}
$aZoneLinkedAdInfos = MAX_cacheGetZoneLinkedAdInfos ($zoneId);
if (is_array($aZoneInfo)) {
if (isset($aZoneInfo['forceappend']) && $aZoneInfo['forceappend'] == 't') {
$g_prepend .= $aZoneInfo['prepend'];
$g_append = $aZoneInfo['append'] . $g_append;
$appendedThisZone = true;
}
$aZoneLinkedAdInfos += $aZoneInfo;
$aLinkedAd = _adSelectCommon($aZoneLinkedAdInfos, $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'] = $aZoneLinkedAdInfos['zone_companion'];
$aLinkedAd['block_zone'] = @$aZoneInfo['block_zone'];
$aLinkedAd['cap_zone'] = @$aZoneInfo['cap_zone'];
$aLinkedAd['session_cap_zone'] = @$aZoneInfo['session_cap_zone'];
$aLinkedAd['affiliate_id'] = @$aZoneInfo['publisher_id'];
if (!$appendedThisZone) {
$aLinkedAd['append'] .= @$aZoneInfo['append'] . $g_append;
$aLinkedAd['prepend'] = $g_prepend . @$aZoneInfo['prepend'] . $aLinkedAd['prepend'];
} else {
$aLinkedAd['append'] .= $g_append;
$aLinkedAd['prepend'] = $g_prepend . $aLinkedAd['prepend'];
}
return ($aLinkedAd);
}
$zoneId = _getNextZone($zoneId, $aZoneInfo);
}
}
if (!empty($aZoneInfo['default_banner_image_url'])) {
return array(
'default' => true,
'default_banner_image_url' => $aZoneInfo['default_banner_image_url'],
'default_banner_destination_url' => $aZoneInfo['default_banner_destination_url']
);
}
return false;
}
function _adSelectCommon($aAds, $context, $source, $richMedia)
{
OX_Delivery_Common_hook('preAdSelect', array(&$aAds, &$context, &$source, &$richMedia));
if (!empty($aAds['ext_adselection'])) {
$adSelectFunction = OX_Delivery_Common_getFunctionFromComponentIdentifier($aAds['ext_adselection'], 'adSelect');
}
if (empty($adSelectFunction) || !function_exists($adSelectFunction)) {
$adSelectFunction = '_adSelect';
}
if (!empty($aAds['count_active'])) {
if (isset($aAds['zone_companion']) && isset($context)) {
foreach ($context as $contextEntry) {
if (isset($contextEntry['==']) && preg_match('/^companionid:/', $contextEntry['=='])) {
if ($aLinkedAd = _adSelectInnerLoop($adSelectFunction, $aAds, $context, $source, $richMedia, true)) {
return $aLinkedAd;
}
}
}
}
$aLinkedAd = _adSelectInnerLoop($adSelectFunction, $aAds, $context, $source, $richMedia);
if (is_array($aLinkedAd)) {
return $aLinkedAd;
}
}
return false;
}
function _adSelectInnerLoop($adSelectFunction, $aAds, $context, $source, $richMedia, $companion = false)
{
$aCampaignTypes = array(
'xAds' => false,  'ads' => array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1),
'lAds' => false,  'eAds' => array(-2),  );
$GLOBALS['_MAX']['considered_ads'][] = &$aAds;
foreach ($aCampaignTypes as $type => $aPriorities) {
if ($aPriorities) {
$ad_picked = false;
foreach ($aPriorities as $pri) {
if (!$ad_picked) {
$aLinkedAd = OX_Delivery_Common_hook('adSelect',
array(&$aAds, &$context, &$source, &$richMedia, $companion, $type, $pri), $adSelectFunction);
if (is_array($aLinkedAd)) {
$ad_picked = true;
}
if ($aLinkedAd == $GLOBALS['OX_adSelect_SkipOtherPriorityLevels']) {
$ad_picked = true;
}
}
else
{
if (!empty($aAds[$type][$pri])) {
$aContext = _adSelectBuildContextArray($aAds[$type][$pri], $type, $context);
_adSelectDiscardNonMatchingAds($aAds[$type][$pri], $aContext, $source, $richMedia);
}
}
}
if ($ad_picked && is_array ($aLinkedAd)) {
return $aLinkedAd;
}
} else {
$aLinkedAd = OX_Delivery_Common_hook('adSelect', array(&$aAds, &$context, &$source, &$richMedia, $companion, $type), $adSelectFunction);
if (is_array($aLinkedAd)) {
return $aLinkedAd;
}
}
}
return false;
}
function _adSelect(&$aLinkedAdInfos, $context, $source, $richMedia, $companion, $adArrayVar = 'ads', $cp = null)
{
if (!is_array($aLinkedAdInfos)) { return; }
if (!is_null($cp) && isset($aLinkedAdInfos[$adArrayVar][$cp])) {
$aAds = &$aLinkedAdInfos[$adArrayVar][$cp];
} elseif (is_null($cp) && isset($aLinkedAdInfos[$adArrayVar])) {
$aAds = &$aLinkedAdInfos[$adArrayVar];
} else {
$aAds = array();
}
if (count($aAds) == 0) {
return;
}
$aContext = _adSelectBuildContextArray($aAds, $adArrayVar, $context, $companion);
_adSelectDiscardNonMatchingAds($aAds, $aContext, $source, $richMedia);
if (count($aAds) == 0) {
return;
}
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'];
if ($adArrayVar == 'eAds') {
if (!empty ($conf['delivery']['ecpmSelectionRate'])) {
$selection_rate = floatval ($conf['delivery']['ecpmSelectionRate']);
if (!_controlTrafficEnabled ($aAds) ||
(mt_rand (0, $GLOBALS['_MAX']['MAX_RAND']) /
$GLOBALS['_MAX']['MAX_RAND']) <= $selection_rate)
{
$max_ecpm = 0;
$top_ecpms = array();
foreach ($aAds as $key => $ad) {
if ($ad['ecpm'] < $max_ecpm) {
continue;
} elseif ($ad['ecpm'] > $max_ecpm) {
$top_ecpms = array();
$max_ecpm = $ad['ecpm'];
}
$top_ecpms[$key] = 1;
}
if ($max_ecpm <= 0)
{
$GLOBALS['_MAX']['ECPM_CONTROL'] = 1;
$total_priority = _setPriorityFromWeights($aAds);
} else {
$GLOBALS['_MAX']['ECPM_SELECTION'] = 1;
$total_priority = count ($top_ecpms);
foreach ($aAds as $key => $ad) {
if (!empty ($top_ecpms[$key])) {
$aAds[$key]['priority'] = 1 / $total_priority;
} else {
$aAds[$key]['priority'] = 0;
}
}
}
}
else
{
$GLOBALS['_MAX']['ECPM_CONTROL'] = 1;
$total_priority = _setPriorityFromWeights($aAds);
}
}
} else if (isset($cp)) {
$used_priority = 0;
for ($i = 10; $i > $cp; $i--)
{
if (isset ($aLinkedAdInfos['priority_used'][$adArrayVar][$i]))
{
$used_priority += $aLinkedAdInfos['priority_used'][$adArrayVar][$i];
}
}
if ($used_priority >= 1) {
return $GLOBALS['OX_adSelect_SkipOtherPriorityLevels'];
}
$remaining_priority = 1 - $used_priority;
$total_priority_orig = 0;
foreach ($aAds as $ad) {
$total_priority_orig += $ad['priority'] * $ad['priority_factor'];
}
$aLinkedAdInfos['priority_used'][$adArrayVar][$i] = $total_priority_orig;
if ($total_priority_orig <= 0) {
return;
}
if ($total_priority_orig > $remaining_priority
|| $companion
)
{
$scaling_denom = $total_priority_orig;
if ($cp >= PRI_ECPM_FROM &&
$cp <= PRI_ECPM_TO &&
!empty ($conf['delivery']['ecpmSelectionRate']))
{
$selection_rate = floatval ($conf['delivery']['ecpmSelectionRate']);
if (!_controlTrafficEnabled ($aAds) ||
(mt_rand (0, $GLOBALS['_MAX']['MAX_RAND']) /
$GLOBALS['_MAX']['MAX_RAND']) <= $selection_rate)
{
$GLOBALS['_MAX']['ECPM_SELECTION'] = 1;
foreach ($aAds as $key => $ad) {
$ecpms[] = $ad['ecpm'];
$adids[] = $key;
}
array_multisort ($ecpms, SORT_DESC, $adids);
$p_avail = $remaining_priority;
$ad_count = count ($aAds);
$i = 0;
while ($i < $ad_count) {
$l = $i;
while ($l < $ad_count - 1 &&
$ecpms[$l + 1] == $ecpms[$i]) {
$l++;
}
$p_needed = 0;
for ($a_idx = $i; $a_idx <= $l; $a_idx++) {
$id = $adids[$a_idx];
$p_needed += $aAds[$id]['priority'] * $aAds[$id]['priority_factor'];
}
if ($p_needed > $p_avail) {
$scale = $p_avail / $p_needed;
for ($a_idx = $i; $a_idx <= $l; $a_idx++) {
$id = $adids[$a_idx];
$aAds[$id]['priority'] = $aAds[$id]['priority'] * $scale;
}
$p_avail = 0;
for ($a_idx = $l + 1; $a_idx < $ad_count; $a_idx++) {
$id = $adids[$a_idx];
$aAds[$id]['priority'] = 0;
}
break;
} else {
$p_avail -= $p_needed;
$i = $l + 1;
}
}
$scaling_denom = $remaining_priority;
} else {
$GLOBALS['_MAX']['ECPM_CONTROL'] = 1;
}
}
$scaling_factor = 1 / $scaling_denom;
}
else
{
$scaling_factor = 1 / $remaining_priority;
}
$total_priority = 0;
foreach ($aAds as $key => $ad) {
$newPriority =
$ad['priority'] * $ad['priority_factor'] * $scaling_factor;
$aAds[$key]['priority'] = $newPriority;
$total_priority += $newPriority;
}
} else {
$total_priority = _setPriorityFromWeights($aAds);
}
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'];
$random_num =
mt_rand (0, $GLOBALS['_MAX']['MAX_RAND'])
/ $GLOBALS['_MAX']['MAX_RAND'];
  if ($random_num > $total_priority) {
return;
}
$low = 0;
$high = 0;
foreach($aAds as $aLinkedAd) {
if (!empty($aLinkedAd['priority'])) {
$low = $high;
$high += $aLinkedAd['priority'];
if ($high > $random_num && $low <= $random_num) {
 $ad = MAX_cacheGetAd($aLinkedAd['ad_id']);
$ad['tracker_status'] = (!empty($aLinkedAd['tracker_status'])) ? $aLinkedAd['tracker_status'] : null;
if($ad['width'] == $ad['height'] && $ad['width'] == -1) {
$ad['width'] = $aLinkedAd['width'];
$ad['height'] = $aLinkedAd['height'];
}
return $ad;
}
}
}
return;
}
function _controlTrafficEnabled (&$aAds)
{
$control_enabled = true;
if (empty ($GLOBALS['_MAX']['CONF']['delivery']['enableControlOnPureCPM']))
{
$control_enabled = false;
foreach ($aAds as $ad) {
if ($ad['revenue_type'] != MAX_FINANCE_CPM)
{
$control_enabled = true;
break;
}
}
}
return $control_enabled;
}
function _adSelectCheckCriteria($aAd, $aContext, $source, $richMedia)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (!empty ($aAd['expire_time'])) {
$expire = strtotime ($aAd['expire_time']);
$now = MAX_commonGetTimeNow ();
if ($expire > 0 && $now > $expire) {
OX_Delivery_logMessage('Campaign has expired for bannerid '.$aAd['ad_id'], 7);
return false;
}
}
if (isset($aContext['banner']['exclude'][$aAd['ad_id']])) {
OX_Delivery_logMessage('List of excluded banners list contains bannerid '.$aAd['ad_id'], 7);
return false;
}
if (isset($aContext['campaign']['exclude'][$aAd['placement_id']])) {
OX_Delivery_logMessage('List of excluded campaigns contains bannerid '.$aAd['ad_id'], 7);
return false;
}
if (isset($aContext['client']['exclude'][$aAd['client_id']])) {
OX_Delivery_logMessage('List of excluded clients contains bannerid '.$aAd['ad_id'], 7);
return false;
}
if (!empty($aContext['banner']['include']) && !isset($aContext['banner']['include'][$aAd['ad_id']])) {
OX_Delivery_logMessage('List of included banners does not contain bannerid '.$aAd['ad_id'], 7);
return false;
}
if (!empty($aContext['campaign']['include']) && !isset($aContext['campaign']['include'][$aAd['placement_id']])) {
OX_Delivery_logMessage('List of included campaigns does not contain bannerid '.$aAd['ad_id'], 7);
return false;
}
if (  $richMedia == false &&
$aAd['alt_filename'] == '' &&
!($aAd['contenttype'] == 'jpeg' || $aAd['contenttype'] == 'gif' || $aAd['contenttype'] == 'png') &&
!($aAd['type'] == 'url' && $aAd['contenttype'] == '')
) {
OX_Delivery_logMessage('No alt image specified for richmedia bannerid '.$aAd['ad_id'], 7);
return false;
}
if (MAX_limitationsIsAdForbidden($aAd)) {
OX_Delivery_logMessage('MAX_limitationsIsAdForbidden = true for bannerid '.$aAd['ad_id'], 7);
return false;
}
if ($GLOBALS['_MAX']['SSL_REQUEST'] && $aAd['type'] == 'html' && $aAd['html_ssl_unsafe']) {
OX_Delivery_logMessage('"http:" on SSL found for html bannerid '.$aAd['ad_id'], 7);
return false;
}
if ($GLOBALS['_MAX']['SSL_REQUEST'] && $aAd['type'] == 'url' && $aAd['url_ssl_unsafe']) {
OX_Delivery_logMessage('"http:" on SSL found in imagurl for url bannerid '.$aAd['ad_id'], 7);
return false;
}
if ($conf['delivery']['acls'] && !MAX_limitationsCheckAcl($aAd, $source)) {
OX_Delivery_logMessage('MAX_limitationsCheckAcl = false for bannerid '.$aAd['ad_id'], 7);
return false;
}
return true;
}
function _adSelectBuildContextArray(&$aLinkedAds, $adArrayVar, $context, $companion = false)
{
$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;
}
if (empty($value)) {
continue;
}
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 '==':
if ($companion) {
$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'])) {
foreach ($aBanner['zone_companion'] AS $companionCampaign) {
$value = 'companionid:'.$companionCampaign;
if ($aBanner['placement_id'] == $companionCampaign) {
$context[] = array('==' => $value);
} else {
$key = array_search(array('==', $value), $context);
if ($key === false) {
$context[] = array('!=' => $value);
}
}
}
}
if (isset($aBanner['advertiser_limitation']) && $aBanner['advertiser_limitation'] == '1') {
$context[] = array('!=' => 'clientid:' . $aBanner['client_id']);
}
return $context;
}
function _adSelectDiscardNonMatchingAds(&$aAds, $aContext, $source, $richMedia)
{
if (empty($GLOBALS['_MAX']['CONF']['delivery']['aclsDirectSelection']) && !empty($GLOBALS['_MAX']['DIRECT_SELECTION'])) {
return;
}
foreach ($aAds as $adId => $aAd) {
OX_Delivery_logMessage('_adSelectDiscardNonMatchingAds: checking bannerid '.$aAd['ad_id'], 7);
if (!_adSelectCheckCriteria($aAd, $aContext, $source, $richMedia)) {
OX_Delivery_logMessage('failed _adSelectCheckCriteria: bannerid '.$aAd['ad_id'], 7);
unset($aAds[$adId]);
} else {
OX_Delivery_logMessage('passed _adSelectCheckCriteria: bannerid '.$aAd['ad_id'], 7);
}
}
return;
}


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 (substr($conf['file']['flash'], 0, 4) == 'http') {
if (file_exists(MAX_PATH . '/www/delivery/' . basename($conf['file']['flash']))) {
return file_get_contents(MAX_PATH . '/www/delivery/' . basename($conf['file']['flash']));
} else {
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']);
}
}


require_once OX_PATH . '/lib/pear/Log.php';

require_once OX_PATH . '/lib/pear/PEAR.php';

class OX
{
function assetPath($asset = null)
{
global $installing;
$aConf = $GLOBALS['_MAX']['CONF'];
$assetsVersion = $aConf['webpath']['adminAssetsVersion'];
$prefix = $installing ? '' : MAX::constructURL(MAX_URL_ADMIN, '');
$pathWithSuffix = $prefix . "assets";
if (strlen($assetsVersion))
{
$pathWithSuffix .= "/" . $assetsVersion;
}
if ($asset != null)
{
return $pathWithSuffix . "/" . $asset;
}
else
{
return $pathWithSuffix;
}
}
function realPathRelative($path) {
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' == $part) continue;
if ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
return implode(DIRECTORY_SEPARATOR, $absolutes);
}
}

require_once 'XML/RPC/Server.php';

$GLOBALS['_OA']['invocationType'] = 'xmlrpc';
if (empty($GLOBALS['HTTP_RAW_POST_DATA'])) {
$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents('php://input');
}
XML_RPC_Client::setAutoBase64(true);
$xmlRpcView_OA =
array(
'sig' => array(
array(
$GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Int'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Boolean'],  $GLOBALS['XML_RPC_Array']  )
),
'doc' => 'When passed the "environment/cookies" struct, "what", "campaignid", "target", "source", ' .
'"withText", "context" returns the cookies to be set and the HTML code to display the ' .
'appropriate advertisement.'
);
$xmlRpcSPC_OA =
array(
'sig' => array(
array(
$GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Boolean'],  $GLOBALS['XML_RPC_Boolean'],  $GLOBALS['XML_RPC_Boolean'],  )
),
'doc' => 'When passed the "environment/cookies" struct, "what", "target", "source", ' .
'"withtext", "block" and "blockcampaign" returns the cookies to be set and an array of HTML code to display the ' .
'selected advertisements.'
);
$xmlRpcView_Max =
array(
'sig' => array(
array(
$GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Boolean'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Struct']  ),
array(
$GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Boolean'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_Array']  )
),
'doc' => '2.3 backwards compatibility method - deprecated'
);
$xmlRpcView_PAN =
array(
'sig' => array(
array(
$GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Int'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Boolean']  ),
array(
$GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_Struct'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Int'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_String'],  $GLOBALS['XML_RPC_Boolean'],  $GLOBALS['XML_RPC_Array']  )
),
'doc' => '2.0 Backwards compatibility method - deprecated'
);
function OA_Delivery_XmlRpc_View($params)
{
global $XML_RPC_erruser;
global $XML_RPC_String, $XML_RPC_Struct, $XML_RPC_Array;
$numParams = $params->getNumParams();
if ($numParams != 7) {
$errorCode = $XML_RPC_erruser + 21;
$errorMsg = 'Incorrect number of parameters';
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
for ($i = 0; $i < $numParams; $i++)
{
$p = $params->getParam($i);
if ($i == 6) { $view_params[] = ''; }
if ($i) {
$view_params[] = XML_RPC_decode($p);
} else {
$p = XML_RPC_decode($p);
if (!isset($p['remote_addr'])) {
$errorCode = $XML_RPC_erruser + 22;
$errorMsg = "Missing 'remote_addr' member";
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
if (!isset($p['cookies']) || !is_array($p['cookies'])) {
$errorCode = $XML_RPC_erruser + 23;
$errorMsg = "Missing 'cookies' member";
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
$aServerVars = array(
'remote_addr' => 'REMOTE_ADDR',
'remote_host' => 'REMOTE_HOST',
'request_uri' => 'REQUEST_URI',
'https' => 'HTTPS',
'server_name' => 'SERVER_NAME',
'http_host' => 'HTTP_HOST',
'accept_language' => 'HTTP_ACCEPT_LANGUAGE',
'referer' => 'HTTP_REFERER',
'user_agent' => 'HTTP_USER_AGENT',
'via' => 'HTTP_VIA',
'forwarded' => 'HTTP_FORWARDED',
'forwarded_for' => 'HTTP_FORWARDED_FOR',
'x_forwarded' => 'HTTP_X_FORWARDED',
'x_forwarded_for' => 'HTTP_X_FORWARDED_FOR',
'client_ip' => 'HTTP_CLIENT_IP'
);
foreach ($aServerVars as $xmlName => $varName) {
if (isset($p[$xmlName])) {
$_SERVER[$varName] = $p[$xmlName];
}
}
foreach ($p['cookies'] as $key => $value) {
$_COOKIE[$key] = MAX_commonAddslashesRecursive($value);
}
MAX_remotehostSetInfo(true);
OX_Delivery_Common_hook('postInit');
MAX_cookieUnpackCapping();
}
}
$view_params[] = true;
$view_params[] = '';
$view_params[] =
(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http').'://'.
OX_getHostName().
$_SERVER['REQUEST_URI'];
$view_params[] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$escape = array(
'addslashes',
'intval',
'addslashes',
'addslashes',
'intval',
'addslashes',
'MAX_commonAddslashesRecursive',
'intval',
'addslashes',
'addslashes',
'',  );
foreach ($escape as $key => $callback) {
if (is_callable($callback)) {
$view_params[$key] = $callback($view_params[$key]);
}
}
$output = call_user_func_array('MAX_adSelect', $view_params);
if (!is_array($output)) {
$output = array();
} elseif (isset($output['contenttype']) && $output['contenttype'] == 'swf') {
$output['html'] = MAX_flashGetFlashObjectExternal() . $output['html'];
}
MAX_cookieFlush();
$output['cookies'] = $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'];
return new XML_RPC_Response(XML_RPC_encode($output));
}
function OA_Delivery_XmlRpc_SPC($params)
{
global $XML_RPC_erruser;
global $XML_RPC_String, $XML_RPC_Struct, $XML_RPC_Array;
$numParams = $params->getNumParams();
if ($numParams != 7) {
$errorCode = $XML_RPC_erruser + 21;
$errorMsg = 'Incorrect number of parameters';
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
$vars = array(
1 => 'what',
2 => 'target',
3 => 'source',
4 => 'withtext',
5 => 'block',
6 => 'blockcampaign',
);
for ($i = 0; $i < $numParams; $i++)
{
$p = $params->getParam($i);
if ($i) {
${$vars[$i]} = XML_RPC_decode($p);
} else {
$p = XML_RPC_decode($p);
if (!isset($p['remote_addr'])) {
$errorCode = $XML_RPC_erruser + 22;
$errorMsg = "Missing 'remote_addr' member";
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
if (!isset($p['cookies']) || !is_array($p['cookies'])) {
$errorCode = $XML_RPC_erruser + 23;
$errorMsg = "Missing 'cookies' member";
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
$aServerVars = array(
'remote_addr' => 'REMOTE_ADDR',
'remote_host' => 'REMOTE_HOST',
'request_uri' => 'REQUEST_URI',
'https' => 'HTTPS',
'server_name' => 'SERVER_NAME',
'http_host' => 'HTTP_HOST',
'accept_language' => 'HTTP_ACCEPT_LANGUAGE',
'referer' => 'HTTP_REFERER',
'user_agent' => 'HTTP_USER_AGENT',
'via' => 'HTTP_VIA',
'forwarded' => 'HTTP_FORWARDED',
'forwarded_for' => 'HTTP_FORWARDED_FOR',
'x_forwarded' => 'HTTP_X_FORWARDED',
'x_forwarded_for' => 'HTTP_X_FORWARDED_FOR',
'client_ip' => 'HTTP_CLIENT_IP'
);
foreach ($aServerVars as $xmlName => $varName) {
if (isset($p[$xmlName])) {
$_SERVER[$varName] = $p[$xmlName];
}
}
foreach ($p['cookies'] as $key => $value) {
$_COOKIE[$key] = MAX_commonAddslashesRecursive($value);
}
MAX_remotehostSetInfo(true);
OX_Delivery_Common_hook('postInit');
MAX_cookieUnpackCapping();
}
}
$richmedia = true;
$ct0 = '';
$context = array();
global $loc, $referer;
$loc =
(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http').'://'.
OX_getHostName().
$_SERVER['REQUEST_URI'];
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if (ctype_digit($what)) {
$zones = OA_cacheGetPublisherZones($what);
$nz = false;
} else {
parse_str($what, $zones);
$nz = true;
}
$spc_output = array();
foreach ($zones as $zone => $data) {
if (empty($zone)) continue;
if ($nz) {
$varname = $zone;
$zoneid = $data;
} else {
$varname = $zoneid = $zone;
}
unset($GLOBALS['_MAX']['deliveryData']);
$output = MAX_adSelect('zone:'.$zoneid, '', $target, $source, $withtext, '', $context, $richmedia, $ct0, $GLOBALS['loc'], $GLOBALS['referer']);
$spc_output[$varname] = $output;
if (!empty($block) && !empty($output['bannerid'])) {
$output['context'][] = array('!=' => 'bannerid:' . $output['bannerid']);
}
if (!empty($blockcampaign) && !empty($output['campaignid'])) {
$output['context'][] = array('!=' => 'campaignid:' . $output['campaignid']);
}
if (!empty($output['context'])) {
foreach ($output['context'] as $id => $contextArray) {
if (!in_array($contextArray, $context)) {
$context[] = $contextArray;
}
}
}
}
return new XML_RPC_Response(XML_RPC_encode($spc_output));
$output = call_user_func_array('MAX_adSelect', $view_params);
if (!is_array($output)) {
$output = array();
} elseif (isset($output['contenttype']) && $output['contenttype'] == 'swf') {
$output['html'] = MAX_flashGetFlashObjectExternal() . $output['html'];
}
MAX_cookieFlush();
$output['cookies'] = $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'];
return new XML_RPC_Response(XML_RPC_encode($output));
}
function OA_Delivery_XmlRpc_View_Max($params)
{
global $XML_RPC_erruser;
global $XML_RPC_String, $XML_RPC_Struct, $XML_RPC_Array, $XML_RPC_Int;
$numParams = $params->getNumParams();
if ($numParams < 6) {
$errorCode = $XML_RPC_erruser + 2;
$errorMsg = 'Incorrect number of parameters';
return new XML_RPC_Response(0, $errorCode, $errorMsg);
}
$whatXmlRpcValue = $params->getParam(0);
$targetXmlRpcValue = $params->getParam(1);
$sourceXmlRpcValue = $params->getParam(2);
$withTextXmlRpcValue = $params->getParam(3);
$remoteAddressXmlRpcValue = $params->getParam(4);
$cookiesXmlRpcValue = $params->getParam(5);
if ($numParams >= 7) {
$contextXmlRpcValue = $params->getParam(6);
} else {
$contextXmlRpcValue = new XML_RPC_Value(array(), $XML_RPC_Array);
}
$campaignidXmlRpcValue = new XML_RPC_Value(0, $XML_RPC_Int);
$remoteInfoXmlRpcValue = new XML_RPC_Value(
array(
'remote_addr' => $remoteAddressXmlRpcValue,
'cookies' => $cookiesXmlRpcValue
),
$XML_RPC_Struct
);
$msg = new XML_RPC_Message('openads.view', array(
$remoteInfoXmlRpcValue,
$whatXmlRpcValue,
$campaignidXmlRpcValue,
$targetXmlRpcValue,
$sourceXmlRpcValue,
$withTextXmlRpcValue,
$contextXmlRpcValue
));
$xmlResponse = OA_Delivery_XmlRpc_View($msg);
if (XML_RPC_Base::isError($xmlResponse)) {
return $xmlResponse;
}
$output = XML_RPC_decode($xmlResponse->value());
$cookies = $output['cookies'];
unset($output['cookies']);
return new XML_RPC_Response(
new XML_RPC_Value(array(
XML_RPC_encode($output),
XML_RPC_encode($cookies)
),
$XML_RPC_Array
)
);
}
function OA_Delivery_XmlRpc_View_PAN($params)
{
$remoteInfoXmlRpcValue = $params->getParam(0);
$remote_info = XML_RPC_Decode($params->getParam(0));
$remote_info['cookies'] = array();
$remoteInfoXmlRpcValue = XML_RPC_encode($remote_info);
if ($params->getNumParams() > 6) {
$contextXmlRpcValue = $params->getParam(6);
} else {
$contextXmlRpcValue = new XML_RPC_Value(array(), $XML_RPC_Array);
}
$msg = new XML_RPC_Message('phpAds.view', array(
$remoteInfoXmlRpcValue,
$params->getParam(1),
$params->getParam(2),
$params->getParam(3),
$params->getParam(4),
$params->getParam(5),
$contextXmlRpcValue
));
$xmlResponse = OA_Delivery_XmlRpc_View($msg);
return $xmlResponse;
}

$server = new XML_RPC_Server(array(
'openads.view' => array(
'function' => 'OA_Delivery_XmlRpc_View',
'signature' => $xmlRpcView_OA['sig'],
'docstring' => $xmlRpcView_OA['doc']
),
'openads.spc' => array(
'function' => 'OA_Delivery_XmlRpc_SPC',
'signature' => $xmlRpcSPC_OA['sig'],
'docstring' => $xmlRpcSPC_OA['doc']
),
'phpAds.view' => array(
'function' => 'OA_Delivery_XmlRpc_View_PAN',
'signature' => $xmlRpcView_PAN['sig'],
'docstring' => $xmlRpcView_PAN['doc']
),
'max.view' => array(
'function' => 'OA_Delivery_XmlRpc_View_Max',
'signature' => $xmlRpcView_Max['sig'],
'docstring' => $xmlRpcView_Max['doc']
)
)
);
