Beispiel #1
0
 /**
  * Check start/end dates - note that check is the reverse of normal check:
  * if the operation interval is <= 60, must be start/end of an hour, to
  * make sure we update all the operation intervals in the hour, and if
  * the operation interval > 60, must be the start/end of an operation
  * interval, to make sure we update all the hours in the operation interval.
  *
  * @static
  * @param Date $oStartDate
  * @param Date $oEndDate
  * @return boolean
  */
 function checkDates($oStartDate, $oEndDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $operationInterval = $aConf['maintenance']['operation_interval'];
     if ($operationInterval <= 60) {
         // Must ensure that only one hour is being summarised
         if (!OX_OperationInterval::checkDatesInSameHour($oStartDate, $oEndDate)) {
             return false;
         }
         // Now check that the start and end dates are match the start and
         // end of the hour
         $oHourStart = new Date();
         $oHourStart->setYear($oStartDate->getYear());
         $oHourStart->setMonth($oStartDate->getMonth());
         $oHourStart->setDay($oStartDate->getDay());
         $oHourStart->setHour($oStartDate->getHour());
         $oHourStart->setMinute('00');
         $oHourStart->setSecond('00');
         $oHourEnd = new Date();
         $oHourEnd->setYear($oEndDate->getYear());
         $oHourEnd->setMonth($oEndDate->getMonth());
         $oHourEnd->setDay($oEndDate->getDay());
         $oHourEnd->setHour($oEndDate->getHour());
         $oHourEnd->setMinute('59');
         $oHourEnd->setSecond('59');
         if (!$oStartDate->equals($oHourStart)) {
             return false;
         }
         if (!$oEndDate->equals($oHourEnd)) {
             return false;
         }
     } else {
         // Must ensure that only one operation interval is being summarised
         $operationIntervalID = OX_OperationInterval::convertDaySpanToOperationIntervalID($oStartDate, $oEndDate, $operationInterval);
         if (is_bool($operationIntervalID) && !$operationIntervalID) {
             return false;
         }
         // Now check that the start and end dates match the start and end
         // of the operation interval
         list($oOperationIntervalStart, $oOperationIntervalEnd) = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate, $operationInterval);
         if (!$oStartDate->equals($oOperationIntervalStart)) {
             return false;
         }
         if (!$oEndDate->equals($oOperationIntervalEnd)) {
             return false;
         }
     }
     return true;
 }
Beispiel #2
0
 /**
  * A method for obtaining the targeting statistics of an ad or placement
  * for a single day, where the data is summarised by operation interval.
  *
  * @param integer    $id    The ad or placement ID.
  * @param string     $type  Either "ad" or "placement".
  * @param PEAR::Date $oDate A date representing the day required.
  *
  * @return mixed Returns false in the event of incorrect input, or in the case
  *               of being unable to connect to the database, otherwise, returns
  *               an array of arrays:
  *
  *
  * array(
  *     [$operationIntervalId] => array(
  *                                  ['interval_start']             => PEAR::Date
  *                                  ['interval_end']               => PEAR::Date
  *                                  ['ad_required_impressions']    => integer
  *                                  ['ad_requested_impressions']   => integer
  *                                  ['ad_actual_impressions']      => integer
  *                                  ['zones_forecast_impressions'] => integer
  *                                  ['zones_actual_impressions']   => integer
  *                                  ['average']                    => integer
  *                               )
  *      .
  *      .
  *      .
  * )
  *
  * or:
  *
  * array(
  *     [$operationIntervalId] => array(
  *                                  ['interval_start']                  => PEAR::Date
  *                                  ['interval_end']                    => PEAR::Date
  *                                  ['placement_required_impressions']  => integer
  *                                  ['placement_requested_impressions'] => integer
  *                                  ['placement_actual_impressions']    => integer
  *                                  ['zones_forecast_impressions']      => integer
  *                                  ['zones_actual_impressions']        => integer
  *                                  ['average']                         => integer
  *                               )
  *      .
  *      .
  *      .
  * )
  *
  * For the ad or placement and day specified, returns an array for each
  * operation interval in the day, consisting of the operation interval start
  * and end dates, and the total number of impressions requested by the ad, or
  * all ads in the placement (for all zones the ads are linked to), as well as
  * the total number of impressions actually delivered by the ad, or all ads
  * in the placement (for all zones the ads are linked to).
  *
  * The individual ad/zone impressions requested values may need to be
  * calculated as an "averge" value, in the event that there are multiple,
  * differing values for an ad in a zone for an operation interval -- in
  * much the same way as is done in
  * OA_Dal_Maintenance_Priority::getPreviousAdDeliveryInfo() -- before
  * the total impressions requested value can be calculated.
  */
 function getDailyTargetingStatistics($id, $type, $oDate)
 {
     if (!$this->_testGetTargetingStatisticsDayParameters($id, $type, $oDate)) {
         return false;
     }
     // Ensure that, if a placement, the placement has advertisements
     $aAdIds = $this->_testGetTargetingStatisticsSpanPlacement($id, $type);
     if ($aAdIds === false) {
         return false;
     }
     // Prepare the results array
     $aResult = array();
     // Get a date for the start of the day
     $oStartDate = new Date();
     $oStartDate->copy($oDate);
     $oStartDate->setHour(0);
     $oStartDate->setMinute(0);
     $oStartDate->setSecond(0);
     // Get a date for the end of the day
     $oEndOfDayDate = new Date();
     $oEndOfDayDate->copy($oDate);
     $oEndOfDayDate->setHour(23);
     $oEndOfDayDate->setMinute(59);
     $oEndOfDayDate->setSecond(59);
     // Get the first operation interval of the day
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate);
     // Get dates to be used in date comparisons
     $oCompareDate = new Date();
     $oCompareDate->copy($aDates['start']);
     $oCompareEndDate = new Date();
     $oCompareEndDate->copy($oEndOfDayDate);
     while ($oCompareDate->before($oEndOfDayDate)) {
         // Get the operation interval ID
         $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
         // Get the results for this operation interval
         $aResult[$operationIntervalId] = $this->getOperationIntervalTargetingStatistics($aAdIds, $type, $aDates['start'], $aDates['end']);
         if ($aResult[$operationIntervalId] === false) {
             return false;
         }
         // Get the next operation interval dates
         $aDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($aDates['start']);
         // Update the comparison dates
         $oCompareDate = new Date();
         $oCompareDate->copy($aDates['start']);
         $oCompareEndDate = new Date();
         $oCompareEndDate->copy($oEndOfDayDate);
     }
     return $aResult;
 }
 function _getOperationIntervalInfo(&$operationIntervalId, &$operationInterval, &$dateStart, &$dateEnd)
 {
     $date = new Date();
     $operationInterval = new OX_OperationInterval();
     $operationIntervalId = $operationInterval->convertDateToOperationIntervalID($date);
     $operationInterval = OX_OperationInterval::getOperationInterval();
     $aOperationIntervalDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($date);
     $dateStart = DBC::makeLiteral($aOperationIntervalDates['start']->format(TIMESTAMP_FORMAT));
     $dateEnd = DBC::makeLiteral($aOperationIntervalDates['end']->format(TIMESTAMP_FORMAT));
 }
 /**
  * A method to test the getAdLifetimeZoneImpressionsRemaining() method.
  *
  * Test 1: Test with invalid parameters, and ensure that zero is returned.
  * Test 2: Test with equal start and end dates, and ensure just that OI's
  *         data is returned.
  * Test 3: Test with a small range of dates in one week, that the correct
  *         sum is returned.
  * Test 4: Test with a small range of dates over three days, covering two
  *         weeks, and ensure that the correct result is returned.
  * Test 5: Test with a limitation that blocks less than 50% of the remaining
  *         range, and ensure that the correct result is returned.
  * Test 6: Test with a limitation that blocks more than 50% of the remaining
  *         range, and ensure that the correct result is returned.
  */
 function testGetAdLifetimeZoneImpressionsRemaining()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 60;
     $aDeliveryLimitations = array();
     $oDeliveryLimitationManager = new OA_Maintenance_Priority_DeliveryLimitation($aDeliveryLimitations);
     // Test 1
     $oDate = new Date('2006-02-15 11:07:15');
     $aCumulativeZoneForecast = array();
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining('foo', $oDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 0);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oDate, 'foo', $aCumulativeZoneForecast);
     $this->assertEqual($result, 0);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oDate, $oDate, 'foo');
     $this->assertEqual($result, 0);
     // Test 2
     $oDate = new Date('2006-02-15 23:07:15');
     $aCumulativeZoneForecast = array();
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oDate, $oDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 1);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
     $aCumulativeZoneForecast[$operationIntervalID] = 50;
     $previousOperationIntervalId = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aCumulativeZoneForecast[$previousOperationIntervalId] = 5;
     $nextOperationIntervalId = OX_OperationInterval::nextOperationIntervalID($operationIntervalID);
     $aCumulativeZoneForecast[$nextOperationIntervalId] = 7;
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oDate, $oDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 50);
     // Test 3
     $oStartDate = new Date('2006-02-15 11:07:15');
     $oEndDate = new Date('2006-02-15 23:59:59');
     $aCumulativeZoneForecast = array();
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 10:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 1;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 11:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 10;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 12:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 100;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 13:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 1000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 14:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 10000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 15:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 100000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-15 16:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 1000000;
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oStartDate, $oEndDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 1111110 + 7);
     // Test 4
     $oStartDate = new Date('2006-02-18 22:07:15');
     $oEndDate = new Date('2006-02-20 23:59:59');
     $aCumulativeZoneForecast = array();
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-18 21:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 1;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-18 22:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 10;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-18 23:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 100;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-19 00:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 1000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-19 01:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 10000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-19 02:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 100000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-19 03:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 1000000;
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID(new Date('2006-02-19 04:00:01'));
     $aCumulativeZoneForecast[$operationIntervalID] = 10000000;
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oStartDate, $oEndDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 110 + 11111000 + 19 + 24);
     // Test 5
     $oStartDate = new Date('2006-02-07 12:07:15');
     $oEndDate = new Date('2006-02-07 23:59:59');
     $aDeliveryLimitations = array(array('ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Hour', 'comparison' => '!~', 'data' => '23', 'executionorder' => 0));
     $oDeliveryLimitationManager = new OA_Maintenance_Priority_DeliveryLimitation($aDeliveryLimitations);
     $oDeliveryLimitationManager->getActiveAdOperationIntervals(12, $oStartDate, $oEndDate);
     $aCumulativeZoneForecast = array();
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oStartDate, $oEndDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 11);
     // Test 6
     $oStartDate = new Date('2006-02-07 12:07:15');
     $oEndDate = new Date('2006-02-08 23:59:59');
     $aDeliveryLimitations = array(array('ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Hour', 'comparison' => '=~', 'data' => '22', 'executionorder' => 0));
     $oDeliveryLimitationManager = new OA_Maintenance_Priority_DeliveryLimitation($aDeliveryLimitations);
     $oDeliveryLimitationManager->getActiveAdOperationIntervals(12, $oStartDate, $oEndDate);
     $aCumulativeZoneForecast = array();
     $aCumulativeZoneForecast = $this->_fillForecastArray($aCumulativeZoneForecast);
     $result = $oDeliveryLimitationManager->getAdLifetimeZoneImpressionsRemaining($oStartDate, $oEndDate, $aCumulativeZoneForecast);
     $this->assertEqual($result, 2);
     TestEnv::restoreConfig();
 }
 /**
  * Method to test the getZonesForecastsForAllZones method.
  *
  * Requirements:
  * Test 1: Test with no Date registered in the service locator, ensure false returned.
  * Test 2: Test with a Date registered in the service locator, no data in the database,
  *         and ensure no data is returned.
  * Test 3: Test with forecast data but no actual impressions
  * Test 3.5: Test with actual data but no forecast impressions
  * Test 4: Test with data both in, and not in, the current OI, and ensure the correct
  *         data is returned.
  * Test 5: Repeat Test 4, but with additional zones (that don't have data) in the zones
  *         table.
  */
 function testGetAllZonesImpInv()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     $zoneForecastDefaultZoneImpressions = 0;
     // $oMaxDalMaintenance->getZoneForecastDefaultZoneImpressions();
     // Test 1
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertFalse($result);
     // Test 2
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertEqual($result, array(0 => $zoneForecastDefaultZoneImpressions));
     // Zone 0
     // Test 3
     // generate the first zone
     $aZones = $this->_generateTestZones(1);
     //         only generate previous OI delivered impressions, should return zone 0 only
     $oDate =& $oServiceLocator->get('now');
     $oNewDate = new Date();
     $oNewDate->copy($oDate);
     $oNewDate->subtractSeconds($conf['maintenance']['operationInterval'] * 60 + 1);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate);
     $this->_generateTestHistory(1, $aDates, 42, 0);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => $zoneForecastDefaultZoneImpressions);
     $this->assertEqual($result, $expected);
     // Test 3.5
     // generate the second zone
     $aZones = $this->_generateTestZones(1);
     //     only generate previous OI forecasted impressions, should return zone 0 only
     $oNewDate = new Date();
     $oNewDate->copy($aDates['start']);
     $oNewDate->subtractSeconds(1);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate);
     $this->_generateTestHistory(2, $aDates, 0, 37);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => $zoneForecastDefaultZoneImpressions, 2 => $zoneForecastDefaultZoneImpressions);
     $this->assertEqual($result, $expected);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 4
     $oDate =& $oServiceLocator->get('now');
     // generate three zone
     $this->_generateTestZones(3);
     // set forecast and impressions for OI - 1
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->_generateTestHistory(1, $aDates, 42, 100);
     $this->_generateTestHistory(2, $aDates, 5, 2);
     $this->_generateTestHistory(3, $aDates, 9999, 9999);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => 42, 2 => 5, 3 => 9999);
     $this->assertEqual($result, $expected);
     // Test 5
     // New zone must appear in the array with default forecast
     $aZones = $this->_generateTestZones(1);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => 42, 2 => 5, 3 => 9999, 4 => $zoneForecastDefaultZoneImpressions);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertEqual($result, $expected);
     // register forecast for the OI before, this should not affect current OI forecast
     $oDate =& $oServiceLocator->get('now');
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $currentOpIntID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
     $this->_generateTestHistory(1, $aDates, 3700, 0);
     $this->_generateTestHistory(2, $aDates, 300, 0);
     $this->_generateTestHistory(3, $aDates, 500, 0);
     $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones();
     $this->assertEqual($result, $expected);
     DataGenerator::cleanUp();
 }
 /**
  * A method to test the MAX_Delivery_log_logConversion() function.
  */
 function test_MAX_Delivery_log_logConversion()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 60;
     $GLOBALS['_MAX']['NOW'] = time();
     $oNowDate = new Date($GLOBALS['_MAX']['NOW']);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
     $intervalStart = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $oConversionDate = new Date();
     $oConversionDate->copy($oNowDate);
     $oConversionDate->subtractSeconds(60);
     $_SERVER['REMOTE_ADDR'] = '127.0.0.99';
     // Test to ensure that the openXDeliveryLog plugin's data bucket
     // table does not exist
     $oTable = new OA_DB_Table();
     $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a');
     $this->assertFalse($tableExists);
     // Test calling the main logging function without any plugins installed,
     // to ensure that this does not result in any kind of error
     $aConversion = array('action_type' => MAX_CONNECTION_AD_CLICK, 'tracker_type' => MAX_CONNECTION_TYPE_SALE, 'status' => MAX_CONNECTION_STATUS_APPROVED, 'cid' => 2, 'zid' => 3, 'dt' => $GLOBALS['_MAX']['NOW'] - 60, 'window' => 60);
     MAX_Delivery_log_logConversion(1, $aConversion);
     // Install the openXDeliveryLog plugin
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     // Test to ensure that the openXDeliveryLog plugin's data bucket
     // table now does exist
     $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a');
     $this->assertTrue($tableExists);
     // Ensure that there are is nothing logged in the data bucket table
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 0);
     // Call the conversion logging function
     $aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion);
     // Ensure that the data was logged correctly
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->server_conv_id = 1;
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a->fetch();
     $this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
     $this->assertEqual($doData_bkt_a->tracker_id, 1);
     $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->creative_id, 2);
     $this->assertEqual($doData_bkt_a->zone_id, 3);
     $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
     $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
     $this->assertEqual($doData_bkt_a->window, 60);
     $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
     $this->assertTrue(is_array($aConversionInfo));
     $this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion']));
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 1);
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB');
     $aConversion['cid'] = 5;
     // Call the conversion logging function
     $aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion);
     // Ensure that the data was logged correctly
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 2);
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->server_conv_id = 1;
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a->fetch();
     $this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
     $this->assertEqual($doData_bkt_a->tracker_id, 1);
     $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->creative_id, 2);
     $this->assertEqual($doData_bkt_a->zone_id, 3);
     $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
     $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
     $this->assertEqual($doData_bkt_a->window, 60);
     $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
     $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
     $doData_bkt_a->server_conv_id = 2;
     $doData_bkt_a->find();
     $rows = $doData_bkt_a->getRowCount();
     $this->assertEqual($rows, 1);
     $doData_bkt_a->fetch();
     $this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
     $this->assertEqual($doData_bkt_a->tracker_id, 1);
     $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($doData_bkt_a->creative_id, 5);
     $this->assertEqual($doData_bkt_a->zone_id, 3);
     $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
     $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
     $this->assertEqual($doData_bkt_a->window, 60);
     $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
     $this->assertTrue(is_array($aConversionInfo));
     $this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion']));
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 2);
     $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB');
     // Uninstall the openXDeliveryLog plugin
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Restore the test configuration file
     TestEnv::restoreConfig();
 }
 /**
  * A method to prune a bucket of all records up to and
  * including the time given.
  *
  * @param Date $oEnd   Prune until this interval_start (inclusive).
  * @param Date $oStart Only prune before this interval_start date (inclusive)
  *                     as well. Optional.
  * @return mixed Either the number of rows pruned, or an MDB2_Error objet.
  */
 public function pruneBucket($oBucket, $oEnd, $oStart = null)
 {
     $sTableName = $oBucket->getBucketTableName();
     if (!is_null($oStart)) {
         OA::debug('  - Pruning the ' . $sTableName . ' table for data with operation interval start between ' . $oStart->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStart->tz->getShortName() . ' and ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG);
     } else {
         OA::debug('  - Pruning the ' . $sTableName . ' table for all data with operation interval start equal to or before ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG);
     }
     // As this is raw data being processed, data will not be logged based on the operation interval,
     // but based on the time the raw data was collected. Adjust the $oEnd value accordingly...
     if (!is_null($oStart)) {
         $aStartDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStart);
     }
     $aEndDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oEnd);
     OA::debug('    - The ' . $sTableName . ' table is a raw data table. Data logged in real-time, not operation intervals.', PEAR_LOG_INFO);
     if (!is_null($oStart)) {
         OA::debug('    - Accordingly, pruning of the ' . $sTableName . ' table will be performed based on data that has a logged date between ', PEAR_LOG_INFO);
         OA::debug('      ' . $aStartDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aStartDates['start']->tz->getShortName() . ' and ' . $aEndDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aEndDates['end']->tz->getShortName(), PEAR_LOG_INFO);
     } else {
         OA::debug('    - Accordingly, pruning of the ' . $sTableName . ' table will be performed based on data that has a logged date equal to', PEAR_LOG_INFO);
         OA::debug('      or before ' . $aEndDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aEndDates['end']->tz->getShortName(), PEAR_LOG_INFO);
     }
     $query = "\n            DELETE FROM\n                {$sTableName}\n            WHERE\n                date_time <= " . DBC::makeLiteral($aEndDates['end']->format('%Y-%m-%d %H:%M:%S'));
     if (!is_null($oStart)) {
         $query .= "\n                AND\n                date_time >= " . DBC::makeLiteral($aStartDates['start']->format('%Y-%m-%d %H:%M:%S'));
     }
     $oDbh = OA_DB::singleton();
     return $oDbh->exec($query);
 }
 /**
  * A method to check that two Dates represent either the start and end
  * of an operation interval, if the operation interval is less than an
  * hour, or the start and end of an hour otherwise.
  *
  * @static
  * @param Date $oStart The interval start date.
  * @param Date $oEnd The interval end date.
  * @param integer $operationInterval The operation interval in minutes.
  * @return bool Returns true if the dates are correct interval
  *              start/end dates, false otherwise.
  */
 function checkIntervalDates($oStart, $oEnd, $operationInterval = 0)
 {
     if ($operationInterval < 1) {
         $operationInterval = OX_OperationInterval::getOperationInterval();
     }
     if ($operationInterval <= 60) {
         // Must ensure that only one operation interval is being summarised
         $operationIntervalID = OX_OperationInterval::convertDateRangeToOperationIntervalID($oStart, $oEnd, $operationInterval);
         if (is_bool($operationIntervalID) && !$operationIntervalID) {
             return false;
         }
         // Now check that the start and end dates match the start and end
         // of the operation interval
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStart, $operationInterval);
         if (!$oStart->equals($aDates['start'])) {
             return false;
         }
         if (!$oEnd->equals($aDates['end'])) {
             return false;
         }
     } else {
         // Must ensure that only one hour is being summarised
         if (!OX_OperationInterval::checkDatesInSameHour($oStart, $oEnd)) {
             return false;
         }
         // Now check that the start and end dates are match the start and
         // end of the hour
         $oHourStart = new Date();
         $oHourStart->copy($oStart);
         $oHourStart->setMinute('00');
         $oHourStart->setSecond('00');
         $oHourEnd = new Date();
         $oHourEnd->copy($oEnd);
         $oHourEnd->setMinute('59');
         $oHourEnd->setSecond('59');
         if (!$oStart->equals($oHourStart)) {
             return false;
         }
         if (!$oEnd->equals($oHourEnd)) {
             return false;
         }
     }
     return true;
 }
Beispiel #9
0
 /**
  * A method to determine the lifetime ad conversions left before expiration.
  *
  * @param integer    $campaignId The campaign ID.
  * @param PEAR::Date $oDate      An optional date. If present, sets an upper
  *                               date boundary of the end of the operation
  *                               interval the date is in to limit the delivery
  *                               statistics used in determining how many
  *                               conversions have delivered. Can be used to
  *                               determine the the lifetime ad conversions left
  *                               before expiration at a previous time.
  * @return mixed The number of ad conversions remaining, or the
  *               string "unlimited".
  */
 function getAdConversionsLeft($campaignId, $oDate = null)
 {
     global $strUnlimited;
     $prefix = $this->getTablePrefix();
     // Get the campaign info
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->get($campaignId);
     $aData = $doCampaigns->toArray();
     if ($aData['clicks'] > 0) {
         // Get the campaign delivery info
         if (!is_null($oDate)) {
             // Get the end of operation interval the date represents
             $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
             $oDate = $aDates['end'];
         }
         $dalDataIntermediateAd = OA_Dal::factoryDAL('data_intermediate_ad');
         $record = $dalDataIntermediateAd->getDeliveredByCampaign($campaignId, $oDate);
         $aDeliveryData = $record->toArray();
         return $aData['conversions'] - $aDeliveryData['conversions_delivered'];
     } else {
         return $strUnlimited;
     }
 }
Beispiel #10
0
 /**
  * A method to return the forcast impressions for a zone, indexed by operation interval,
  * from the current operation interval through the past week. If no forecast stored in
  * the database, uses the defualt value from the configuration file.
  *
  * @param integer $zoneId The Zone ID.
  * @return mixed An array on success, false on failure. The array is of the format:
  *                   array(
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['forecast_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['forecast_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                                   .
  *                                   .
  *                                   .
  *                   )
  */
 function getPreviousWeekZoneForcastImpressions($zoneId)
 {
     if (empty($zoneId) || !is_numeric($zoneId)) {
         OA::debug('Invalid zone ID argument', PEAR_LOG_ERR);
         return false;
     }
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oDate =& $oServiceLocator->get('now');
     if (!$oDate) {
         return false;
     }
     // Get the start and end ranges of the current week
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $oDateWeekStart = new Date();
     $oDateWeekStart->copy($aDates['end']);
     $oDateWeekStart->subtractSeconds(SECONDS_PER_WEEK - 1);
     $oDateWeekEnd = new Date();
     $oDateWeekEnd->copy($aDates['end']);
     // Select the zone forecasts from the database
     $tableName = $this->_getTablename('data_summary_zone_impression_history');
     $query = "\n            SELECT\n                zone_id AS zone_id,\n                forecast_impressions AS forecast_impressions,\n                operation_interval_id AS operation_interval_id,\n                interval_start AS interval_start,\n                interval_end AS interval_end\n            FROM\n                {$tableName}\n            WHERE\n                zone_id = {$zoneId}\n                AND operation_interval = {$aConf['maintenance']['operationInterval']}\n                AND interval_start >= '" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "'\n                AND interval_end <= '" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "'\n                AND zone_id != 0\n            ORDER BY\n                interval_start";
     $rc = $this->oDbh->query($query);
     if (!PEAR::isError($rc)) {
         // Sort the results into an array indexed by the operation interval ID
         $aFinalResult = array();
         while ($aRow = $rc->fetchRow()) {
             $aFinalResult[$aRow['operation_interval_id']] = array('zone_id' => $aRow['zone_id'], 'forecast_impressions' => $aRow['forecast_impressions'], 'operation_interval_id' => $aRow['operation_interval_id']);
         }
     }
     // Check each operation interval ID has a forecast impression value,
     // and if not, set to the system default.
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         if (!isset($aFinalResult[$operationIntervalID])) {
             $aFinalResult[$operationIntervalID] = array('zone_id' => $zoneId, 'forecast_impressions' => ZONE_FORECAST_DEFAULT_ZONE_IMPRESSIONS, 'operation_interval_id' => $operationIntervalID);
         }
     }
     return $aFinalResult;
 }
Beispiel #11
0
 /**
  * A method to return data about the times that various Maintenance
  * processes ran.
  *
  * @param string $tableName The name of the log_maintenance_* table to get data from.
  *                          Must be a complete table name, including prefix, if
  *                          required.
  * @param array  $aAdditionalFields An array of strings, representing any additional
  *                                  data fields to return, along with the default
  *                                  'updated_to' field.
  * @param string $whereClause Optional string, containing a valid SQL WHERE clause,
  *                            if this is required to limit the results of the log data
  *                            before ordering and returning.
  * @param string $orderBy Optional string to specify the DB field used to sort the data
  *                        into DESCENDING order, before selecting the first value. Default
  *                        is 'start_run'.
  * @param array $aAlternateInfo Optional array containing two fields, 'tableName', which
  *                              is a string of the name of a raw table which will be searched
  *                              for the earliest date/time, in the event that no valid
  *                              'updated_to' field could be found in the main table, and 'type',
  *                              which is a string of either value 'oi' or 'hour'. The returned
  *                              'updated_to' value will either be the end of the operation
  *                              interval (if 'type' is 'oi') or the end of the hour (if 'type'
  *                              is 'hour') prior to any date/time found in the alternate raw
  *                              table. Note that if the alternate raw table is used, then ONLY
  *                              the 'updated_to' value is returned - any $aAdditionalFields
  *                              values will be ignored.
  * @return mixed False on error, null no no result, otherwise, an array containing the
  *               'updated_to' field, which represents the time that the Maintenance
  *               process last completed updating data until, as well as any additional
  *               fields (see $aAdditionalFields parameter), unless the alternate raw table
  *               was used (see $alternateRawTableName parameter).
  */
 function getProcessLastRunInfo($tableName, $aAdditionalFields = array(), $whereClause = null, $orderBy = 'start_run', $aAlternateInfo = array())
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     // Test input values $aAdditionalFields and $aAlternateInfo are arrays
     if (!is_array($aAdditionalFields) || !is_array($aAlternateInfo)) {
         return false;
     }
     $query = "\n            SELECT\n                updated_to";
     if (!empty($aAdditionalFields)) {
         $query .= ', ' . implode(', ', $aAdditionalFields);
     }
     $tableName = $this->_getTablename($tableName);
     $query .= "\n            FROM\n                {$tableName}";
     if (!is_null($whereClause)) {
         $query .= "\n                {$whereClause}";
     }
     $query .= "\n            ORDER BY {$orderBy} DESC\n            LIMIT 1";
     OA::debug('- Obtaining maintenance process run information from ' . $tableName, PEAR_LOG_DEBUG);
     $rc = $this->oDbh->query($query);
     if (PEAR::isError($rc)) {
         return false;
     }
     $aResult = $rc->fetchRow();
     if (!is_null($aResult)) {
         // The process run information was found, return.
         return $aResult;
     }
     if (!empty($aAlternateInfo['tableName']) && !empty($aAlternateInfo['type'])) {
         // No result was found above, and an alternate raw table was specified,
         // so search the raw table to see if a valid result can be generated
         // on the basis of the earliest raw data value
         $tableName = $this->_getTablename($aAlternateInfo['tableName']);
         $query = "\n                SELECT\n                    date_time AS date\n                FROM\n                    {$tableName}\n                ORDER BY date ASC\n                LIMIT 1";
         OA::debug('- Maintenance process run information not found - trying to get data from ' . $aAlternateInfo['tableName'], PEAR_LOG_DEBUG);
         $rc = $this->oDbh->query($query);
         if (PEAR::isError($rc)) {
             return false;
         }
         if ($rc->numRows() > 0) {
             // A raw data result was found - convert it to the end of the previous
             // operation interval, or hour
             $aResult = $rc->fetchRow();
             $oDate = new Date($aResult['date']);
             if ($aAlternateInfo['type'] == 'oi') {
                 $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
                 $oResultDate = $aDates['start'];
             } else {
                 if ($aAlternateInfo['type'] == 'hour') {
                     $oResultDate = new Date($oDate->format('%Y-%m-%d %H:00:00'));
                 }
             }
             $oResultDate->subtractSeconds(1);
             return array('updated_to' => $oResultDate->format('%Y-%m-%d %H:%M:%S'));
         }
     }
     // No result found, return null
     return null;
 }
 /**
  * Method to test the getPreviousAdDeliveryInfo method.
  *
  * Requirements:
  * Test 1:   Test with no Date registered in the service locator, ensure false returned.
  * Test 2:   Test with a Date registered in the service locator, no data in the database,
  *           and ensure no data is returned.
  *
  * Test 3:   Test with ONLY impression data, but NOT in the previous OI, and ensure no
  *           data is returned.
  * Test 4:   Test with ONLY impression data, in the previous OI, and ensure that ONLY
  *           data relating to the impressions is returned.
  * Test 5:   Test with ONLY impression data, in the 2nd previous OI, and ensure that
  *           no data is returned.
  * Test 5a:  Re-test with ONLY impression data, in the 2nd previous OI, but pass in the
  *           ad/zone pair, and ensure that no data is returned.
  *
  * Test 6:   Test with ONLY prioritisation data, but NOT in the previous OI, and
  *           ensure no data is returned.
  * Test 7:   Test with ONLY prioritisation data, in the previous OI, and ensure that
  *           ONLY data relating to the prioritisation is returned.
  * Test 8:   Test with ONLY prioritisation data, in the 2nd previous OI, and ensure no
  *           data is returned.
  * Test 8a:  Re-test with ONLY prioritisation data, in the 2nd previous OI, but pass in
  *           the ad/zone pair, and ensure that ONLY data relating to the prioritisation
  *           is returned.
  *
  * Test 9:   Test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data NOT in the previous OI, and ensure no data is returned.
  * Test 10:  Test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data in the previous OI, and ensure ONLY data relating to the prioritisation
  *           is returned.
  * Test 11:  Test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data in the 2nd previous OI, and ensure no data is returned.
  * Test 11a: Re-test with BOTH impressions data NOT in the previous OI, and prioritisation
  *           data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that
  *           ONLY data relating to the prioritisation is returned.
  *
  * Test 12:  Test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data NOT in the previous OI, and ensure no data is returned.
  * Test 13:  Test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data in the previous OI, and ensure ONLY data relating to the prioritisation
  *           is returned.
  * Test 14:  Test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data in the 2nd previous OI, and ensure no data is returned.
  * Test 14a: Re-test with BOTH impressions data in the 2nd previous OI, and prioritisation
  *           data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that
  *           all data is returned.
  *
  * Test 15:  Test with BOTH impressions data in the previous OI, and prioritisation
  *           data NOT in the previous OI, and ensure that ONLY data relating to the
  *           impressions is returned.
  * Test 16:  Test with BOTH impressions data in the previous OI, and prioritisation
  *           data in the previous OI, and ensure that all data is returned.
  * Test 17:  Test with BOTH impressions data in the previous OI, and prioritisation
  *           data in the 2nd previous OI, and ensure that all data is returned.
  * Test 17a: Re-test with BOTH impressions data in the previous OI, and prioritisation
  *           data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that
  *           all data is returned.
  *
  * Test 18:  Perform a more realistic test, with data for the ads/zones in various
  *           past OIs, and including some ads with multiple prioritisation data
  *           per OI, as well as ads with no prioritisation data in some OIs, and
  *           ensure that the correct values are returned for each one. Test that:
  *           - Only ad/zones that delivered in the previous operation interval,
  *             or were requested to deliver in the previous operation interval,
  *             but didn't (i.e. not in other intervals) are returned in the
  *             results.
  *           - That prioritisation information where just ONE set of data exists
  *             is returned correctly.
  *           - That prioritisation information where multiple sets of INDENTICAL
  *             data exists is returned correctly.
  *           - That prioritisation information where multiple sets of DIFFERENT
  *             data exists is returned correctly.
  *           - That prioritisation information from older sets of data is
  *             returned correctly.
  * Test 18a: Re-test, but also include ad/zone pairs that are in/not in the above
  *           set of data, and ensure that these ad/zone pairs are also included
  *           in the results.
  */
 function testGetPreviousAdDeliveryInfo()
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     $aEmptyZoneAdArray = array();
     $aAdParams = array('ad_id' => 1, 'active' => 't', 'type' => 'sql', 'weight' => 1);
     $oAd = new OA_Maintenance_Priority_Ad($aAdParams);
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->addAdvert($oAd);
     $aZoneAdArray = array($oZone->id => $oZone);
     // Test 1
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertFalse($result);
     // Test 2
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     // Test 3
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $oNow = new Date();
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 4
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 5, 5a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 6
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0.1, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 7
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 8, 8a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 9
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 10
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 11, 11a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 12
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 13
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertNull($result[1][1]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 14, 14a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 0);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 15
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 16
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 17, 17a
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 1);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertEqual($result[1][1]['required_impressions'], 1);
     $this->assertEqual($result[1][1]['requested_impressions'], 1);
     $this->assertEqual($result[1][1]['priority_factor'], 0.5);
     $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 18
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId2 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId3 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 5, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 4, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 2, 10, 10, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 9, 9, 59, 59, 0, 95, 0.995, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 10, 10, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 20, 20, 0, 0.8, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 200, 200, 0, 0.2, 0.95, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 100, 100, 0, 0.4, 0.95, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray);
     $this->assertEqual(count($result), 4);
     $this->assertEqual(count($result[1]), 2);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $this->assertEqual($result[1][2]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][2]['zone_id'], 2);
     $this->assertEqual($result[1][2]['required_impressions'], 10);
     $this->assertEqual($result[1][2]['requested_impressions'], 10);
     $this->assertEqual($result[1][2]['priority_factor'], 0.5);
     $this->assertEqual($result[1][2]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][2]['impressions'], 1);
     $this->assertEqual(count($result[2]), 2);
     $this->assertEqual($result[2][3]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][3]['zone_id'], 3);
     $this->assertEqual($result[2][3]['required_impressions'], 30);
     $this->assertEqual($result[2][3]['requested_impressions'], 30);
     $this->assertEqual($result[2][3]['priority_factor'], 0.4);
     $this->assertEqual($result[2][3]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][3]['impressions'], 2);
     $this->assertEqual($result[2][4]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][4]['zone_id'], 4);
     $this->assertEqual($result[2][4]['required_impressions'], 15);
     $this->assertEqual($result[2][4]['requested_impressions'], 15);
     $this->assertEqual($result[2][4]['priority_factor'], 0.6);
     $this->assertEqual($result[2][4]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][4]['impressions'], 2);
     $this->assertEqual(count($result[3]), 1);
     $this->assertEqual($result[3][5]['ad_id'], $bannerId3);
     $this->assertEqual($result[3][5]['zone_id'], 5);
     $this->assertEqual($result[3][5]['required_impressions'], 150);
     $this->assertEqual($result[3][5]['requested_impressions'], 150);
     $this->assertEqual($result[3][5]['priority_factor'], 0.3);
     $this->assertEqual($result[3][5]['past_zone_traffic_fraction'], 0.95);
     $this->assertEqual($result[3][5]['impressions'], 5);
     $this->assertEqual(count($result[9]), 1);
     $this->assertEqual($result[9][9]['ad_id'], 9);
     $this->assertEqual($result[9][9]['zone_id'], 9);
     $this->assertEqual($result[9][9]['required_impressions'], 59);
     $this->assertEqual($result[9][9]['requested_impressions'], 59);
     $this->assertEqual($result[9][9]['priority_factor'], 95);
     $this->assertEqual($result[9][9]['past_zone_traffic_fraction'], 0.995);
     $this->assertNull($result[9][9]['impressions']);
     $oDate =& $oServiceLocator->get('now');
     DataGenerator::cleanUp();
     $oServiceLocator->register('now', $oDate);
     // Test 18a
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 4));
     $aAdParams = array('ad_id' => 10, 'active' => 't', 'type' => 'sql', 'weight' => 1);
     $oAd = new OA_Maintenance_Priority_Ad($aAdParams);
     $oZone->addAdvert($oAd);
     $aAdParams = array('ad_id' => 11, 'active' => 't', 'type' => 'sql', 'weight' => 1);
     $oAd = new OA_Maintenance_Priority_Ad($aAdParams);
     $oZone->addAdvert($oAd);
     $aZoneAdArray = array($oZone->id => $oZone);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $bannerId1 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 1, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId2 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 2, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $bannerId3 = $this->_insertCampaignBanner();
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 5, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 100, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 200, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 4, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 10, 0, 4, 1000, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     }
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     }
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 11, 0, 4, 2000, $oNow->format('%Y-%m-%d %H:%M:%S'));
     $idDia = $this->_insertDataIntermediateAd($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 2, 10, 10, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 9, 9, 59, 59, 0, 95, 0.995, $oNow->format('%Y-%m-%d %H:%M:%S'), 0);
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 10, 10, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 20, 20, 0, 0.8, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 200, 200, 0, 0.2, 0.95, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 100, 100, 0, 0.4, 0.95, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 10, 4, 1000, 1000, 0, 1, 0.9, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID);
     }
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) {
         $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     }
     $oSpecialDate = new Date($aDates['end']);
     $oSpecialDate->addSeconds(1);
     $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 11, 4, 2000, 2000, 0, 1, 0.9, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S'));
     $this->_insertDataSummaryAdZoneAssoc($aData);
     $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray);
     $this->assertEqual(count($result), 5);
     $this->assertEqual(count($result[1]), 2);
     $this->assertEqual($result[1][1]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][1]['zone_id'], 1);
     $this->assertNull($result[1][1]['required_impressions']);
     $this->assertNull($result[1][1]['requested_impressions']);
     $this->assertNull($result[1][1]['priority_factor']);
     $this->assertNull($result[1][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result[1][1]['impressions'], 1);
     $this->assertEqual($result[1][2]['ad_id'], $bannerId1);
     $this->assertEqual($result[1][2]['zone_id'], 2);
     $this->assertEqual($result[1][2]['required_impressions'], 10);
     $this->assertEqual($result[1][2]['requested_impressions'], 10);
     $this->assertEqual($result[1][2]['priority_factor'], 0.5);
     $this->assertEqual($result[1][2]['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($result[1][2]['impressions'], 1);
     $this->assertEqual(count($result[2]), 2);
     $this->assertEqual($result[2][3]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][3]['zone_id'], 3);
     $this->assertEqual($result[2][3]['required_impressions'], 30);
     $this->assertEqual($result[2][3]['requested_impressions'], 30);
     $this->assertEqual($result[2][3]['priority_factor'], 0.4);
     $this->assertEqual($result[2][3]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][3]['impressions'], 2);
     $this->assertEqual($result[2][4]['ad_id'], $bannerId2);
     $this->assertEqual($result[2][4]['zone_id'], 4);
     $this->assertEqual($result[2][4]['required_impressions'], 15);
     $this->assertEqual($result[2][4]['requested_impressions'], 15);
     $this->assertEqual($result[2][4]['priority_factor'], 0.6);
     $this->assertEqual($result[2][4]['past_zone_traffic_fraction'], 0.5);
     $this->assertEqual($result[2][4]['impressions'], 2);
     $this->assertEqual(count($result[3]), 1);
     $this->assertEqual($result[3][5]['ad_id'], $bannerId3);
     $this->assertEqual($result[3][5]['zone_id'], 5);
     $this->assertEqual($result[3][5]['required_impressions'], 150);
     $this->assertEqual($result[3][5]['requested_impressions'], 150);
     $this->assertEqual($result[3][5]['priority_factor'], 0.3);
     $this->assertEqual($result[3][5]['past_zone_traffic_fraction'], 0.95);
     $this->assertEqual($result[3][5]['impressions'], 5);
     $this->assertEqual(count($result[9]), 1);
     $this->assertEqual($result[9][9]['ad_id'], 9);
     $this->assertEqual($result[9][9]['zone_id'], 9);
     $this->assertEqual($result[9][9]['required_impressions'], 59);
     $this->assertEqual($result[9][9]['requested_impressions'], 59);
     $this->assertEqual($result[9][9]['priority_factor'], 95);
     $this->assertEqual($result[9][9]['past_zone_traffic_fraction'], 0.995);
     $this->assertNull($result[9][9]['impressions']);
     $this->assertEqual(count($result[10]), 1);
     $this->assertEqual($result[10][4]['ad_id'], 10);
     $this->assertEqual($result[10][4]['zone_id'], 4);
     $this->assertEqual($result[10][4]['required_impressions'], 1000);
     $this->assertEqual($result[10][4]['requested_impressions'], 1000);
     $this->assertEqual($result[10][4]['priority_factor'], 1);
     $this->assertEqual($result[10][4]['past_zone_traffic_fraction'], 0.9);
     $this->assertEqual($result[10][4]['impressions'], 1000);
     TestEnv::restoreEnv();
 }
Beispiel #13
0
 /**
  * The main method of the class, that is run by the controlling
  * task runner class.
  */
 function run()
 {
     OA::debug('Running Maintenance Priority Engine: ' . $this->taskName, PEAR_LOG_DEBUG);
     // Record the start of this ECPM run
     $oStartDate = new Date();
     // Get the details of the last time Priority Compensation started running
     $aDates = $this->oDal->getMaintenancePriorityLastRunInfo(DAL_PRIORITY_UPDATE_ECPM, array('start_run', 'end_run'));
     if (!is_null($aDates)) {
         // Set the details of the last time Priority Compensation started running
         $this->aLastRun['start_run'] = new Date($aDates['start_run']);
         // Set the details of the current date/time
         $oServiceLocator =& OA_ServiceLocator::instance();
         $this->aLastRun['now'] =& $oServiceLocator->get('now');
     }
     $this->oDateNow = $this->getDateNow();
     $this->aOIDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->oDateNow);
     $this->runAlgorithm();
     // Record the completion of the task in the database
     // Note that the $oUpdateTo parameter is "null", as this value is not
     // appropriate when recording Priority Compensation task runs - all that
     // matters is the start/end dates.
     OA::debug('- Recording completion of the ' . $this->taskName, PEAR_LOG_DEBUG);
     $oEndDate = new Date();
     $this->oDal->setMaintenancePriorityLastRunInfo($oStartDate, $oEndDate, null, DAL_PRIORITY_UPDATE_ECPM);
 }
 /**
  * Method to test the updatePriorities method.
  *
  * Test 1: Test with no Date registered in the service locator, ensure false returned.
  * Test 2: Test with no data in the database, ensure data is correctly stored.
  * Test 3: Test with previous test data in the database, ensure data is correctly stored.
  * Test 4: Test with an obscene number of items, and ensure that the packet size is
  *         not exceeded (no asserts, test suite will simply fail if unable to work).
  */
 function testUpdatePriorities()
 {
     /**
      * @TODO Locate where clean up doesn't happen before this test, and fix!
      */
     TestEnv::restoreEnv();
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority();
     // Insert the data into the ad_zone_assoc table, as an ad is linked to a zone
     $this->_generateTestData();
     // Test 1
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $aData = array(array('ads' => array(array('ad_id' => $this->aIds['ad'], 'zone_id' => $this->aIds['zone'], 'required_impressions' => '1000', 'requested_impressions' => '1000', 'priority' => '0.45', 'priority_factor' => null, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => null))));
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     $this->assertFalse($result);
     // Test 2
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     $this->assertTrue($result);
     $query = "\n            SELECT\n                ad_id,\n                zone_id,\n                priority\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']} AND zone_id = {$this->aIds['zone']}";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['zone']);
     $this->assertEqual($aRow['priority'], 0.45);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']}";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['zone']);
     $this->assertEqual($aRow['required_impressions'], 1000);
     $this->assertEqual($aRow['requested_impressions'], 1000);
     $this->assertEqual($aRow['priority'], 0.45);
     $this->assertNull($aRow['priority_factor']);
     $this->assertFalse($aRow['priority_factor_limited']);
     $this->assertNull($aRow['past_zone_traffic_fraction']);
     $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertNull($aRow['expired']);
     $this->assertNull($aRow['expired_by']);
     // Test 3
     $aData = array(array('ads' => array(array('ad_id' => $this->aIds['ad'], 'zone_id' => $this->aIds['zone'], 'required_impressions' => 2000, 'requested_impressions' => 2000, 'priority' => 0.9, 'priority_factor' => 0.1, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => 0.99), array('ad_id' => $this->aIds['ad'] + 1, 'zone_id' => $this->aIds['ad'] + 1, 'required_impressions' => 500, 'requested_impressions' => 500, 'priority' => 0.1, 'priority_factor' => 0.2, 'priority_factor_limited' => true, 'past_zone_traffic_fraction' => 0.45))));
     $oOldDate = new Date();
     $oOldDate->copy($oDate);
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     $this->assertTrue($result);
     $query = "\n            SELECT\n                ad_id,\n                zone_id,\n                priority\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']} AND zone_id = {$this->aIds['zone']}";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['zone']);
     $this->assertEqual($aRow['priority'], 0.9);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']}\n                AND expired IS NOT NULL";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oOldDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oOldDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['required_impressions'], 1000);
     $this->assertEqual($aRow['requested_impressions'], 1000);
     $this->assertEqual($aRow['priority'], 0.45);
     $this->assertNull($aRow['priority_factor']);
     $this->assertFalse($aRow['priority_factor_limited']);
     $this->assertNull($aRow['past_zone_traffic_fraction']);
     $this->assertEqual($aRow['created'], $oOldDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertEqual($aRow['expired'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['expired_by'], 0);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = {$this->aIds['ad']}\n                AND expired IS NULL";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['zone_id'], $this->aIds['ad']);
     $this->assertEqual($aRow['required_impressions'], 2000);
     $this->assertEqual($aRow['requested_impressions'], 2000);
     $this->assertEqual($aRow['priority'], 0.9);
     $this->assertEqual($aRow['priority_factor'], 0.1);
     $this->assertFalse($aRow['priority_factor_limited']);
     $this->assertEqual($aRow['past_zone_traffic_fraction'], 0.99);
     $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertNull($aRow['expired']);
     $this->assertNull($aRow['expired_by']);
     $query = "\n            SELECT\n                operation_interval,\n                operation_interval_id,\n                interval_start,\n                interval_end,\n                ad_id,\n                zone_id,\n                required_impressions,\n                requested_impressions,\n                priority,\n                priority_factor,\n                priority_factor_limited,\n                past_zone_traffic_fraction,\n                created,\n                created_by,\n                expired,\n                expired_by\n            FROM\n                " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n            WHERE\n                ad_id = " . ($this->aIds['ad'] + 1);
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']);
     $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID);
     $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['ad_id'], $this->aIds['ad'] + 1);
     $this->assertEqual($aRow['zone_id'], $this->aIds['ad'] + 1);
     $this->assertEqual($aRow['required_impressions'], 500);
     $this->assertEqual($aRow['requested_impressions'], 500);
     $this->assertEqual($aRow['priority'], 0.1);
     $this->assertEqual($aRow['priority_factor'], 0.2);
     $this->assertTrue($aRow['priority_factor_limited']);
     $this->assertEqual($aRow['past_zone_traffic_fraction'], 0.45);
     $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S'));
     $this->assertEqual($aRow['created_by'], 0);
     $this->assertNull($aRow['expired']);
     $this->assertNull($aRow['expired_by']);
     // Test 4
     $aData = array();
     for ($i = 1; $i < 5000; $i++) {
         $aData[$i] = array('ads' => array(array('ad_id' => $i, 'zone_id' => $i, 'required_impressions' => 2000, 'requested_impressions' => 2000, 'priority' => 0.9, 'priority_factor' => 0.1, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => 0.99)));
     }
     $oOldDate = new Date();
     $oOldDate->copy($oDate);
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $result = $oMaxDalMaintenance->updatePriorities($aData);
     TestEnv::restoreEnv('dropTmpTables');
 }
 /**
  * A method to obtain the sum of the zone forecast impression value, for all the zones
  * an advertisement is linked to, cloned out over the advertisement's entire remaining
  * lifetime in the campaign, with any blocked operation intervals removed.
  *
  * Requires that the getActiveAdOperationIntervals() method have previously been
  * called to function correctly.
  *
  * @param PEAR::Date $oNowDate The current date.
  * @param PEAR::Date $oEndDate The end date of the campaign. Note that if the end
  *                             date supplied is not at the end of a day, it will be
  *                             converted to be treated as such.
  * @param array $aCumulativeZoneForecast The cumulative forecast impressions, indexed
  *                                       by operation interval ID, of all the zones the
  *                                       advertisement is linked to.
  *                  array(
  *                      [operation_interval_id] => forecast_impressions,
  *                      [operation_interval_id] => forecast_impressions
  *                                  .
  *                                  .
  *                                  .
  *                  )
  * @return integer The ad's total remaining zone impression forecast for all zone for
  *                 the remaining life of the ad.
  */
 function getAdLifetimeZoneImpressionsRemaining($oNowDate, $oEndDate, $aCumulativeZoneForecast)
 {
     $totalAdLifetimeZoneImpressionsRemaining = 0;
     // Test the parameters, if invalid, return zero
     if (!is_a($oNowDate, 'date') || !is_a($oEndDate, 'date') || !is_array($aCumulativeZoneForecast) || count($aCumulativeZoneForecast) != OX_OperationInterval::operationIntervalsPerWeek()) {
         OA::debug('  - Invalid parameters to getAdLifetimeZoneImpressionsRemaining, returning 0', PEAR_LOG_ERR);
         return $totalAdLifetimeZoneImpressionsRemaining;
     }
     // Ensure that the end of campaign date is at the end of the day
     $oEndDateCopy = new Date($oEndDate);
     $oEndDateCopy->setHour(23);
     $oEndDateCopy->setMinute(59);
     $oEndDateCopy->setSecond(59);
     // Ensure that the $aCumulativeZoneForecast array is sorted by key, so that it can
     // be accessed by array_slice, regardless of the order that the forecast data was added
     // to the array
     ksort($aCumulativeZoneForecast);
     // Step 1: Calculate the sum of the forecast values from "now" until the end of "today"
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
     $oEndOfToday = new Date($aDates['start']);
     $oEndOfToday->setTZ($oEndDate->tz);
     $oEndOfToday->setHour(23);
     $oEndOfToday->setMinute(59);
     $oEndOfToday->setSecond(59);
     $oStart = $aDates['start'];
     while ($oStart->before($oEndOfToday)) {
         // Find the Operation Interval ID for this Operation Interval
         $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oStart);
         // As iteration over every OI is required anyway, test to see if
         // the ad is blocked in this OI; if not, add the forecast values to the
         // running total
         if (empty($this->aBlockedOperationIntervalDates[$oStart->format('%Y-%m-%d %H:%M:%S')])) {
             $totalAdLifetimeZoneImpressionsRemaining += $aCumulativeZoneForecast[$operationIntervalID];
         }
         // Go to the next operation interval in "today"
         $oStart = OX_OperationInterval::addOperationIntervalTimeSpan($oStart);
     }
     // Step 2: Calculate how many times each day of the week occurs between the end of
     //         "today" (i.e. starting "tomorrow morning") and the last day the ad can run
     $aDays = array();
     $oStartOfTomorrow = new Date($oEndOfToday);
     $oStartOfTomorrow->addSeconds(1);
     $oTempDate = new Date();
     $oTempDate->copy($oStartOfTomorrow);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
     while ($aDates['start']->before($oEndDateCopy)) {
         // Increase the count for this day of the week
         $aDays[$aDates['start']->getDayOfWeek()]++;
         // Go to the next day
         $oTempDate->addSeconds(SECONDS_PER_DAY);
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
     }
     // Step 3: For every possible day of the week (assuming that day of the week is in the
     //         ad's remaining lifetime), calculate the sum of the forecast values for every
     //         operation interval in that day
     if (!empty($aDays)) {
         $operationIntervalsPerDay = OX_OperationInterval::operationIntervalsPerDay();
         $oTempDate = new Date($oStartOfTomorrow);
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
         for ($counter = 0; $counter < 7; $counter++) {
             // Are there any instances of this day in the campaign?
             if ($aDays[$oTempDate->getDayOfWeek()] > 0) {
                 // Calculate the sum of the zone forecasts for this day of week
                 $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate);
                 $dayStartOperationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
                 $aDayCumulativeZoneForecast = array_slice($aCumulativeZoneForecast, $dayStartOperationIntervalId, $operationIntervalsPerDay);
                 $forecastSum = array_sum($aDayCumulativeZoneForecast);
                 // Multiply this day's forecast sum value by the number of times this
                 // day of week appears in the remainder of the campaign and add the
                 // value to the running total
                 $totalAdLifetimeZoneImpressionsRemaining += $forecastSum * $aDays[$oTempDate->getDayOfWeek()];
             }
             // Go to the next day
             $oTempDate->addSeconds(SECONDS_PER_DAY);
         }
     }
     // Step 4: Subtract any blocked interval values
     if ($this->blockedOperationIntervalCount > 0) {
         OA::debug("      - Subtracting {$this->blockedOperationIntervalCount} blocked intervals", PEAR_LOG_DEBUG);
         foreach ($this->aBlockedOperationIntervalDates as $aDates) {
             if ($aDates['start']->after($oEndOfToday)) {
                 $blockedOperationInvervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
                 $totalAdLifetimeZoneImpressionsRemaining -= $aCumulativeZoneForecast[$blockedOperationInvervalID];
             }
         }
     }
     // Return the calculated value
     return $totalAdLifetimeZoneImpressionsRemaining;
 }
 /**
  * A method to distribute the calculated required campaign impressions between the campaign's
  * children advertisements. Impression allocation takes in to account ad weight, and the number
  * of operations intervals the ad will be active in given date/time delivery limitations, and
  * the pattern of available impressions for the zone(s) the advertisements are linked to.
  *
  * The calculated ad impressions are written to the temporary table tmp_ad_required_impression
  * for later analysis by the {@link OA_Maintenance_Priority_AdServer_Task_AllocateZoneImpressions}
  * class.
  *
  * @param array $aCampaigns An array of {@link OX_Maintenance_Priority_Campaign} objects which require
  *                          that their total required impressions be distributed between the
  *                          component advertisements.
  */
 function distributeCampaignImpressions($aCampaigns)
 {
     // Create an array for storing required ad impressions
     $aRequiredAdImpressions = array();
     // Get the current operation interval start/end dates
     $aCurrentOperationIntervalDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->_getDate());
     // For each campaign
     foreach ($aCampaigns as $oCampaign) {
         OA::debug('  - Distributing impression inventory requirements for campaign ID: ' . $oCampaign->id, PEAR_LOG_DEBUG);
         $adsCount = count($oCampaign->aAds);
         OA::debug("    - Campaign has {$adsCount} ads.", PEAR_LOG_DEBUG);
         // Get date object to represent campaign expiration date
         if ($oCampaign->impressionTargetDaily > 0 || $oCampaign->clickTargetDaily > 0 || $oCampaign->conversionTargetDaily > 0) {
             // The campaign has a daily target to meet, so treat the
             // campaign as if it expires at the end of "today", regardless
             // of the existance of any activation or expiration dates that
             // may (or may not) be set for the campaign
             $oCampaignExpiryDate = new Date($this->_getDate());
             $oCampaignExpiryDate->setTZ($this->currentTz);
             $oCampaignExpiryDate->setHour(23);
             $oCampaignExpiryDate->setMinute(59);
             $oCampaignExpiryDate->setSecond(59);
             $oCampaignExpiryDate->toUTC();
             // Unless the campaign has an expiry date and it happens before the end of today
             if (!empty($oCampaign->expireTime)) {
                 if ($oCampaignExpiryDate->after($this->_getDate($oCampaign->expireTime))) {
                     $oCampaignExpiryDate = $this->_getDate($oCampaign->expireTime);
                 }
             }
         } else {
             if (!empty($oCampaign->expireTime) && ($oCampaign->impressionTargetTotal > 0 || $oCampaign->clickTargetTotal > 0 || $oCampaign->conversionTargetTotal > 0)) {
                 // The campaign has an expiration date, and has some kind of
                 // (total) inventory requirement, so treat the campaign as if
                 // it expires at the expiration date/time
                 $oCampaignExpiryDate = $this->_getDate($oCampaign->expireTime);
             } else {
                 // Error! There should not be any other kind of high-priority
                 // campaign in terms of activation/expiration dates and
                 // either (total) inventory requirements or daily targets
                 $message = "- Error calculating the end date for Campaign ID {$oCampaign->id}";
                 OA::debug($message, PEAR_LOG_ERR);
                 continue;
             }
         }
         // Determine number of remaining operation intervals for campaign
         $message = "    - Calculating campaign remaining operation intervals.";
         OA::debug($message, PEAR_LOG_DEBUG);
         $campaignRemainingOperationIntervals = OX_OperationInterval::getIntervalsRemaining($aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate);
         // For all ads in the campaign, determine:
         // - If the ad is capable of delivery in the current operation
         //   interval, or not, based on if it is linked to any zones, and,
         //   if so:
         // - If the ad is capable of delivery in the current operation
         //   interval, or not, based on delivery limitation(s), and if so;
         // - The result of the weight of the ad multiplied by the
         //   number of operation intervals remaining in which the ad
         //   is capable of delivering
         $aAdZones = array();
         $aAdDeliveryLimitations = array();
         $aAdBlockedForCurrentOI = array();
         $aAdWeightRemainingOperationIntervals = array();
         $aInvalidAdIds = array();
         reset($oCampaign->aAds);
         while (list($key, $oAd) = each($oCampaign->aAds)) {
             // Only calculate values for active ads
             if ($oAd->active && $oAd->weight > 0) {
                 $message = "    - Calculating remaining operation intervals for ad ID: {$oAd->id}";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 // Get all zones associated with the ad
                 $aAdsZones = $this->oDal->getAdZoneAssociationsByAds(array($oAd->id));
                 $aAdZones[$oAd->id] = @$aAdsZones[$oAd->id];
                 if (is_null($aAdZones[$oAd->id])) {
                     $aInvalidAdIds[] = $oAd->id;
                     $message = "      - Ad ID {$oAd->id} has no linked zones, will skip...";
                     OA::debug($message, PEAR_LOG_ERR);
                     continue;
                 }
                 // Prepare a delivery limitation object for the ad
                 $aAdDeliveryLimitations[$oAd->id] = new OA_Maintenance_Priority_DeliveryLimitation($oAd->getDeliveryLimitations());
                 // Is the ad blocked from delivering in the current operation interval?
                 $aAdBlockedForCurrentOI[$oAd->id] = $aAdDeliveryLimitations[$oAd->id]->deliveryBlocked($aCurrentOperationIntervalDates['start']);
                 // Determine how many operation intervals remain that the ad can deliver in
                 $adRemainingOperationIntervals = $aAdDeliveryLimitations[$oAd->id]->getActiveAdOperationIntervals($campaignRemainingOperationIntervals, $aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate);
                 // Determine the value of the ad weight multiplied by the number
                 // of operation intervals remaining that the ad can deliver in
                 if ($oAd->weight > 0) {
                     $aAdWeightRemainingOperationIntervals[$oAd->id] = $oAd->weight * $adRemainingOperationIntervals;
                 } else {
                     $aAdWeightRemainingOperationIntervals[$oAd->id] = 0;
                 }
             }
         }
         // Get the total sum of the ad weight * remaining OI values
         $sumAdWeightRemainingOperationIntervals = array_sum($aAdWeightRemainingOperationIntervals);
         // For each (active) ad that is capable of delivering in the current
         // operation interval, determine how many of the campaign's required
         // impressions should be alloced as the ad's required impressions
         // For each advertisement
         reset($oCampaign->aAds);
         while (list($key, $oAd) = each($oCampaign->aAds)) {
             if (in_array($oAd->id, $aInvalidAdIds)) {
                 OA::debug('       - Skipping ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
                 continue;
             }
             OA::debug('     - Calculating required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
             // Get impressions required
             $totalRequiredAdImpressions = 0;
             if ($oAd->active && $oAd->weight > 0 && $aAdBlockedForCurrentOI[$oAd->id] !== true) {
                 $totalRequiredAdImpressions = $oCampaign->requiredImpressions * ($aAdWeightRemainingOperationIntervals[$oAd->id] / $sumAdWeightRemainingOperationIntervals);
             }
             if ($totalRequiredAdImpressions <= 0) {
                 OA::debug('       - No required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
                 continue;
             }
             // Based on the average zone pattern of the zones the ad is
             // linked to, calculate how many of these impressions should
             // be delivered in the next operation interval
             OA::debug('       - Calculating next OI required impressions for ad ID: ' . $oAd->id, PEAR_LOG_DEBUG);
             $oAd->requiredImpressions = $this->_getAdImpressions($oAd, $totalRequiredAdImpressions, $aCurrentOperationIntervalDates['start'], $oCampaignExpiryDate, $aAdDeliveryLimitations[$oAd->id], $aAdZones[$oAd->id]);
             $aRequiredAdImpressions[] = array('ad_id' => $oAd->id, 'required_impressions' => $oAd->requiredImpressions);
         }
     }
     // Save the required impressions into the temporary database table
     OA::setTempDebugPrefix('- ');
     // Check if table exists
     if (!isset($GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression'])) {
         if ($this->oTable->createTable('tmp_ad_required_impression', null, true) !== false) {
             // Remember that table was created
             $GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression'] = true;
         }
     }
     $this->oDal->saveRequiredAdImpressions($aRequiredAdImpressions);
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of migrating bucket-based logged data to the
  * statistics table(s) specified by the appropriate plugin
  * components.
  */
 function run()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     if ($this->oController->updateIntermediate) {
         // Locate all plugin components which may require bucket data to be
         // migrated from bucket tables to statistics tables
         $aSummariseComponents = $this->_locateComponents();
         // Are there any components that require data to be migrated?
         if (empty($aSummariseComponents)) {
             OA::debug('There are no installed plugins that require data migration', PEAR_LOG_DEBUG);
             return;
         }
         $message = '- Migrating bucket-based logged data to the statistics tables.';
         $this->oController->report .= $message . "\n";
         // Get the MSE DAL to perform the data migration
         $oServiceLocator =& OA_ServiceLocator::instance();
         $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
         // Prepare the "now" date
         $oNowDate =& $oServiceLocator->get('now');
         if (!$oNowDate) {
             $oNowDate = new Date();
         }
         // Prepare an array of possible start and end dates for the migration, unless they have been set already
         if (empty($this->aRunDates)) {
             $this->aRunDates = array();
             $oStartDate = new Date();
             $oStartDate->copy($this->oController->oLastDateIntermediate);
             $oStartDate->addSeconds(1);
             while (Date::compare($oStartDate, $this->oController->oUpdateIntermediateToDate) < 0) {
                 // Calcuate the end of the operation interval
                 $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate);
                 $oEndDate = new Date();
                 $oEndDate->copy($aDates['end']);
                 // Store the dates
                 $oStoreStartDate = new Date();
                 $oStoreStartDate->copy($oStartDate);
                 $oStoreEndDate = new Date();
                 $oStoreEndDate->copy($oEndDate);
                 $this->aRunDates[] = array('start' => $oStoreStartDate, 'end' => $oStoreEndDate);
                 // Go to the next operation interval
                 $oStartDate->copy($oEndDate);
                 $oStartDate->addSeconds(1);
             }
         }
         // Check to see if any historical raw data needs to be migrated,
         // post-upgrade, and if so, migrate the data; requires that the
         // default openXDeliveryLog plugin is installed, so the migration
         // will not be called if it is not
         if (key_exists('openXDeliveryLog', $this->aPackages)) {
             $this->_postUpgrade();
         }
         // Prepare arrays of all of the migration maps of raw migrations
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'raw');
         // Run each migration map separately, even if it's for the same table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             foreach ($aMaps as $componentClassName => $aMigrationDetails) {
                 foreach ($this->aRunDates as $aDates) {
                     $message = "- Migrating raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = "  to the '{$statisticsTable}' table, for operation interval range";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = '  ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $result = $oDal->summariseBucketsRaw($statisticsTable, $aMigrationDetails, $aDates);
                     if (PEAR::isError($result)) {
                         // Oh noz! The bucket data could not be migrated
                         // Tell the user all about it, but then just keep on truckin'...
                         $message = "   ERROR: Could not migrate raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                         OA::debug($message, PEAR_LOG_ERR);
                         $message = "   Error message was: {$result->message}";
                         OA::debug($message, PEAR_LOG_ERR);
                     } else {
                         $message = "  - Migrated {$result} row(s)";
                         OA::debug($message, PEAR_LOG_DEBUG);
                         $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                         if (PEAR::isError($pruneResult)) {
                             // Oh noz! The bucket data could not be pruned, and this is
                             // critical - if we can't prune the data, we'll end up double
                             // counting, so exit with a critical error...
                             $message = "   ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Error message was: {$pruneResult->message}";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Aborting maintenance execution";
                             OA::debug($message, PEAR_LOG_CRIT);
                             exit;
                         } else {
                             $message = "  - Pruned {$pruneResult} row(s)";
                             OA::debug($message, PEAR_LOG_DEBUG);
                         }
                     }
                 }
             }
         }
         // Prepare arrays of all of the migration maps of supplementary raw migrations
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'rawSupplementary');
         // Run each migration map separately, even if it's for the same table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             foreach ($aMaps as $componentClassName => $aMigrationDetails) {
                 foreach ($this->aRunDates as $aDates) {
                     $message = "- Migrating supplementary raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = "  to the '{$statisticsTable}' table, for operation interval range";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $message = '  ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                     OA::debug($message, PEAR_LOG_DEBUG);
                     $result = $oDal->summariseBucketsRawSupplementary($statisticsTable, $aMigrationDetails, $aDates);
                     if (PEAR::isError($result)) {
                         // Oh noz! The bucket data could not be migrated
                         // Tell the user all about it, but then just keep on truckin'...
                         $message = "   ERROR: Could not migrate supplementary raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table";
                         OA::debug($message, PEAR_LOG_ERR);
                         $message = "   Error message was: {$result->message}";
                         OA::debug($message, PEAR_LOG_ERR);
                     } else {
                         $message = "  - Migrated {$result} row(s)";
                         OA::debug($message, PEAR_LOG_DEBUG);
                         $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                         if (PEAR::isError($pruneResult)) {
                             // Oh noz! The bucket data could not be pruned, and this is
                             // critical - if we can't prune the data, we'll end up double
                             // counting, so exit with a critical error...
                             $message = "   ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Error message was: {$pruneResult->message}";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Aborting maintenance execution";
                             OA::debug($message, PEAR_LOG_CRIT);
                             exit;
                         } else {
                             $message = "  - Pruned {$pruneResult} row(s)";
                             OA::debug($message, PEAR_LOG_DEBUG);
                         }
                     }
                 }
             }
         }
         // Prepare arrays of all of the migration maps of aggregate migrations
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'aggregate');
         // Run each migration map by statistics table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             $aBucketTables = array();
             foreach ($aMaps as $aMap) {
                 $aBucketTables[] = $aMap['bucketTable'];
             }
             foreach ($this->aRunDates as $aDates) {
                 $aExtras = array();
                 // Is this the data_intermeidate_ad statistics table? It's special!
                 if ($statisticsTable == $aConf['table']['prefix'] . 'data_intermediate_ad') {
                     $aExtras = array('operation_interval' => $aConf['maintenance']['operationInterval'], 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']), 'interval_start' => $oDal->oDbh->quote($aDates['start']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString, 'interval_end' => $oDal->oDbh->quote($aDates['end']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString, 'creative_id' => 0, 'updated' => $oDal->oDbh->quote($oNowDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString);
                 }
                 $message = "- Migrating aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = "  to the '{$statisticsTable}' table, for operation interval range";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = '  ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $result = $oDal->summariseBucketsAggregate($statisticsTable, $aMaps, $aDates, $aExtras);
                 if (PEAR::isError($result)) {
                     // Oh noz! The bucket data could not be migrated
                     // Tell the user all about it, but then just keep on truckin'...
                     $message = "   ERROR: Could not migrate aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                     OA::debug($message, PEAR_LOG_ERR);
                     $message = "   Error message was: {$result->message}";
                     OA::debug($message, PEAR_LOG_ERR);
                 } else {
                     $message = "  - Migrated {$result} row(s)";
                     OA::debug($message, PEAR_LOG_DEBUG);
                     foreach ($aMaps as $componentClassName => $aMap) {
                         $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                         if (PEAR::isError($pruneResult)) {
                             // Oh noz! The bucket data could not be pruned, and this is
                             // critical - if we can't prune the data, we'll end up double
                             // counting, so exit with a critical error...
                             $message = "   ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Error message was: {$pruneResult->message}";
                             OA::debug($message, PEAR_LOG_CRIT);
                             $message = "   Aborting maintenance execution";
                             OA::debug($message, PEAR_LOG_CRIT);
                             exit;
                         } else {
                             $message = "  - Pruned {$pruneResult} row(s)";
                             OA::debug($message, PEAR_LOG_DEBUG);
                         }
                     }
                 }
             }
         }
         // Prepare arrays of all of the migration maps of custom migrations
         // (If we refactor stats this will be the one and only method.)
         $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'custom');
         // Run each migration map by statistics table
         foreach ($aRunComponents as $statisticsTable => $aMaps) {
             $aBucketTables = array();
             foreach ($aMaps as $aMap) {
                 $aBucketTables[] = $aMap['bucketTable'];
             }
             foreach ($this->aRunDates as $aDates) {
                 $aExtras = array();
                 $message = "- Migrating aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = "  to the '{$statisticsTable}' table, for operation interval range";
                 OA::debug($message, PEAR_LOG_DEBUG);
                 $message = '  ' . $aDates['start']->format('%Y-%m%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName();
                 OA::debug($message, PEAR_LOG_DEBUG);
                 // Call the components migrateStats method.
                 foreach ($aMaps as $componentClassName => $aMap) {
                     $result = $aSummariseComponents[$statisticsTable][$componentClassName]->migrateStatistics($aDates['end']);
                     if (PEAR::isError($result)) {
                         // Oh noz! The bucket data could not be migrated
                         // Tell the user all about it, but then just keep on truckin'...
                         $message = "   ERROR: Could not migrate aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)";
                         OA::debug($message, PEAR_LOG_ERR);
                         $message = "   Error message was: {$result->message}.";
                         OA::debug($message, PEAR_LOG_ERR);
                     } else {
                         // Only prune the bucket if we migrated the stats successfully.
                         $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']);
                     }
                 }
             }
         }
     }
     $this->aRunDates = array();
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of determining what operation intervals
  * and/or hours, if any, need to be updated during the MSE run.
  */
 function run()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNowDate =& $oServiceLocator->get('now');
     if (!$oNowDate) {
         $oNowDate = new Date();
     }
     $this->oController->report = "Maintenance Statistics Report\n";
     $this->oController->report .= "=====================================\n\n";
     $message = '- Maintenance start run time is ' . $oNowDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oNowDate->tz->getShortName();
     $this->oController->report .= $message . "\n";
     OA::debug($message, PEAR_LOG_DEBUG);
     // Don't update unless the time is right!
     $this->oController->updateIntermediate = false;
     $this->oController->updateFinal = false;
     // Test to see if a date for when the statistics were last updated
     // has been set in the service locator (for re-generation of stats)
     $oLastUpdatedDate =& $oServiceLocator->get('lastUpdatedDate');
     // Determine when the last intermediate table update happened
     if (is_a($oLastUpdatedDate, 'Date')) {
         $this->oController->oLastDateIntermediate = $oLastUpdatedDate;
     } else {
         $this->oController->oLastDateIntermediate = $this->_getMaintenanceStatisticsLastRunInfo(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oNowDate);
         if (is_null($this->oController->oLastDateIntermediate)) {
             // The MSE has never run, look to see if delivery data exists
             $this->oController->oLastDateIntermediate = $this->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI);
         }
     }
     if (is_null($this->oController->oLastDateIntermediate)) {
         // Could not find a last update date, so don't run MSE
         $message = '- Maintenance statistics has never been run before, and no logged delivery data was located in ';
         $this->oController->report .= $message . "\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         $message = '  the database, so maintenance statistics will not be run for the intermediate tables';
         $this->oController->report .= $message . "\n\n";
         OA::debug($message, PEAR_LOG_DEBUG);
     } else {
         // Found a last update date
         $message = '- Maintenance statistics last updated intermediate table statistics to ' . $this->oController->oLastDateIntermediate->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateIntermediate->tz->getShortName();
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         // Does the last update date found occur on the end of an operation interval?
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->oController->oLastDateIntermediate);
         if (Date::compare($this->oController->oLastDateIntermediate, $aDates['end']) != 0) {
             $message = '- Last intermediate table updated to date of ' . $this->oController->oLastDateIntermediate->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateIntermediate->tz->getShortName() . ' is not on the current operation interval boundary';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
             $message = '- OPERATION INTERVAL LENGTH CHANGE SINCE LAST RUN';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
             $message = '- Extending the time until next update';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
             $this->oController->sameOI = false;
         }
         // Calculate the date after which the next operation interval-based update can happen
         $oRequiredDate = new Date();
         if ($this->oController->sameOI) {
             $oRequiredDate->copy($this->oController->oLastDateIntermediate);
             $oRequiredDate->addSeconds($aConf['maintenance']['operationInterval'] * 60);
         } else {
             $oRequiredDate->copy($aDates['end']);
         }
         $message = '- Current time must be after ' . $oRequiredDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oRequiredDate->tz->getShortName() . ' for the next intermediate table update to happen';
         $this->oController->report .= $message . "\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         if (Date::compare($oNowDate, $oRequiredDate) > 0) {
             $this->oController->updateIntermediate = true;
             // Update intermediate tables to the end of the previous (not current) operation interval
             $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
             $this->oController->oUpdateIntermediateToDate = new Date();
             $this->oController->oUpdateIntermediateToDate->copy($aDates['start']);
             $this->oController->oUpdateIntermediateToDate->subtractSeconds(1);
         } else {
             // An operation interval hasn't passed, so don't update
             $message = "- At least {$aConf['maintenance']['operationInterval']} minutes have " . 'not passed since the last operation interval update';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
         }
     }
     // Determine when the last final table update happened
     if ($oLastUpdatedDate !== false) {
         $this->oController->oLastDateFinal = $oLastUpdatedDate;
     } else {
         $this->oController->oLastDateFinal = $this->_getMaintenanceStatisticsLastRunInfo(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oNowDate);
         if (is_null($this->oController->oLastDateFinal)) {
             // The MSE has never run, look to see if delivery data exists
             $this->oController->oLastDateFinal = $this->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR);
         }
     }
     if (is_null($this->oController->oLastDateFinal)) {
         // Could not find a last update date, so don't run MSE
         $message = '- Maintenance statistics has never been run before, and no logged delivery data was located in ';
         $this->oController->report .= $message . "\n" . OA::debug($message, PEAR_LOG_DEBUG);
         $message = '  the database, so maintenance statistics will not be run for the final tables';
         $this->oController->report .= $message . "\n\n";
         OA::debug($message, PEAR_LOG_DEBUG);
     } else {
         // Found a last update date
         $message = '- Maintenance statistics last updated final table statistics to ' . $this->oController->oLastDateFinal->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateFinal->tz->getShortName();
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         // Calculate the date after which the next hour-based update can happen
         $oRequiredDate = new Date();
         $oRequiredDate->copy($this->oController->oLastDateFinal);
         $oRequiredDate->addSeconds(60 * 60);
         $message = '- Current time must be after ' . $oRequiredDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oRequiredDate->tz->getShortName() . ' for the next intermediate table update to happen';
         $this->oController->report .= $message . "\n";
         OA::debug($message, PEAR_LOG_DEBUG);
         if (Date::compare($oNowDate, $oRequiredDate) > 0) {
             $this->oController->updateFinal = true;
             // Update final tables to the end of the previous (not current) hour
             $this->oController->oUpdateFinalToDate = new Date($oNowDate->format('%Y-%m-%d %H:00:00'));
             $this->oController->oUpdateFinalToDate->subtractSeconds(1);
         } else {
             // An hour hasn't passed, so don't update
             $message = '- At least 60 minutes have NOT passed since the last final table update';
             $this->oController->report .= $message . "\n";
             OA::debug($message, PEAR_LOG_DEBUG);
         }
     }
     // Is an update of any type going to happen?
     if ($this->oController->updateIntermediate || $this->oController->updateFinal) {
         $message = "- Maintenance statistics will be run";
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_INFO);
         if ($this->oController->updateIntermediate) {
             $message = '- The intermediate table statistics will be updated';
             $this->oController->report .= $message . ".\n";
             OA::debug($message, PEAR_LOG_INFO);
         }
         if ($this->oController->updateFinal) {
             $message = '- The final table statistics will be updated';
             $this->oController->report .= $message . ".\n";
             OA::debug($message, PEAR_LOG_INFO);
         }
         $this->oController->report .= "\n";
     } else {
         $message = "- Maintenance statistics will NOT be run";
         $this->oController->report .= $message . ".\n";
         OA::debug($message, PEAR_LOG_INFO);
         $this->oController->report .= "\n";
     }
 }
 function forecast()
 {
     // Determine type of update required
     $type = $this->_getUpdateTypeRequired();
     // Are we updating the ZIF values for all operation intervals?
     if ($type !== true) {
         // No, only updating the ZIF values for some operation intervals,
         // so, need to check to see if there are any active zones in the
         // system that do NOT have any ZIF values yet (ie. they are newly
         // added zones that need to be fully updated) or if there are
         // any active zones that have used the default forecast value at
         // any point in the past week (ie. recently added zones that need
         // to have their past forecast values updated so that Zone Patterning
         // will not allocate impressions on the basis of the default forecast
         $this->aNewZoneIDs = $this->oDal->getNewZones($this->aActiveZoneIDs);
         if (PEAR::isError($this->aNewZoneIDs)) {
             OA::debug('- Error retrieving new zone list, exiting', PEAR_LOG_CRIT);
             exit;
         }
         $this->aRecentZoneIDs = $this->oDal->getRecentZones($this->aActiveZoneIDs, $this->oDateNow);
         if (PEAR::isError($this->aRecentZoneIDs)) {
             OA::debug('- Error retrieving recent zone list, exiting', PEAR_LOG_CRIT);
             exit;
         }
         // If there are new zones found, then the "complete last week" range of
         // operation intervals will be needed for these zones - prepare this
         // range now, in advance of it being needed
         if (!empty($this->aNewZoneIDs)) {
             $this->aFullWeekRanges = $this->_getOperationIntervalRanges(true);
         }
     }
     // Convert the required update type into an array of operation interval ID
     // ranges, being the operation interval IDs where all zones require their
     // ZIF values to be udpated
     $aRanges = $this->_getOperationIntervalRanges($type);
     // For every active zone in the system...
     foreach ($this->aActiveZoneIDs as $zoneId) {
         // ... calculate that zone's ZIF data as required
         OA::debug("- Calculating the ZIF data for Zone ID {$zoneId}", PEAR_LOG_DEBUG);
         // Is this a new zone?
         $newZone = false;
         if (in_array($zoneId, $this->aNewZoneIDs)) {
             // Calculate the ZIF values for the complete last week, as this
             // new zone won't have any ZIF information, even if the MPE has
             // previously been run
             OA::debug("  - Found as new zone, updating for complete week", PEAR_LOG_DEBUG);
             $newZone = true;
             $aUseRanges =& $this->aFullWeekRanges;
         } else {
             // Calculate the ZIF values for just the required ranges, if present
             $aUseRanges =& $aRanges;
         }
         $this->_calculateZoneImpressionForecastValues($zoneId, $aUseRanges, $newZone);
         // ... and also calculate the zone's new "past" ZIF update data, if required
         if (in_array($zoneId, $this->aRecentZoneIDs)) {
             $this->_calculatePastZoneImpressionForecastValues($zoneId);
         }
     }
     // Save any ZIF data that has been calculated
     if (!empty($this->aForecastResults)) {
         $this->oDal->saveZoneImpressionForecasts($this->aForecastResults);
         // Update to ensure additional info passed in about how to save...
     }
     // Update any "past" ZIF data for recently created zones that has been calculated
     if (!empty($this->aPastForecastResults)) {
         // Calcuate the date from which to update the "past" ZIF values
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->oDateNow);
         $oPastStartDate = new Date();
         $oPastStartDate->copy($aDates['start']);
         $oPastStartDate->subtractSeconds(SECONDS_PER_WEEK - OX_OperationInterval::secondsPerOperationInterval());
         $this->oDal->updatePastZoneImpressionForecasts($this->aPastForecastResults, $oPastStartDate);
     }
 }
 /**
  * A method to test the MAX_Delivery_log_logAdRequest(),
  * MAX_Delivery_log_logAdImpression() and MAX_Delivery_log_logAdClick()
  * functions.
  */
 function testRequestImpressionClickFunction()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInterval'] = 60;
     $GLOBALS['_MAX']['NOW'] = time();
     $oNowDate = new Date($GLOBALS['_MAX']['NOW']);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
     $intervalStart = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $aTables = array('MAX_Delivery_log_logAdRequest' => 'data_bkt_r', 'MAX_Delivery_log_logAdImpression' => 'data_bkt_m', 'MAX_Delivery_log_logAdClick' => 'data_bkt_c');
     foreach ($aTables as $function => $table) {
         // Test to ensure that the openXDeliveryLog plugin's data bucket
         // table does not exist
         $oTable = new OA_DB_Table();
         $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . $table);
         $this->assertFalse($tableExists);
         // Test calling the main logging function without any plugins installed,
         // to ensure that this does not result in any kind of error
         unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']);
         call_user_func_array($function, array(1, 1));
     }
     // Install the openXDeliveryLog plugin
     TestEnv::installPluginPackage('openXDeliveryLog', false);
     foreach ($aTables as $function => $table) {
         // Test to ensure that the openXDeliveryLog plugin's data bucket
         // table now does exist
         $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . $table);
         $this->assertTrue($tableExists);
         // Ensure that there are is nothing logged in the data bucket table
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 0);
         // Call the main logging function
         unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']);
         call_user_func_array($function, array(1, 1));
         // Ensure that the data was logged correctly
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         if ($table == 'data_bkt_r') {
             // Request logging is disabled by default. Nothing should have been logged by now
             $this->assertEqual($rows, 0);
             // Enable it
             $GLOBALS['_MAX']['CONF']['logging']['adRequests'] = true;
             unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']);
             call_user_func_array($function, array(1, 1));
             // Now ensure that the data was logged correctly
             $doData_bkt->find();
             $rows = $doData_bkt->getRowCount();
         }
         $this->assertEqual($rows, 1);
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->creative_id = 1;
         $doData_bkt->zone_id = 1;
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 1);
         $doData_bkt->fetch();
         $this->assertEqual($doData_bkt->count, 1);
         $this->assertEqual($doData_bkt->interval_start, $intervalStart);
         // Call the main logging function again
         unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']);
         call_user_func_array($function, array(1, 1));
         // Ensure that the data was logged correctly
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 1);
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->creative_id = 1;
         $doData_bkt->zone_id = 1;
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 1);
         $doData_bkt->fetch();
         $this->assertEqual($doData_bkt->count, 2);
         $this->assertEqual($doData_bkt->interval_start, $intervalStart);
         // Call the main logging function again, but with a differen
         // creative/zone pair
         unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']);
         call_user_func_array($function, array(2, 1));
         // Ensure that the data was logged correctly
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 2);
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->creative_id = 1;
         $doData_bkt->zone_id = 1;
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 1);
         $doData_bkt->fetch();
         $this->assertEqual($doData_bkt->count, 2);
         $this->assertEqual($doData_bkt->interval_start, $intervalStart);
         $doData_bkt = OA_Dal::factoryDO($table);
         $doData_bkt->creative_id = 2;
         $doData_bkt->zone_id = 1;
         $doData_bkt->find();
         $rows = $doData_bkt->getRowCount();
         $this->assertEqual($rows, 1);
         $doData_bkt->fetch();
         $this->assertEqual($doData_bkt->count, 1);
         $this->assertEqual($doData_bkt->interval_start, $intervalStart);
     }
     // Uninstall the openXDeliveryLog plugin
     TestEnv::uninstallPluginPackage('openXDeliveryLog', false);
     // Restore the test configuration file
     TestEnv::restoreConfig();
 }
 /**
  * The method to test the getZonesForecasts() method.
  */
 function testgetZonesForecasts()
 {
     $this->_createTestData();
     $operationInterval = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'];
     $oDal = new OA_Dal_Maintenance_Priority();
     $oLowerDate = new Date('2007-09-16 12:00:00');
     $oUpperDate = new Date('2007-09-16 17:00:00');
     $lowerDateStr = $oLowerDate->format(self::DATE_TIME_FORMAT);
     $upperDateStr = $oUpperDate->format(self::DATE_TIME_FORMAT);
     $weeks = 2;
     // Test with bad input
     $badAgencyId = -1;
     $result = $oDal->getZonesForecasts($lowerDateStr, $upperDateStr);
     $expected = array();
     $this->assertEqual($result, $expected);
     // Test with data outside the range
     $oDate = new Date('2007-09-16 11:00:00');
     $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $previousOIDate = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $startDateStr = $aDates['start']->format(self::DATE_TIME_FORMAT);
     $endDateStr = $aDates['end']->format(self::DATE_TIME_FORMAT);
     $doDIA = OA_Dal::factoryDO('data_intermediate_ad');
     $aDIAs = DataGenerator::generate($doDIA, 1);
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
     $doDIA->date_time = $startDateStr;
     $doDIA->operation_interval = $operationInterval;
     $doDIA->zone_id = $this->zoneId1;
     $doDIA->ad_id = 1;
     $doDIA->impressions = 1000;
     $doDIA->update();
     $result = $oDal->getZonesForecasts($startDateStr, $endDateStr);
     $expected = array();
     $this->assertEqual($result, $expected);
     // Test with data inside the range
     $oDate = new Date('2007-09-16 13:00:00');
     $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $previousOIDate = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $startDateStr = $aDates['start']->format(self::DATE_TIME_FORMAT);
     $endDateStr = $aDates['end']->format(self::DATE_TIME_FORMAT);
     $aDIAs = DataGenerator::generate($doDIA, 1);
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
     $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT);
     $doDIA->operation_interval = $operationInterval;
     $doDIA->zone_id = $this->zoneId1;
     $doDIA->ad_id = 1;
     $doDIA->impressions = 70;
     $doDIA->update();
     $result = $oDal->getZonesForecasts($startDateStr, $endDateStr);
     $expected = array($this->zoneId1 => 70);
     $this->assertEqual($result, $expected);
     // Test with more data from the same zone
     $oDate = new Date('2007-09-16 14:00:00');
     $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $previousOIDate = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate);
     $startDateStr = $aDates['start']->format(self::DATE_TIME_FORMAT);
     $endDateStr = $aDates['end']->format(self::DATE_TIME_FORMAT);
     $aDIAs = DataGenerator::generate($doDIA, 3);
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
     $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT);
     $doDIA->operation_interval = $operationInterval;
     $doDIA->zone_id = $this->zoneId1;
     $doDIA->ad_id = 2;
     $doDIA->impressions = 90;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[1]);
     $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT);
     $doDIA->operation_interval = $operationInterval;
     $doDIA->zone_id = $this->zoneId1;
     $doDIA->ad_id = 4;
     $doDIA->impressions = 110;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[2]);
     $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT);
     $doDIA->operation_interval = $operationInterval;
     $doDIA->zone_id = $this->zoneId2;
     $doDIA->ad_id = 4;
     $doDIA->impressions = 15000;
     $doDIA->update();
     $result = $oDal->getZonesForecasts($startDateStr, $endDateStr);
     $expected = array($this->zoneId1 => 200, $this->zoneId2 => 15000);
     $this->assertEqual($result, $expected);
     DataGenerator::cleanUp();
 }
 /**
  * The test to ensure that a campaign with banners that have time-based
  * delivery limitations are correctly prioritised by the MPE.
  *
  * Test Basis:
  *
  * - One campaign, running from 2008-02-26 to 2008-02-27 (2 days).
  * - Booked impressions of 48,000 impressions (i.e. 1,000 per hour
  *     required on average).
  * - Two banners in the zone, both with weight one.
  *   - Banner ID 1 has a Time:Date delivery limitation, to only allow
  *       the banner to deliver on 2008-02-26.
  *   - Banner ID 2 has a Time:Date delivery limitation, to only allow
  *       the banner to deliver on 2008-02-27.
  * - The campaign is linked to one constantly delivering zone (at
  *     1,000 impressions per hour).
  *
  * - Run the MPE with an OI of 60 minutes for the two days of the
  *     campaign lifetime, and assume that all required impressions
  *     allocated to the banner(s) are delivered.
  *
  * The expected result of this is that the MPE should allocate 1,000
  * impressions per hour for Banner ID 1 all day on 2008-02-26, and
  * 1,000 impressions per hour for Banner ID 2 all day on 2008-02-37.
  */
 function testCampaign()
 {
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $aConf['maintenance']['operationInteval'] = 60;
     $aConf['priority']['useZonePatterning'] = false;
     OA_setTimeZone('GMT');
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('now', new Date('2008-02-27'));
     // Prepare the test campaign
     $doCampaigns = OA_Dal::factoryDO('campaigns');
     $doCampaigns->views = 48000;
     $doCampaigns->clicks = -1;
     $doCampaigns->conversions = -1;
     $doCampaigns->activate_time = '2008-02-26 00:00:00';
     $doCampaigns->expire_time = '2008-02-27 23:59:59';
     $doCampaigns->priority = 10;
     $doCampaigns->target_impression = 0;
     $doCampaigns->target_click = 0;
     $doCampaigns->target_conversion = 0;
     $campaignId = DataGenerator::generateOne($doCampaigns);
     // Prepare the first banner
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->active = 't';
     $doBanners->weight = 1;
     $bannerId1 = DataGenerator::generateOne($doBanners);
     $doAcls = OA_Dal::factoryDO('acls');
     $doAcls->bannerid = $bannerId1;
     $doAcls->logical = 'and';
     $doAcls->type = 'deliveryLimitations:Time:Date';
     $doAcls->comparison = '==';
     $doAcls->data = '20080226';
     $doAcls->executionorder = 0;
     DataGenerator::generateOne($doAcls);
     // Prepare the second banner
     $doBanners = OA_Dal::factoryDO('banners');
     $doBanners->campaignid = $campaignId;
     $doBanners->active = 't';
     $doBanners->weight = 1;
     $bannerId2 = DataGenerator::generateOne($doBanners);
     $doAcls = OA_Dal::factoryDO('acls');
     $doAcls->bannerid = $bannerId2;
     $doAcls->logical = 'and';
     $doAcls->type = 'deliveryLimitations:Time:Date';
     $doAcls->comparison = '==';
     $doAcls->data = '20080227';
     $doAcls->executionorder = 0;
     DataGenerator::generateOne($doAcls);
     // Prepare the zone
     $doZones = OA_Dal::factoryDO('zones');
     $zoneId = DataGenerator::generateOne($doZones);
     // Link the banners to the zone
     $doAd_zone_assoc = OA_Dal::factoryDO('ad_zone_assoc');
     $doAd_zone_assoc->zone_id = $zoneId;
     $doAd_zone_assoc->ad_id = $bannerId1;
     DataGenerator::generateOne($doAd_zone_assoc);
     $doAd_zone_assoc = OA_Dal::factoryDO('ad_zone_assoc');
     $doAd_zone_assoc->zone_id = $zoneId;
     $doAd_zone_assoc->ad_id = $bannerId2;
     DataGenerator::generateOne($doAd_zone_assoc);
     // Run the code to get the required ad impressions over
     // the 48 hour period of the test
     for ($counter = 1; $counter <= 48; $counter++) {
         // Set the "current" date/time that the MPE would be
         // running at for the appropriate hour of the test
         $oNowDate = new Date('2008-02-26 00:00:01');
         $oNowDate->addSeconds(($counter - 1) * SECONDS_PER_HOUR);
         $oServiceLocator->register('now', $oNowDate);
         // Run the code to get the required ad impressions
         $oGetRequiredAdImpressionsLifetime = new OA_Maintenance_Priority_AdServer_Task_GetRequiredAdImpressionsLifetime();
         $oGetRequiredAdImpressionsLifetime->run();
         // Test that 1,000 impressions have been "required" for
         // the appropriate banner
         $query = "SELECT * FROM tmp_ad_required_impression";
         $rsRequiredImpression = DBC::NewRecordSet($query);
         $rsRequiredImpression->find();
         $aRequiredImpressions = $rsRequiredImpression->getAll();
         $this->assertTrue(is_array($aRequiredImpressions), "No array for required impressions SQL result in test hour {$counter}");
         $this->assertEqual(count($aRequiredImpressions), 1, "More than one row found for required impressions SQL result in test hour {$counter}");
         $this->assertTrue(is_array($aRequiredImpressions[0]), "Badly formatted result row for required impressions SQL result in test hour {$counter}");
         $this->assertEqual(count($aRequiredImpressions[0]), 2, "Badly formatted result row for required impressions SQL result in test hour {$counter}");
         $bannerId = $aRequiredImpressions[0]['ad_id'];
         if ($counter <= 24) {
             $this->assertEqual($bannerId, $bannerId1, "Expected required impressions for banner ID {$bannerId1} in test hour {$counter}");
         } else {
             $this->assertEqual($bannerId, $bannerId2, "Expected required impressions for banner ID {$bannerId2} in test hour {$counter}");
         }
         $impressions = $aRequiredImpressions[0]['required_impressions'];
         $this->assertEqual($impressions, 1000, "Incorrectly requested {$impressions} impressions instead of 1000 in test hour {$counter}");
         // Insert the required impressions for the banner into the
         // data_intermediate_ad table, as if the delivery has occurred,
         // so that the next hour's test is based on delivery having happened
         $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
         $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oNowDate);
         $doData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad');
         $doData_intermediate_ad->day = $aDates['start']->format('%Y-%m-%d');
         $doData_intermediate_ad->hour = $aDates['start']->format('%H');
         $doData_intermediate_ad->operation_interval = $aConf['maintenance']['operationInteval'];
         $doData_intermediate_ad->operation_interval_id = $operationIntervalId;
         $doData_intermediate_ad->interval_start = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
         $doData_intermediate_ad->interval_end = $aDates['end']->format('%Y-%m-%d %H:%M:%S');
         $doData_intermediate_ad->ad_id = $bannerId;
         $doData_intermediate_ad->zone_id = $zoneId;
         $doData_intermediate_ad->requests = $impressions;
         $doData_intermediate_ad->impressions = $impressions;
         $doData_intermediate_ad->clicks = 0;
         $doData_intermediate_ad->conversions = 0;
         DataGenerator::generateOne($doData_intermediate_ad);
         // Drop the temporary table that is used to store the
         // required impressions, so that it does not interfer
         // with the next test run in the loop
         unset($GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression']);
         $oTable =& OA_DB_Table_Priority::singleton();
         foreach ($oTable->aDefinition['tables'] as $tableName => $aTable) {
             $oTable->truncateTable($tableName);
             $oTable->dropTable($tableName);
         }
     }
 }
Beispiel #23
0
 /**
  * A method to manage the migration of conversions from the final conversion
  * tables to the old-style intermediate table.
  *
  * @TODO Deprecate, when conversion data is no longer required in the
  *       old format intermediate and summary tables.
  *
  * @param PEAR::Date $oStart The start date/time to migrate from.
  * @param PEAR::Date $oEnd   The end date/time to migrate to.
  */
 function manageConversions($oStart, $oEnd)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     // The custom IF function in PgSQL is not suitable for this query, we need explicit use of CASE
     if ($this->oDbh->dbsyntax == 'pgsql') {
         $sqlBasketValue = "CASE WHEN v.purpose = 'basket_value' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " THEN diavv.value::numeric ELSE 0 END";
         $sqlNumItems = "CASE WHEN v.purpose = 'num_items' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " THEN diavv.value::integer ELSE 0 END";
     } else {
         $sqlBasketValue = "IF(v.purpose = 'basket_value' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . ", diavv.value, 0)";
         $sqlNumItems = "IF(v.purpose = 'num_items' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . ", diavv.value, 0)";
     }
     // Prepare the query to obtain all of the conversions, and their associated total number
     // of items and total basket values (where they exist), ready for update/insertion into
     // the data_intermediate_ad table
     $query = "\n            SELECT\n                DATE_FORMAT(diac.tracker_date_time, '%Y-%m-%d %H:00:00'){$this->timestampCastString} AS date_f,\n                diac.ad_id AS ad_id,\n                diac.zone_id AS zone_id,\n                COUNT(DISTINCT(diac.data_intermediate_ad_connection_id)) AS conversions,\n                SUM({$sqlBasketValue}) AS total_basket_value,\n                SUM({$sqlNumItems}) AS total_num_items\n            FROM\n                " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad_connection', true) . " AS diac\n            LEFT JOIN\n                " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', true) . " AS diavv\n            USING\n                (\n                    data_intermediate_ad_connection_id\n                )\n            LEFT JOIN\n                " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'variables', true) . " AS v\n            ON\n                (\n                    diavv.tracker_variable_id = v.variableid\n                    AND v.purpose IN ('basket_value', 'num_items')\n                )\n            WHERE\n                diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . "\n                AND diac.inside_window = 1\n                AND diac.tracker_date_time >= " . $this->oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n                AND diac.tracker_date_time <= " . $this->oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n            GROUP BY\n                diac.data_intermediate_ad_connection_id,\n                date_f,\n                diac.ad_id,\n                diac.zone_id";
     OA::debug('- Selecting conversion data for migration to the "old style" intermediate table for ', PEAR_LOG_DEBUG);
     OA::debug('  conversion in the range ' . $oStart->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStart->tz->getShortName() . ' to ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG);
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     while ($aRow = $rsResult->fetchRow()) {
         // Prepare the update query
         $query = "\n                UPDATE\n                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad', true) . "\n                SET\n                    conversions = conversions + " . $this->oDbh->quote($aRow['conversions'], 'integer') . ",\n                    total_basket_value = total_basket_value + " . $this->oDbh->quote($aRow['total_basket_value'], 'float') . ",\n                    total_num_items = total_num_items + " . $this->oDbh->quote($aRow['total_num_items'], 'integer') . "\n                WHERE\n                    date_time = " . $this->oDbh->quote($aRow['date_f'], 'timestamp') . "\n                    AND ad_id = " . $this->oDbh->quote($aRow['ad_id'], 'integer') . "\n                    AND zone_id = " . $this->oDbh->quote($aRow['zone_id'], 'integer');
         $rsUpdateResult = $this->oDbh->exec($query);
         if (PEAR::isError($rsUpdateResult)) {
             return MAX::raiseError($rsUpdateResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
         }
         if ($rsUpdateResult == 0) {
             // Could not perform the update - try an insert instead
             $oDate = new Date($aRow['date_f']);
             $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
             $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
             $query = "\n                    INSERT INTO\n                        " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad', true) . "\n                        (\n                            date_time,\n                            operation_interval,\n                            operation_interval_id,\n                            interval_start,\n                            interval_end,\n                            ad_id,\n                            creative_id,\n                            zone_id,\n                            conversions,\n                            total_basket_value,\n                            total_num_items\n                        )\n                    VALUES\n                        (\n                            " . $this->oDbh->quote($aRow['date_f'], 'timestamp') . ",\n                            " . $this->oDbh->quote($aConf['maintenance']['operationInterval'], 'integer') . ",\n                            " . $this->oDbh->quote($operationIntervalId, 'integer') . ",\n                            " . $this->oDbh->quote($aDates['start']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . ",\n                            " . $this->oDbh->quote($aDates['end']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . ",\n                            " . $this->oDbh->quote($aRow['ad_id'], 'integer') . ",\n                            0,\n                            " . $this->oDbh->quote($aRow['zone_id'], 'integer') . ",\n                            " . $this->oDbh->quote($aRow['conversions'], 'integer') . ",\n                            " . $this->oDbh->quote($aRow['total_basket_value'], 'float') . ",\n                            " . $this->oDbh->quote($aRow['total_num_items'], 'integer') . "\n                        )";
             $rsInsertResult = $this->oDbh->exec($query);
         }
     }
 }
Beispiel #24
0
 /**
  * A method to return the forecast impressions for a zone, indexed by operation interval,
  * from the current operation interval through the past week. If no forecast stored in
  * the database for a given OI, uses average of forecasts found.
  *
  * @param integer $zoneId The Zone ID.
  * @return mixed An array on success, false on failure. The array is of the format:
  *                   array(
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                       [operation_interval_id] => array(
  *                                                      ['zone_id']               => zone_id,
  *                                                      ['forecast_impressions']  => forecast_impressions,
  *                                                      ['operation_interval_id'] => operation_interval_id
  *                                                  )
  *                                   .
  *                                   .
  *                                   .
  *                   )
  */
 function getPreviousWeekZoneForcastImpressions($zoneId)
 {
     if (empty($zoneId) || !is_numeric($zoneId)) {
         OA::debug('Invalid zone ID argument', PEAR_LOG_ERR);
         return false;
     }
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oDate =& $oServiceLocator->get('now');
     if (!$oDate) {
         return false;
     }
     // Get previous OI
     $oPreviousOI = new Date($oDate);
     $oPreviousOI->subtractSeconds(OX_OperationInterval::getOperationInterval() * 60);
     // Get the start and end ranges of the current week, up to the previous OI
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oPreviousOI);
     $oDateWeekStart = new Date();
     $oDateWeekStart->copy($aDates['end']);
     $oDateWeekStart->subtractSeconds(SECONDS_PER_WEEK - 1);
     $oDateWeekEnd = new Date();
     $oDateWeekEnd->copy($aDates['end']);
     // Select the zone forecasts from the database
     $tableName = $this->_getTablename('data_intermediate_ad');
     $oneHourInterval = OA_Dal::quoteInterval(1, 'hour');
     $query = "\n            SELECT\n                SUM(impressions) AS forecast_impressions,\n                operation_interval_id AS operation_interval_id,\n                interval_start AS interval_start,\n                interval_end AS interval_end\n            FROM\n            {$tableName}\n            WHERE\n                zone_id = {$zoneId}\n                AND operation_interval = {$aConf['maintenance']['operationInterval']}\n                AND interval_start >= '" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "'\n                AND interval_end <= '" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "'\n                AND date_time > DATE_SUB('" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "', {$oneHourInterval})\n                AND date_time < DATE_ADD('" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "', {$oneHourInterval})\n                AND zone_id != 0\n            GROUP BY\n            \tinterval_start,\n            \tinterval_end,\n            \toperation_interval_id\n            ORDER BY\n                interval_start";
     $rc = $this->oDbh->query($query);
     $totalForecastImpressions = 0;
     $count = 0;
     if (!PEAR::isError($rc)) {
         // Sort the results into an array indexed by the operation interval ID
         $aFinalResult = array();
         while ($aRow = $rc->fetchRow()) {
             $aFinalResult[$aRow['operation_interval_id']] = array('zone_id' => $zoneId, 'forecast_impressions' => $aRow['forecast_impressions'], 'operation_interval_id' => $aRow['operation_interval_id']);
             $count++;
             $totalForecastImpressions += $aRow['forecast_impressions'];
         }
     }
     $averageForecastImpressions = 0;
     if ($count > 0) {
         $averageForecastImpressions = floor($totalForecastImpressions / $count);
     }
     if ($averageForecastImpressions == 0) {
         $averageForecastImpressions = $this->getZoneForecastDefaultZoneImpressions();
     }
     // Check each operation interval ID has a forecast impression value,
     // and if not, set to the system default.
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         if (!isset($aFinalResult[$operationIntervalID])) {
             $aFinalResult[$operationIntervalID] = array('zone_id' => $zoneId, 'forecast_impressions' => $averageForecastImpressions, 'operation_interval_id' => $operationIntervalID);
         }
     }
     // Overwrite current OI with previous OI to match the zone forecasting algorithm
     $currOI = OX_OperationInterval::convertDateToOperationIntervalID($oDate);
     $prevOI = OX_OperationInterval::previousOperationIntervalID($currOI);
     $aFinalResult[$currOI]['forecast_impressions'] = $aFinalResult[$prevOI]['forecast_impressions'];
     // Return data
     return $aFinalResult;
 }
 /**
  * A method to test the convertDateToOperationIntervalStartAndEndDates() method.
  */
 function testConvertDateToOperationIntervalStartAndEndDates()
 {
     // Test a date in the first operation interval ID in the week before the test was
     // written, using a default operation interval of 60 minutes
     $date = new Date('2004-08-08 00:40:00');
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($date, 60);
     $this->assertEqual($aDates['start'], new Date('2004-08-08 00:00:00'));
     $this->assertEqual($aDates['end'], new Date('2004-08-08 00:59:59'));
     // Test the same date, but with an operation interval of 30 minutes
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($date, 30);
     $this->assertEqual($aDates['start'], new Date('2004-08-08 00:30:00'));
     $this->assertEqual($aDates['end'], new Date('2004-08-08 00:59:59'));
 }
 /**
  * A method to test the getPreviousWeekZoneForcastImpressions() method.
  *
  * Test 1: Test with bad input, and ensure false is returned.
  * Test 2: Test with no date in the service locator, and ensure that
  *         false is returned.
  * Test 3: Test with no data, and ensure that an array with the default
  *         forecast for each zone is returned.
  * Test 4: Test with data, and ensure that an array with the correct
  *         forecasts is returned.
  */
 function testGetPreviousWeekZoneForcastImpressions()
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $oDal = new OA_Dal_Maintenance_Priority();
     // Test 1
     $aResult = $oDal->getPreviousWeekZoneForcastImpressions('foo');
     $this->assertFalse($aResult);
     // Test 2
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->remove('now');
     $aResult = $oDal->getPreviousWeekZoneForcastImpressions(1);
     $this->assertFalse($aResult);
     // Test 3
     $oDate = new Date();
     $oServiceLocator->register('now', $oDate);
     $aResult = $oDal->getPreviousWeekZoneForcastImpressions(1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), OX_OperationInterval::operationIntervalsPerWeek());
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         $expected = array('zone_id' => 1, 'forecast_impressions' => $oDal->getZoneForecastDefaultZoneImpressions(), 'operation_interval_id' => $operationIntervalID);
         $this->assertEqual($aResult[$operationIntervalID], $expected);
     }
     // Test 4
     // Insert impressions for the previous operation interval
     $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $firstIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
     $startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $doDIA = OA_Dal::factoryDO('data_intermediate_ad');
     $aDIAs = DataGenerator::generate($doDIA, 4);
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
     $startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $doDIA->date_time = $startDate;
     $doDIA->interval_start = $startDate;
     $doDIA->interval_end = $endDate;
     $doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
     $doDIA->operation_interval_id = $firstIntervalID;
     $doDIA->zone_id = 1;
     $doDIA->ad_id = 1;
     $doDIA->impressions = 4000;
     $doDIA->update();
     // Insert forcast for the (N - 2) OI
     // for two different ads in this OI
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
     $secondIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
     $startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[1]);
     $doDIA->date_time = $startDate;
     $doDIA->interval_start = $startDate;
     $doDIA->interval_end = $endDate;
     $doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
     $doDIA->operation_interval_id = $secondIntervalID;
     $doDIA->zone_id = 1;
     $doDIA->ad_id = 1;
     $doDIA->impressions = 4990;
     $doDIA->update();
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[2]);
     $doDIA->date_time = $startDate;
     $doDIA->interval_start = $startDate;
     $doDIA->interval_end = $endDate;
     $doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
     $doDIA->operation_interval_id = $secondIntervalID;
     $doDIA->zone_id = 1;
     $doDIA->ad_id = 2;
     $doDIA->impressions = 10;
     $doDIA->update();
     // Insert forcast for the second previous operation interval, but
     // one week ago (so it should not be in the result set)
     $oNewDate = new Date();
     $oNewDate->copy($aDates['start']);
     $oNewDate->subtractSeconds(SECONDS_PER_WEEK);
     $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oNewDate);
     $intervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
     $startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
     $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[3]);
     $doDIA->date_time = $startDate;
     $doDIA->interval_start = $startDate;
     $doDIA->interval_end = $endDate;
     $doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
     $doDIA->operation_interval_id = $intervalID;
     $doDIA->zone_id = 1;
     $doDIA->ad_id = 1;
     $doDIA->impressions = 1000;
     $doDIA->update();
     // What's the current OI?
     $currentIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oServiceLocator->get('now'));
     $aResult = $oDal->getPreviousWeekZoneForcastImpressions(1);
     $this->assertTrue(is_array($aResult));
     $this->assertEqual(count($aResult), OX_OperationInterval::operationIntervalsPerWeek());
     for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
         $this->assertTrue(is_array($aResult[$operationIntervalID]));
         $this->assertEqual(count($aResult[$operationIntervalID]), 3);
         $this->assertEqual($aResult[$operationIntervalID]['zone_id'], 1);
         if ($operationIntervalID == $firstIntervalID || $operationIntervalID == $currentIntervalID) {
             // Current and previous OI forecasts should be the same
             $this->assertEqual($aResult[$operationIntervalID]['forecast_impressions'], 4000);
         } elseif ($operationIntervalID == $secondIntervalID) {
             $this->assertEqual($aResult[$operationIntervalID]['forecast_impressions'], 5000);
         } else {
             $this->assertEqual($aResult[$operationIntervalID]['forecast_impressions'], 4500);
             // average between both known forecast
         }
         $this->assertEqual($aResult[$operationIntervalID]['operation_interval_id'], $operationIntervalID);
     }
     DataGenerator::cleanUp();
 }