/www/delivery/ck.php

https://github.com/creath/revive-adserver · PHP · 3277 lines · 3224 code · 30 blank · 23 comment · 560 complexity · 5d81693d63e8c4f0ca566526653d46d1 MD5 · raw file

  1. <?php
  2. /*
  3. +---------------------------------------------------------------------------+
  4. | Revive Adserver |
  5. | http://www.revive-adserver.com |
  6. | |
  7. | Copyright: See the COPYRIGHT.txt file. |
  8. | License: GPLv2 or later, see the LICENSE.txt file. |
  9. +---------------------------------------------------------------------------+
  10. */
  11. /**
  12. * This is autogenerated file which contains all files from the "delivery_dev"
  13. * folder of Revive Adserver merged into a single output file. On systems
  14. * without a PHP opcode cache that is configured to not regularly check for
  15. * file updates, this autogenerated file can dramatically improve the
  16. * performance of Revive Adserver's delivery engine.
  17. *
  18. * !!!Warning!!!
  19. *
  20. * Do not edit this file. If you need to do any changes to any delivery file,
  21. * check out the source code from GitHub; make the necessary changes to the
  22. * file(s) in the "delivery_dev" folder; and regenerate the delivery files
  23. * using the script located in the "scripts/delivery" directory.
  24. */
  25. function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true)
  26. {
  27. if (!$configPath) {
  28. $configPath = MAX_PATH . '/var';
  29. }
  30. if ($configFile) {
  31. $configFile = '.' . $configFile;
  32. }
  33. $host = OX_getHostName();
  34. $configFileName = $configPath . '/' . $host . $configFile . '.conf.php';
  35. $conf = @parse_ini_file($configFileName, $sections);
  36. if (isset($conf['realConfig'])) {
  37. $realconf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
  38. $conf = mergeConfigFiles($realconf, $conf);
  39. }
  40. if (!empty($conf)) {
  41. return $conf;
  42. } elseif ($configFile === '.plugin') {
  43. $pluginType = basename($configPath);
  44. $defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php';
  45. $conf = @parse_ini_file($defaultConfig, $sections);
  46. if ($conf !== false) {
  47. return $conf;
  48. }
  49. echo "Revive Adserver could not read the default configuration file for the {$pluginType} plugin";
  50. exit(1);
  51. }
  52. $configFileName = $configPath . '/default' . $configFile . '.conf.php';
  53. $conf = @parse_ini_file($configFileName, $sections);
  54. if (isset($conf['realConfig'])) {
  55. $conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections);
  56. }
  57. if (!empty($conf)) {
  58. return $conf;
  59. }
  60. if (file_exists(MAX_PATH . '/var/INSTALLED')) {
  61. echo "Revive Adserver has been installed, but no configuration file was found.\n";
  62. exit(1);
  63. }
  64. echo "Revive Adserver has not been installed yet -- please read the INSTALL.txt file.\n";
  65. exit(1);
  66. }
  67. if (!function_exists('mergeConfigFiles'))
  68. {
  69. function mergeConfigFiles($realConfig, $fakeConfig)
  70. {
  71. foreach ($fakeConfig as $key => $value) {
  72. if (is_array($value)) {
  73. if (!isset($realConfig[$key])) {
  74. $realConfig[$key] = array();
  75. }
  76. $realConfig[$key] = mergeConfigFiles($realConfig[$key], $value);
  77. } else {
  78. if (isset($realConfig[$key]) && is_array($realConfig[$key])) {
  79. $realConfig[$key][0] = $value;
  80. } else {
  81. if (isset($realConfig) && !is_array($realConfig)) {
  82. $temp = $realConfig;
  83. $realConfig = array();
  84. $realConfig[0] = $temp;
  85. }
  86. $realConfig[$key] = $value;
  87. }
  88. }
  89. }
  90. unset($realConfig['realConfig']);
  91. return $realConfig;
  92. }
  93. }
  94. function OX_getMinimumRequiredMemory($limit = null)
  95. {
  96. if ($limit == 'maintenance') {
  97. return 134217728; }
  98. return 134217728; }
  99. function OX_getMemoryLimitSizeInBytes() {
  100. $phpMemoryLimit = ini_get('memory_limit');
  101. if (empty($phpMemoryLimit) || $phpMemoryLimit == -1) {
  102. return -1;
  103. }
  104. $aSize = array(
  105. 'G' => 1073741824,
  106. 'M' => 1048576,
  107. 'K' => 1024
  108. );
  109. $phpMemoryLimitInBytes = $phpMemoryLimit;
  110. foreach($aSize as $type => $multiplier) {
  111. $pos = strpos($phpMemoryLimit, $type);
  112. if (!$pos) {
  113. $pos = strpos($phpMemoryLimit, strtolower($type));
  114. }
  115. if ($pos) {
  116. $phpMemoryLimitInBytes = substr($phpMemoryLimit, 0, $pos) * $multiplier;
  117. }
  118. }
  119. return $phpMemoryLimitInBytes;
  120. }
  121. function OX_checkMemoryCanBeSet()
  122. {
  123. $phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes();
  124. if ($phpMemoryLimitInBytes == -1) {
  125. return true;
  126. }
  127. OX_increaseMemoryLimit($phpMemoryLimitInBytes + 1);
  128. $newPhpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes();
  129. $memoryCanBeSet = ($phpMemoryLimitInBytes != $newPhpMemoryLimitInBytes);
  130. @ini_set('memory_limit', $phpMemoryLimitInBytes);
  131. return $memoryCanBeSet;
  132. }
  133. function OX_increaseMemoryLimit($setMemory) {
  134. $phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes();
  135. if ($phpMemoryLimitInBytes == -1) {
  136. return true;
  137. }
  138. if ($setMemory > $phpMemoryLimitInBytes) {
  139. if (@ini_set('memory_limit', $setMemory) === false) {
  140. return false;
  141. }
  142. }
  143. return true;
  144. }
  145. function setupConfigVariables()
  146. {
  147. $GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'] = '|';
  148. $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'] = '__';
  149. $GLOBALS['_MAX']['thread_id'] = uniqid();
  150. $GLOBALS['_MAX']['SSL_REQUEST'] = false;
  151. if (
  152. (!empty($_SERVER['SERVER_PORT']) && !empty($GLOBALS['_MAX']['CONF']['openads']['sslPort']) && ($_SERVER['SERVER_PORT'] == $GLOBALS['_MAX']['CONF']['openads']['sslPort'])) ||
  153. (!empty($_SERVER['HTTPS']) && ((strtolower($_SERVER['HTTPS']) == 'on') || ($_SERVER['HTTPS'] == 1))) ||
  154. (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) ||
  155. (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && (strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on')) ||
  156. (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && (strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) == 'on')) ||
  157. (!empty($_SERVER['FRONT-END-HTTPS']) && (strtolower($_SERVER['FRONT-END-HTTPS']) == 'on'))
  158. ) {
  159. $GLOBALS['_MAX']['SSL_REQUEST'] = true;
  160. }
  161. $GLOBALS['_MAX']['MAX_RAND'] = isset($GLOBALS['_MAX']['CONF']['priority']['randmax']) ?
  162. $GLOBALS['_MAX']['CONF']['priority']['randmax'] : 2147483647;
  163. list($micro_seconds, $seconds) = explode(" ", microtime());
  164. $GLOBALS['_MAX']['NOW_ms'] = round(1000 *((float)$micro_seconds + (float)$seconds));
  165. if (substr($_SERVER['SCRIPT_NAME'], -11) != 'install.php') {
  166. $GLOBALS['serverTimezone'] = date_default_timezone_get();
  167. OA_setTimeZoneUTC();
  168. }
  169. }
  170. function setupServerVariables()
  171. {
  172. if (empty($_SERVER['REQUEST_URI'])) {
  173. $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
  174. if (!empty($_SERVER['QUERY_STRING'])) {
  175. $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
  176. }
  177. }
  178. }
  179. function setupDeliveryConfigVariables()
  180. {
  181. if (!defined('MAX_PATH')) {
  182. define('MAX_PATH', dirname(__FILE__).'/../..');
  183. }
  184. if (!defined('OX_PATH')) {
  185. define('OX_PATH', MAX_PATH);
  186. }
  187. if (!defined('RV_PATH')) {
  188. define('RV_PATH', MAX_PATH);
  189. }
  190. if (!defined('LIB_PATH')) {
  191. define('LIB_PATH', MAX_PATH. DIRECTORY_SEPARATOR. 'lib'. DIRECTORY_SEPARATOR. 'OX');
  192. }
  193. if ( !(isset($GLOBALS['_MAX']['CONF']))) {
  194. $GLOBALS['_MAX']['CONF'] = parseDeliveryIniFile();
  195. }
  196. setupConfigVariables();
  197. }
  198. function OA_setTimeZone($timezone)
  199. {
  200. date_default_timezone_set($timezone);
  201. $GLOBALS['_DATE_TIMEZONE_DEFAULT'] = $timezone;
  202. }
  203. function OA_setTimeZoneUTC()
  204. {
  205. OA_setTimeZone('UTC');
  206. }
  207. function OA_setTimeZoneLocal()
  208. {
  209. $tz = !empty($GLOBALS['_MAX']['PREF']['timezone']) ? $GLOBALS['_MAX']['PREF']['timezone'] : 'GMT';
  210. OA_setTimeZone($tz);
  211. }
  212. function OX_getHostName()
  213. {
  214. if (!empty($_SERVER['HTTP_HOST'])) {
  215. $host = explode(':', $_SERVER['HTTP_HOST']);
  216. $host = $host[0];
  217. } else if (!empty($_SERVER['SERVER_NAME'])) {
  218. $host = explode(':', $_SERVER['SERVER_NAME']);
  219. $host = $host[0];
  220. }
  221. return $host;
  222. }
  223. function OX_getHostNameWithPort()
  224. {
  225. if (!empty($_SERVER['HTTP_HOST'])) {
  226. $host = $_SERVER['HTTP_HOST'];
  227. } else if (!empty($_SERVER['SERVER_NAME'])) {
  228. $host = $_SERVER['SERVER_NAME'];
  229. }
  230. return $host;
  231. }
  232. function setupIncludePath()
  233. {
  234. static $checkIfAlreadySet;
  235. if (isset($checkIfAlreadySet)) {
  236. return;
  237. }
  238. $checkIfAlreadySet = true;
  239. $oxPearPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'pear';
  240. $oxZendPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib';
  241. set_include_path($oxPearPath . PATH_SEPARATOR . $oxZendPath . PATH_SEPARATOR . get_include_path());
  242. }
  243. OX_increaseMemoryLimit(OX_getMinimumRequiredMemory());
  244. if (!defined('E_DEPRECATED')) {
  245. define('E_DEPRECATED', 0);
  246. }
  247. setupServerVariables();
  248. setupDeliveryConfigVariables();
  249. $conf = $GLOBALS['_MAX']['CONF'];
  250. $GLOBALS['_OA']['invocationType'] = array_search(basename($_SERVER['SCRIPT_FILENAME']), $conf['file']);
  251. if (!empty($conf['debug']['production'])) {
  252. error_reporting(E_ALL & ~(E_NOTICE | E_WARNING | E_DEPRECATED | E_STRICT));
  253. } else {
  254. error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT));
  255. }
  256. $file = '/lib/max/Delivery/common.php';
  257. $GLOBALS['_MAX']['FILES'][$file] = true;
  258. $file = '/lib/max/Delivery/cookie.php';
  259. $GLOBALS['_MAX']['FILES'][$file] = true;
  260. $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array();
  261. if (!is_callable('MAX_cookieSet')) {
  262. if (!empty($conf['cookie']['plugin']) && is_readable(MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php")) {
  263. include MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php";
  264. } else {
  265. function MAX_cookieSet($name, $value, $expire, $path = '/', $domain = null) { return MAX_cookieClientCookieSet($name, $value, $expire, $path, $domain); }
  266. function MAX_cookieUnset($name) { return MAX_cookieClientCookieUnset($name); }
  267. function MAX_cookieFlush() { return MAX_cookieClientCookieFlush(); }
  268. function MAX_cookieLoad() { return true; }
  269. }
  270. }
  271. function MAX_cookieAdd($name, $value, $expire = 0)
  272. {
  273. if (!isset($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
  274. $GLOBALS['_MAX']['COOKIE']['CACHE'] = array();
  275. }
  276. $GLOBALS['_MAX']['COOKIE']['CACHE'][$name] = array($value, $expire);
  277. }
  278. function MAX_cookieSetViewerIdAndRedirect($viewerId) {
  279. $aConf = $GLOBALS['_MAX']['CONF'];
  280. MAX_cookieAdd($aConf['var']['viewerId'], $viewerId, _getTimeYearFromNow());
  281. MAX_cookieFlush();
  282. if ($GLOBALS['_MAX']['SSL_REQUEST']) {
  283. $url = MAX_commonConstructSecureDeliveryUrl(basename($_SERVER['SCRIPT_NAME']));
  284. } else {
  285. $url = MAX_commonConstructDeliveryUrl(basename($_SERVER['SCRIPT_NAME']));
  286. }
  287. $url .= "?{$aConf['var']['cookieTest']}=1&" . $_SERVER['QUERY_STRING'];
  288. MAX_header("Location: {$url}");
  289. exit;
  290. }
  291. function _getTimeThirtyDaysFromNow()
  292. {
  293. return MAX_commonGetTimeNow() + 2592000; }
  294. function _getTimeYearFromNow()
  295. {
  296. return MAX_commonGetTimeNow() + 31536000; }
  297. function _getTimeYearAgo()
  298. {
  299. return MAX_commonGetTimeNow() - 31536000; }
  300. function MAX_cookieUnpackCapping()
  301. {
  302. $conf = $GLOBALS['_MAX']['CONF'];
  303. $cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
  304. if (!is_array($cookieNames))
  305. return;
  306. foreach ($cookieNames as $cookieName) {
  307. if (!empty($_COOKIE[$cookieName])) {
  308. if (!is_array($_COOKIE[$cookieName])) {
  309. $output = array();
  310. $data = explode('_', $_COOKIE[$cookieName]);
  311. foreach ($data as $pair) {
  312. list($name, $value) = explode('.', $pair);
  313. $output[$name] = $value;
  314. }
  315. $_COOKIE[$cookieName] = $output;
  316. }
  317. }
  318. if (!empty($_COOKIE['_' . $cookieName]) && is_array($_COOKIE['_' . $cookieName])) {
  319. foreach ($_COOKIE['_' . $cookieName] as $adId => $cookie) {
  320. if (_isBlockCookie($cookieName)) {
  321. $_COOKIE[$cookieName][$adId] = $cookie;
  322. } else {
  323. if (isset($_COOKIE[$cookieName][$adId])) {
  324. $_COOKIE[$cookieName][$adId] += $cookie;
  325. } else {
  326. $_COOKIE[$cookieName][$adId] = $cookie;
  327. }
  328. }
  329. MAX_cookieUnset("_{$cookieName}[{$adId}]");
  330. }
  331. }
  332. }
  333. }
  334. function _isBlockCookie($cookieName)
  335. {
  336. return in_array($cookieName, array(
  337. $GLOBALS['_MAX']['CONF']['var']['blockAd'],
  338. $GLOBALS['_MAX']['CONF']['var']['blockCampaign'],
  339. $GLOBALS['_MAX']['CONF']['var']['blockZone'],
  340. $GLOBALS['_MAX']['CONF']['var']['lastView'],
  341. $GLOBALS['_MAX']['CONF']['var']['lastClick'],
  342. $GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'],
  343. ));
  344. }
  345. function MAX_cookieGetUniqueViewerId($create = true)
  346. {
  347. static $uniqueViewerId = null;
  348. if(!is_null($uniqueViewerId)) {
  349. return $uniqueViewerId;
  350. }
  351. $conf = $GLOBALS['_MAX']['CONF'];
  352. if (isset($_COOKIE[$conf['var']['viewerId']])) {
  353. $uniqueViewerId = $_COOKIE[$conf['var']['viewerId']];
  354. } elseif ($create) {
  355. $uniqueViewerId = md5(uniqid('', true)); $GLOBALS['_MAX']['COOKIE']['newViewerId'] = true;
  356. }
  357. return $uniqueViewerId;
  358. }
  359. function MAX_cookieGetCookielessViewerID()
  360. {
  361. if (empty($_SERVER['REMOTE_ADDR']) || empty($_SERVER['HTTP_USER_AGENT'])) {
  362. return '';
  363. }
  364. $cookiePrefix = $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'];
  365. return $cookiePrefix . substr(md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']), 0, 32-(strlen($cookiePrefix)));
  366. }
  367. function MAX_Delivery_cookie_cappingOnRequest()
  368. {
  369. if (isset($GLOBALS['_OA']['invocationType']) &&
  370. ($GLOBALS['_OA']['invocationType'] == 'xmlrpc' || $GLOBALS['_OA']['invocationType'] == 'view')
  371. ) {
  372. return true;
  373. }
  374. return !$GLOBALS['_MAX']['CONF']['logging']['adImpressions'];
  375. }
  376. function MAX_Delivery_cookie_setCapping($type, $id, $block = 0, $cap = 0, $sessionCap = 0)
  377. {
  378. $conf = $GLOBALS['_MAX']['CONF'];
  379. $setBlock = false;
  380. if ($cap > 0) {
  381. $expire = MAX_commonGetTimeNow() + $conf['cookie']['permCookieSeconds'];
  382. if (!isset($_COOKIE[$conf['var']['cap' . $type]][$id])) {
  383. $value = 1;
  384. $setBlock = true;
  385. } else if ($_COOKIE[$conf['var']['cap' . $type]][$id] >= $cap) {
  386. $value = -$_COOKIE[$conf['var']['cap' . $type]][$id]+1;
  387. $setBlock = true;
  388. } else {
  389. $value = 1;
  390. }
  391. MAX_cookieAdd("_{$conf['var']['cap' . $type]}[{$id}]", $value, $expire);
  392. }
  393. if ($sessionCap > 0) {
  394. if (!isset($_COOKIE[$conf['var']['sessionCap' . $type]][$id])) {
  395. $value = 1;
  396. $setBlock = true;
  397. } else if ($_COOKIE[$conf['var']['sessionCap' . $type]][$id] >= $sessionCap) {
  398. $value = -$_COOKIE[$conf['var']['sessionCap' . $type]][$id]+1;
  399. $setBlock = true;
  400. } else {
  401. $value = 1;
  402. }
  403. MAX_cookieAdd("_{$conf['var']['sessionCap' . $type]}[{$id}]", $value, 0);
  404. }
  405. if ($block > 0 || $setBlock) {
  406. MAX_cookieAdd("_{$conf['var']['block' . $type]}[{$id}]", MAX_commonGetTimeNow(), _getTimeThirtyDaysFromNow());
  407. }
  408. }
  409. function MAX_cookieClientCookieSet($name, $value, $expire, $path = '/', $domain = null)
  410. {
  411. if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xmlrpc') {
  412. if (!isset($GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'])) {
  413. $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'] = array();
  414. }
  415. $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'][$name] = array($value, $expire);
  416. } else {
  417. @setcookie($name, $value, $expire, $path, $domain);
  418. }
  419. }
  420. function MAX_cookieClientCookieUnset($name)
  421. {
  422. $conf = $GLOBALS['_MAX']['CONF'];
  423. $domain = (!empty($conf['cookie']['domain'])) ? $conf['cookie']['domain'] : null;
  424. MAX_cookieSet($name, false, _getTimeYearAgo(), '/', $domain);
  425. MAX_cookieSet(str_replace('_', '%5F', urlencode($name)), false, _getTimeYearAgo(), '/', $domain);
  426. }
  427. function MAX_cookieClientCookieFlush()
  428. {
  429. $conf = $GLOBALS['_MAX']['CONF'];
  430. MAX_cookieSendP3PHeaders();
  431. if (!empty($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
  432. reset($GLOBALS['_MAX']['COOKIE']['CACHE']);
  433. while (list($name,$v) = each ($GLOBALS['_MAX']['COOKIE']['CACHE'])) {
  434. list($value, $expire) = $v;
  435. if ($name == $conf['var']['viewerId']) {
  436. MAX_cookieClientCookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
  437. } else {
  438. MAX_cookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
  439. }
  440. }
  441. $GLOBALS['_MAX']['COOKIE']['CACHE'] = array();
  442. }
  443. $cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'];
  444. if (!is_array($cookieNames))
  445. return;
  446. $maxCookieSize = !empty($conf['cookie']['maxCookieSize']) ? $conf['cookie']['maxCookieSize'] : 2048;
  447. foreach ($cookieNames as $cookieName) {
  448. if (empty($_COOKIE["_{$cookieName}"])) {
  449. continue;
  450. }
  451. switch ($cookieName) {
  452. case $conf['var']['blockAd'] :
  453. case $conf['var']['blockCampaign'] :
  454. case $conf['var']['blockZone'] : $expire = _getTimeThirtyDaysFromNow(); break;
  455. case $conf['var']['lastClick'] :
  456. case $conf['var']['lastView'] :
  457. case $conf['var']['capAd'] :
  458. case $conf['var']['capCampaign'] :
  459. case $conf['var']['capZone'] : $expire = _getTimeYearFromNow(); break;
  460. case $conf['var']['sessionCapCampaign'] :
  461. case $conf['var']['sessionCapAd'] :
  462. case $conf['var']['sessionCapZone'] : $expire = 0; break;
  463. }
  464. if (!empty($_COOKIE[$cookieName]) && is_array($_COOKIE[$cookieName])) {
  465. $data = array();
  466. foreach ($_COOKIE[$cookieName] as $adId => $value) {
  467. $data[] = "{$adId}.{$value}";
  468. }
  469. while (strlen(implode('_', $data)) > $maxCookieSize) {
  470. $data = array_slice($data, 1);
  471. }
  472. MAX_cookieSet($cookieName, implode('_', $data), $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null));
  473. }
  474. }
  475. }
  476. function MAX_cookieSendP3PHeaders() {
  477. if ($GLOBALS['_MAX']['CONF']['p3p']['policies']) {
  478. MAX_header("P3P: ". _generateP3PHeader());
  479. }
  480. }
  481. function _generateP3PHeader()
  482. {
  483. $conf = $GLOBALS['_MAX']['CONF'];
  484. $p3p_header = '';
  485. if ($conf['p3p']['policies']) {
  486. if ($conf['p3p']['policyLocation'] != '') {
  487. $p3p_header .= " policyref=\"".$conf['p3p']['policyLocation']."\"";
  488. }
  489. if ($conf['p3p']['policyLocation'] != '' && $conf['p3p']['compactPolicy'] != '') {
  490. $p3p_header .= ", ";
  491. }
  492. if ($conf['p3p']['compactPolicy'] != '') {
  493. $p3p_header .= " CP=\"".$conf['p3p']['compactPolicy']."\"";
  494. }
  495. }
  496. return $p3p_header;
  497. }
  498. $file = '/lib/max/Delivery/remotehost.php';
  499. $GLOBALS['_MAX']['FILES'][$file] = true;
  500. function MAX_remotehostSetInfo($run = false)
  501. {
  502. if (empty($GLOBALS['_OA']['invocationType']) || $run || ($GLOBALS['_OA']['invocationType'] != 'xmlrpc')) {
  503. MAX_remotehostProxyLookup();
  504. MAX_remotehostReverseLookup();
  505. MAX_remotehostSetGeoInfo();
  506. }
  507. }
  508. function MAX_remotehostProxyLookup()
  509. {
  510. $conf = $GLOBALS['_MAX']['CONF'];
  511. if ($conf['logging']['proxyLookup']) {
  512. OX_Delivery_logMessage('checking remote host proxy', 7);
  513. $proxy = false;
  514. if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  515. $proxy = true;
  516. } elseif (!empty($_SERVER['REMOTE_HOST'])) {
  517. $aProxyHosts = array(
  518. 'proxy',
  519. 'cache',
  520. 'inktomi'
  521. );
  522. foreach ($aProxyHosts as $proxyName) {
  523. if (strpos($_SERVER['REMOTE_HOST'], $proxyName) !== false) {
  524. $proxy = true;
  525. break;
  526. }
  527. }
  528. }
  529. if ($proxy) {
  530. OX_Delivery_logMessage('proxy detected', 7);
  531. $aHeaders = array(
  532. 'HTTP_FORWARDED',
  533. 'HTTP_FORWARDED_FOR',
  534. 'HTTP_X_FORWARDED',
  535. 'HTTP_X_FORWARDED_FOR',
  536. 'HTTP_CLIENT_IP'
  537. );
  538. foreach ($aHeaders as $header) {
  539. if (!empty($_SERVER[$header])) {
  540. $ip = $_SERVER[$header];
  541. break;
  542. }
  543. }
  544. if (!empty($ip)) {
  545. foreach (explode(',', $ip) as $ip) {
  546. $ip = trim($ip);
  547. if (($ip != 'unknown') && (!MAX_remotehostPrivateAddress($ip))) {
  548. $_SERVER['REMOTE_ADDR'] = $ip;
  549. $_SERVER['REMOTE_HOST'] = '';
  550. $_SERVER['HTTP_VIA'] = '';
  551. OX_Delivery_logMessage('real address set to '.$ip, 7);
  552. break;
  553. }
  554. }
  555. }
  556. }
  557. }
  558. }
  559. function MAX_remotehostReverseLookup()
  560. {
  561. if (empty($_SERVER['REMOTE_HOST'])) {
  562. if ($GLOBALS['_MAX']['CONF']['logging']['reverseLookup']) {
  563. $_SERVER['REMOTE_HOST'] = @gethostbyaddr($_SERVER['REMOTE_ADDR']);
  564. } else {
  565. $_SERVER['REMOTE_HOST'] = $_SERVER['REMOTE_ADDR'];
  566. }
  567. }
  568. }
  569. function MAX_remotehostSetGeoInfo()
  570. {
  571. if (!function_exists('parseDeliveryIniFile')) {
  572. }
  573. $aConf = $GLOBALS['_MAX']['CONF'];
  574. $type = (!empty($aConf['geotargeting']['type'])) ? $aConf['geotargeting']['type'] : null;
  575. if (!is_null($type) && $type != 'none') {
  576. $aComponent = explode(':', $aConf['geotargeting']['type']);
  577. if (!empty($aComponent[1]) && (!empty($aConf['pluginGroupComponents'][$aComponent[1]]))) {
  578. $GLOBALS['_MAX']['CLIENT_GEO'] = OX_Delivery_Common_hook('getGeoInfo', array(), $type);
  579. }
  580. }
  581. }
  582. function MAX_remotehostPrivateAddress($ip)
  583. {
  584. $ip = ip2long($ip);
  585. if (!$ip) return false;
  586. return (MAX_remotehostMatchSubnet($ip, '10.0.0.0', 8) ||
  587. MAX_remotehostMatchSubnet($ip, '172.16.0.0', 12) ||
  588. MAX_remotehostMatchSubnet($ip, '192.168.0.0', 16) ||
  589. MAX_remotehostMatchSubnet($ip, '127.0.0.0', 8)
  590. );
  591. }
  592. function MAX_remotehostMatchSubnet($ip, $net, $mask)
  593. {
  594. $net = ip2long($net);
  595. if (!is_integer($ip)) {
  596. $ip = ip2long($ip);
  597. }
  598. if (!$ip || !$net) {
  599. return false;
  600. }
  601. if (is_integer($mask)) {
  602. if ($mask > 32 || $mask <= 0)
  603. return false;
  604. elseif ($mask == 32)
  605. $mask = ~0;
  606. else
  607. $mask = ~((1 << (32 - $mask)) - 1);
  608. } elseif (!($mask = ip2long($mask))) {
  609. return false;
  610. }
  611. return ($ip & $mask) == ($net & $mask) ? true : false;
  612. }
  613. $file = '/lib/max/Delivery/log.php';
  614. $GLOBALS['_MAX']['FILES'][$file] = true;
  615. $file = '/lib/max/Dal/Delivery.php';
  616. $GLOBALS['_MAX']['FILES'][$file] = true;
  617. $file = '/lib/OA/Dal/Delivery.php';
  618. $GLOBALS['_MAX']['FILES'][$file] = true;
  619. function OA_Dal_Delivery_getAccountTZs()
  620. {
  621. $aConf = $GLOBALS['_MAX']['CONF'];
  622. $query = "
  623. SELECT
  624. value
  625. FROM
  626. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['application_variable'])."
  627. WHERE
  628. name = 'admin_account_id'
  629. ";
  630. $res = OA_Dal_Delivery_query($query);
  631. if (is_resource($res) && OA_Dal_Delivery_numRows($res)) {
  632. $adminAccountId = (int)OA_Dal_Delivery_result($res, 0, 0);
  633. } else {
  634. $adminAccountId = false;
  635. }
  636. $query = "
  637. SELECT
  638. a.account_id AS account_id,
  639. apa.value AS timezone
  640. FROM
  641. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a JOIN
  642. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa ON (apa.account_id = a.account_id) JOIN
  643. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['preferences'])." AS p ON (p.preference_id = apa.preference_id)
  644. WHERE
  645. a.account_type IN ('ADMIN', 'MANAGER') AND
  646. p.preference_name = 'timezone'
  647. ";
  648. $res = OA_Dal_Delivery_query($query);
  649. $aResult = array(
  650. 'adminAccountId' => $adminAccountId,
  651. 'aAccounts' => array()
  652. );
  653. if (is_resource($res)) {
  654. while ($row = OA_Dal_Delivery_fetchAssoc($res)) {
  655. $accountId = (int)$row['account_id'];
  656. if ($accountId === $adminAccountId) {
  657. $aResult['default'] = $row['timezone'];
  658. } else {
  659. $aResult['aAccounts'][$accountId] = $row['timezone'];
  660. }
  661. }
  662. }
  663. if (empty($aResult['default'])) {
  664. $aResult['default'] = 'UTC';
  665. }
  666. return $aResult;
  667. }
  668. function OA_Dal_Delivery_getZoneInfo($zoneid) {
  669. $aConf = $GLOBALS['_MAX']['CONF'];
  670. $zoneid = (int)$zoneid;
  671. $query = "
  672. SELECT
  673. z.zoneid AS zone_id,
  674. z.zonename AS name,
  675. z.delivery AS type,
  676. z.description AS description,
  677. z.width AS width,
  678. z.height AS height,
  679. z.chain AS chain,
  680. z.prepend AS prepend,
  681. z.append AS append,
  682. z.appendtype AS appendtype,
  683. z.forceappend AS forceappend,
  684. z.inventory_forecast_type AS inventory_forecast_type,
  685. z.block AS block_zone,
  686. z.capping AS cap_zone,
  687. z.session_capping AS session_cap_zone,
  688. z.show_capped_no_cookie AS show_capped_no_cookie_zone,
  689. z.ext_adselection AS ext_adselection,
  690. z.affiliateid AS publisher_id,
  691. a.agencyid AS agency_id,
  692. a.account_id AS trafficker_account_id,
  693. m.account_id AS manager_account_id
  694. FROM
  695. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['zones'])." AS z,
  696. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['affiliates'])." AS a,
  697. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['agency'])." AS m
  698. WHERE
  699. z.zoneid = {$zoneid}
  700. AND
  701. z.affiliateid = a.affiliateid
  702. AND
  703. a.agencyid = m.agencyid";
  704. $rZoneInfo = OA_Dal_Delivery_query($query);
  705. if (!is_resource($rZoneInfo)) {
  706. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
  707. }
  708. $aZoneInfo = OA_Dal_Delivery_fetchAssoc($rZoneInfo);
  709. if (empty($aZoneInfo)) {
  710. return false;
  711. }
  712. $query = "
  713. SELECT
  714. p.preference_id AS preference_id,
  715. p.preference_name AS preference_name
  716. FROM
  717. {$aConf['table']['prefix']}{$aConf['table']['preferences']} AS p
  718. WHERE
  719. p.preference_name = 'default_banner_image_url'
  720. OR
  721. p.preference_name = 'default_banner_destination_url'";
  722. $rPreferenceInfo = OA_Dal_Delivery_query($query);
  723. if (!is_resource($rPreferenceInfo)) {
  724. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
  725. }
  726. if (OA_Dal_Delivery_numRows($rPreferenceInfo) != 2) {
  727. return $aZoneInfo;
  728. }
  729. $aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo);
  730. $variableName = $aPreferenceInfo['preference_name'] . '_id';
  731. $$variableName = $aPreferenceInfo['preference_id'];
  732. $aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo);
  733. $variableName = $aPreferenceInfo['preference_name'] . '_id';
  734. $$variableName = $aPreferenceInfo['preference_id'];
  735. $query = "
  736. SELECT
  737. 'default_banner_destination_url_trafficker' AS item,
  738. apa.value AS value
  739. FROM
  740. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
  741. WHERE
  742. apa.account_id = {$aZoneInfo['trafficker_account_id']}
  743. AND
  744. apa.preference_id = $default_banner_destination_url_id
  745. UNION
  746. SELECT
  747. 'default_banner_destination_url_manager' AS item,
  748. apa.value AS value
  749. FROM
  750. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
  751. WHERE
  752. apa.account_id = {$aZoneInfo['manager_account_id']}
  753. AND
  754. apa.preference_id = $default_banner_destination_url_id
  755. UNION
  756. SELECT
  757. 'default_banner_image_url_trafficker' AS item,
  758. apa.value AS value
  759. FROM
  760. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
  761. WHERE
  762. apa.account_id = {$aZoneInfo['trafficker_account_id']}
  763. AND
  764. apa.preference_id = $default_banner_image_url_id
  765. UNION
  766. SELECT
  767. 'default_banner_image_url_manager' AS item,
  768. apa.value AS value
  769. FROM
  770. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa
  771. WHERE
  772. apa.account_id = {$aZoneInfo['manager_account_id']}
  773. AND
  774. apa.preference_id = $default_banner_image_url_id
  775. UNION
  776. SELECT
  777. 'default_banner_image_url_admin' AS item,
  778. apa.value AS value
  779. FROM
  780. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa,
  781. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a
  782. WHERE
  783. apa.account_id = a.account_id
  784. AND
  785. a.account_type = 'ADMIN'
  786. AND
  787. apa.preference_id = $default_banner_image_url_id
  788. UNION
  789. SELECT
  790. 'default_banner_destination_url_admin' AS item,
  791. apa.value AS value
  792. FROM
  793. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa,
  794. ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a
  795. WHERE
  796. apa.account_id = a.account_id
  797. AND
  798. a.account_type = 'ADMIN'
  799. AND
  800. apa.preference_id = $default_banner_destination_url_id";
  801. $rDefaultBannerInfo = OA_Dal_Delivery_query($query);
  802. if (!is_resource($rDefaultBannerInfo)) {
  803. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
  804. }
  805. if (OA_Dal_Delivery_numRows($rDefaultBannerInfo) == 0) {
  806. if ($aConf['defaultBanner']['imageUrl'] != '') {
  807. $aZoneInfo['default_banner_image_url'] = $aConf['defaultBanner']['imageUrl'];
  808. }
  809. return $aZoneInfo;
  810. }
  811. $aDefaultImageURLs = array();
  812. $aDefaultDestinationURLs = array();
  813. while ($aRow = OA_Dal_Delivery_fetchAssoc($rDefaultBannerInfo)) {
  814. if (stristr($aRow['item'], 'default_banner_image_url')) {
  815. $aDefaultImageURLs[$aRow['item']] = $aRow['value'];
  816. } else if (stristr($aRow['item'], 'default_banner_destination_url')) {
  817. $aDefaultDestinationURLs[$aRow['item']] = $aRow['value'];
  818. }
  819. }
  820. $aTypes = array(
  821. 0 => 'admin',
  822. 1 => 'manager',
  823. 2 => 'trafficker'
  824. );
  825. foreach ($aTypes as $type) {
  826. if (isset($aDefaultImageURLs['default_banner_image_url_' . $type])) {
  827. $aZoneInfo['default_banner_image_url'] = $aDefaultImageURLs['default_banner_image_url_' . $type];
  828. }
  829. if (isset($aDefaultDestinationURLs['default_banner_destination_url_' . $type])) {
  830. $aZoneInfo['default_banner_destination_url'] = $aDefaultDestinationURLs['default_banner_destination_url_' . $type];
  831. }
  832. }
  833. return $aZoneInfo;
  834. }
  835. function OA_Dal_Delivery_getPublisherZones($publisherid) {
  836. $conf = $GLOBALS['_MAX']['CONF'];
  837. $publisherid = (int)$publisherid;
  838. $rZones = OA_Dal_Delivery_query("
  839. SELECT
  840. z.zoneid AS zone_id,
  841. z.affiliateid AS publisher_id,
  842. z.zonename AS name,
  843. z.delivery AS type
  844. FROM
  845. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z
  846. WHERE
  847. z.affiliateid={$publisherid}
  848. ");
  849. if (!is_resource($rZones)) {
  850. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false;
  851. }
  852. while ($aZone = OA_Dal_Delivery_fetchAssoc($rZones)) {
  853. $aZones[$aZone['zone_id']] = $aZone;
  854. }
  855. return ($aZones);
  856. }
  857. function OA_Dal_Delivery_getZoneLinkedAds($zoneid) {
  858. $conf = $GLOBALS['_MAX']['CONF'];
  859. $zoneid = (int)$zoneid;
  860. $aRows = OA_Dal_Delivery_getZoneInfo($zoneid);
  861. $aRows['xAds'] = array();
  862. $aRows['ads'] = array();
  863. $aRows['lAds'] = array();
  864. $aRows['eAds'] = array();
  865. $aRows['count_active'] = 0;
  866. $aRows['zone_companion'] = false;
  867. $aRows['count_active'] = 0;
  868. $totals = array(
  869. 'xAds' => 0,
  870. 'ads' => 0,
  871. 'lAds' => 0
  872. );
  873. $query = "
  874. SELECT
  875. d.bannerid AS ad_id,
  876. d.campaignid AS placement_id,
  877. d.status AS status,
  878. d.description AS name,
  879. d.storagetype AS type,
  880. d.contenttype AS contenttype,
  881. d.pluginversion AS pluginversion,
  882. d.filename AS filename,
  883. d.imageurl AS imageurl,
  884. d.htmltemplate AS htmltemplate,
  885. d.htmlcache AS htmlcache,
  886. d.width AS width,
  887. d.height AS height,
  888. d.weight AS weight,
  889. d.seq AS seq,
  890. d.target AS target,
  891. d.url AS url,
  892. d.alt AS alt,
  893. d.statustext AS statustext,
  894. d.bannertext AS bannertext,
  895. d.adserver AS adserver,
  896. d.block AS block_ad,
  897. d.capping AS cap_ad,
  898. d.session_capping AS session_cap_ad,
  899. d.compiledlimitation AS compiledlimitation,
  900. d.acl_plugins AS acl_plugins,
  901. d.prepend AS prepend,
  902. d.append AS append,
  903. d.bannertype AS bannertype,
  904. d.alt_filename AS alt_filename,
  905. d.alt_imageurl AS alt_imageurl,
  906. d.alt_contenttype AS alt_contenttype,
  907. d.parameters AS parameters,
  908. d.transparent AS transparent,
  909. d.ext_bannertype AS ext_bannertype,
  910. az.priority AS priority,
  911. az.priority_factor AS priority_factor,
  912. az.to_be_delivered AS to_be_delivered,
  913. c.campaignid AS campaign_id,
  914. c.priority AS campaign_priority,
  915. c.weight AS campaign_weight,
  916. c.companion AS campaign_companion,
  917. c.block AS block_campaign,
  918. c.capping AS cap_campaign,
  919. c.session_capping AS session_cap_campaign,
  920. c.show_capped_no_cookie AS show_capped_no_cookie,
  921. c.clientid AS client_id,
  922. c.expire_time AS expire_time,
  923. c.revenue_type AS revenue_type,
  924. c.ecpm_enabled AS ecpm_enabled,
  925. c.ecpm AS ecpm,
  926. c.clickwindow AS clickwindow,
  927. c.viewwindow AS viewwindow,
  928. m.advertiser_limitation AS advertiser_limitation,
  929. a.account_id AS account_id,
  930. z.affiliateid AS affiliate_id,
  931. a.agencyid as agency_id
  932. FROM
  933. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN
  934. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN
  935. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z ON (az.zone_id = z.zoneid) JOIN
  936. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN
  937. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m ON (m.clientid = c.clientid) LEFT JOIN
  938. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = m.agencyid)
  939. WHERE
  940. az.zone_id = {$zoneid}
  941. AND
  942. d.status <= 0
  943. AND
  944. c.status <= 0
  945. ";
  946. $rAds = OA_Dal_Delivery_query($query);
  947. if (!is_resource($rAds)) {
  948. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  949. }
  950. $aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives();
  951. while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
  952. $aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null;
  953. if ($aAd['campaign_priority'] == -1) {
  954. $aRows['xAds'][$aAd['ad_id']] = $aAd;
  955. $aRows['count_active']++;
  956. } elseif ($aAd['campaign_priority'] == 0) {
  957. $aRows['lAds'][$aAd['ad_id']] = $aAd;
  958. $aRows['count_active']++;
  959. } elseif ($aAd['campaign_priority'] == -2) {
  960. $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  961. $aRows['count_active']++;
  962. } else {
  963. $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  964. $aRows['count_active']++;
  965. }
  966. if ($aAd['campaign_companion'] == 1) {
  967. $aRows['zone_companion'][] = $aAd['placement_id'];
  968. }
  969. }
  970. if (is_array($aRows['xAds'])) {
  971. $totals['xAds'] = _setPriorityFromWeights($aRows['xAds']);
  972. }
  973. if (is_array($aRows['ads'])) {
  974. $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads']);
  975. }
  976. if (is_array($aRows['eAds'])) {
  977. $totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']);
  978. }
  979. if (is_array($aRows['lAds'])) {
  980. $totals['lAds'] = _setPriorityFromWeights($aRows['lAds']);
  981. }
  982. $aRows['priority'] = $totals;
  983. return $aRows;
  984. }
  985. function OA_Dal_Delivery_getZoneLinkedAdInfos($zoneid) {
  986. $conf = $GLOBALS['_MAX']['CONF'];
  987. $zoneid = (int)$zoneid;
  988. $aRows['xAds'] = array();
  989. $aRows['ads'] = array();
  990. $aRows['lAds'] = array();
  991. $aRows['eAds'] = array();
  992. $aRows['zone_companion'] = false;
  993. $aRows['count_active'] = 0;
  994. $query =
  995. "SELECT "
  996. ."d.bannerid AS ad_id, " ."d.campaignid AS placement_id, " ."d.status AS status, " ."d.width AS width, "
  997. ."d.ext_bannertype AS ext_bannertype, "
  998. ."d.height AS height, "
  999. ."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, "
  1000. ."c.clientid AS client_id, " ."c.expire_time AS expire_time, "
  1001. ."c.revenue_type AS revenue_type, "
  1002. ."c.ecpm_enabled AS ecpm_enabled, "
  1003. ."c.ecpm AS ecpm, "
  1004. ."ct.status AS tracker_status, "
  1005. .OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe, "
  1006. .OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe "
  1007. ."FROM "
  1008. .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN "
  1009. .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN "
  1010. .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN "
  1011. .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = c.campaignid) "
  1012. ."WHERE "
  1013. ."az.zone_id = {$zoneid} "
  1014. ."AND "
  1015. ."d.status <= 0 "
  1016. ."AND "
  1017. ."c.status <= 0 ";
  1018. $rAds = OA_Dal_Delivery_query($query);
  1019. if (!is_resource($rAds)) {
  1020. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1021. }
  1022. while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
  1023. if ($aAd['campaign_priority'] == -1) {
  1024. $aRows['xAds'][$aAd['ad_id']] = $aAd;
  1025. $aRows['count_active']++;
  1026. } elseif ($aAd['campaign_priority'] == 0) {
  1027. $aRows['lAds'][$aAd['ad_id']] = $aAd;
  1028. $aRows['count_active']++;
  1029. } elseif ($aAd['campaign_priority'] == -2) {
  1030. $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  1031. $aRows['count_active']++;
  1032. } else {
  1033. $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  1034. $aRows['count_active']++;
  1035. }
  1036. if ($aAd['campaign_companion'] == 1) {
  1037. $aRows['zone_companion'][] = $aAd['placement_id']; }
  1038. }
  1039. return $aRows;
  1040. }
  1041. function OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid = '', $lastpart = true) {
  1042. $conf = $GLOBALS['_MAX']['CONF'];
  1043. $campaignid = (int)$campaignid;
  1044. if ($campaignid > 0) {
  1045. $precondition = " AND d.campaignid = '".$campaignid."' ";
  1046. } else {
  1047. $precondition = '';
  1048. }
  1049. $aRows['xAds'] = array();
  1050. $aRows['ads'] = array();
  1051. $aRows['lAds'] = array();
  1052. $aRows['count_active'] = 0;
  1053. $aRows['zone_companion'] = false;
  1054. $aRows['count_active'] = 0;
  1055. $totals = array(
  1056. 'xAds' => 0,
  1057. 'ads' => 0,
  1058. 'lAds' => 0
  1059. );
  1060. $query = OA_Dal_Delivery_buildAdInfoQuery($search, $lastpart, $precondition);
  1061. $rAds = OA_Dal_Delivery_query($query);
  1062. if (!is_resource($rAds)) {
  1063. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1064. }
  1065. while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
  1066. if ($aAd['campaign_priority'] == -1) {
  1067. $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
  1068. $aRows['xAds'][$aAd['ad_id']] = $aAd;
  1069. $aRows['count_active']++;
  1070. $totals['xAds'] += $aAd['priority'];
  1071. } elseif ($aAd['campaign_priority'] == 0) {
  1072. $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
  1073. $aRows['lAds'][$aAd['ad_id']] = $aAd;
  1074. $aRows['count_active']++;
  1075. $totals['lAds'] += $aAd['priority'];
  1076. } elseif ($aAd['campaign_priority'] == -2) {
  1077. $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  1078. $aRows['count_active']++;
  1079. } else {
  1080. $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  1081. $aRows['count_active']++;
  1082. }
  1083. }
  1084. return $aRows;
  1085. }
  1086. function OA_Dal_Delivery_getLinkedAds($search, $campaignid = '', $lastpart = true) {
  1087. $conf = $GLOBALS['_MAX']['CONF'];
  1088. $campaignid = (int)$campaignid;
  1089. if ($campaignid > 0) {
  1090. $precondition = " AND d.campaignid = '".$campaignid."' ";
  1091. } else {
  1092. $precondition = '';
  1093. }
  1094. $aRows['xAds'] = array();
  1095. $aRows['ads'] = array();
  1096. $aRows['lAds'] = array();
  1097. $aRows['count_active'] = 0;
  1098. $aRows['zone_companion'] = false;
  1099. $aRows['count_active'] = 0;
  1100. $totals = array(
  1101. 'xAds' => 0,
  1102. 'ads' => 0,
  1103. 'lAds' => 0
  1104. );
  1105. $query = OA_Dal_Delivery_buildQuery($search, $lastpart, $precondition);
  1106. $rAds = OA_Dal_Delivery_query($query);
  1107. if (!is_resource($rAds)) {
  1108. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1109. }
  1110. $aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives();
  1111. while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) {
  1112. $aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null;
  1113. if ($aAd['campaign_priority'] == -1) {
  1114. $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
  1115. $aRows['xAds'][$aAd['ad_id']] = $aAd;
  1116. $aRows['count_active']++;
  1117. $totals['xAds'] += $aAd['priority'];
  1118. } elseif ($aAd['campaign_priority'] == 0) {
  1119. $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight'];
  1120. $aRows['lAds'][$aAd['ad_id']] = $aAd;
  1121. $aRows['count_active']++;
  1122. $totals['lAds'] += $aAd['priority'];
  1123. } elseif ($aAd['campaign_priority'] == -2) {
  1124. $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  1125. $aRows['count_active']++;
  1126. } else {
  1127. $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd;
  1128. $aRows['count_active']++;
  1129. }
  1130. }
  1131. if (isset($aRows['xAds']) && is_array($aRows['xAds'])) {
  1132. $totals['xAds'] = _setPriorityFromWeights($aRows['xAds']);
  1133. }
  1134. if (isset($aRows['ads']) && is_array($aRows['ads'])) {
  1135. if (isset($aRows['lAds']) && is_array($aRows['lAds']) && count($aRows['lAds']) > 0) {
  1136. $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], true);
  1137. } else {
  1138. $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], false);
  1139. }
  1140. }
  1141. if (is_array($aRows['eAds'])) {
  1142. $totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']);
  1143. }
  1144. if (isset($aRows['lAds']) && is_array($aRows['lAds'])) {
  1145. $totals['lAds'] = _setPriorityFromWeights($aRows['lAds']);
  1146. }
  1147. $aRows['priority'] = $totals;
  1148. return $aRows;
  1149. }
  1150. function OA_Dal_Delivery_getAd($ad_id) {
  1151. $conf = $GLOBALS['_MAX']['CONF'];
  1152. $ad_id = (int)$ad_id;
  1153. $query = "
  1154. SELECT
  1155. d.bannerid AS ad_id,
  1156. d.campaignid AS placement_id,
  1157. d.status AS status,
  1158. d.description AS name,
  1159. d.storagetype AS type,
  1160. d.contenttype AS contenttype,
  1161. d.pluginversion AS pluginversion,
  1162. d.filename AS filename,
  1163. d.imageurl AS imageurl,
  1164. d.htmltemplate AS htmltemplate,
  1165. d.htmlcache AS htmlcache,
  1166. d.width AS width,
  1167. d.height AS height,
  1168. d.weight AS weight,
  1169. d.seq AS seq,
  1170. d.target AS target,
  1171. d.url AS url,
  1172. d.alt AS alt,
  1173. d.statustext AS statustext,
  1174. d.bannertext AS bannertext,
  1175. d.adserver AS adserver,
  1176. d.block AS block_ad,
  1177. d.capping AS cap_ad,
  1178. d.session_capping AS session_cap_ad,
  1179. d.compiledlimitation AS compiledlimitation,
  1180. d.acl_plugins AS acl_plugins,
  1181. d.prepend AS prepend,
  1182. d.append AS append,
  1183. d.bannertype AS bannertype,
  1184. d.alt_filename AS alt_filename,
  1185. d.alt_imageurl AS alt_imageurl,
  1186. d.alt_contenttype AS alt_contenttype,
  1187. d.parameters AS parameters,
  1188. d.transparent AS transparent,
  1189. d.ext_bannertype AS ext_bannertype,
  1190. c.campaignid AS campaign_id,
  1191. c.block AS block_campaign,
  1192. c.capping AS cap_campaign,
  1193. c.session_capping AS session_cap_campaign,
  1194. c.show_capped_no_cookie AS show_capped_no_cookie,
  1195. m.clientid AS client_id,
  1196. c.clickwindow AS clickwindow,
  1197. c.viewwindow AS viewwindow,
  1198. m.advertiser_limitation AS advertiser_limitation,
  1199. m.agencyid AS agency_id
  1200. FROM
  1201. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d,
  1202. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c,
  1203. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m
  1204. WHERE
  1205. d.bannerid={$ad_id}
  1206. AND
  1207. d.campaignid = c.campaignid
  1208. AND
  1209. m.clientid = c.clientid
  1210. ";
  1211. $rAd = OA_Dal_Delivery_query($query);
  1212. if (!is_resource($rAd)) {
  1213. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1214. } else {
  1215. return (OA_Dal_Delivery_fetchAssoc($rAd));
  1216. }
  1217. }
  1218. function OA_Dal_Delivery_getChannelLimitations($channelid) {
  1219. $conf = $GLOBALS['_MAX']['CONF'];
  1220. $channelid = (int)$channelid;
  1221. $rLimitation = OA_Dal_Delivery_query("
  1222. SELECT
  1223. acl_plugins,compiledlimitation
  1224. FROM
  1225. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['channel'])."
  1226. WHERE
  1227. channelid={$channelid}");
  1228. if (!is_resource($rLimitation)) {
  1229. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1230. }
  1231. $limitations = OA_Dal_Delivery_fetchAssoc($rLimitation);
  1232. return $limitations;
  1233. }
  1234. function OA_Dal_Delivery_getCreative($filename)
  1235. {
  1236. $conf = $GLOBALS['_MAX']['CONF'];
  1237. $rCreative = OA_Dal_Delivery_query("
  1238. SELECT
  1239. contents,
  1240. t_stamp
  1241. FROM
  1242. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['images'])."
  1243. WHERE
  1244. filename = '".OX_escapeString($filename)."'
  1245. ");
  1246. if (!is_resource($rCreative)) {
  1247. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1248. } else {
  1249. $aResult = OA_Dal_Delivery_fetchAssoc($rCreative);
  1250. $aResult['contents'] = OX_unescapeBlob($aResult['contents']);
  1251. $aResult['t_stamp'] = strtotime($aResult['t_stamp'] . ' GMT');
  1252. return ($aResult);
  1253. }
  1254. }
  1255. function OA_Dal_Delivery_getTracker($trackerid)
  1256. {
  1257. $conf = $GLOBALS['_MAX']['CONF'];
  1258. $trackerid = (int)$trackerid;
  1259. $rTracker = OA_Dal_Delivery_query("
  1260. SELECT
  1261. t.clientid AS advertiser_id,
  1262. t.trackerid AS tracker_id,
  1263. t.trackername AS name,
  1264. t.variablemethod AS variablemethod,
  1265. t.description AS description,
  1266. t.viewwindow AS viewwindow,
  1267. t.clickwindow AS clickwindow,
  1268. t.blockwindow AS blockwindow,
  1269. t.appendcode AS appendcode
  1270. FROM
  1271. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['trackers'])." AS t
  1272. WHERE
  1273. t.trackerid={$trackerid}
  1274. ");
  1275. if (!is_resource($rTracker)) {
  1276. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1277. } else {
  1278. return (OA_Dal_Delivery_fetchAssoc($rTracker));
  1279. }
  1280. }
  1281. function OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid = null)
  1282. {
  1283. $aConf = $GLOBALS['_MAX']['CONF'];
  1284. $trackerid = (int)$trackerid;
  1285. $rCreatives = OA_Dal_Delivery_query("
  1286. SELECT
  1287. b.bannerid AS ad_id,
  1288. b.campaignid AS placement_id,
  1289. c.viewwindow AS view_window,
  1290. c.clickwindow AS click_window,
  1291. ct.status AS status,
  1292. t.type AS tracker_type
  1293. FROM
  1294. {$aConf['table']['prefix']}{$aConf['table']['banners']} AS b,
  1295. {$aConf['table']['prefix']}{$aConf['table']['campaigns_trackers']} AS ct,
  1296. {$aConf['table']['prefix']}{$aConf['table']['campaigns']} AS c,
  1297. {$aConf['table']['prefix']}{$aConf['table']['trackers']} AS t
  1298. WHERE
  1299. ct.trackerid=t.trackerid
  1300. AND c.campaignid=b.campaignid
  1301. AND b.campaignid = ct.campaignid
  1302. " . ((!empty($trackerid)) ? ' AND t.trackerid='.$trackerid : '') . "
  1303. ");
  1304. if (!is_resource($rCreatives)) {
  1305. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1306. } else {
  1307. $output = array();
  1308. while ($aRow = OA_Dal_Delivery_fetchAssoc($rCreatives)) {
  1309. $output[$aRow['ad_id']] = $aRow;
  1310. }
  1311. return $output;
  1312. }
  1313. }
  1314. function OA_Dal_Delivery_getTrackerVariables($trackerid)
  1315. {
  1316. $conf = $GLOBALS['_MAX']['CONF'];
  1317. $trackerid = (int)$trackerid;
  1318. $rVariables = OA_Dal_Delivery_query("
  1319. SELECT
  1320. v.variableid AS variable_id,
  1321. v.trackerid AS tracker_id,
  1322. v.name AS name,
  1323. v.datatype AS type,
  1324. purpose AS purpose,
  1325. reject_if_empty AS reject_if_empty,
  1326. is_unique AS is_unique,
  1327. unique_window AS unique_window,
  1328. v.variablecode AS variablecode
  1329. FROM
  1330. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['variables'])." AS v
  1331. WHERE
  1332. v.trackerid={$trackerid}
  1333. ");
  1334. if (!is_resource($rVariables)) {
  1335. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1336. } else {
  1337. $output = array();
  1338. while ($aRow = OA_Dal_Delivery_fetchAssoc($rVariables)) {
  1339. $output[$aRow['variable_id']] = $aRow;
  1340. }
  1341. return $output;
  1342. }
  1343. }
  1344. function OA_Dal_Delivery_getMaintenanceInfo()
  1345. {
  1346. $conf = $GLOBALS['_MAX']['CONF'];
  1347. $result = OA_Dal_Delivery_query("
  1348. SELECT
  1349. value AS maintenance_timestamp
  1350. FROM
  1351. ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['application_variable'])."
  1352. WHERE name = 'maintenance_timestamp'
  1353. ");
  1354. if (!is_resource($result)) {
  1355. return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null;
  1356. } else {
  1357. $result = OA_Dal_Delivery_fetchAssoc($result);
  1358. return $result['maintenance_timestamp'];
  1359. }
  1360. }
  1361. function OA_Dal_Delivery_buildQuery($part, $lastpart, $precondition)
  1362. {
  1363. $conf = $GLOBALS['_MAX']['CONF'];
  1364. $aColumns = array(
  1365. 'd.bannerid AS ad_id',
  1366. 'd.campaignid AS placement_id',
  1367. 'd.status AS status',
  1368. 'd.description AS name',
  1369. 'd.storagetype AS type',
  1370. 'd.contenttype AS contenttype',
  1371. 'd.pluginversion AS pluginversion',
  1372. 'd.filename AS filename',
  1373. 'd.imageurl AS imageurl',
  1374. 'd.htmltemplate AS htmltemplate',
  1375. 'd.htmlcache AS htmlcache',
  1376. 'd.width AS width',
  1377. 'd.height AS height',
  1378. 'd.weight AS weight',
  1379. 'd.seq AS seq',
  1380. 'd.target AS target',
  1381. 'd.url AS url',
  1382. 'd.alt AS alt',
  1383. 'd.statustext AS statustext',
  1384. 'd.bannertext AS bannertext',
  1385. 'd.adserver AS adserver',
  1386. 'd.block AS block_ad',
  1387. 'd.capping AS cap_ad',
  1388. 'd.session_capping AS session_cap_ad',
  1389. 'd.compiledlimitation AS compiledlimitation',
  1390. 'd.acl_plugins AS acl_plugins',
  1391. 'd.prepend AS prepend',
  1392. 'd.append AS append',
  1393. 'd.bannertype AS bannertype',
  1394. 'd.alt_filename AS alt_filename',
  1395. 'd.alt_imageurl AS alt_imageurl',
  1396. 'd.alt_contenttype AS alt_contenttype',
  1397. 'd.parameters AS parameters',
  1398. 'd.transparent AS transparent',
  1399. 'd.ext_bannertype AS ext_bannertype',
  1400. 'az.priority AS priority',
  1401. 'az.priority_factor AS priority_factor',
  1402. 'az.to_be_delivered AS to_be_delivered',
  1403. 'm.campaignid AS campaign_id',
  1404. 'm.priority AS campaign_priority',
  1405. 'm.weight AS campaign_weight',
  1406. 'm.companion AS campaign_companion',
  1407. 'm.block AS block_campaign',
  1408. 'm.capping AS cap_campaign',
  1409. 'm.session_capping AS session_cap_campaign',
  1410. 'm.show_capped_no_cookie AS show_capped_no_cookie',
  1411. 'm.clickwindow AS clickwindow',
  1412. 'm.viewwindow AS viewwindow',
  1413. 'cl.clientid AS client_id',
  1414. 'm.expire_time AS expire_time',
  1415. 'm.revenue_type AS revenue_type',
  1416. 'm.ecpm_enabled AS ecpm_enabled',
  1417. 'm.ecpm AS ecpm',
  1418. 'cl.advertiser_limitation AS advertiser_limitation',
  1419. 'a.account_id AS account_id',
  1420. 'a.agencyid AS agency_id'
  1421. );
  1422. $aTables = array(
  1423. "".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d",
  1424. "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (d.campaignid = m.campaignid) ",
  1425. "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (m.clientid = cl.clientid) ",
  1426. "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)"
  1427. );
  1428. $select = "
  1429. az.zone_id = 0
  1430. AND m.status <= 0
  1431. AND d.status <= 0";
  1432. if ($precondition != '')
  1433. $select .= " $precondition ";
  1434. if ($part != '')
  1435. {
  1436. $conditions = '';
  1437. $onlykeywords = true;
  1438. $part_array = explode(',', $part);
  1439. for ($k=0; $k < count($part_array); $k++)
  1440. {
  1441. if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_')
  1442. {
  1443. $operator = 'AND';
  1444. $part_array[$k] = substr($part_array[$k], 1);
  1445. }
  1446. elseif (substr($part_array[$k], 0, 1) == '-')
  1447. {
  1448. $operator = 'NOT';
  1449. $part_array[$k] = substr($part_array[$k], 1);
  1450. }
  1451. else
  1452. $operator = 'OR';
  1453. if($part_array[$k] != '' && $part_array[$k] != ' ')
  1454. {
  1455. if(preg_match('#^(?:size:)?(\d+)x(\d+)$#', $part_array[$k], $m))
  1456. {
  1457. $width = (int)$m[1];
  1458. $height = (int)$m[2];
  1459. if ($operator == 'OR') {
  1460. $conditions .= "OR (d.width = {$width} AND d.height = {$height}) ";
  1461. } elseif ($operator == 'AND') {
  1462. $conditions .= "AND (d.width = {$width} AND d.height = {$height}) ";
  1463. } else {
  1464. $conditions .= "AND (d.width <> {$width} OR d.height <> {$height}) ";
  1465. }
  1466. $onlykeywords = false;
  1467. }
  1468. elseif (preg_match('#^width:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
  1469. {
  1470. $min = (int)$m[1];
  1471. $range = !empty($m[2]);
  1472. $max = (int)$m[3];
  1473. if (!$range && $min) {
  1474. if ($operator == 'OR') {
  1475. $conditions .= "OR d.width = {$min} ";
  1476. } elseif ($operator == 'AND') {
  1477. $conditions .= "AND d.width = {$min} ";
  1478. } else {
  1479. $conditions .= "AND d.width <> {$min} ";
  1480. }
  1481. } else {
  1482. if (!$min) {
  1483. $min = 1;
  1484. }
  1485. if (!$max)
  1486. {
  1487. if ($operator == 'OR') {
  1488. $conditions .= "OR d.width >= {$min} ";
  1489. } elseif ($operator == 'AND') {
  1490. $conditions .= "AND d.width >= {$min} ";
  1491. } else {
  1492. $conditions .= "AND d.width < {$min} ";
  1493. }
  1494. } else {
  1495. if ($operator == 'OR') {
  1496. $conditions .= "OR (d.width >= {$min} AND d.width <= {$max}) ";
  1497. } elseif ($operator == 'AND') {
  1498. $conditions .= "AND (d.width >= {$min} AND d.width <= {$max}) ";
  1499. } else {
  1500. $conditions .= "AND (d.width < {$min} OR d.width > {$max}) ";
  1501. }
  1502. }
  1503. }
  1504. $onlykeywords = false;
  1505. }
  1506. elseif (preg_match('#^height:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
  1507. {
  1508. $min = (int)$m[1];
  1509. $range = !empty($m[2]);
  1510. $max = (int)$m[3];
  1511. if (!$range && $min) {
  1512. if ($operator == 'OR') {
  1513. $conditions .= "OR d.height = {$min} ";
  1514. } elseif ($operator == 'AND') {
  1515. $conditions .= "AND d.height = {$min} ";
  1516. } else {
  1517. $conditions .= "AND d.height <> {$min} ";
  1518. }
  1519. } else {
  1520. if (!$min) {
  1521. $min = 1;
  1522. }
  1523. if (!$max)
  1524. {
  1525. if ($operator == 'OR') {
  1526. $conditions .= "OR d.height >= {$min} ";
  1527. } elseif ($operator == 'AND') {
  1528. $conditions .= "AND d.height >= {$min} ";
  1529. } else {
  1530. $conditions .= "AND d.height < {$min} ";
  1531. }
  1532. } else {
  1533. if ($operator == 'OR') {
  1534. $conditions .= "OR (d.height >= {$min} AND d.height <= {$max}) ";
  1535. } elseif ($operator == 'AND') {
  1536. $conditions .= "AND (d.height >= {$min} AND d.height <= {$max}) ";
  1537. } else {
  1538. $conditions .= "AND (d.height < {$min} OR d.height > {$max}) ";
  1539. }
  1540. }
  1541. }
  1542. $onlykeywords = false;
  1543. }
  1544. elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?(\d+)$#', $part_array[$k], $m))
  1545. {
  1546. $bannerid = (int)$m[1];
  1547. if ($bannerid)
  1548. {
  1549. if ($operator == 'OR') {
  1550. $conditions .= "OR d.bannerid = {$bannerid} ";
  1551. } elseif ($operator == 'AND') {
  1552. $conditions .= "AND d.bannerid = {$bannerid} ";
  1553. } else {
  1554. $conditions .= "AND d.bannerid <> {$bannerid} ";
  1555. }
  1556. }
  1557. $onlykeywords = false;
  1558. }
  1559. elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?(\d+)$#', $part_array[$k], $m))
  1560. {
  1561. $campaignid = (int)$m[1];
  1562. if ($campaignid)
  1563. {
  1564. if ($operator == 'OR') {
  1565. $conditions .= "OR d.campaignid = {$campaignid} ";
  1566. } elseif ($operator == 'AND') {
  1567. $conditions .= "AND d.campaignid = {$campaignid} ";
  1568. } else {
  1569. $conditions .= "AND d.campaignid <> {$campaignid} ";
  1570. }
  1571. }
  1572. $onlykeywords = false;
  1573. }
  1574. elseif (substr($part_array[$k], 0, 7) == 'format:')
  1575. {
  1576. $format = OX_escapeString(trim(stripslashes(substr($part_array[$k], 7))));
  1577. if (!empty($format))
  1578. {
  1579. if ($operator == 'OR') {
  1580. $conditions .= "OR d.contenttype = '{$format}' ";
  1581. } elseif ($operator == 'AND') {
  1582. $conditions .= "AND d.contenttype = '{$format}' ";
  1583. } else {
  1584. $conditions .= "AND d.contenttype <> '{$format}' ";
  1585. }
  1586. }
  1587. $onlykeywords = false;
  1588. }
  1589. elseif ($part_array[$k] == 'html')
  1590. {
  1591. if ($operator == 'OR') {
  1592. $conditions .= "OR d.storagetype = 'html' ";
  1593. } elseif ($operator == 'AND') {
  1594. $conditions .= "AND d.storagetype = 'html' ";
  1595. } else {
  1596. $conditions .= "AND d.storagetype <> 'html' ";
  1597. }
  1598. $onlykeywords = false;
  1599. }
  1600. elseif ($part_array[$k] == 'textad')
  1601. {
  1602. if ($operator == 'OR') {
  1603. $conditions .= "OR d.storagetype = 'txt' ";
  1604. } elseif ($operator == 'AND') {
  1605. $conditions .= "AND d.storagetype = 'txt' ";
  1606. } else {
  1607. $conditions .= "AND d.storagetype <> 'txt' ";
  1608. }
  1609. $onlykeywords = false;
  1610. }
  1611. else
  1612. {
  1613. $conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]);
  1614. }
  1615. }
  1616. }
  1617. $conditions = strstr($conditions, ' ');
  1618. if ($lastpart == true && $onlykeywords == true)
  1619. $conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global');
  1620. if ($conditions != '') $select .= ' AND ('.$conditions.') ';
  1621. }
  1622. $columns = implode(",\n ", $aColumns);
  1623. $tables = implode("\n ", $aTables);
  1624. $leftJoin = "
  1625. LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS c ON (c.clientid = m.clientid)
  1626. LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = c.agencyid)
  1627. ";
  1628. $query = "SELECT\n " . $columns . "\nFROM\n " . $tables . $leftJoin . "\nWHERE " . $select;
  1629. return $query;
  1630. }
  1631. function OA_Dal_Delivery_buildAdInfoQuery($part, $lastpart, $precondition)
  1632. {
  1633. $conf = $GLOBALS['_MAX']['CONF'];
  1634. $aColumns = array(
  1635. 'd.bannerid AS ad_id',
  1636. 'd.campaignid AS placement_id',
  1637. 'd.status AS status',
  1638. 'd.storagetype AS type',
  1639. 'd.contenttype AS contenttype',
  1640. 'd.weight AS weight',
  1641. 'd.width AS width',
  1642. 'd.ext_bannertype AS ext_bannertype',
  1643. 'd.height AS height',
  1644. 'd.adserver AS adserver',
  1645. 'd.block AS block_ad',
  1646. 'd.capping AS cap_ad',
  1647. 'd.session_capping AS session_cap_ad',
  1648. 'd.compiledlimitation AS compiledlimitation',
  1649. 'd.acl_plugins AS acl_plugins',
  1650. 'd.alt_filename AS alt_filename',
  1651. 'az.priority AS priority',
  1652. 'az.priority_factor AS priority_factor',
  1653. 'az.to_be_delivered AS to_be_delivered',
  1654. 'm.campaignid AS campaign_id',
  1655. 'm.priority AS campaign_priority',
  1656. 'm.weight AS campaign_weight',
  1657. 'm.companion AS campaign_companion',
  1658. 'm.block AS block_campaign',
  1659. 'm.capping AS cap_campaign',
  1660. 'm.session_capping AS session_cap_campaign',
  1661. 'm.show_capped_no_cookie AS show_capped_no_cookie',
  1662. 'cl.clientid AS client_id',
  1663. 'm.expire_time AS expire_time',
  1664. 'm.revenue_type AS revenue_type',
  1665. 'm.ecpm_enabled AS ecpm_enabled',
  1666. 'm.ecpm AS ecpm',
  1667. 'ct.status AS tracker_status',
  1668. OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe",
  1669. OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe",
  1670. );
  1671. $aTables = array(
  1672. "".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d",
  1673. "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)",
  1674. "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (m.campaignid = d.campaignid) ",
  1675. );
  1676. $select = "
  1677. az.zone_id = 0
  1678. AND m.status <= 0
  1679. AND d.status <= 0";
  1680. if ($precondition != '')
  1681. $select .= " $precondition ";
  1682. if ($part != '')
  1683. {
  1684. $conditions = '';
  1685. $onlykeywords = true;
  1686. $part_array = explode(',', $part);
  1687. for ($k=0; $k < count($part_array); $k++)
  1688. {
  1689. if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_')
  1690. {
  1691. $operator = 'AND';
  1692. $part_array[$k] = substr($part_array[$k], 1);
  1693. }
  1694. elseif (substr($part_array[$k], 0, 1) == '-')
  1695. {
  1696. $operator = 'NOT';
  1697. $part_array[$k] = substr($part_array[$k], 1);
  1698. }
  1699. else
  1700. $operator = 'OR';
  1701. if($part_array[$k] != '' && $part_array[$k] != ' ')
  1702. {
  1703. if(preg_match('#^(?:size:)?(\d+)x(\d+)$#', $part_array[$k], $m))
  1704. {
  1705. $width = (int)$m[1];
  1706. $height = (int)$m[2];
  1707. if ($operator == 'OR') {
  1708. $conditions .= "OR (d.width = {$width} AND d.height = {$height}) ";
  1709. } elseif ($operator == 'AND') {
  1710. $conditions .= "AND (d.width = {$width} AND d.height = {$height}) ";
  1711. } else {
  1712. $conditions .= "AND (d.width <> {$width} OR d.height <> {$height}) ";
  1713. }
  1714. $onlykeywords = false;
  1715. }
  1716. elseif (preg_match('#^width:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
  1717. {
  1718. $min = (int)$m[1];
  1719. $range = !empty($m[2]);
  1720. $max = (int)$m[3];
  1721. if (!$range && $min) {
  1722. if ($operator == 'OR') {
  1723. $conditions .= "OR d.width = {$min} ";
  1724. } elseif ($operator == 'AND') {
  1725. $conditions .= "AND d.width = {$min} ";
  1726. } else {
  1727. $conditions .= "AND d.width <> {$min} ";
  1728. }
  1729. } else {
  1730. if (!$min) {
  1731. $min = 1;
  1732. }
  1733. if (!$max)
  1734. {
  1735. if ($operator == 'OR') {
  1736. $conditions .= "OR d.width >= {$min} ";
  1737. } elseif ($operator == 'AND') {
  1738. $conditions .= "AND d.width >= {$min} ";
  1739. } else {
  1740. $conditions .= "AND d.width < {$min} ";
  1741. }
  1742. } else {
  1743. if ($operator == 'OR') {
  1744. $conditions .= "OR (d.width >= {$min} AND d.width <= {$max}) ";
  1745. } elseif ($operator == 'AND') {
  1746. $conditions .= "AND (d.width >= {$min} AND d.width <= {$max}) ";
  1747. } else {
  1748. $conditions .= "AND (d.width < {$min} OR d.width > {$max}) ";
  1749. }
  1750. }
  1751. }
  1752. $onlykeywords = false;
  1753. }
  1754. elseif (preg_match('#^height:(\d*)(-?)(\d*)$#', $part_array[$k], $m))
  1755. {
  1756. $min = (int)$m[1];
  1757. $range = !empty($m[2]);
  1758. $max = (int)$m[3];
  1759. if (!$range && $min) {
  1760. if ($operator == 'OR') {
  1761. $conditions .= "OR d.height = {$min} ";
  1762. } elseif ($operator == 'AND') {
  1763. $conditions .= "AND d.height = {$min} ";
  1764. } else {
  1765. $conditions .= "AND d.height <> {$min} ";
  1766. }
  1767. } else {
  1768. if (!$min) {
  1769. $min = 1;
  1770. }
  1771. if (!$max)
  1772. {
  1773. if ($operator == 'OR') {
  1774. $conditions .= "OR d.height >= {$min} ";
  1775. } elseif ($operator == 'AND') {
  1776. $conditions .= "AND d.height >= {$min} ";
  1777. } else {
  1778. $conditions .= "AND d.height < {$min} ";
  1779. }
  1780. } else {
  1781. if ($operator == 'OR') {
  1782. $conditions .= "OR (d.height >= {$min} AND d.height <= {$max}) ";
  1783. } elseif ($operator == 'AND') {
  1784. $conditions .= "AND (d.height >= {$min} AND d.height <= {$max}) ";
  1785. } else {
  1786. $conditions .= "AND (d.height < {$min} OR d.height > {$max}) ";
  1787. }
  1788. }
  1789. }
  1790. $onlykeywords = false;
  1791. }
  1792. elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?(\d+)$#', $part_array[$k], $m))
  1793. {
  1794. $bannerid = (int)$m[1];
  1795. if ($bannerid)
  1796. {
  1797. if ($operator == 'OR') {
  1798. $conditions .= "OR d.bannerid = {$bannerid} ";
  1799. } elseif ($operator == 'AND') {
  1800. $conditions .= "AND d.bannerid = {$bannerid} ";
  1801. } else {
  1802. $conditions .= "AND d.bannerid <> {$bannerid} ";
  1803. }
  1804. }
  1805. $onlykeywords = false;
  1806. }
  1807. elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?(\d+)$#', $part_array[$k], $m))
  1808. {
  1809. $campaignid = (int)$m[1];
  1810. if ($campaignid)
  1811. {
  1812. if ($operator == 'OR') {
  1813. $conditions .= "OR d.campaignid = {$campaignid} ";
  1814. } elseif ($operator == 'AND') {
  1815. $conditions .= "AND d.campaignid = {$campaignid} ";
  1816. } else {
  1817. $conditions .= "AND d.campaignid <> {$campaignid} ";
  1818. }
  1819. }
  1820. $onlykeywords = false;
  1821. }
  1822. elseif (substr($part_array[$k], 0, 7) == 'format:')
  1823. {
  1824. $format = OX_escapeString(trim(stripslashes(substr($part_array[$k], 7))));
  1825. if (!empty($format))
  1826. {
  1827. if ($operator == 'OR') {
  1828. $conditions .= "OR d.contenttype = '{$format}' ";
  1829. } elseif ($operator == 'AND') {
  1830. $conditions .= "AND d.contenttype = '{$format}' ";
  1831. } else {
  1832. $conditions .= "AND d.contenttype <> '{$format}' ";
  1833. }
  1834. }
  1835. $onlykeywords = false;
  1836. }
  1837. elseif ($part_array[$k] == 'html')
  1838. {
  1839. if ($operator == 'OR') {
  1840. $conditions .= "OR d.storagetype = 'html' ";
  1841. } elseif ($operator == 'AND') {
  1842. $conditions .= "AND d.storagetype = 'html' ";
  1843. } else {
  1844. $conditions .= "AND d.storagetype <> 'html' ";
  1845. }
  1846. $onlykeywords = false;
  1847. }
  1848. elseif ($part_array[$k] == 'textad')
  1849. {
  1850. if ($operator == 'OR') {
  1851. $conditions .= "OR d.storagetype = 'txt' ";
  1852. } elseif ($operator == 'AND') {
  1853. $conditions .= "AND d.storagetype = 'txt' ";
  1854. } else {
  1855. $conditions .= "AND d.storagetype <> 'txt' ";
  1856. }
  1857. $onlykeywords = false;
  1858. }
  1859. else
  1860. {
  1861. $conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]);
  1862. }
  1863. }
  1864. }
  1865. $conditions = strstr($conditions, ' ');
  1866. if ($lastpart == true && $onlykeywords == true)
  1867. $conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global');
  1868. if ($conditions != '') $select .= ' AND ('.$conditions.') ';
  1869. }
  1870. $columns = implode(",\n ", $aColumns);
  1871. $tables = implode("\n ", $aTables);
  1872. $leftJoin = "
  1873. LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = m.campaignid)
  1874. LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (cl.clientid = m.clientid)
  1875. LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = cl.agencyid)
  1876. ";
  1877. $query = "SELECT\n " . $columns . "\nFROM\n " . $tables . $leftJoin . "\nWHERE " . $select;
  1878. return $query;
  1879. }
  1880. function _setPriorityFromWeights(&$aAds)
  1881. {
  1882. if (!count($aAds)) {
  1883. return 0;
  1884. }
  1885. $aCampaignWeights = array();
  1886. $aCampaignAdWeight = array();
  1887. foreach ($aAds as $v) {
  1888. if (!isset($aCampaignWeights[$v['placement_id']])) {
  1889. $aCampaignWeights[$v['placement_id']] = $v['campaign_weight'];
  1890. $aCampaignAdWeight[$v['placement_id']] = 0;
  1891. }
  1892. $aCampaignAdWeight[$v['placement_id']] += $v['weight'];
  1893. }
  1894. foreach ($aCampaignWeights as $k => $v) {
  1895. if ($aCampaignAdWeight[$k]) {
  1896. $aCampaignWeights[$k] /= $aCampaignAdWeight[$k];
  1897. }
  1898. }
  1899. $totalPri = 0;
  1900. foreach ($aAds as $k => $v) {
  1901. $aAds[$k]['priority'] = $aCampaignWeights[$v['placement_id']] * $v['weight'];
  1902. $totalPri += $aAds[$k]['priority'];
  1903. }
  1904. if ($totalPri) {
  1905. foreach ($aAds as $k => $v) {
  1906. $aAds[$k]['priority'] /= $totalPri;
  1907. }
  1908. return 1;
  1909. }
  1910. return 0;
  1911. }
  1912. function _getTotalPrioritiesByCP($aAdsByCP, $includeBlank = true)
  1913. {
  1914. $totals = array();
  1915. $total_priority_cp = array();
  1916. $blank_priority = 1;
  1917. foreach ($aAdsByCP as $campaign_priority => $aAds) {
  1918. $total_priority_cp[$campaign_priority] = 0;
  1919. foreach ($aAds as $key => $aAd) {
  1920. $blank_priority -= (double)$aAd['priority'];
  1921. if ($aAd['to_be_delivered']) {
  1922. $priority = $aAd['priority'] * $aAd['priority_factor'];
  1923. } else {
  1924. $priority = 0.00001;
  1925. }
  1926. $total_priority_cp[$campaign_priority] += $priority;
  1927. }
  1928. }
  1929. $total_priority = 0;
  1930. if ($includeBlank) {
  1931. $total_priority = $blank_priority <= 1e-15 ? 0 : $blank_priority;
  1932. }
  1933. ksort($total_priority_cp);
  1934. foreach($total_priority_cp as $campaign_priority => $priority) {
  1935. $total_priority += $priority;
  1936. if ($total_priority) {
  1937. $totals[$campaign_priority] = $priority / $total_priority;
  1938. } else {
  1939. $totals[$campaign_priority] = 0;
  1940. }
  1941. }
  1942. return $totals;
  1943. }
  1944. function MAX_Dal_Delivery_Include()
  1945. {
  1946. static $included;
  1947. if (isset($included)) {
  1948. return;
  1949. }
  1950. $included = true;
  1951. $conf = $GLOBALS['_MAX']['CONF'];
  1952. if (isset($conf['origin']['type']) && is_readable(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php')) {
  1953. require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php');
  1954. } else {
  1955. require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['database']['type']) . '.php');
  1956. }
  1957. }
  1958. function MAX_trackerbuildJSVariablesScript($trackerid, $conversionInfo, $trackerJsCode = null)
  1959. {
  1960. $conf = $GLOBALS['_MAX']['CONF'];
  1961. $buffer = '';
  1962. $url = MAX_commonGetDeliveryUrl($conf['file']['conversionvars']);
  1963. $tracker = MAX_cacheGetTracker($trackerid);
  1964. $variables = MAX_cacheGetTrackerVariables($trackerid);
  1965. $variableQuerystring = '';
  1966. if (empty($trackerJsCode)) {
  1967. $trackerJsCode = md5(uniqid('', true));
  1968. } else {
  1969. $tracker['variablemethod'] = 'default';
  1970. }
  1971. if (!empty($variables)) {
  1972. if ($tracker['variablemethod'] == 'dom') {
  1973. $buffer .= "
  1974. function MAX_extractTextDom(o)
  1975. {
  1976. var txt = '';
  1977. if (o.nodeType == 3) {
  1978. txt = o.data;
  1979. } else {
  1980. for (var i = 0; i < o.childNodes.length; i++) {
  1981. txt += MAX_extractTextDom(o.childNodes[i]);
  1982. }
  1983. }
  1984. return txt;
  1985. }
  1986. function MAX_TrackVarDom(id, v)
  1987. {
  1988. if (max_trv[id][v]) { return; }
  1989. var o = document.getElementById(v);
  1990. if (o) {
  1991. max_trv[id][v] = escape(o.tagName == 'INPUT' ? o.value : MAX_extractTextDom(o));
  1992. }
  1993. }";
  1994. $funcName = 'MAX_TrackVarDom';
  1995. } elseif ($tracker['variablemethod'] == 'default') {
  1996. $buffer .= "
  1997. function MAX_TrackVarDefault(id, v)
  1998. {
  1999. if (max_trv[id][v]) { return; }
  2000. if (typeof(window[v]) == undefined) { return; }
  2001. max_trv[id][v] = window[v];
  2002. }";
  2003. $funcName = 'MAX_TrackVarDefault';
  2004. } else {
  2005. $buffer .= "
  2006. function MAX_TrackVarJs(id, v, c)
  2007. {
  2008. if (max_trv[id][v]) { return; }
  2009. if (typeof(window[v]) == undefined) { return; }
  2010. if (typeof(c) != 'undefined') {
  2011. eval(c);
  2012. }
  2013. max_trv[id][v] = window[v];
  2014. }";
  2015. $funcName = 'MAX_TrackVarJs';
  2016. }
  2017. $buffer .= "
  2018. if (!max_trv) { var max_trv = new Array(); }
  2019. if (!max_trv['{$trackerJsCode}']) { max_trv['{$trackerJsCode}'] = new Array(); }";
  2020. foreach($variables as $key => $variable) {
  2021. $variableQuerystring .= "&{$variable['name']}=\"+max_trv['{$trackerJsCode}']['{$variable['name']}']+\"";
  2022. if ($tracker['variablemethod'] == 'custom') {
  2023. $buffer .= "
  2024. {$funcName}('{$trackerJsCode}', '{$variable['name']}', '".addcslashes($variable['variablecode'], "'")."');";
  2025. } else {
  2026. $buffer .= "
  2027. {$funcName}('{$trackerJsCode}', '{$variable['name']}');";
  2028. }
  2029. }
  2030. if (!empty($variableQuerystring)) {
  2031. $conversionInfoParams = array();
  2032. foreach ($conversionInfo as $plugin => $pluginData) {
  2033. if (is_array($pluginData)) {
  2034. foreach ($pluginData as $key => $value) {
  2035. $conversionInfoParams[] = $key . '=' . urlencode($value);
  2036. }
  2037. }
  2038. }
  2039. $conversionInfoParams = '&' . implode('&', $conversionInfoParams);
  2040. $buffer .= "
  2041. document.write (\"<\" + \"script language='JavaScript' type='text/javascript' src='\");
  2042. document.write (\"$url?trackerid=$trackerid{$conversionInfoParams}{$variableQuerystring}'\");";
  2043. $buffer .= "\n\tdocument.write (\"><\\/scr\"+\"ipt>\");";
  2044. }
  2045. }
  2046. if(!empty($tracker['appendcode'])) {
  2047. $tracker['appendcode'] = preg_replace('/("\?trackerid=\d+&amp;inherit)=1/', '$1='.$trackerJsCode, $tracker['appendcode']);
  2048. $jscode = MAX_javascriptToHTML($tracker['appendcode'], "MAX_{$trackerid}_appendcode");
  2049. $jscode = preg_replace("/\{m3_trackervariable:(.+?)\}/", "\"+max_trv['{$trackerJsCode}']['$1']+\"", $jscode);
  2050. $buffer .= "\n".preg_replace('/^/m', "\t", $jscode)."\n";
  2051. }
  2052. if (empty($buffer)) {
  2053. $buffer = "document.write(\"\");";
  2054. }
  2055. return $buffer;
  2056. }
  2057. function MAX_trackerCheckForValidAction($trackerid)
  2058. {
  2059. $aTrackerLinkedAds = MAX_cacheGetTrackerLinkedCreatives($trackerid);
  2060. if (empty($aTrackerLinkedAds)) {
  2061. return false;
  2062. }
  2063. $aPossibleActions = _getActionTypes();
  2064. $now = MAX_commonGetTimeNow();
  2065. $aConf = $GLOBALS['_MAX']['CONF'];
  2066. $aMatchingActions = array();
  2067. foreach ($aTrackerLinkedAds as $creativeId => $aLinkedInfo) {
  2068. foreach ($aPossibleActions as $actionId => $action) {
  2069. if (!empty($aLinkedInfo[$action . '_window']) && !empty($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId])) {
  2070. if (stristr($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], ' ')) {
  2071. list($value, $extra) = explode(' ', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], 2);
  2072. $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId] = $value;
  2073. } else {
  2074. $extra = '';
  2075. }
  2076. list($lastAction, $zoneId) = explode('-', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId]);
  2077. $lastAction = MAX_commonUnCompressInt($lastAction);
  2078. $lastSeenSecondsAgo = $now - $lastAction;
  2079. if ($lastSeenSecondsAgo <= $aLinkedInfo[$action . '_window'] && $lastSeenSecondsAgo > 0) {
  2080. $aMatchingActions[$lastSeenSecondsAgo] = array(
  2081. 'action_type' => $actionId,
  2082. 'tracker_type' => $aLinkedInfo['tracker_type'],
  2083. 'status' => $aLinkedInfo['status'],
  2084. 'cid' => $creativeId,
  2085. 'zid' => $zoneId,
  2086. 'dt' => $lastAction,
  2087. 'window' => $aLinkedInfo[$action . '_window'],
  2088. 'extra' => $extra,
  2089. );
  2090. }
  2091. }
  2092. }
  2093. }
  2094. if (empty($aMatchingActions)) {
  2095. return false;
  2096. }
  2097. ksort($aMatchingActions);
  2098. return array_shift($aMatchingActions);
  2099. }
  2100. function _getActionTypes()
  2101. {
  2102. return array(0 => 'view', 1 => 'click');
  2103. }
  2104. function _getTrackerTypes()
  2105. {
  2106. return array(1 => 'sale', 2 => 'lead', 3 => 'signup');
  2107. }
  2108. function MAX_Delivery_log_logAdRequest($adId, $zoneId, $aAd = array())
  2109. {
  2110. if (empty($GLOBALS['_MAX']['CONF']['logging']['adRequests'])) { return true; }
  2111. OX_Delivery_Common_hook('logRequest', array($adId, $zoneId, $aAd, _viewersHostOkayToLog($adId, $zoneId)));
  2112. }
  2113. function MAX_Delivery_log_logAdImpression($adId, $zoneId)
  2114. {
  2115. if (empty($GLOBALS['_MAX']['CONF']['logging']['adImpressions'])) { return true; }
  2116. OX_Delivery_Common_hook('logImpression', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId)));
  2117. }
  2118. function MAX_Delivery_log_logAdClick($adId, $zoneId)
  2119. {
  2120. if (empty($GLOBALS['_MAX']['CONF']['logging']['adClicks'])) { return true; }
  2121. OX_Delivery_Common_hook('logClick', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId)));
  2122. }
  2123. function MAX_Delivery_log_logConversion($trackerId, $aConversion)
  2124. {
  2125. if (empty($GLOBALS['_MAX']['CONF']['logging']['trackerImpressions'])) { return true; }
  2126. $aConf = $GLOBALS['_MAX']['CONF'];
  2127. if (!empty($aConf['lb']['enabled'])) {
  2128. $aConf['rawDatabase']['host'] = $_SERVER['SERVER_ADDR'];
  2129. } else {
  2130. $aConf['rawDatabase']['host'] = 'singleDB';
  2131. }
  2132. if (isset($aConf['rawDatabase']['serverRawIp'])) {
  2133. $serverRawIp = $aConf['rawDatabase']['serverRawIp'];
  2134. } else {
  2135. $serverRawIp = $aConf['rawDatabase']['host'];
  2136. }
  2137. $aConversionInfo = OX_Delivery_Common_hook('logConversion', array($trackerId, $serverRawIp, $aConversion, _viewersHostOkayToLog(null, null, $trackerId)));
  2138. if (is_array($aConversionInfo)) {
  2139. return $aConversionInfo;
  2140. }
  2141. return false;
  2142. }
  2143. function MAX_Delivery_log_logVariableValues($aVariables, $trackerId, $serverConvId, $serverRawIp)
  2144. {
  2145. $aConf = $GLOBALS['_MAX']['CONF'];
  2146. foreach ($aVariables as $aVariable) {
  2147. if (isset($_GET[$aVariable['name']])) {
  2148. $value = $_GET[$aVariable['name']];
  2149. if (!strlen($value) || $value == 'undefined') {
  2150. unset($aVariables[$aVariable['variable_id']]);
  2151. continue;
  2152. }
  2153. switch ($aVariable['type']) {
  2154. case 'int':
  2155. case 'numeric':
  2156. $value = preg_replace('/[^0-9.]/', '', $value);
  2157. $value = floatval($value);
  2158. break;
  2159. case 'date':
  2160. if (!empty($value)) {
  2161. $value = date('Y-m-d H:i:s', strtotime($value));
  2162. } else {
  2163. $value = '';
  2164. }
  2165. break;
  2166. }
  2167. } else {
  2168. unset($aVariables[$aVariable['variable_id']]);
  2169. continue;
  2170. }
  2171. $aVariables[$aVariable['variable_id']]['value'] = $value;
  2172. }
  2173. if (count($aVariables)) {
  2174. OX_Delivery_Common_hook('logConversionVariable', array($aVariables, $trackerId, $serverConvId, $serverRawIp, _viewersHostOkayToLog(null, null, $trackerId)));
  2175. }
  2176. }
  2177. function _viewersHostOkayToLog($adId=0, $zoneId=0, $trackerId=0)
  2178. {
  2179. $aConf = $GLOBALS['_MAX']['CONF'];
  2180. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  2181. $okToLog = true;
  2182. if (!empty($aConf['logging']['enforceUserAgents'])) {
  2183. $aKnownBrowsers = explode('|', strtolower($aConf['logging']['enforceUserAgents']));
  2184. $allowed = false;
  2185. foreach ($aKnownBrowsers as $browser) {
  2186. if (strpos($agent, $browser) !== false) {
  2187. $allowed = true;
  2188. break;
  2189. }
  2190. }
  2191. OX_Delivery_logMessage('user-agent browser : '.$agent.' is '.($allowed ? '' : 'not ').'allowed', 7);
  2192. if (!$allowed) {
  2193. $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'enforceUserAgents';
  2194. $okToLog = false;
  2195. }
  2196. }
  2197. if (!empty($aConf['logging']['ignoreUserAgents'])) {
  2198. $aKnownBots = explode('|', strtolower($aConf['logging']['ignoreUserAgents']));
  2199. foreach ($aKnownBots as $bot) {
  2200. if (strpos($agent, $bot) !== false) {
  2201. OX_Delivery_logMessage('user-agent '.$agent.' is a known bot '.$bot, 7);
  2202. $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreUserAgents';
  2203. $okToLog = false;
  2204. }
  2205. }
  2206. }
  2207. if (!empty($aConf['logging']['ignoreHosts'])) {
  2208. $hosts = str_replace(',', '|', $aConf['logging']['ignoreHosts']);
  2209. $hosts = '#^('.$hosts.')$#i';
  2210. $hosts = str_replace('.', '\.', $hosts);
  2211. $hosts = str_replace('*', '[^.]+', $hosts);
  2212. if (preg_match($hosts, $_SERVER['REMOTE_ADDR'])) {
  2213. OX_Delivery_logMessage('viewer\'s ip is in the ignore list '.$_SERVER['REMOTE_ADDR'], 7);
  2214. $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_ip';
  2215. $okToLog = false;
  2216. }
  2217. if (preg_match($hosts, $_SERVER['REMOTE_HOST'])) {
  2218. OX_Delivery_logMessage('viewer\'s host is in the ignore list '.$_SERVER['REMOTE_HOST'], 7);
  2219. $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_host';
  2220. $okToLog = false;
  2221. }
  2222. }
  2223. if ($okToLog) OX_Delivery_logMessage('viewer\'s host is OK to log', 7);
  2224. $result = OX_Delivery_Common_Hook('filterEvent', array($adId, $zoneId, $trackerId));
  2225. if (!empty($result) && is_array($result)) {
  2226. foreach ($result as $pci => $value) {
  2227. if ($value == true) {
  2228. $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = $pci;
  2229. $okToLog = false;
  2230. }
  2231. }
  2232. }
  2233. return $okToLog;
  2234. }
  2235. function MAX_Delivery_log_getArrGetVariable($name)
  2236. {
  2237. $varName = $GLOBALS['_MAX']['CONF']['var'][$name];
  2238. return isset($_GET[$varName]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_GET[$varName]) : array();
  2239. }
  2240. function MAX_Delivery_log_ensureIntegerSet(&$aArray, $index)
  2241. {
  2242. if (!is_array($aArray)) {
  2243. $aArray = array();
  2244. }
  2245. if (empty($aArray[$index])) {
  2246. $aArray[$index] = 0;
  2247. } else {
  2248. if (!is_integer($aArray[$index])) {
  2249. $aArray[$index] = intval($aArray[$index]);
  2250. }
  2251. }
  2252. }
  2253. function MAX_Delivery_log_setAdLimitations($index, $aAds, $aCaps)
  2254. {
  2255. _setLimitations('Ad', $index, $aAds, $aCaps);
  2256. }
  2257. function MAX_Delivery_log_setCampaignLimitations($index, $aCampaigns, $aCaps)
  2258. {
  2259. _setLimitations('Campaign', $index, $aCampaigns, $aCaps);
  2260. }
  2261. function MAX_Delivery_log_setZoneLimitations($index, $aZones, $aCaps)
  2262. {
  2263. _setLimitations('Zone', $index, $aZones, $aCaps);
  2264. }
  2265. function MAX_Delivery_log_setLastAction($index, $aAdIds, $aZoneIds, $aSetLastSeen, $action = 'view')
  2266. {
  2267. $aConf = $GLOBALS['_MAX']['CONF'];
  2268. if (!empty($aSetLastSeen[$index])) {
  2269. $cookieData = MAX_commonCompressInt(MAX_commonGetTimeNow()) . "-" . $aZoneIds[$index];
  2270. $conversionParams = OX_Delivery_Common_hook('addConversionParams', array(&$index, &$aAdIds, &$aZoneIds, &$aSetLastSeen, &$action, &$cookieData));
  2271. if (!empty($conversionParams) && is_array($conversionParams)) {
  2272. foreach ($conversionParams as $params) {
  2273. if (!empty($params) && is_array($params)) {
  2274. foreach ($params as $key => $value) {
  2275. $cookieData .= " {$value}";
  2276. }
  2277. }
  2278. }
  2279. }
  2280. MAX_cookieAdd("_{$aConf['var']['last' . ucfirst($action)]}[{$aAdIds[$index]}]", $cookieData, _getTimeThirtyDaysFromNow());
  2281. }
  2282. }
  2283. function MAX_Delivery_log_setClickBlocked($index, $aAdIds)
  2284. {
  2285. $aConf = $GLOBALS['_MAX']['CONF'];
  2286. MAX_cookieAdd("_{$aConf['var']['blockLoggingClick']}[{$aAdIds[$index]}]", MAX_commonCompressInt(MAX_commonGetTimeNow()), _getTimeThirtyDaysFromNow());
  2287. }
  2288. function MAX_Delivery_log_isClickBlocked($adId, $aBlockLoggingClick)
  2289. {
  2290. if (isset($GLOBALS['conf']['logging']['blockAdClicksWindow']) && $GLOBALS['conf']['logging']['blockAdClicksWindow'] != 0) {
  2291. if (isset($aBlockLoggingClick[$adId])) {
  2292. $endBlock = MAX_commonUnCompressInt($aBlockLoggingClick[$adId]) + $GLOBALS['conf']['logging']['blockAdClicksWindow'];
  2293. if ($endBlock >= MAX_commonGetTimeNow()) {
  2294. OX_Delivery_logMessage('adID '.$adId.' click is still blocked by block logging window ', 7);
  2295. return true;
  2296. }
  2297. }
  2298. }
  2299. return false;
  2300. }
  2301. function _setLimitations($type, $index, $aItems, $aCaps)
  2302. {
  2303. MAX_Delivery_log_ensureIntegerSet($aCaps['block'], $index);
  2304. MAX_Delivery_log_ensureIntegerSet($aCaps['capping'], $index);
  2305. MAX_Delivery_log_ensureIntegerSet($aCaps['session_capping'], $index);
  2306. MAX_Delivery_cookie_setCapping(
  2307. $type,
  2308. $aItems[$index],
  2309. $aCaps['block'][$index],
  2310. $aCaps['capping'][$index],
  2311. $aCaps['session_capping'][$index]
  2312. );
  2313. }
  2314. function MAX_commonGetDeliveryUrl($file = null)
  2315. {
  2316. $conf = $GLOBALS['_MAX']['CONF'];
  2317. if ($GLOBALS['_MAX']['SSL_REQUEST']) {
  2318. $url = MAX_commonConstructSecureDeliveryUrl($file);
  2319. } else {
  2320. $url = MAX_commonConstructDeliveryUrl($file);
  2321. }
  2322. return $url;
  2323. }
  2324. function MAX_commonConstructDeliveryUrl($file)
  2325. {
  2326. $conf = $GLOBALS['_MAX']['CONF'];
  2327. return 'http://' . $conf['webpath']['delivery'] . '/' . $file;
  2328. }
  2329. function MAX_commonConstructSecureDeliveryUrl($file)
  2330. {
  2331. $conf = $GLOBALS['_MAX']['CONF'];
  2332. if ($conf['openads']['sslPort'] != 443) {
  2333. $path = preg_replace('#/#', ':' . $conf['openads']['sslPort'] . '/', $conf['webpath']['deliverySSL'], 1);
  2334. } else {
  2335. $path = $conf['webpath']['deliverySSL'];
  2336. }
  2337. return 'https://' . $path . '/' . $file;
  2338. }
  2339. function MAX_commonConstructPartialDeliveryUrl($file, $ssl = false)
  2340. {
  2341. $conf = $GLOBALS['_MAX']['CONF'];
  2342. if ($ssl) {
  2343. return '//' . $conf['webpath']['deliverySSL'] . '/' . $file;
  2344. } else {
  2345. return '//' . $conf['webpath']['delivery'] . '/' . $file;
  2346. }
  2347. }
  2348. function MAX_commonRemoveSpecialChars(&$var)
  2349. {
  2350. static $magicQuotes;
  2351. if (!isset($magicQuotes)) {
  2352. $magicQuotes = get_magic_quotes_gpc();
  2353. }
  2354. if (isset($var)) {
  2355. if (!is_array($var)) {
  2356. if ($magicQuotes) {
  2357. $var = stripslashes($var);
  2358. }
  2359. $var = strip_tags($var);
  2360. $var = str_replace(array("\n", "\r"), array('', ''), $var);
  2361. $var = trim($var);
  2362. } else {
  2363. array_walk($var, 'MAX_commonRemoveSpecialChars');
  2364. }
  2365. }
  2366. }
  2367. function MAX_commonConvertEncoding($content, $toEncoding, $fromEncoding = 'UTF-8', $aExtensions = null) {
  2368. if (($toEncoding == $fromEncoding) || empty($toEncoding)) {
  2369. return $content;
  2370. }
  2371. if (!isset($aExtensions) || !is_array($aExtensions)) {
  2372. $aExtensions = array('iconv', 'mbstring', 'xml');
  2373. }
  2374. if (is_array($content)) {
  2375. foreach ($content as $key => $value) {
  2376. $content[$key] = MAX_commonConvertEncoding($value, $toEncoding, $fromEncoding, $aExtensions);
  2377. }
  2378. return $content;
  2379. } else {
  2380. $toEncoding = strtoupper($toEncoding);
  2381. $fromEncoding = strtoupper($fromEncoding);
  2382. $aMap = array();
  2383. $aMap['mbstring']['WINDOWS-1255'] = 'ISO-8859-8'; $aMap['xml']['ISO-8859-15'] = 'ISO-8859-1'; $converted = false;
  2384. foreach ($aExtensions as $extension) {
  2385. $mappedFromEncoding = isset($aMap[$extension][$fromEncoding]) ? $aMap[$extension][$fromEncoding] : $fromEncoding;
  2386. $mappedToEncoding = isset($aMap[$extension][$toEncoding]) ? $aMap[$extension][$toEncoding] : $toEncoding;
  2387. switch ($extension) {
  2388. case 'iconv':
  2389. if (function_exists('iconv')) {
  2390. $converted = @iconv($mappedFromEncoding, $mappedToEncoding, $content);
  2391. }
  2392. break;
  2393. case 'mbstring':
  2394. if (function_exists('mb_convert_encoding')) {
  2395. $converted = @mb_convert_encoding($content, $mappedToEncoding, $mappedFromEncoding);
  2396. }
  2397. break;
  2398. case 'xml':
  2399. if (function_exists('utf8_encode')) {
  2400. if ($mappedToEncoding == 'UTF-8' && $mappedFromEncoding == 'ISO-8859-1') {
  2401. $converted = utf8_encode($content);
  2402. } elseif ($mappedToEncoding == 'ISO-8859-1' && $mappedFromEncoding == 'UTF-8') {
  2403. $converted = utf8_decode($content);
  2404. }
  2405. }
  2406. break;
  2407. }
  2408. }
  2409. return $converted ? $converted : $content;
  2410. }
  2411. }
  2412. function MAX_commonSendContentTypeHeader($type = 'text/html', $charset = null)
  2413. {
  2414. $header = 'Content-type: ' . $type;
  2415. if (!empty($charset) && preg_match('/^[a-zA-Z0-9_-]+$/D', $charset)) {
  2416. $header .= '; charset=' . $charset;
  2417. }
  2418. MAX_header($header);
  2419. }
  2420. function MAX_commonSetNoCacheHeaders()
  2421. {
  2422. MAX_header('Pragma: no-cache');
  2423. MAX_header('Cache-Control: private, max-age=0, no-cache');
  2424. MAX_header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2425. }
  2426. function MAX_commonAddslashesRecursive($a)
  2427. {
  2428. if (is_array($a)) {
  2429. reset($a);
  2430. while (list($k,$v) = each($a)) {
  2431. $a[$k] = MAX_commonAddslashesRecursive($v);
  2432. }
  2433. reset ($a);
  2434. return ($a);
  2435. } else {
  2436. return is_null($a) ? null : addslashes($a);
  2437. }
  2438. }
  2439. function MAX_commonRegisterGlobalsArray($args = array())
  2440. {
  2441. static $magic_quotes_gpc;
  2442. if (!isset($magic_quotes_gpc)) {
  2443. $magic_quotes_gpc = ini_get('magic_quotes_gpc');
  2444. }
  2445. $found = false;
  2446. foreach($args as $key) {
  2447. if (isset($_GET[$key])) {
  2448. $value = $_GET[$key];
  2449. $found = true;
  2450. }
  2451. if (isset($_POST[$key])) {
  2452. $value = $_POST[$key];
  2453. $found = true;
  2454. }
  2455. if ($found) {
  2456. if (!$magic_quotes_gpc) {
  2457. if (!is_array($value)) {
  2458. $value = addslashes($value);
  2459. } else {
  2460. $value = MAX_commonAddslashesRecursive($value);
  2461. }
  2462. }
  2463. $GLOBALS[$key] = $value;
  2464. $found = false;
  2465. }
  2466. }
  2467. }
  2468. function MAX_commonDeriveSource($source)
  2469. {
  2470. return MAX_commonEncrypt(trim(urldecode($source)));
  2471. }
  2472. function MAX_commonEncrypt($string)
  2473. {
  2474. $convert = '';
  2475. if (isset($string) && substr($string,1,4) != 'obfs' && $GLOBALS['_MAX']['CONF']['delivery']['obfuscate']) {
  2476. $strLen = strlen($string);
  2477. for ($i=0; $i < $strLen; $i++) {
  2478. $dec = ord(substr($string,$i,1));
  2479. if (strlen($dec) == 2) {
  2480. $dec = 0 . $dec;
  2481. }
  2482. $dec = 324 - $dec;
  2483. $convert .= $dec;
  2484. }
  2485. $convert = '{obfs:' . $convert . '}';
  2486. return ($convert);
  2487. } else {
  2488. return $string;
  2489. }
  2490. }
  2491. function MAX_commonDecrypt($string)
  2492. {
  2493. $conf = $GLOBALS['_MAX']['CONF'];
  2494. $convert = '';
  2495. if (isset($string) && substr($string,1,4) == 'obfs' && $conf['delivery']['obfuscate']) {
  2496. $strLen = strlen($string);
  2497. for ($i=6; $i < $strLen-1; $i = $i+3) {
  2498. $dec = substr($string,$i,3);
  2499. $dec = 324 - $dec;
  2500. $dec = chr($dec);
  2501. $convert .= $dec;
  2502. }
  2503. return ($convert);
  2504. } else {
  2505. return($string);
  2506. }
  2507. }
  2508. function MAX_commonInitVariables()
  2509. {
  2510. MAX_commonRegisterGlobalsArray(array('context', 'source', 'target', 'withText', 'withtext', 'ct0', 'what', 'loc', 'referer', 'zoneid', 'campaignid', 'bannerid', 'clientid', 'charset'));
  2511. global $context, $source, $target, $withText, $withtext, $ct0, $what, $loc, $referer, $zoneid, $campaignid, $bannerid, $clientid, $charset;
  2512. if (isset($withText) && !isset($withtext)) $withtext = $withText;
  2513. $withtext = (isset($withtext) && is_numeric($withtext) ? $withtext : 0 );
  2514. $ct0 = (isset($ct0) ? $ct0 : '' );
  2515. $context = (isset($context) ? $context : array() );
  2516. $target = (isset($target) && (!empty($target)) && (!strpos($target , chr(32))) ? $target : '' );
  2517. $charset = (isset($charset) && (!empty($charset)) && (!strpos($charset, chr(32))) ? $charset : 'UTF-8' );
  2518. $bannerid = (isset($bannerid) && is_numeric($bannerid) ? $bannerid : '' );
  2519. $campaignid = (isset($campaignid) && is_numeric($campaignid) ? $campaignid : '' );
  2520. $clientid = (isset($clientid) && is_numeric($clientid) ? $clientid : '' );
  2521. $zoneid = (isset($zoneid) && is_numeric($zoneid) ? $zoneid : '' );
  2522. if (!isset($what))
  2523. {
  2524. if (!empty($bannerid)) {
  2525. $what = 'bannerid:'.$bannerid;
  2526. } elseif (!empty($campaignid)) {
  2527. $what = 'campaignid:'.$campaignid;
  2528. } elseif (!empty($zoneid)) {
  2529. $what = 'zone:'.$zoneid;
  2530. } else {
  2531. $what = '';
  2532. }
  2533. }
  2534. elseif (preg_match('/^([a-z]+):(\d+)$/', $what, $matches))
  2535. {
  2536. switch ($matches[1])
  2537. {
  2538. case 'zoneid':
  2539. case 'zone':
  2540. $zoneid = $matches[2];
  2541. break;
  2542. case 'bannerid':
  2543. $bannerid = $matches[2];
  2544. break;
  2545. case 'campaignid':
  2546. $campaignid = $matches[2];
  2547. break;
  2548. case 'clientid':
  2549. $clientid = $matches[2];
  2550. break;
  2551. }
  2552. }
  2553. if (!isset($clientid)) $clientid = '';
  2554. if (empty($campaignid)) $campaignid = $clientid;
  2555. $source = MAX_commonDeriveSource($source);
  2556. if (!empty($loc)) {
  2557. $loc = stripslashes($loc);
  2558. } elseif (!empty($_SERVER['HTTP_REFERER'])) {
  2559. $loc = $_SERVER['HTTP_REFERER'];
  2560. } else {
  2561. $loc = '';
  2562. }
  2563. if (!empty($referer)) {
  2564. $_SERVER['HTTP_REFERER'] = stripslashes($referer);
  2565. } else {
  2566. if (isset($_SERVER['HTTP_REFERER'])) unset($_SERVER['HTTP_REFERER']);
  2567. }
  2568. $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array(
  2569. $GLOBALS['_MAX']['CONF']['var']['blockAd'],
  2570. $GLOBALS['_MAX']['CONF']['var']['capAd'],
  2571. $GLOBALS['_MAX']['CONF']['var']['sessionCapAd'],
  2572. $GLOBALS['_MAX']['CONF']['var']['blockCampaign'],
  2573. $GLOBALS['_MAX']['CONF']['var']['capCampaign'],
  2574. $GLOBALS['_MAX']['CONF']['var']['sessionCapCampaign'],
  2575. $GLOBALS['_MAX']['CONF']['var']['blockZone'],
  2576. $GLOBALS['_MAX']['CONF']['var']['capZone'],
  2577. $GLOBALS['_MAX']['CONF']['var']['sessionCapZone'],
  2578. $GLOBALS['_MAX']['CONF']['var']['lastClick'],
  2579. $GLOBALS['_MAX']['CONF']['var']['lastView'],
  2580. $GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'],
  2581. );
  2582. if (strtolower($charset) == 'unicode') { $charset = 'utf-8'; }
  2583. }
  2584. function MAX_commonDisplay1x1()
  2585. {
  2586. MAX_header('Content-Type: image/gif');
  2587. MAX_header('Content-Length: 43');
  2588. echo base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==');
  2589. }
  2590. function MAX_commonGetTimeNow()
  2591. {
  2592. if (!isset($GLOBALS['_MAX']['NOW'])) {
  2593. $GLOBALS['_MAX']['NOW'] = time();
  2594. }
  2595. return $GLOBALS['_MAX']['NOW'];
  2596. }
  2597. function MAX_getRandomNumber($length = 10)
  2598. {
  2599. return substr(md5(uniqid(time(), true)), 0, $length);
  2600. }
  2601. function MAX_header($value)
  2602. {
  2603. header($value);
  2604. }
  2605. function MAX_redirect($url)
  2606. {
  2607. if (!preg_match('/^(?:javascript|data):/i', $url)) {
  2608. header('Location: '.$url);
  2609. MAX_sendStatusCode(302);
  2610. }
  2611. }
  2612. function MAX_sendStatusCode($iStatusCode) {
  2613. $aConf = $GLOBALS['_MAX']['CONF'];
  2614. $arr = array(
  2615. 100 => 'Continue',
  2616. 101 => 'Switching Protocols',
  2617. 200 => 'OK',
  2618. 201 => 'Created',
  2619. 202 => 'Accepted',
  2620. 203 => 'Non-Authoritative Information',
  2621. 204 => 'No Content',
  2622. 205 => 'Reset Content',
  2623. 206 => 'Partial Content',
  2624. 300 => 'Multiple Choices',
  2625. 301 => 'Moved Permanently',
  2626. 302 => 'Found',
  2627. 303 => 'See Other',
  2628. 304 => 'Not Modified',
  2629. 305 => 'Use Proxy',
  2630. 306 => '[Unused]',
  2631. 307 => 'Temporary Redirect',
  2632. 400 => 'Bad Request',
  2633. 401 => 'Unauthorized',
  2634. 402 => 'Payment Required',
  2635. 403 => 'Forbidden',
  2636. 404 => 'Not Found',
  2637. 405 => 'Method Not Allowed',
  2638. 406 => 'Not Acceptable',
  2639. 407 => 'Proxy Authentication Required',
  2640. 408 => 'Request Timeout',
  2641. 409 => 'Conflict',
  2642. 410 => 'Gone',
  2643. 411 => 'Length Required',
  2644. 412 => 'Precondition Failed',
  2645. 413 => 'Request Entity Too Large',
  2646. 414 => 'Request-URI Too Long',
  2647. 415 => 'Unsupported Media Type',
  2648. 416 => 'Requested Range Not Satisfiable',
  2649. 417 => 'Expectation Failed',
  2650. 500 => 'Internal Server Error',
  2651. 501 => 'Not Implemented',
  2652. 502 => 'Bad Gateway',
  2653. 503 => 'Service Unavailable',
  2654. 504 => 'Gateway Timeout',
  2655. 505 => 'HTTP Version Not Supported'
  2656. );
  2657. if (isset($arr[$iStatusCode])) {
  2658. $text = $iStatusCode . ' ' . $arr[$iStatusCode];
  2659. if (!empty($aConf['delivery']['cgiForceStatusHeader']) && strpos(php_sapi_name(), 'cgi') !== 0) {
  2660. MAX_header('Status: ' . $text);
  2661. } else {
  2662. MAX_header($_SERVER["SERVER_PROTOCOL"] .' ' . $text);
  2663. }
  2664. }
  2665. }
  2666. function MAX_commonPackContext($context = array())
  2667. {
  2668. $include = array();
  2669. $exclude = array();
  2670. foreach ($context as $idx => $value) {
  2671. reset($value);
  2672. list($key, $value) = each($value);
  2673. list($item,$id) = explode(':', $value);
  2674. switch ($item) {
  2675. case 'campaignid': $value = 'c:' . $id; break;
  2676. case 'clientid': $value = 'a:' . $id; break;
  2677. case 'bannerid': $value = 'b:' . $id; break;
  2678. case 'companionid': $value = 'p:' . $id; break;
  2679. }
  2680. switch ($key) {
  2681. case '!=': $exclude[$value] = true; break;
  2682. case '==': $include[$value] = true; break;
  2683. }
  2684. }
  2685. $exclude = array_keys($exclude);
  2686. $include = array_keys($include);
  2687. return base64_encode(implode('#', $exclude) . '|' . implode('#', $include));
  2688. }
  2689. function MAX_commonUnpackContext($context = '')
  2690. {
  2691. list($exclude,$include) = explode('|', base64_decode($context));
  2692. return array_merge(_convertContextArray('!=', explode('#', $exclude)), _convertContextArray('==', explode('#', $include)));
  2693. }
  2694. function MAX_commonCompressInt($int)
  2695. {
  2696. return base_convert($int, 10, 36);
  2697. }
  2698. function MAX_commonUnCompressInt($string)
  2699. {
  2700. return base_convert($string, 36, 10);
  2701. }
  2702. function _convertContextArray($key, $array)
  2703. {
  2704. $unpacked = array();
  2705. foreach ($array as $value) {
  2706. if (empty($value)) { continue; }
  2707. list($item, $id) = explode(':', $value);
  2708. switch ($item) {
  2709. case 'c': $unpacked[] = array($key => 'campaignid:' . $id); break;
  2710. case 'a': $unpacked[] = array($key => 'clientid:' . $id); break;
  2711. case 'b': $unpacked[] = array($key => 'bannerid:' . $id); break;
  2712. case 'p': $unpacked[] = array($key => 'companionid:'.$id); break;
  2713. }
  2714. }
  2715. return $unpacked;
  2716. }
  2717. function OX_Delivery_Common_hook($hookName, $aParams = array(), $functionName = '')
  2718. {
  2719. $return = null;
  2720. if (!empty($functionName)) {
  2721. $aParts = explode(':', $functionName);
  2722. if (count($aParts) === 3) {
  2723. $functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($functionName, $hookName);
  2724. }
  2725. if (function_exists($functionName)) {
  2726. $return = call_user_func_array($functionName, $aParams);
  2727. }
  2728. } else {
  2729. if (!empty($GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName])) {
  2730. $return = array();
  2731. $hooks = explode('|', $GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName]);
  2732. foreach ($hooks as $identifier) {
  2733. $functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hookName);
  2734. if (function_exists($functionName)) {
  2735. OX_Delivery_logMessage('calling on '.$functionName, 7);
  2736. $return[$identifier] = call_user_func_array($functionName, $aParams);
  2737. }
  2738. }
  2739. }
  2740. }
  2741. return $return;
  2742. }
  2743. function OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hook = null)
  2744. {
  2745. $aInfo = explode(':', $identifier);
  2746. $functionName = 'Plugin_' . implode('_', $aInfo) . '_Delivery' . (!empty($hook) ? '_' . $hook : '');
  2747. if (!function_exists($functionName)) {
  2748. if (!empty($GLOBALS['_MAX']['CONF']['pluginSettings']['useMergedFunctions'])) _includeDeliveryPluginFile('/var/cache/' . OX_getHostName() . '_mergedDeliveryFunctions.php');
  2749. if (!function_exists($functionName)) {
  2750. _includeDeliveryPluginFile($GLOBALS['_MAX']['CONF']['pluginPaths']['plugins'] . '/' . implode('/', $aInfo) . '.delivery.php');
  2751. if (!function_exists($functionName)) {
  2752. _includeDeliveryPluginFile('/lib/OX/Extension/' . $aInfo[0] . '/' . $aInfo[0] . 'Delivery.php');
  2753. $functionName = 'Plugin_' . $aInfo[0] . '_delivery';
  2754. if (!empty($hook) && function_exists($functionName . '_' . $hook)) {
  2755. $functionName .= '_' . $hook;
  2756. }
  2757. }
  2758. }
  2759. }
  2760. return $functionName;
  2761. }
  2762. function _includeDeliveryPluginFile($fileName)
  2763. {
  2764. if (!in_array($fileName, array_keys($GLOBALS['_MAX']['FILES']))) {
  2765. $GLOBALS['_MAX']['FILES'][$fileName] = true;
  2766. if (file_exists(MAX_PATH . $fileName)) {
  2767. include MAX_PATH . $fileName;
  2768. }
  2769. }
  2770. }
  2771. function OX_Delivery_logMessage($message, $priority = 6)
  2772. {
  2773. $conf = $GLOBALS['_MAX']['CONF'];
  2774. if (empty($conf['deliveryLog']['enabled'])) return true;
  2775. $priorityLevel = is_numeric($conf['deliveryLog']['priority']) ? $conf['deliveryLog']['priority'] : 6;
  2776. if ($priority > $priorityLevel && empty($_REQUEST[$conf['var']['trace']])) { return true; }
  2777. error_log('[' . date('r') . "] {$conf['log']['ident']}-delivery-{$GLOBALS['_MAX']['thread_id']}: {$message}\n", 3, MAX_PATH . '/var/' . $conf['deliveryLog']['name']);
  2778. OX_Delivery_Common_hook('logMessage', array($message, $priority));
  2779. return true;
  2780. }
  2781. $file = '/lib/max/Delivery/cache.php';
  2782. $GLOBALS['_MAX']['FILES'][$file] = true;
  2783. define ('OA_DELIVERY_CACHE_FUNCTION_ERROR', 'Function call returned an error');
  2784. $GLOBALS['OA_Delivery_Cache'] = array(
  2785. 'prefix' => 'deliverycache_',
  2786. 'host' => OX_getHostName(),
  2787. 'expiry' => $GLOBALS['_MAX']['CONF']['delivery']['cacheExpire']
  2788. );
  2789. function OA_Delivery_Cache_fetch($name, $isHash = false, $expiryTime = null)
  2790. {
  2791. $filename = OA_Delivery_Cache_buildFileName($name, $isHash);
  2792. $aCacheVar = OX_Delivery_Common_hook(
  2793. 'cacheRetrieve',
  2794. array($filename),
  2795. $GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin']
  2796. );
  2797. if ($aCacheVar !== false) {
  2798. if ($aCacheVar['cache_name'] != $name) {
  2799. OX_Delivery_logMessage("Cache ERROR: {$name} != {$aCacheVar['cache_name']}", 7);
  2800. return false;
  2801. }
  2802. if ($expiryTime === null) {
  2803. $expiryTime = $GLOBALS['OA_Delivery_Cache']['expiry'];
  2804. }
  2805. $now = MAX_commonGetTimeNow();
  2806. if ( (isset($aCacheVar['cache_time']) && $aCacheVar['cache_time'] + $expiryTime < $now)
  2807. || (isset($aCacheVar['cache_expire']) && $aCacheVar['cache_expire'] < $now) )
  2808. {
  2809. OA_Delivery_Cache_store($name, $aCacheVar['cache_contents'], $isHash);
  2810. OX_Delivery_logMessage("Cache EXPIRED: {$name}", 7);
  2811. return false;
  2812. }
  2813. OX_Delivery_logMessage("Cache HIT: {$name}", 7);
  2814. return $aCacheVar['cache_contents'];
  2815. }
  2816. OX_Delivery_logMessage("Cache MISS {$name}", 7);
  2817. return false;
  2818. }
  2819. function OA_Delivery_Cache_store($name, $cache, $isHash = false, $expireAt = null)
  2820. {
  2821. if ($cache === OA_DELIVERY_CACHE_FUNCTION_ERROR) {
  2822. return false;
  2823. }
  2824. $filename = OA_Delivery_Cache_buildFileName($name, $isHash);
  2825. $aCacheVar = array();
  2826. $aCacheVar['cache_contents'] = $cache;
  2827. $aCacheVar['cache_name'] = $name;
  2828. $aCacheVar['cache_time'] = MAX_commonGetTimeNow();
  2829. $aCacheVar['cache_expire'] = $expireAt;
  2830. return OX_Delivery_Common_hook(
  2831. 'cacheStore',
  2832. array($filename, $aCacheVar),
  2833. $GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin']
  2834. );
  2835. }
  2836. function OA_Delivery_Cache_store_return($name, $cache, $isHash = false, $expireAt = null)
  2837. {
  2838. OX_Delivery_Common_hook(
  2839. 'preCacheStore_'.OA_Delivery_Cache_getHookName($name),
  2840. array($name, &$cache)
  2841. );
  2842. if (OA_Delivery_Cache_store($name, $cache, $isHash, $expireAt)) {
  2843. return $cache;
  2844. }
  2845. $currentCache = OA_Delivery_Cache_fetch($name, $isHash);
  2846. if ($currentCache === false) {
  2847. return $cache;
  2848. }
  2849. return $currentCache;
  2850. }
  2851. function OA_Delivery_Cache_getHookName($name)
  2852. {
  2853. $pos = strpos($name, '^');
  2854. return $pos ? substr($name, 0, $pos) : substr($name, 0, strpos($name, '@'));
  2855. }
  2856. function OA_Delivery_Cache_buildFileName($name, $isHash = false)
  2857. {
  2858. if(!$isHash) {
  2859. $name = md5($name);
  2860. }
  2861. return $GLOBALS['OA_Delivery_Cache']['prefix'].$name.'.php';
  2862. }
  2863. function OA_Delivery_Cache_getName($functionName)
  2864. {
  2865. $args = func_get_args();
  2866. $args[0] = strtolower(str_replace('MAX_cacheGet', '', $args[0]));
  2867. return join('^', $args).'@'.$GLOBALS['OA_Delivery_Cache']['host'];
  2868. }
  2869. function MAX_cacheGetAd($ad_id, $cached = true)
  2870. {
  2871. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $ad_id);
  2872. if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
  2873. MAX_Dal_Delivery_Include();
  2874. $aRows = OA_Dal_Delivery_getAd($ad_id);
  2875. $aRows = OA_Delivery_Cache_store_return($sName, $aRows);
  2876. }
  2877. return $aRows;
  2878. }
  2879. function MAX_cacheGetAccountTZs($cached = true)
  2880. {
  2881. $sName = OA_Delivery_Cache_getName(__FUNCTION__);
  2882. if (!$cached || ($aResult = OA_Delivery_Cache_fetch($sName)) === false) {
  2883. MAX_Dal_Delivery_Include();
  2884. $aResult = OA_Dal_Delivery_getAccountTZs();
  2885. $aResult = OA_Delivery_Cache_store_return($sName, $aResult);
  2886. }
  2887. return $aResult;
  2888. }
  2889. function MAX_cacheGetZoneLinkedAds($zoneId, $cached = true)
  2890. {
  2891. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
  2892. if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
  2893. MAX_Dal_Delivery_Include();
  2894. $aRows = OA_Dal_Delivery_getZoneLinkedAds($zoneId);
  2895. $aRows = OA_Delivery_Cache_store_return($sName, $aRows);
  2896. }
  2897. return $aRows;
  2898. }
  2899. function MAX_cacheGetZoneLinkedAdInfos($zoneId, $cached = true)
  2900. {
  2901. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
  2902. if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
  2903. MAX_Dal_Delivery_Include();
  2904. $aRows = OA_Dal_Delivery_getZoneLinkedAdInfos($zoneId);
  2905. $aRows = OA_Delivery_Cache_store_return($sName, $aRows);
  2906. }
  2907. return $aRows;
  2908. }
  2909. function MAX_cacheGetZoneInfo($zoneId, $cached = true)
  2910. {
  2911. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId);
  2912. if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) {
  2913. MAX_Dal_Delivery_Include();
  2914. $aRows = OA_Dal_Delivery_getZoneInfo($zoneId);
  2915. $aRows = OA_Delivery_Cache_store_return($sName, $aRows);
  2916. }
  2917. return $aRows;
  2918. }
  2919. function MAX_cacheGetLinkedAds($search, $campaignid, $laspart, $cached = true)
  2920. {
  2921. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart);
  2922. if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) {
  2923. MAX_Dal_Delivery_Include();
  2924. $aAds = OA_Dal_Delivery_getLinkedAds($search, $campaignid, $laspart);
  2925. $aAds = OA_Delivery_Cache_store_return($sName, $aAds);
  2926. }
  2927. return $aAds;
  2928. }
  2929. function MAX_cacheGetLinkedAdInfos($search, $campaignid, $laspart, $cached = true)
  2930. {
  2931. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart);
  2932. if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) {
  2933. MAX_Dal_Delivery_Include();
  2934. $aAds = OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid, $laspart);
  2935. $aAds = OA_Delivery_Cache_store_return($sName, $aAds);
  2936. }
  2937. return $aAds;
  2938. }
  2939. function MAX_cacheGetCreative($filename, $cached = true)
  2940. {
  2941. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $filename);
  2942. if (!$cached || ($aCreative = OA_Delivery_Cache_fetch($sName)) === false) {
  2943. MAX_Dal_Delivery_Include();
  2944. $aCreative = OA_Dal_Delivery_getCreative($filename);
  2945. $aCreative['contents'] = addslashes(serialize($aCreative['contents']));
  2946. $aCreative = OA_Delivery_Cache_store_return($sName, $aCreative);
  2947. }
  2948. $aCreative['contents'] = unserialize(stripslashes($aCreative['contents']));
  2949. return $aCreative;
  2950. }
  2951. function MAX_cacheGetTracker($trackerid, $cached = true)
  2952. {
  2953. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
  2954. if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) {
  2955. MAX_Dal_Delivery_Include();
  2956. $aTracker = OA_Dal_Delivery_getTracker($trackerid);
  2957. $aTracker = OA_Delivery_Cache_store_return($sName, $aTracker);
  2958. }
  2959. return $aTracker;
  2960. }
  2961. function MAX_cacheGetTrackerLinkedCreatives($trackerid = null, $cached = true)
  2962. {
  2963. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
  2964. if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) {
  2965. MAX_Dal_Delivery_Include();
  2966. $aTracker = OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid);
  2967. $aTracker = OA_Delivery_Cache_store_return($sName, $aTracker);
  2968. }
  2969. return $aTracker;
  2970. }
  2971. function MAX_cacheGetTrackerVariables($trackerid, $cached = true)
  2972. {
  2973. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid);
  2974. if (!$cached || ($aVariables = OA_Delivery_Cache_fetch($sName)) === false) {
  2975. MAX_Dal_Delivery_Include();
  2976. $aVariables = OA_Dal_Delivery_getTrackerVariables($trackerid);
  2977. $aVariables = OA_Delivery_Cache_store_return($sName, $aVariables);
  2978. }
  2979. return $aVariables;
  2980. }
  2981. function MAX_cacheCheckIfMaintenanceShouldRun($cached = true)
  2982. {
  2983. $interval = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] * 60;
  2984. $delay = intval(($GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] / 12) * 60);
  2985. $now = MAX_commonGetTimeNow();
  2986. $today = strtotime(date('Y-m-d'), $now);
  2987. $nextRunTime = $today + (floor(($now - $today) / $interval) + 1) * $interval + $delay;
  2988. if ($nextRunTime - $now > $interval) {
  2989. $nextRunTime -= $interval;
  2990. }
  2991. $cName = OA_Delivery_Cache_getName(__FUNCTION__);
  2992. if (!$cached || ($lastRunTime = OA_Delivery_Cache_fetch($cName)) === false) {
  2993. MAX_Dal_Delivery_Include();
  2994. $lastRunTime = OA_Dal_Delivery_getMaintenanceInfo();
  2995. if ($lastRunTime >= $nextRunTime - $delay) {
  2996. $nextRunTime += $interval;
  2997. }
  2998. OA_Delivery_Cache_store($cName, $lastRunTime, false, $nextRunTime);
  2999. }
  3000. return $lastRunTime < $nextRunTime - $interval;
  3001. }
  3002. function MAX_cacheGetChannelLimitations($channelid, $cached = true)
  3003. {
  3004. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $channelid);
  3005. if (!$cached || ($limitations = OA_Delivery_Cache_fetch($sName)) === false) {
  3006. MAX_Dal_Delivery_Include();
  3007. $limitations = OA_Dal_Delivery_getChannelLimitations($channelid);
  3008. $limitations = OA_Delivery_Cache_store_return($sName, $limitations);
  3009. }
  3010. return $limitations;
  3011. }
  3012. function MAX_cacheGetGoogleJavaScript($cached = true)
  3013. {
  3014. $sName = OA_Delivery_Cache_getName(__FUNCTION__);
  3015. if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) {
  3016. $file = '/lib/max/Delivery/google.php';
  3017. if(!isset($GLOBALS['_MAX']['FILES'][$file])) {
  3018. include MAX_PATH . $file;
  3019. }
  3020. $output = MAX_googleGetJavaScript();
  3021. $output = OA_Delivery_Cache_store_return($sName, $output);
  3022. }
  3023. return $output;
  3024. }
  3025. function OA_cacheGetPublisherZones($affiliateid, $cached = true)
  3026. {
  3027. $sName = OA_Delivery_Cache_getName(__FUNCTION__, $affiliateid);
  3028. if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) {
  3029. MAX_Dal_Delivery_Include();
  3030. $output = OA_Dal_Delivery_getPublisherZones($affiliateid);
  3031. $output = OA_Delivery_Cache_store_return($sName, $output);
  3032. }
  3033. return $output;
  3034. }
  3035. OX_Delivery_logMessage('starting delivery script: ' . basename($_SERVER['REQUEST_URI']), 7);
  3036. if (!empty($_REQUEST[$conf['var']['trace']])) {
  3037. OX_Delivery_logMessage('trace enabled: ' . $_REQUEST[$conf['var']['trace']], 7);
  3038. }
  3039. MAX_remotehostSetInfo();
  3040. MAX_commonInitVariables();
  3041. MAX_cookieLoad();
  3042. MAX_cookieUnpackCapping();
  3043. if (empty($GLOBALS['_OA']['invocationType']) || $GLOBALS['_OA']['invocationType'] != 'xmlrpc') {
  3044. OX_Delivery_Common_hook('postInit');
  3045. }
  3046. function MAX_querystringConvertParams()
  3047. {
  3048. $conf = $GLOBALS['_MAX']['CONF'];
  3049. $qs = $_SERVER['QUERY_STRING'];
  3050. $dest = false;
  3051. $destStr = $conf['var']['dest'] . '=';
  3052. $pos = strpos($qs, $destStr);
  3053. if ($pos === false) {
  3054. $destStr = 'dest=';
  3055. $pos = strpos($qs, $destStr);
  3056. }
  3057. if ($pos !== false) {
  3058. $dest = urldecode(substr($qs, $pos + strlen($destStr)));
  3059. $qs = substr($qs, 0, $pos);
  3060. }
  3061. $aGet = array();
  3062. $paramStr = $conf['var']['params'] . '=';
  3063. $paramPos = strpos($qs, $paramStr);
  3064. if (is_numeric($paramPos)) {
  3065. $qs = urldecode(substr($qs, $paramPos + strlen($paramStr)));
  3066. $delim = $qs{0};
  3067. if (is_numeric($delim)) {
  3068. $delim = substr($qs, 1, $delim);
  3069. }
  3070. $qs = substr($qs, strlen($delim) + 1);
  3071. MAX_querystringParseStr($qs, $aGet, $delim);
  3072. $qPos = isset($aGet[$conf['var']['dest']]) ? strpos($aGet[$conf['var']['dest']], '?') : false;
  3073. $aPos = isset($aGet[$conf['var']['dest']]) ? strpos($aGet[$conf['var']['dest']], '&') : false;
  3074. if ($aPos && !$qPos) {
  3075. $desturl = substr($aGet[$conf['var']['dest']], 0, $aPos);
  3076. $destparams = substr($aGet[$conf['var']['dest']], $aPos+1);
  3077. $aGet[$conf['var']['dest']] = $desturl . '?' . $destparams;
  3078. }
  3079. } else {
  3080. parse_str($qs, $aGet);
  3081. }
  3082. if ($dest !== false) {
  3083. $aGet[$conf['var']['dest']] = $dest;
  3084. }
  3085. $n = isset($_GET[$conf['var']['n']]) ? $_GET[$conf['var']['n']] : '';
  3086. if (empty($n)) {
  3087. $n = isset($aGet[$conf['var']['n']]) ? $aGet[$conf['var']['n']] : '';
  3088. }
  3089. if (!empty($n) && !empty($_COOKIE[$conf['var']['vars']][$n])) {
  3090. $aVars = unserialize(stripslashes($_COOKIE[$conf['var']['vars']][$n]));
  3091. foreach ($aVars as $name => $value) {
  3092. if (!isset($_GET[$name])) {
  3093. $aGet[$name] = $value;
  3094. }
  3095. }
  3096. }
  3097. $_GET = $aGet;
  3098. $_REQUEST = $_GET + $_POST + $_COOKIE;
  3099. }
  3100. function MAX_querystringGetDestinationUrl($adId = null)
  3101. {
  3102. $conf = $GLOBALS['_MAX']['CONF'];
  3103. $dest = isset($_REQUEST[$conf['var']['dest']]) ? $_REQUEST[$conf['var']['dest']] : '';
  3104. if (empty($dest) && !empty($adId)) {
  3105. $aAd = MAX_cacheGetAd($adId);
  3106. if (!empty($aAd)) {
  3107. $dest = $aAd['url'];
  3108. }
  3109. }
  3110. if (empty($dest)) {
  3111. return;
  3112. }
  3113. $aVariables = array();
  3114. $aValidVariables = array_values($conf['var']);
  3115. $componentParams = OX_Delivery_Common_hook('addUrlParams', array(array('bannerid' => $adId)));
  3116. if (!empty($componentParams) && is_array($componentParams)) {
  3117. foreach ($componentParams as $params) {
  3118. if (!empty($params) && is_array($params)) {
  3119. foreach ($params as $key => $value) {
  3120. $aValidVariables[] = $key;
  3121. }
  3122. }
  3123. }
  3124. }
  3125. $destParams = parse_url($dest);
  3126. if (!empty($destParams['query'])) {
  3127. $destQuery = explode('&', $destParams['query']);
  3128. if (!empty($destQuery)) {
  3129. foreach ($destQuery as $destPair) {
  3130. list($destName, $destValue) = explode('=', $destPair);
  3131. $aValidVariables[] = $destName;
  3132. }
  3133. }
  3134. }
  3135. foreach ($_GET as $name => $value) {
  3136. if (!in_array($name, $aValidVariables)) {
  3137. $aVariables[] = $name . '=' . $value;
  3138. }
  3139. }
  3140. foreach ($_POST as $name => $value) {
  3141. if (!in_array($name, $aValidVariables)) {
  3142. $aVariables[] = $name . '=' . $value;
  3143. }
  3144. }
  3145. if (!empty($aVariables)) {
  3146. $dest .= ((strpos($dest, '?') > 0) ? '&' : '?') . implode('&', $aVariables);
  3147. }
  3148. return $dest;
  3149. }
  3150. function MAX_querystringParseStr($qs, &$aArr, $delim = '&')
  3151. {
  3152. $aArr = $_GET;
  3153. $aElements = explode($delim, $qs);
  3154. foreach($aElements as $element) {
  3155. $len = strpos($element, '=');
  3156. if ($len !== false) {
  3157. $name = substr($element, 0, $len);
  3158. $value = substr($element, $len+1);
  3159. $aArr[$name] = urldecode($value);
  3160. }
  3161. }
  3162. }
  3163. MAX_commonSetNoCacheHeaders();
  3164. MAX_querystringConvertParams();
  3165. MAX_commonRemoveSpecialChars($_REQUEST);
  3166. $viewerId = MAX_cookieGetUniqueViewerID();
  3167. if (!empty($GLOBALS['_MAX']['COOKIE']['newViewerId']) && empty($_GET[$conf['var']['cookieTest']])) {
  3168. MAX_cookieSetViewerIdAndRedirect($viewerId);
  3169. }
  3170. $adId = isset($_REQUEST[$conf['var']['adId']]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_REQUEST[$conf['var']['adId']]) : array();
  3171. $zoneId = isset($_REQUEST[$conf['var']['zoneId']]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_REQUEST[$conf['var']['zoneId']]) : array();
  3172. $creativeId = isset($_REQUEST[$conf['var']['creativeId']]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_REQUEST[$conf['var']['creativeId']]) : array();
  3173. $lastClick = isset($_REQUEST[$conf['var']['lastClick']]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_REQUEST[$conf['var']['lastClick']]) : array();
  3174. $aBlockLoggingClick = isset($_REQUEST[$conf['var']['blockLoggingClick']]) ? $_REQUEST[$conf['var']['blockLoggingClick']] : array();
  3175. if (!empty($conf['deliveryLog']['enabled'])) {
  3176. foreach ($adId as $k => $v) {
  3177. OX_Delivery_logMessage('$adId['.$k.']='.$v, 7);
  3178. }
  3179. foreach ($zoneId as $k => $v) {
  3180. OX_Delivery_logMessage('$zoneId['.$k.']='.$v, 7);
  3181. }
  3182. foreach ($creativeId as $k => $v) {
  3183. OX_Delivery_logMessage('$creativeId['.$k.']='.$v, 7);
  3184. }
  3185. foreach ($lastClick as $k => $v) {
  3186. OX_Delivery_logMessage('$lastClick['.$k.']='.$v, 7);
  3187. }
  3188. foreach ($aBlockLoggingClick as $k => $v) {
  3189. OX_Delivery_logMessage('$aBlockLoggingClick['.$k.']='.$v, 7);
  3190. }
  3191. }
  3192. if (empty($adId) && !empty($zoneId)) {
  3193. foreach ($zoneId as $index => $zone) {
  3194. $adId[$index] = _getZoneAd($zone);
  3195. $creativeId[$index] = 0;
  3196. }
  3197. }
  3198. for ($i = 0; $i < count($adId); $i++) {
  3199. $adId[$i] = intval($adId[$i]);
  3200. $zoneId[$i] = intval($zoneId[$i]);
  3201. if (isset($creativeId[$i])) {
  3202. $creativeId[$i] = intval($creativeId[$i]);
  3203. } else {
  3204. $creativeId[$i] = 0;
  3205. }
  3206. if (($adId[$i] > 0 || $adId[$i] == -1) && ($conf['logging']['adClicks']) && !(isset($_GET['log']) && ($_GET['log'] == 'no'))) {
  3207. if (!MAX_Delivery_log_isClickBlocked($adId[$i], $aBlockLoggingClick)) {
  3208. if (isset($GLOBALS['conf']['logging']['blockAdClicksWindow']) && $GLOBALS['conf']['logging']['blockAdClicksWindow'] != 0) {
  3209. MAX_Delivery_log_setClickBlocked($i, $adId);
  3210. }
  3211. MAX_Delivery_log_logAdClick($adId[$i], $zoneId[$i]);
  3212. MAX_Delivery_log_setLastAction($i, $adId, $zoneId, $lastClick, 'click');
  3213. }
  3214. }
  3215. }
  3216. MAX_cookieAdd($conf['var']['viewerId'], $viewerId, time() + $conf['cookie']['permCookieSeconds']);
  3217. MAX_cookieFlush();
  3218. $destination = MAX_querystringGetDestinationUrl($adId[0]);
  3219. if (!empty($destination) && empty($_GET['trackonly'])) {
  3220. if (!preg_match('/[\r\n]/', $destination)) {
  3221. MAX_redirect($destination);
  3222. }
  3223. }
  3224. function _getZoneAd($zoneId)
  3225. {
  3226. $conf = $GLOBALS['conf'];
  3227. $zoneLinkedAds = MAX_cacheGetZoneLinkedAds($zoneId, false);
  3228. if (!empty($zoneLinkedAds['xAds']) && count($zoneLinkedAds['xAds']) == 1) {
  3229. reset($zoneLinkedAds['xAds']);
  3230. list($adId, $ad) = each($zoneLinkedAds['xAds']);
  3231. } elseif (!empty($zoneLinkedAds['ads']) && count($zoneLinkedAds['ads']) == 1) {
  3232. reset($zoneLinkedAds['ads']);
  3233. foreach($zoneLinkedAds['ads'] as $priority => $ads) {
  3234. foreach($ads as $adId => $ad) {
  3235. break;
  3236. }
  3237. }
  3238. } elseif (!empty($zoneLinkedAds['lAds']) && count($zoneLinkedAds['lAds']) == 1) {
  3239. reset($zoneLinkedAds['lAds']);
  3240. list($adId, $ad) = each($zoneLinkedAds['lAds']);
  3241. }
  3242. if (!empty($ad['url'])) {
  3243. $_REQUEST[$conf['var']['dest']] = $ad['url'];
  3244. }
  3245. return $adId;
  3246. }