<?php

/*
+---------------------------------------------------------------------------+
| OpenX v2.4                                                                |
| ==========                                                                |
|                                                                           |
| Copyright (c) 2003-2008 OpenX Limited                                     |
| For contact details, see: http://www.openx.org/                           |
|                                                                           |
| This program is free software; you can redistribute it and/or modify      |
| it under the terms of the GNU General Public License as published by      |
| the Free Software Foundation; either version 2 of the License, or         |
| (at your option) any later version.                                       |
|                                                                           |
| This program is distributed in the hope that it will be useful,           |
| but WITHOUT ANY WARRANTY; without even the implied warranty of            |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             |
| GNU General Public License for more details.                              |
|                                                                           |
| You should have received a copy of the GNU General Public License         |
| along with this program; if not, write to the Free Software               |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA |
+---------------------------------------------------------------------------+
$Id: fc.php 18656 2008-04-10 11:33:49Z david.keen@openx.org $
*/

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

// Require the initialisation file
function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true)
{
// Set up the configuration .ini file path location
if (!$configPath) {
$configPath = MAX_PATH . '/var';
}
if ($configFile) {
$configFile = '.' . $configFile;
}
$host = getHostName();
$configFileName = $configPath . '/' . $host . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $conf;
} elseif ($configFile === '.plugin') {
// For plugins, if no configuration file is found, return the sane default values
$pluginType = basename($configPath);
$defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php';
$conf = @parse_ini_file($defaultConfig, $sections);
if ($conf !== false) {
// check for false here - it's possible file doesn't exist
return $conf;
}
echo "OpenX could not read the default configuration file for the {$pluginType} plugin";
exit(1);
}
// Check for a 'default.conf.php' file
$configFileName = $configPath . '/default' . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $conf;
}
// Check to ensure Max hasn't been installed
if (file_exists(MAX_PATH . '/var/INSTALLED')) {
echo "OpenX has been installed, but no configuration file was found.\n";
exit(1);
}
// Max hasn't been installed, so delivery engine can't run
echo "OpenX has not been installed yet -- please read the INSTALL.txt file.\n";
exit(1);
}
function setupConfigVariables()
{
$GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'] = '|';
$GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'] = '__';
// Set the URL access mechanism
if (!empty($GLOBALS['_MAX']['CONF']['openads']['requireSSL'])) {
$GLOBALS['_MAX']['HTTP'] = 'https://';
} else {
if (isset($_SERVER['SERVER_PORT'])) {
if (isset($GLOBALS['_MAX']['CONF']['openads']['sslPort'])
&& $_SERVER['SERVER_PORT'] == $GLOBALS['_MAX']['CONF']['openads']['sslPort'])
{
$GLOBALS['_MAX']['HTTP'] = 'https://';
} else {
$GLOBALS['_MAX']['HTTP'] = 'http://';
}
}
}
// Maximum random number (use default if doesn't exist - eg the case when application is upgraded)
$GLOBALS['_MAX']['MAX_RAND'] = isset($GLOBALS['_MAX']['CONF']['priority']['randmax']) ?
$GLOBALS['_MAX']['CONF']['priority']['randmax'] : 2147483647;
// Set time zone, for more info @see setTimeZoneLocation()
if (!empty($GLOBALS['_MAX']['CONF']['timezone']['location'])) {
setTimeZoneLocation($GLOBALS['_MAX']['CONF']['timezone']['location']);
}
}
function setupServerVariables()
{
// PHP-CGI/IIS combination does not set REQUEST_URI
if (empty($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
if (!empty($_SERVER['QUERY_STRING'])) {
$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
}
}
}
function setupDeliveryConfigVariables()
{
if (!defined('MAX_PATH')) {
define('MAX_PATH', dirname(__FILE__).'/../..');
}
// Ensure that the initialisation has not been run before
if ( !(isset($GLOBALS['_MAX']['CONF']))) {
// Parse the Max configuration file
$GLOBALS['_MAX']['CONF'] = parseDeliveryIniFile();
}
// Set up the common configuration variables
setupConfigVariables();
}
function setTimeZoneLocation($location)
{
if (version_compare(phpversion(), '5.1.0', '>=')) {
// Set new time zone
date_default_timezone_set($location);
} else {
// Set new time zone
putenv("TZ={$location}");
}
}
function getHostName()
{
if (!empty($_SERVER['HTTP_HOST'])) {
$host = explode(':', $_SERVER['HTTP_HOST']);
$host = $host[0];
} else if (!empty($_SERVER['SERVER_NAME'])) {
$host = explode(':', $_SERVER['SERVER_NAME']);
$host = $host[0];
}
return $host;
}
function getHostNameWithPort()
{
if (!empty($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST'];
} else if (!empty($_SERVER['SERVER_NAME'])) {
$host = $_SERVER['SERVER_NAME'];
}
return $host;
}
function setupIncludePath()
{
static $checkIfAlreadySet;
if (isset($checkIfAlreadySet)) {
return;
}
$checkIfAlreadySet = true;
// Define the PEAR installation path
$existingPearPath = ini_get('include_path');
$newPearPath = MAX_PATH . DIRECTORY_SEPARATOR.'lib' . DIRECTORY_SEPARATOR . 'pear';
if (!empty($existingPearPath)) {
$newPearPath .= PATH_SEPARATOR . $existingPearPath;
}
if (!ereg("\.", $newPearPath)) {
$newPearPath = '.'.PATH_SEPARATOR . $newPearPath;
}
ini_set('include_path', $newPearPath);
}
function getMinimumRequiredMemory()
{
if (version_compare(phpversion(), '5.2.0', '>=')) {
return $GLOBALS['_MAX']['REQUIRED_MEMORY']['PHP5'];
}
return $GLOBALS['_MAX']['REQUIRED_MEMORY']['PHP4'];
}
function increaseMemoryLimit($setMemory) {
$memory = getMemorySizeInBytes();
if ($memory == -1) {
// unlimited
return true;
}
if ($setMemory > $memory) {
if (@ini_set('memory_limit', $setMemory) === false) {
return false;
}
}
return true;
}
function getMemorySizeInBytes() {
$phpMemory = ini_get('memory_limit');
if (empty($phpMemory) || $phpMemory == -1) {
// unlimited
return -1;
}
$aSize = array(
'G' => 1073741824,
'M' => 1048576,
'K' => 1024
);
$size = $phpMemory;
foreach($aSize as $type => $multiplier) {
$pos = strpos($phpMemory, $type);
if (!$pos) {
$pos = strpos($phpMemory, strtolower($type));
}
if ($pos) {
$size = substr($phpMemory, 0, $pos) * $multiplier;
}
}
return $size;
}
setupServerVariables();
setupDeliveryConfigVariables();
$conf = $GLOBALS['_MAX']['CONF'];
// Set the log file
if (!empty($conf['debug']['logfile'])) {
@ini_set('error_log', MAX_PATH . '/var/' . $conf['debug']['logfile']);
}
// Disable all notices and warnings, as some PAN code still
// generates PHP warnings in places
if (!empty($conf['debug']['production'])) {
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
} else {
// show all errors when developing
error_reporting(E_ALL);
}
$file = '/lib/max/Delivery/common.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
$file = '/lib/max/Delivery/cookie.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
$GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array();
function MAX_cookieSet($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) {
$conf = $GLOBALS['_MAX']['CONF'];
MAX_cookieSet($conf['var']['viewerId'], $viewerId, _getTimeYearFromNow());
MAX_cookieFlush();
// Determine if the access to OpenX was made using HTTPS
if ($_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) {
$url = MAX_commonConstructSecureDeliveryUrl(basename($_SERVER['PHP_SELF']));
} else {
$url = MAX_commonConstructDeliveryUrl(basename($_SERVER['PHP_SELF']));
}
$url .= "?{$conf['var']['cookieTest']}=1&" . $_SERVER['QUERY_STRING'];
MAX_header("Location: {$url}");
exit;
}
function MAX_cookieFlush()
{
$conf = $GLOBALS['_MAX']['CONF'];
MAX_cookieSendP3PHeaders();
if (!empty($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
// Set cookies
reset($GLOBALS['_MAX']['COOKIE']['CACHE']);
while (list($name,$v) = each ($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
list($value, $expire) = $v;
MAX_setcookie($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
}
// Clear cache
$GLOBALS['_MAX']['COOKIE']['CACHE'] = array();
}
// Compact all individual cookies into packed except for any cookies for the current bannerid
// We only need to set these packed cookies if new capping data has been merged
$cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
if (!is_array($cookieNames))
return;
// For each type of cookie, repack if necessary
foreach ($cookieNames as $cookieName) {
// We only need to write out the compacted cookie if a new item is to be inserted (or updated)
if (empty($_COOKIE["_{$cookieName}"])) {
continue;
}
switch ($cookieName) {
case $conf['var']['blockAd']            : $expire = _getTimeThirtyDaysFromNow(); break;
case $conf['var']['capAd']              : $expire = _getTimeYearFromNow(); break;
case $conf['var']['sessionCapAd']       : $expire = 0; break;
case $conf['var']['blockCampaign']      : $expire = _getTimeThirtyDaysFromNow(); break;
case $conf['var']['capCampaign']        : $expire = _getTimeYearFromNow(); break;
case $conf['var']['sessionCapCampaign'] : $expire = 0; break;
case $conf['var']['blockZone']          : $expire = _getTimeThirtyDaysFromNow(); break;
case $conf['var']['capZone']            : $expire = _getTimeYearFromNow(); break;
case $conf['var']['sessionCapZone']     : $expire = 0; break;
}
if (!empty($_COOKIE[$cookieName]) && is_array($_COOKIE[$cookieName])) {
$data = array();
foreach ($_COOKIE[$cookieName] as $adId => $value) {
$data[] = "{$adId}.{$value}";
}
// RFC says that maximum cookie data length is 4096 bytes
// So we are assuming that 2048 will be valid in most browsers
// Discard oldest data until we are under the limit
while (strlen(implode('_', $data)) > 2048) {
$data = array_slice($data, 1);
}
MAX_setcookie($cookieName, implode('_', $data), $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
}
}
}
function _getTimeThirtyDaysFromNow()
{
return MAX_commonGetTimeNow() + 2592000; // 30*24*60*60;
}
function _getTimeYearFromNow()
{
return MAX_commonGetTimeNow() + 31536000; // 365*24*60*60;
}
function _getTimeYearAgo()
{
return MAX_commonGetTimeNow() - 31536000; // 365*24*60*60;
}
function MAX_cookieUnpackCapping()
{
$conf = $GLOBALS['_MAX']['CONF'];
$cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
if (!is_array($cookieNames))
return;
// For each type of cookie, unpack and add any newly set cookies to this array
foreach ($cookieNames as $cookieName) {
if (!empty($_COOKIE[$cookieName])) {
if (!is_array($_COOKIE[$cookieName])) {
$output = array();
$data = explode('_', $_COOKIE[$cookieName]);
foreach ($data as $pair) {
list($name, $value) = explode('.', $pair);
$output[$name] = $value;
}
$_COOKIE[$cookieName] = $output;
}
}
if (!empty($_COOKIE['_' . $cookieName]) && is_array($_COOKIE['_' . $cookieName])) {
foreach ($_COOKIE['_' . $cookieName] as $adId => $cookie) {
if (_isBlockCookie($cookieName)) {
$_COOKIE[$cookieName][$adId] = $cookie;
} else {
if (isset($_COOKIE[$cookieName][$adId])) {
$_COOKIE[$cookieName][$adId] += $cookie;
} else {
$_COOKIE[$cookieName][$adId] = $cookie;
}
}
// Delete the temporary capping cookie
MAX_cookieSet("_{$cookieName}[{$adId}]", false, _getTimeYearAgo());
// Work around a bug in IE where the cookie name is sometimes URL-encoded
MAX_cookieSet("%5F" . urlencode($cookieName.'['.$adId.']'), false, _getTimeYearAgo());
}
}
}
}
function _isBlockCookie($cookieName)
{
if ($cookieName == $GLOBALS['_MAX']['CONF']['var']['blockAd']) {
return true;
}
if ($cookieName == $GLOBALS['_MAX']['CONF']['var']['blockCampaign']) {
return true;
}
if ($cookieName == $GLOBALS['_MAX']['CONF']['var']['blockZone']) {
return true;
}
return false;
}
function MAX_cookieGetUniqueViewerID($create = true)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (isset($_COOKIE[$conf['var']['viewerId']])) {
$userid = $_COOKIE[$conf['var']['viewerId']];
} else {
if ($create) {
$remote_address = $_SERVER['REMOTE_ADDR'];
$local_address  = $conf['webpath']['delivery']; // How do I get the IP address of this server?
// Get the exact time
list($usec, $sec) = explode(" ", microtime());
$time = (float) $usec + (float) $sec;
// Get a random number
$random = mt_rand(0,999999999);
$userid = substr(md5($local_address.$time.$remote_address.$random),0,32);  // Need to find a way to generate this...
$GLOBALS['_MAX']['COOKIE']['newViewerId'] = true;
} else {
$userid = null;
}
}
return $userid;
}
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_cookieSendP3PHeaders() {
// Send P3P headers
if ($GLOBALS['_MAX']['CONF']['p3p']['policies']) {
MAX_header("P3P: ". _generateP3PHeader());
}
}
function MAX_Delivery_cookie_cappingOnRequest()
{
if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xml-rpc') {
return true;
}
return !$GLOBALS['_MAX']['CONF']['logging']['adImpressions'];
}
function MAX_Delivery_cookie_setCapping($type, $id, $block = 0, $cap = 0, $sessionCap = 0)
{
$conf = $GLOBALS['_MAX']['CONF'];
$setBlock = false;
if ($cap > 0) {
// This capping cookie requires a "permanent" expiration time
$expire = MAX_commonGetTimeNow() + $conf['cookie']['permCookieSeconds'];
// The unpack capping cookies function adds this value to the counter, so to reset it we add a negative number
if (!isset($_COOKIE[$conf['var']['cap' . $type]][$id])) {
$value = 1;
$setBlock = true;
} else if ($_COOKIE[$conf['var']['cap' . $type]][$id] >= $cap) {
$value = -$_COOKIE[$conf['var']['cap' . $type]][$id]+1;
// Also reset the last-seen when resetting the frequency counter
$setBlock = true;
} else {
$value = 1;
}
MAX_cookieSet("_{$conf['var']['cap' . $type]}[{$id}]", $value, $expire);
}
if ($sessionCap > 0) {
// The unpack capping cookies function deals with imcrementing the counter
// The expiry is set to 0 to make a session cookie
// The unpack capping cookies function adds this value to the counter, so to reset it we add a negative number
if (!isset($_COOKIE[$conf['var']['sessionCap' . $type]][$id])) {
$value = 1;
$setBlock = true;
} else if ($_COOKIE[$conf['var']['sessionCap' . $type]][$id] >= $sessionCap) {
$value = -$_COOKIE[$conf['var']['sessionCap' . $type]][$id]+1;
// Also reset the last-seen when resetting the frequency counter
$setBlock = true;
} else {
$value = 1;
}
MAX_cookieSet("_{$conf['var']['sessionCap' . $type]}[{$id}]", $value, 0);
}
if ($block > 0 || $setBlock) {
// This blocking cookie is limited to 30 days
// Store a cookie using the current time so that the system knows when
// the last time this viewer saw this ad, an ad in this campaign or an
// ad in this zone
MAX_cookieSet("_{$conf['var']['block' . $type]}[{$id}]", MAX_commonGetTimeNow(), _getTimeThirtyDaysFromNow());
}
}
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_remotehostProxyLookup()
{
$conf = $GLOBALS['_MAX']['CONF'];
// Should proxy lookup conversion be performed?
if ($conf['logging']['proxyLookup']) {
// Determine if the viewer has come via an HTTP proxy
$proxy = false;
if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$proxy = true;
} elseif (!empty($_SERVER['REMOTE_HOST'])) {
$aProxyHosts = array(
'proxy',
'cache',
'inktomi'
);
foreach ($aProxyHosts as $proxyName) {
if (strpos($_SERVER['REMOTE_HOST'], $proxyName) !== false) {
$proxy = true;
break;
}
}
}
// Has the viewer come via an HTTP proxy?
if ($proxy) {
// Try to find the "real" IP address the viewer has come from
$aHeaders = array(
'HTTP_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_FORWARDED_FOR',
'HTTP_CLIENT_IP'
);
foreach ($aHeaders as $header) {
if (!empty($_SERVER[$header])) {
$ip = $_SERVER[$header];
break;
}
}
if (!empty($ip)) {
// The "remote IP" may be a list, ensure that
// only the last item is used in that case
$ip = explode(',', $ip);
$ip = trim($ip[count($ip) - 1]);
// If the found address is not unknown or a private network address
if (($ip != 'unknown') && (!MAX_remotehostPrivateAddress($ip))) {
// Set the "real" remote IP address, and unset
// the remote host (as it will be wrong for the
// newly found IP address) and HTTP_VIA header
// (so that we don't accidently do this twice)
$_SERVER['REMOTE_ADDR'] = $ip;
$_SERVER['REMOTE_HOST'] = '';
$_SERVER['HTTP_VIA']    = '';
}
}
}
}
}
function MAX_remotehostReverseLookup()
{
// Is the remote host name already set?
if (empty($_SERVER['REMOTE_HOST'])) {
// Should reverse lookups be performed?
if ($GLOBALS['_MAX']['CONF']['logging']['reverseLookup']) {
$_SERVER['REMOTE_HOST'] = @gethostbyaddr($_SERVER['REMOTE_ADDR']);
} else {
$_SERVER['REMOTE_HOST'] = $_SERVER['REMOTE_ADDR'];
}
}
}
function MAX_remotehostSetClientInfo()
{
if ($GLOBALS['_MAX']['CONF']['logging']['sniff'] && isset($_SERVER['HTTP_USER_AGENT'])) {
include MAX_PATH . '/lib/phpSniff/phpSniff.class.php';
$client = new phpSniff($_SERVER['HTTP_USER_AGENT']);
$GLOBALS['_MAX']['CLIENT'] = $client->_browser_info;
}
}
function MAX_remotehostSetGeoInfo()
{
if (!function_exists('parseDeliveryIniFile')) {
function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true)
{
// Set up the configuration .ini file path location
if (!$configPath) {
$configPath = MAX_PATH . '/var';
}
if ($configFile) {
$configFile = '.' . $configFile;
}
$host = getHostName();
$configFileName = $configPath . '/' . $host . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $conf;
} elseif ($configFile === '.plugin') {
// For plugins, if no configuration file is found, return the sane default values
$pluginType = basename($configPath);
$defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php';
$conf = @parse_ini_file($defaultConfig, $sections);
if ($conf !== false) {
// check for false here - it's possible file doesn't exist
return $conf;
}
echo "OpenX could not read the default configuration file for the {$pluginType} plugin";
exit(1);
}
// Check for a 'default.conf.php' file
$configFileName = $configPath . '/default' . $configFile . '.conf.php';
$conf = @parse_ini_file($configFileName, $sections);
if (isset($conf['realConfig'])) {
// added for backward compatibility - realConfig points to different config
$conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
}
if (!empty($conf)) {
return $conf;
}
// Check to ensure Max hasn't been installed
if (file_exists(MAX_PATH . '/var/INSTALLED')) {
echo "OpenX has been installed, but no configuration file was found.\n";
exit(1);
}
// Max hasn't been installed, so delivery engine can't run
echo "OpenX has not been installed yet -- please read the INSTALL.txt file.\n";
exit(1);
}
}
$aConf = $GLOBALS['_MAX']['CONF'];
$type = (!empty($aConf['geotargeting']['type'])) ? $aConf['geotargeting']['type'] : null;
if (!is_null($type) && $type != 'none') {
$functionName = 'MAX_Geo_'.$type.'_getInfo';
if (function_exists($functionName)) {
return;
}
@include(MAX_PATH . '/plugins/geotargeting/' . $type . '/' . $type . '.delivery.php');
if (function_exists($functionName)) {
$GLOBALS['_MAX']['CLIENT_GEO'] = $functionName();
}
}
}
function MAX_remotehostPrivateAddress($ip)
{
setupIncludePath();
require_once 'Net/IPv4.php';
// Define the private address networks, see
// http://rfc.net/rfc1918.html
$aPrivateNetworks = array(
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'127.0.0.0/24'
);
foreach ($aPrivateNetworks as $privateNetwork) {
if (Net_IPv4::ipInNetwork($ip, $privateNetwork)) {
return true;
}
}
return false;
}
$file = '/lib/max/Delivery/log.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
$file = '/lib/max/Dal/Delivery.php';
$GLOBALS['_MAX']['FILES'][$file] = true;
function MAX_Dal_Delivery_Include()
{
static $included;
if (isset($included)) {
return;
}
$included = true;
$conf = $GLOBALS['_MAX']['CONF'];
if (isset($conf['origin']['type']) && is_readable(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php')) {
require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php');
} else {
require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['database']['type']) . '.php');
}
}
function MAX_Delivery_log_logAdRequest($viewerId, $adId, $creativeId, $zoneId)
{
if (_viewersHostOkayToLog()) {
$conf = $GLOBALS['_MAX']['CONF'];
list($geotargeting, $zoneInfo, $userAgentInfo, $maxHttps) = _prepareLogInfo();
$table = $conf['table']['prefix'] . $conf['table']['data_raw_ad_request'];
MAX_Dal_Delivery_Include();
OA_Dal_Delivery_logAction(
$table,
$viewerId,
$adId,
$creativeId,
$zoneId,
$geotargeting,
$zoneInfo,
$userAgentInfo,
$maxHttps
);
}
}
function MAX_Delivery_log_logAdImpression($viewerId, $adId, $creativeId, $zoneId)
{
if (_viewersHostOkayToLog()) {
$conf = $GLOBALS['_MAX']['CONF'];
list($geotargeting, $zoneInfo, $userAgentInfo, $maxHttps) = _prepareLogInfo();
$table = $conf['table']['prefix'] . $conf['table']['data_raw_ad_impression'];
MAX_Dal_Delivery_Include();
OA_Dal_Delivery_logAction(
$table,
$viewerId,
$adId,
$creativeId,
$zoneId,
$geotargeting,
$zoneInfo,
$userAgentInfo,
$maxHttps
);
}
}
function MAX_Delivery_log_logAdClick($viewerId, $adId, $creativeId, $zoneId)
{
if (_viewersHostOkayToLog()) {
$conf = $GLOBALS['_MAX']['CONF'];
list($geotargeting, $zoneInfo, $userAgentInfo, $maxHttps) = _prepareLogInfo();
$table = $conf['table']['prefix'] . $conf['table']['data_raw_ad_click'];
MAX_Dal_Delivery_Include();
OA_Dal_Delivery_logAction(
$table,
$viewerId,
$adId,
$creativeId,
$zoneId,
$geotargeting,
$zoneInfo,
$userAgentInfo,
$maxHttps
);
}
}
function MAX_Delivery_log_logTrackerImpression($viewerId, $trackerId)
{
if (_viewersHostOkayToLog()) {
$conf = $GLOBALS['_MAX']['CONF'];
if (empty($conf['rawDatabase']['host'])) {
if (!empty($conf['lb']['enabled'])) {
$conf['rawDatabase']['host'] = $_SERVER['SERVER_ADDR'];
} else {
$conf['rawDatabase']['host'] = 'singleDB';
}
}
if (isset($conf['rawDatabase']['serverRawIp'])) {
$serverRawIp = $conf['rawDatabase']['serverRawIp'];
} else {
$serverRawIp = $conf['rawDatabase']['host'];
}
list($geotargeting, $zoneInfo, $userAgentInfo, $maxHttps) = _prepareLogInfo();
$table = $conf['table']['prefix'] . $conf['table']['data_raw_tracker_impression'];
MAX_Dal_Delivery_Include();
$rawTrackerImpressionId = OA_Dal_Delivery_logTracker(
$table,
$viewerId,
$trackerId,
$serverRawIp,
$geotargeting,
$zoneInfo,
$userAgentInfo,
$maxHttps
);
return array('server_raw_tracker_impression_id' => $rawTrackerImpressionId, 'server_raw_ip' => $serverRawIp);
}
return false;
}
function MAX_Delivery_log_logVariableValues($variables, $trackerId, $serverRawTrackerImpressionId, $serverRawIp)
{
$conf = $GLOBALS['_MAX']['CONF'];
// Get the variable information, including the Variable ID
foreach ($variables as $variable) {
if (isset($_GET[$variable['name']])) {
$value = $_GET[$variable['name']];
// Do not save variable if empty or if the JS engine set it to "undefined"
if (!strlen($value) || $value == 'undefined') {
unset($variables[$variable['variable_id']]);
continue;
}
// Sanitize by datatype
switch ($variable['type']) {
case 'int':
case 'numeric':
// Strip useless chars, such as currency
$value = preg_replace('/[^0-9.]/', '', $value);
$value = floatval($value); break;
case 'date':
if (!empty($value)) {
$value = date('Y-m-d H:i:s', strtotime($value));
} else {
$value = '';
}
break;
}
} else {
// Do not save anything if the variable isn't set
unset($variables[$variable['variable_id']]);
continue;
}
$variables[$variable['variable_id']]['value'] = $value;
}
if (count($variables)) {
MAX_Dal_Delivery_Include();
OA_Dal_Delivery_logVariableValues($variables, $serverRawTrackerImpressionId, $serverRawIp);
}
}
function _viewersHostOkayToLog()
{
$conf = $GLOBALS['_MAX']['CONF'];
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
// Check the user-agent against the list of known browsers (if set)
if (!empty($conf['logging']['enforceUserAgents'])) {
$aKnownBrowsers = explode('|', strtolower($conf['logging']['enforceUserAgents']));
$allowed = false;
foreach ($aKnownBrowsers as $browser) {
if (strpos($agent, $browser) !== false) {
$allowed = true;
break;
}
}
if (!$allowed) return false;
}
// Check the user-agent against the list of known bots (if set)
if (!empty($conf['logging']['ignoreUserAgents'])) {
$aKnownBots = explode('|', strtolower($conf['logging']['ignoreUserAgents']));
foreach ($aKnownBots as $bot) {
if (strpos($agent, $bot) !== false) {
return false;
}
}
}
// Check if this IP address has been blocked
if (!empty($conf['logging']['ignoreHosts'])) {
$hosts = str_replace(',', '|', $conf['logging']['ignoreHosts']);
$hosts = '#('.$hosts.')$#i';
// Format the hosts to ignore in a PCRE format
$hosts = str_replace('.', '\.', $hosts);
$hosts = str_replace('*', '[^.]+', $hosts);
// Check if the viewer's IP address is in the ignore list
if (preg_match($hosts, $_SERVER['REMOTE_ADDR'])) {
return false;
}
// Check if the viewer's hostname is in the ignore list
if (preg_match($hosts, $_SERVER['REMOTE_HOST'])) {
return false;
}
}
return true;
}
function _prepareLogInfo()
{
$conf = $GLOBALS['_MAX']['CONF'];
// Get the Geotargeting information, if required
$geotargeting = array();
if (isset($conf['geotargeting']['saveStats']) && $conf['geotargeting']['saveStats'] && !empty($GLOBALS['_MAX']['CLIENT_GEO'])) {
$geotargeting = $GLOBALS['_MAX']['CLIENT_GEO'];
} else {
$geotargeting = array(
'country_code' => null,
'region' => null,
'city' => null,
'postal_code' => null,
'latitude' => null,
'longitude' => null,
'dma_code' => null,
'area_code' => null,
'organisation' => null,
'netspeed' => null,
'continent' => null);
}
// Get the zone location information, if possible
$zoneInfo = array();
if (!empty($_GET['loc'])) {
$zoneInfo = parse_url($_GET['loc']);
} elseif (!empty($_SERVER['HTTP_REFERER'])) {
$zoneInfo = parse_url($_SERVER['HTTP_REFERER']);
}
if (!empty($zoneInfo['scheme'])) {
$zoneInfo['scheme'] = ($zoneInfo['scheme'] == 'https') ? 1 : 0;
}
if (isset($GLOBALS['_MAX']['CHANNELS'])) {
$zoneInfo['channel_ids'] = $GLOBALS['_MAX']['CHANNELS'];
}
// Get the operating system and browser type, if required
if ($conf['logging']['sniff'] && isset($GLOBALS['_MAX']['CLIENT'])) {
$userAgentInfo = array(
'os' => $GLOBALS['_MAX']['CLIENT']['os'],
'long_name' => $GLOBALS['_MAX']['CLIENT']['long_name'],
'browser'   => $GLOBALS['_MAX']['CLIENT']['browser'],
);
} else {
$userAgentInfo = array();
}
// Determine if the access to OpenX was made using HTTPS
$maxHttps = 0;  // https is false
if ($_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) {
$maxHttps = 1;   // https is true
}
if (!isset($zoneInfo['channel_ids'])) $zoneInfo['channel_ids'] = null;
if (!isset($zoneInfo['scheme'])) $zoneInfo['scheme'] = null;
if (!isset($zoneInfo['host'])) $zoneInfo['host'] = null;
if (!isset($zoneInfo['path'])) $zoneInfo['path'] = null;
if (!isset($zoneInfo['query'])) $zoneInfo['query'] = null;
if (!isset($userAgentInfo['os'])) $userAgentInfo['os'] = '';
if (!isset($userAgentInfo['browser'])) $userAgentInfo['browser'] = '';
return array($geotargeting, $zoneInfo, $userAgentInfo, $maxHttps);
}
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 _setLimitations($type, $index, $aItems, $aCaps)
{
// Ensure that the capping values for this item are set
MAX_Delivery_log_ensureIntegerSet($aCaps['block'], $index);
MAX_Delivery_log_ensureIntegerSet($aCaps['capping'], $index);
MAX_Delivery_log_ensureIntegerSet($aCaps['session_capping'], $index);
// Set the capping cookies
MAX_Delivery_cookie_setCapping(
$type,
$aItems[$index],
$aCaps['block'][$index],
$aCaps['capping'][$index],
$aCaps['session_capping'][$index]
);
}
function MAX_commonGetDeliveryUrl($file = null)
{
$conf = $GLOBALS['_MAX']['CONF'];
if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == $conf['openads']['sslPort']) {
$url = MAX_commonConstructSecureDeliveryUrl($file);
} else {
$url = MAX_commonConstructDeliveryUrl($file);
}
return $url;
}
function MAX_commonConstructDeliveryUrl($file)
{
$conf = $GLOBALS['_MAX']['CONF'];
return 'http://' . $conf['webpath']['delivery'] . '/' . $file;
}
function MAX_commonConstructSecureDeliveryUrl($file)
{
$conf = $GLOBALS['_MAX']['CONF'];
if ($conf['openads']['sslPort'] != 443) {
// Fix the delivery host
$path = preg_replace('#/#', ':' . $conf['openads']['sslPort'] . '/', $conf['webpath']['deliverySSL']);
} 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_commonSetNoCacheHeaders()
{
MAX_header('Pragma: no-cache');
MAX_header('Cache-Control: private, max-age=0, no-cache');
MAX_header('Date: '.gmdate('D, d M Y H:i:s', MAX_commonGetTimeNow()).' GMT');
}
function MAX_commonAddslashesRecursive($a)
{
if (is_array($a)) {
reset($a);
while (list($k,$v) = each($a)) {
$a[$k] = MAX_commonAddslashesRecursive($v);
}
reset ($a);
return ($a);
} else {
return is_null($a) ? null : addslashes($a);
}
}
function MAX_commonRegisterGlobalsArray($args = array())
{
static $magic_quotes_gpc;
if (!isset($magic_quotes_gpc)) {
$magic_quotes_gpc = ini_get('magic_quotes_gpc');
}
$found = false;
foreach($args as $key) {
if (isset($_GET[$key])) {
$value = $_GET[$key];
$found = true;
}
if (isset($_POST[$key])) {
$value = $_POST[$key];
$found = true;
}
if ($found) {
if (!$magic_quotes_gpc) {
if (!is_array($value)) {
$value = addslashes($value);
} else {
$value = MAX_commonAddslashesRecursive($value);
}
}
$GLOBALS[$key] = $value;
$found = false;
}
}
}
function MAX_commonDeriveSource($source)
{
return MAX_commonEncrypt(trim(urldecode($source)));
}
function MAX_commonEncrypt($string)
{
$convert = '';
if (isset($string) && substr($string,1,4) != 'obfs' && $GLOBALS['_MAX']['CONF']['delivery']['obfuscate']) {
$strLen = strlen($string);
for ($i=0; $i < $strLen; $i++) {
$dec = ord(substr($string,$i,1));
if (strlen($dec) == 2) {
$dec = 0 . $dec;
}
$dec = 324 - $dec;
$convert .= $dec;
}
$convert = '{obfs:' . $convert . '}';
return ($convert);
} else {
return $string;
}
}
function MAX_commonDecrypt($string)
{
$conf = $GLOBALS['_MAX']['CONF'];
$convert = '';
if (isset($string) && substr($string,1,4) == 'obfs' && $conf['delivery']['obfuscate']) {
$strLen = strlen($string);
for ($i=6; $i < $strLen-1; $i = $i+3) {
$dec = substr($string,$i,3);
$dec = 324 - $dec;
$dec = chr($dec);
$convert .= $dec;
}
return ($convert);
} else {
return($string);
}
}
function MAX_commonInitVariables()
{
MAX_commonRegisterGlobalsArray(array('context', 'source', 'target', 'withText', 'withtext', 'ct0', 'what', 'loc', 'referer', 'zoneid', 'campaignid', 'bannerid', 'clientid'));
global $context, $source, $target, $withText, $withtext, $ct0, $what, $loc, $referer, $zoneid, $campaignid, $bannerid, $clientid;
if (!isset($context)) 	$context = array();
if (!isset($source))	$source = '';
if (!isset($target)) 	$target = '_blank';
if (isset($withText) && !isset($withtext))  $withtext = $withText;
if (!isset($withtext)) 	$withtext = '';
if (!isset($ct0)) 	$ct0 = '';
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('/^(.+):(.+)$/', $what, $matches)) {
switch ($matches[1]) {
case 'zoneid':
case 'zone':        $zoneid     = $matches[2]; break;
case 'bannerid':    $bannerid   = $matches[2]; break;
case 'campaignid':  $campaignid = $matches[2]; break;
case 'clientid':    $clientid   = $matches[2]; break;
}
}
// 2.0 backwards compatibility - clientid parameter was used to fetch a campaign
if (!isset($clientid))  $clientid = '';
$source = MAX_commonDeriveSource($source);
if (!empty($loc)) {
$loc = stripslashes($loc);
} elseif (!empty($_SERVER['HTTP_REFERER'])) {
$loc = $_SERVER['HTTP_REFERER'];
} else {
$loc = '';
}
// Set real referer - Only valid if passed in
if (!empty($referer)) {
$_SERVER['HTTP_REFERER'] = stripslashes($referer);
} else {
if (isset($_SERVER['HTTP_REFERER'])) unset($_SERVER['HTTP_REFERER']);
}
$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']);
}
function MAX_commonDisplay1x1()
{
MAX_header('Content-Type: image/gif');
MAX_header('Content-Length: 43');
// 1 x 1 gif
echo base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==');
}
function MAX_commonGetTimeNow()
{
static $now;
if (!isset($now)) {
$now = $GLOBALS['_MAX']['NOW'] = time();
}
return $now;
}
function MAX_setcookie($name, $value, $expire, $path, $domain)
{
if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xml-rpc') {
if (!isset($GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'])) {
$GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'] = array();
}
$GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'][$name] = array($value, $expire);
} else {
@setcookie($name, $value, $expire, $path, $domain);
}
}
function MAX_header($value)
{
header($value);
}
function MAX_redirect($url)
{
header('Location: '.$url);
MAX_sendStatusCode(302);
}
function MAX_sendStatusCode($iStatusCode) {
$aConf = $GLOBALS['_MAX']['CONF'];
$arr = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '[Unused]',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
if (isset($arr[$iStatusCode])) {
$text = $iStatusCode . ' ' . $arr[$iStatusCode];
// Using header('Status: foo') with CGI sapis appears to be deprecated but PHP-CGI seems to discard
// the Reason-Phrase and some webservers do not add a default one. Some bad spiders do not cope
// with that, that's why we added the cgiForceStatusHeader confgiuration directive. If enabled
// with CGI sapis, OpenX will use a "Status: NNN Reason" header, which seems to fix the behaviour
// on the tested webserver (Apache 1.3, running php-cgi)
if (!empty($aConf['delivery']['cgiForceStatusHeader']) && strpos(php_sapi_name(), 'cgi') !== 0) {
header('Status: ' . $text);
} else {
header($_SERVER["SERVER_PROTOCOL"] .' ' . $text);
}
}
}
function MAX_commonPackContext($context = array())
{
//return base64_encode(serialize($context));
$include = array();
$exclude = array();
foreach ($context as $idx => $value) {
reset($value);
list($key, $value) = each($value);
list($item,$id) = explode(':', $value);
switch ($item) {
case 'campaignid':  $value = 'c:' . $id; break;
case 'bannerid':    $value = 'b:' . $id; break;
case 'companionid': $value = 'p:' . $id; break;
}
switch ($key) {
case '!=': $exclude[] = $value; break;
case '==': $include[] = $value; break;
}
}
return base64_encode(implode('#', $exclude) . '|' . implode('#', $include));
}
function MAX_commonUnpackContext($context = '')
{
//return unserialize(base64_decode($context));
list($exclude,$include) = explode('|', base64_decode($context));
return array_merge(_convertContextArray('!=', explode('#', $exclude)), _convertContextArray('==', explode('#', $include)));
}
function _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 'b': $unpacked[] = array($key => 'bannerid:' .  $id); break;
case 'p': $unpacked[] = array($key => 'companionid:'.$id); break;
}
}
return $unpacked;
}
$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(
'path'   => MAX_PATH.'/var/cache/',
'prefix' => 'deliverycache_',
'host'   => getHostName(),
'expiry' => $GLOBALS['_MAX']['CONF']['delivery']['cacheExpire']
);
if (!empty($GLOBALS['_MAX']['CONF']['delivery']['cachePath'])) {
$GLOBALS['OA_Delivery_Cache']['path'] = trim($GLOBALS['_MAX']['CONF']['delivery']['cachePath']).'/';
}
function OA_Delivery_Cache_fetch($name, $isHash = false, $expiryTime = null)
{
$filename = OA_Delivery_Cache_buildFileName($name, $isHash);
$cache_complete = false;
$cache_contents = '';
// We are assuming that most of the time cache will exists
$ok = @include($filename);
if ($ok && $cache_complete == true) {
// Make sure that the cache name matches
if ($cache_name != $name) {
return false;
}
// The method used to implement cache expiry imposes two cache writes if the cache is
// expired and the database is available, but avoid the need to check for file existence
// and modification time.
if ($expiryTime === null) {
$expiryTime = $GLOBALS['OA_Delivery_Cache']['expiry'];
}
$now = MAX_commonGetTimeNow();
if (    (isset($cache_time) && $cache_time + $expiryTime < $now)
|| (isset($cache_expire) && $cache_expire < $now) )
{
// Update expiry, needed to enable permanent caching if needed
OA_Delivery_Cache_store($name, $cache_contents, $isHash);
return false;
}
return $cache_contents;
}
return false;
}
function OA_Delivery_Cache_store($name, $cache, $isHash = false, $expireAt = null)
{
if ($cache === OA_DELIVERY_CACHE_FUNCTION_ERROR) {
// Don't store the result to enable permanent caching
return false;
}
if (!is_writable($GLOBALS['OA_Delivery_Cache']['path'])) {
return false;
}
$filename = OA_Delivery_Cache_buildFileName($name, $isHash);
$cache_literal  = "<"."?php\n\n";
$cache_literal .= "$"."cache_contents   = ".var_export($cache, true).";\n\n";
$cache_literal .= "$"."cache_name       = '".addcslashes($name, "\\'")."';\n";
$cache_literal .= "$"."cache_time       = ".MAX_commonGetTimeNow().";\n";
if ($expireAt !== null) {
$cache_literal .= "$"."cache_expire     = ".$expireAt.";\n";
}
$cache_literal .= "$"."cache_complete   = true;\n\n";
$cache_literal .= "?".">";
// Write cache to a temp file, then rename it, overwritng the old cache
// On *nix systems this should guarantee atomicity
$tmp_filename = tempnam($GLOBALS['OA_Delivery_Cache']['path'], $GLOBALS['OA_Delivery_Cache']['prefix'].'tmp_');
if ($fp = @fopen($tmp_filename, 'wb')) {
@fwrite ($fp, $cache_literal, strlen($cache_literal));
@fclose ($fp);
if (!@rename($tmp_filename, $filename)) {
// On some systems rename() doesn't overwrite destination
@unlink($filename);
if (!@rename($tmp_filename, $filename)) {
// Make sure that no temporary file is left over
// if the destination is not writable
@unlink($tmp_filename);
}
}
return true;
}
return false;
}
function OA_Delivery_Cache_store_return($name, $cache, $isHash = false, $expireAt = null)
{
if (OA_Delivery_Cache_store($name, $cache, $isHash, $expireAt)) {
return $cache;
}
return OA_Delivery_Cache_fetch($name, $isHash);
}
function OA_Delivery_Cache_delete($name = '')
{
if ($name != '') {
$filename = OA_Delivery_Cache_buildFileName($name);
if (file_exists($filename)) {
@unlink ($filename);
return true;
}
} else {
$cachedir = @opendir($GLOBALS['OA_Delivery_Cache']['path']);
while (false !== ($filename = @readdir($cachedir))) {
if (preg_match("#^{$GLOBALS['OA_Delivery_Cache']['prefix']}[0-9A-F]{32}.php$#i", $filename))
@unlink ($filename);
}
@closedir($cachedir);
return true;
}
return false;
}
function OA_Delivery_Cache_info()
{
$result = array();
$cachedir = @opendir($GLOBALS['OA_Delivery_Cache']['path']);
while (false !== ($filename = @readdir($cachedir))) {
if (preg_match("#^{$GLOBALS['OA_Delivery_Cache']['prefix']}[0-9A-F]{32}.php$#i", $filename)) {
$cache_complete = false;
$cache_contents = '';
$cache_name     = '';
$ok = @include($filename);
if ($ok && $cache_complete == true) {
$result[$cache_name] = strlen(serialize($cache_contents));
}
}
}
@closedir($cachedir);
return $result;
}
function OA_Delivery_Cache_buildFileName($name, $isHash = false)
{
if(!$isHash) {
// If not a hash yet
$name = md5($name);
}
return $GLOBALS['OA_Delivery_Cache']['path'].$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_cacheGetZoneLinkedAds($zoneId, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aRows = OA_Dal_Delivery_getZoneLinkedAds($zoneId);
$aRows = OA_Delivery_Cache_store_return($sName, $aRows);
}
return $aRows;
}
function MAX_cacheGetZoneInfo($zoneId, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aRows = OA_Dal_Delivery_getZoneInfo($zoneId);
$aRows = OA_Delivery_Cache_store_return($sName, $aRows);
}
return $aRows;
}
function MAX_cacheGetLinkedAds($search, $campaignid, $laspart, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart);
if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aAds = OA_Dal_Delivery_getLinkedAds($search, $campaignid, $laspart);
$aAds = OA_Delivery_Cache_store_return($sName, $aAds);
}
return $aAds;
}
function MAX_cacheGetCreative($filename, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $filename);
if (!$cached || ($aCreative = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aCreative = OA_Dal_Delivery_getCreative($filename);
$aCreative['contents'] = addslashes(serialize($aCreative['contents']));
$aCreative = OA_Delivery_Cache_store_return($sName, $aCreative);
}
$aCreative['contents'] = unserialize(stripslashes($aCreative['contents']));
return $aCreative;
}
function MAX_cacheGetTracker($trackerid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aTracker = OA_Dal_Delivery_getTracker($trackerid);
$aTracker = OA_Delivery_Cache_store_return($sName, $aTracker, $isHash = true);
}
return $aTracker;
}
function MAX_cacheGetTrackerVariables($trackerid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
if (!$cached || ($aVariables = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$aVariables = OA_Dal_Delivery_getTrackerVariables($trackerid);
$aVariables = OA_Delivery_Cache_store_return($sName, $aVariables);
}
return $aVariables;
}
function MAX_cacheCheckIfMaintenanceShouldRun($cached = true)
{
// Default delay is 5 minutes
$interval    = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] * 60;
$delay       = !empty($GLOBALS['_MAX']['CONF']['maintenance']['autoMaintenanceDelay']) ?
$GLOBALS['_MAX']['CONF']['maintenance']['autoMaintenanceDelay'] * 60 :
300;
// Auto-maintenance is disabled if the delay is lower than the OI
if ($delay <= 0 || $delay >= $interval) {
return false;
}
$now         = MAX_commonGetTimeNow();
$today       = strtotime(date('Y-m-d'), $now);
$nextRunTime = $today + (floor(($now - $today) / $interval) + 1) * $interval + $delay;
// Adding the delay could shift the time to the next operation interval,
// make sure to fix it in case it happens
if ($nextRunTime - $now > $interval) {
$nextRunTime -= $interval;
}
$cName  = OA_Delivery_Cache_getName(__FUNCTION__);
if (!$cached || ($lastRunTime = OA_Delivery_Cache_fetch($cName)) === false) {
MAX_Dal_Delivery_Include();
$lastRunTime = OA_Dal_Delivery_getMaintenanceInfo();
// Cache until the next operation interval if scheduled maintenance was run
// during the delay
if ($lastRunTime >= $nextRunTime - $delay) {
$nextRunTime += $interval;
}
OA_Delivery_Cache_store($cName, $lastRunTime, false, $nextRunTime);
}
return $lastRunTime < $nextRunTime - $interval;
}
function MAX_cacheGetChannelLimitations($channelid, $cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__, $channelid);
if (!$cached || ($limitations = OA_Delivery_Cache_fetch($sName)) === false) {
MAX_Dal_Delivery_Include();
$limitations = OA_Dal_Delivery_getChannelLimitations($channelid);
$limitations = OA_Delivery_Cache_store_return($sName, $limitations);
}
return $limitations;
}
function MAX_cacheGetGoogleJavaScript($cached = true)
{
$sName  = OA_Delivery_Cache_getName(__FUNCTION__);
if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) {
include MAX_PATH . '/lib/max/Delivery/google.php';
$output = MAX_googleGetJavaScript();
$output = OA_Delivery_Cache_store_return($sName, $output);
}
return $output;
}
// Set the viewer's remote information used in logging
// and delivery limitation evaluation
MAX_remotehostProxyLookup();
MAX_remotehostReverseLookup();
MAX_remotehostSetClientInfo();
MAX_remotehostSetGeoInfo();
// Set common delivery parameters in the global scope
MAX_commonInitVariables();
// Unpack the packed capping cookies
MAX_cookieUnpackCapping();
$MAX_PLUGINS_AD_PLUGIN_NAME = 'MAX_type';
if(!isset($_GET[$MAX_PLUGINS_AD_PLUGIN_NAME])) {
echo $MAX_PLUGINS_AD_PLUGIN_NAME . ' is not specified';
exit(1);
}
$tagName = $_GET[$MAX_PLUGINS_AD_PLUGIN_NAME];
$tagFileName = MAX_PATH . '/plugins/invocationTags/'.$tagName.'/'.$tagName.'.delivery.php';
if(!file_exists($tagFileName)) {
echo 'Invocation plugin delivery file "' . $tagFileName . '" doesn\'t exists';
exit(1);
}
// include plugin specific delivery script
// (we are not using MAX_Plugin interface for it because it has to be as fast as possible)
include $tagFileName;


?>