function __construct()
 {
     // Check auto-maintenance settings
     $aConf = $GLOBALS['_MAX']['CONF'];
     $this->isAutoMaintenanceEnabled = !empty($aConf['maintenance']['autoMaintenance']);
     // Get time 1 hour ago
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNow = $oServiceLocator->get('now');
     if ($oNow) {
         $oOneHourAgo = new Date($oNow);
     } else {
         $oOneHourAgo = new Date();
     }
     $oOneHourAgo->subtractSpan(new Date_Span('0-1-0-0'));
     // Get last runs
     $oLastCronRun = OX_Maintenance::getLastScheduledRun();
     $oLastRun = OX_Maintenance::getLastRun();
     // Reset minutes and seconds
     if (isset($oLastCronRun)) {
         $oLastCronRun->setMinute(0);
         $oLastCronRun->setSecond(0);
     }
     if (isset($oLastRun)) {
         $oLastRun->setMinute(0);
         $oLastRun->setSecond(0);
     }
     // Check if any kind of maintenance was run
     if (isset($oLastCronRun) && !$oOneHourAgo->after($oLastCronRun)) {
         $this->isScheduledMaintenanceRunning = true;
     } elseif (isset($oLastRun) && !$oOneHourAgo->after($oLastRun)) {
         $this->isAutoMaintenanceRunning = true;
     }
 }
 /**
  * A method to get the "now" date class, eventually subtracting
  * some time
  *
  * @param int $subtractSeconds
  * @return Date
  */
 function &getDate($subtractSeconds = 0)
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNow = new Date($oServiceLocator->get('now'));
     if ($subtractSeconds) {
         $oNow->subtractSeconds($subtractSeconds);
     }
     return $oNow;
 }
 function _useDefaultDal()
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     $dal =& $oServiceLocator->get('MAX_Dal_Inventory_Trackers');
     if (!$dal) {
         $dal = new MAX_Dal_Inventory_Trackers();
     }
     $this->_dal =& $dal;
 }
 function _useDefaultDal()
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     $dal =& $oServiceLocator->get('OA_Dal_PasswordRecovery');
     if (!$dal) {
         $dal = new OA_Dal_PasswordRecovery();
     }
     $this->_dal =& $dal;
 }
 /**
  * A private method for summarising data into the final tables when
  * at least one hour is complete.
  *
  * @access private
  * @param PEAR::Date $oStartDate The start date of the complete hour(s).
  * @param PEAR::Date $oEndDate The end date of the complete hour(s).
  */
 function _saveSummary($oStartDate, $oEndDate)
 {
     $message = '- Updating the data_summary_ad_hourly table for data after ' . $oStartDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStartDate->tz->getShortName();
     $this->oController->report .= $message . ".\n";
     OA::debug($message, PEAR_LOG_DEBUG);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
     $aTypes = array('types' => array(0 => 'request', 1 => 'impression', 2 => 'click'), 'connections' => array(1 => MAX_CONNECTION_AD_IMPRESSION, 2 => MAX_CONNECTION_AD_CLICK));
     $oDal->saveSummary($oStartDate, $oEndDate, $aTypes, 'data_intermediate_ad', 'data_summary_ad_hourly');
 }
 function testRunnerHasResources()
 {
     // Mock the OA_Dal_Maintenance_Priority class used in the constructor method
     $oDal = new MockOA_Dal_Maintenance_Priority($this);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Dal_Maintenance_Priority', $oDal);
     $task = new OA_Maintenance_Priority_AdServer_Task();
     $this->assertTrue(is_object($task->oDal));
     $this->assertTrue(is_a($task->oDal, 'MockOA_Dal_Maintenance_Priority'));
 }
Beispiel #7
0
 /**
  * Method to create/register/return the Maintenance Priority table class.
  *
  * @access private
  * @return OA_DB_Table_Priority
  */
 function &_getMaxTablePriorityObj()
 {
     $dbType = strtolower($GLOBALS['_MAX']['CONF']['database']['type']);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oTable = $oServiceLocator->get('OA_DB_Table_Priority');
     if (!$oTable) {
         $oTable =& OA_DB_Table_Priority::singleton();
         $oServiceLocator->register('OA_DB_Table_Priority', $oTable);
     }
     return $oTable;
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of activating/deactivating campaigns.
  */
 function run()
 {
     if ($this->oController->updateIntermediate) {
         $oServiceLocator =& OA_ServiceLocator::instance();
         $oDate =& $oServiceLocator->get('now');
         $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
         $message = '- Managing (activating/deactivating) campaigns';
         $this->oController->report .= "{$message}.\n";
         OA::debug($message);
         $this->report .= $oDal->manageCampaigns($oDate);
     }
 }
 /**
  * A method to test the run() method.
  */
 function testRun()
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $className = 'OX_Dal_Maintenance_Statistics_' . ucfirst(strtolower($aConf['database']['type']));
     $mockClassName = 'MockOX_Dal_Maintenance_Statistics_' . ucfirst(strtolower($aConf['database']['type']));
     $aConf['maintenance']['operationInterval'] = 60;
     // Test 1: Test with the bucket data not having been migrated,
     //         and ensure that the DAL calls to de-duplicate and
     //         reject conversions are not made
     // Set the controller class
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Mock the MSE DAL used to de-duplicate conversions,
     // and set the expectations of the calls to the DAL
     Mock::generate($className);
     $oDal = new $mockClassName($this);
     $oDal->expectNever('deduplicateConversions');
     $oDal->expectNever('rejectEmptyVarConversions');
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     // Set the controlling class' status and test
     $oDeDuplicateConversions = new OX_Maintenance_Statistics_Task_DeDuplicateConversions();
     $oDeDuplicateConversions->oController->updateIntermediate = false;
     $oDeDuplicateConversions->run();
     $oDal->tally();
     // Test 2: Test with the bucket data having been migrated, and
     //         ensure that the DALL calls to de-duplicate and reject
     //         conversions are made correctly
     // Set the controller class
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Mock the MSE DAL used to de-duplicate conversions,
     // and set the expectations of the calls to the DAL
     Mock::generate($className);
     $oDal = new $mockClassName($this);
     $oDate = new Date('2008-09-08 16:59:59');
     $oDate->addSeconds(1);
     $oDal->expectOnce('deduplicateConversions', array($oDate, new Date('2008-09-08 17:59:59')));
     $oDal->expectOnce('rejectEmptyVarConversions', array($oDate, new Date('2008-09-08 17:59:59')));
     $oDal->OX_Dal_Maintenance_Statistics();
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     // Set the controlling class' status and test
     $oDeDuplicateConversions = new OX_Maintenance_Statistics_Task_DeDuplicateConversions();
     $oDeDuplicateConversions->oController->updateIntermediate = true;
     $oDeDuplicateConversions->oController->oLastDateIntermediate = new Date('2008-09-08 16:59:59');
     $oDeDuplicateConversions->oController->oUpdateIntermediateToDate = new Date('2008-09-08 17:59:59');
     $oDeDuplicateConversions->run();
     $oDal->tally();
     TestEnv::restoreConfig();
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of managing conversions.
  */
 function run()
 {
     if ($this->oController->updateIntermediate) {
         // Preapre the start date for the management of conversions
         $oStartDate = new Date();
         $oStartDate->copy($this->oController->oLastDateIntermediate);
         $oStartDate->addSeconds(1);
         // Get the MSE DAL to perform the conversion management
         $oServiceLocator =& OA_ServiceLocator::instance();
         $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
         // Manage conversions
         $oDal->manageConversions($oStartDate, $this->oController->oUpdateIntermediateToDate);
     }
 }
 /**
  * The main method of the class, that is run by the controlling
  * task runner class.
  */
 function run()
 {
     OA::debug('Running Maintenance Priority Engine: Priority Compensation', PEAR_LOG_DEBUG);
     // Record the start of this Priority Compensation run
     $oStartDate = new Date();
     // Prepare an array for the priority results
     $aPriorities = array();
     // Get the details of the last time Priority Compensation started running
     $aDates = $this->oDal->getMaintenancePriorityLastRunInfo(DAL_PRIORITY_UPDATE_PRIORITY_COMPENSATION, 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');
     }
     // Get all creative/zone information
     $aZones =& $this->_buildClasses();
     // For every zone with creatives linked to it...
     if (!empty($aZones)) {
         $this->globalMessage = '';
         OA::debug('- Calculating priority values for creative/zone pairs', PEAR_LOG_DEBUG);
         foreach ($aZones as $oZone) {
             // Is this Zone ID 0, the Direct Selection zone?
             if ($oZone->id == 0) {
                 // Calculate simplistic priorities based on the required impression
                 // values without any form of priority compensation based on past
                 // information about previous priorities, as this is the Direct
                 // Selection zone, and priority compensation adjustment is not required
                 OA::debug('  - Calculating priority values for creatives in Zone ID ' . $oZone->id . ': Basic', PEAR_LOG_DEBUG);
                 $aPriorities[$oZone->id] = $this->initialPriorities($oZone);
             } else {
                 // Calculate the priorities based on the required impression
                 // values and the past information about previous priorities
                 OA::debug('  - Calculating priority values for creatives in Zone ID ' . $oZone->id . ': Compensated', PEAR_LOG_DEBUG);
                 $aPriorities[$oZone->id] = $this->compensatedPriorities($oZone);
             }
         }
         // Store the calculated priorities
         $this->oDal->updatePriorities($aPriorities);
         // 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 are the start and end dates
         OA::debug('- Recording completion of the Priority Compensation task', PEAR_LOG_DEBUG);
         $oEndDate = new Date();
         $this->oDal->setMaintenancePriorityLastRunInfo($oStartDate, $oEndDate, null, DAL_PRIORITY_UPDATE_PRIORITY_COMPENSATION);
     }
 }
 /**
  * The implementation of the OA_Task::run() method that performs
  * the required task of de-duplicating and rejecting conversions.
  */
 function run()
 {
     if ($this->oController->updateIntermediate) {
         // Preapre the start date for the de-duplication/rejection
         $oStartDate = new Date();
         $oStartDate->copy($this->oController->oLastDateIntermediate);
         $oStartDate->addSeconds(1);
         // Get the MSE DAL to perform the de-duplication
         $oServiceLocator =& OA_ServiceLocator::instance();
         $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
         // De-duplicate conversions
         $oDal->deduplicateConversions($oStartDate, $this->oController->oUpdateIntermediateToDate);
         // Reject empty variable conversions
         $oDal->rejectEmptyVarConversions($oStartDate, $this->oController->oUpdateIntermediateToDate);
     }
 }
Beispiel #13
0
 /**
  * A method to run distributed maintenance.
  */
 function run()
 {
     if (empty($GLOBALS['_MAX']['CONF']['lb']['enabled'])) {
         OA::debug('Distributed stats disabled, not running Maintenance Distributed Engine', PEAR_LOG_INFO);
         return;
     }
     if (!empty($GLOBALS['_MAX']['CONF']['rawDatabase'])) {
         $GLOBALS['_MAX']['CONF']['database'] = $GLOBALS['_MAX']['CONF']['rawDatabase'] + $GLOBALS['_MAX']['CONF']['database'];
         OA::debug('rawDatabase functionality is being used, switching settings', PEAR_LOG_INFO);
     }
     $oLock =& OA_DB_AdvisoryLock::factory();
     if (!$oLock->get(OA_DB_ADVISORYLOCK_DISTRIBUTED)) {
         OA::debug('Maintenance Distributed Engine Already Running', PEAR_LOG_INFO);
         return;
     }
     OA::debug('Running Maintenance Distributed Engine', PEAR_LOG_INFO);
     // Attempt to increase PHP memory
     OX_increaseMemoryLimit(OX_getMinimumRequiredMemory('maintenance'));
     // Ensure the current time is registered with the OA_ServiceLocator
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNow =& $oServiceLocator->get('now');
     if (!$oNow) {
         // Record the current time, and register with the OA_ServiceLocator
         $oNow = new Date();
         $oServiceLocator->register('now', $oNow);
     }
     OA::debug(' - Current time is ' . $oNow->format('%Y-%m-%d %H:%M:%S') . ' ' . $oNow->tz->getShortName(), PEAR_LOG_DEBUG);
     // Get the components of the deliveryLog extension
     $aBuckets = OX_Component::getComponents('deliveryLog');
     // Copy buckets' records with "interval_start" up to and including previous OI start,
     // and then prune the data processed
     $aPreviousOperationIntervalDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oNow);
     OA::debug(' - Will process data for all operation intervals before and up to start', PEAR_LOG_DEBUG);
     OA::debug('   time of ' . $aPreviousOperationIntervalDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aPreviousOperationIntervalDates['start']->tz->getShortName(), PEAR_LOG_DEBUG);
     foreach ($aBuckets as $sBucketName => $oBucketClass) {
         if ($oBucketClass->testStatisticsMigration($oBucketClass->getStatisticsMigration())) {
             $oBucketClass->processBucket($aPreviousOperationIntervalDates['start']);
             $oBucketClass->pruneBucket($aPreviousOperationIntervalDates['start']);
         } else {
             OA::debug('  - Skipping ' . $sBucketName, PEAR_LOG_DEBUG);
         }
     }
     $oLock->release();
     OA::debug('Maintenance Distributed Engine Completed', PEAR_LOG_INFO);
 }
 /**
  * initialisation
  *
  * load the 'requestset' config file
  * do not load the dataset yet - allow child scenario to choose
  *
  * @param string $filename - name of scenario's dataset and config
  * @param string $dbname database name
  */
 function init($filename)
 {
     $GLOBALS['_MAX']['CONF']['table']['prefix'] = '';
     // assign the inputs
     $this->requestFile = SCENARIOS_REQUESTSETS . $filename . '.php';
     // load the request data
     $this->loadRequestset();
     // tweak some conf vals
     $GLOBALS['_MAX']['COOKIE']['newViewerId'] = '';
     $_COOKIE = $HTTP_COOKIE_VARS = array();
     // get service locator instance
     $this->oServiceLocator =& OA_ServiceLocator::instance();
     // start with a clean set of tables
     OA_DB_Table_Core::destroy();
     $this->oCoreTables =& OA_DB_Table_Core::singleton();
     // get the database handler
     $this->oDbh =& OA_DB::singleton();
     // fake the date/time
     $this->setDateTime();
 }
 /**
  * A method to insert the default data into the database.
  *
  * The default data are:
  *
  *  - Test Advertiser 1
  *    - Placement 11
  *      - High Priority
  *      - Daily target of 120 impressions (5 per
  *        hour assuming even delivery each hour)
  *        - Advertisement 111
  *          - Banner Weight 1
  *    - Placement 12
  *      - High Priority
  *      - Runs from 2005-01-01 to 2005-12-31
  *      - Total target of 87,600 (10 per hour
  *        assuming even delivery each hour)
  *        - Advertisement 121
  *          - Banner Weight 2
  *        - Advertisement 122
  *          - Banner Weight 1
  *
  *  - Test Advertiser 2
  *    - Placement 21
  *    - Placement 22
  *
  *  - Test Publisher 1
  *    - Zone 11
  *    - Zone 12
  *
  *  - Test Publisher 2
  *    - Zone 21
  *    - Zone 22
  *
  * - Advertisement 111 is linked to Zone 11
  * - Advertisement 121 is linked to Zone 21
  * - Advertisement 122 is linked to Zone 21 AND Zone 22
  *
  * @static
  * @access public
  * @TODO Complete the specification of the default data and the implementation
  *       of the creation thereof.
  */
 function insertDefaultData()
 {
     $oDbh =& OA_DB::singleton();
     // Set now
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oldNow = $oServiceLocator->get('now');
     $oServiceLocator->register('now', new Date('2005-03-01'));
     // Add a default agency
     $agencyID = Admin_DA::addAgency(array('name' => 'Test Agency', 'contact' => 'Contact Name', 'username' => 'agency', 'email' => '*****@*****.**', 'active' => 1));
     // Add two advertisers for the agency
     $advertiserOneID = Admin_DA::addAdvertiser(array('agencyid' => $agencyID, 'clientname' => 'Test Advertiser 1', 'contact' => 'Contact Name 1', 'clientusername' => 'advertiser1', 'email' => '*****@*****.**'));
     $advertiserTwoID = Admin_DA::addAdvertiser(array('agencyid' => $agencyID, 'clientname' => 'Test Advertiser 2', 'contact' => 'Contact Name 2', 'clientusername' => 'advertiser2', 'email' => '*****@*****.**'));
     // Add the advertiser's placements (campaigns) & advertisements
     $campaignOneOneID = Admin_DA::addPlacement(array('campaignname' => 'Campaign 11 - Manual Daily Target of 120', 'clientid' => $advertiserOneID, 'views' => -1, 'clicks' => -1, 'conversions' => -1, 'status' => OA_ENTITY_STATUS_RUNNING, 'priority' => 2, 'target_impression' => 120, 'target_click' => -1, 'target_conversion' => -1));
     $adOneOneOneID = Admin_DA::addAd(array('campaignid' => $campaignOneOneID, 'description' => 'Advertisement 111', 'active' => 't', 'weight' => 1, 'htmltemplate' => '', 'url' => '', 'bannertext' => '', 'compiledlimitation' => '', 'append' => ''));
     $campaignOneTwoID = Admin_DA::addPlacement(array('campaignname' => 'Campaign 22 - Auto Distribution of 87,600 Impressions', 'clientid' => $advertiserOneID, 'views' => 87600, 'clicks' => -1, 'conversions' => -1, 'status' => OA_ENTITY_STATUS_RUNNING, 'priority' => 2, 'target_impression' => -1, 'target_click' => -1, 'target_conversion' => -1, 'activate_time' => '2005-01-01 00:00:00', 'expire_time' => '2005-12-31 23:59:59'));
     $adOneTwoOneID = Admin_DA::addAd(array('campaignid' => $campaignOneTwoID, 'description' => 'Advertisement 121', 'active' => 't', 'weight' => 2, 'htmltemplate' => '', 'url' => '', 'bannertext' => '', 'compiledlimitation' => '', 'append' => ''));
     $adOneTwoTwoID = Admin_DA::addAd(array('campaignid' => $campaignOneTwoID, 'description' => 'Advertisement 122', 'active' => 't', 'weight' => 1, 'htmltemplate' => '', 'url' => '', 'bannertext' => '', 'compiledlimitation' => '', 'append' => ''));
     // Add two publishers for the agency
     $publisherOneID = Admin_DA::addPublisher(array('agencyid' => $agencyID, 'name' => 'Test Publisher 1', 'contact' => 'Contact Name 1', 'username' => 'publisher1', 'email' => '*****@*****.**'));
     $publisherTwoID = Admin_DA::addPublisher(array('agencyid' => $agencyID, 'name' => 'Test Publisher 1', 'contact' => 'Contact Name 1', 'username' => 'publisher1', 'email' => '*****@*****.**'));
     // Add the publisher's zones
     $zoneOneOneID = Admin_DA::addZone(array('affiliateid' => $publisherOneID, 'zonename' => 'Zone 11', 'type' => 0, 'category' => '', 'ad_selection' => '', 'chain' => '', 'prepend' => '', 'append' => '', 'what' => ''));
     $zoneOneTwoID = Admin_DA::addZone(array('affiliateid' => $publisherOneID, 'zonename' => 'Zone 12', 'type' => 0, 'category' => '', 'ad_selection' => '', 'chain' => '', 'prepend' => '', 'append' => '', 'what' => ''));
     $zoneTwoOneID = Admin_DA::addZone(array('affiliateid' => $publisherOneID, 'zonename' => 'Zone 21', 'type' => 0, 'category' => '', 'ad_selection' => '', 'chain' => '', 'prepend' => '', 'append' => '', 'what' => ''));
     $zoneTwoTwoID = Admin_DA::addZone(array('affiliateid' => $publisherOneID, 'zonename' => 'Zone 22', 'type' => 0, 'category' => '', 'ad_selection' => '', 'chain' => '', 'prepend' => '', 'append' => '', 'what' => ''));
     // Link the ads to the zones
     Admin_DA::addAdZone(array('ad_id' => $adOneOneOneID, 'zone_id' => $zoneOneOneID, 'link_type' => 1));
     Admin_DA::addAdZone(array('ad_id' => $adOneTwoOneID, 'zone_id' => $zoneTwoOneID, 'link_type' => 1));
     Admin_DA::addAdZone(array('ad_id' => $adOneTwoTwoID, 'zone_id' => $zoneTwoOneID, 'link_type' => 1));
     Admin_DA::addAdZone(array('ad_id' => $adOneTwoTwoID, 'zone_id' => $zoneTwoTwoID, 'link_type' => 1));
     // Restore "now"
     if ($oldNow) {
         $oServiceLocator->register('now', $oldNow);
     } else {
         $oServiceLocator->remove('now');
     }
 }
 /**
  * Pruning can be performed where zone_id = 0 (i.e. for direct selection) and where the entry is older than MAX_PREVIOUS_AD_DELIVERY_INFO_LIMIT minutes ago.
  *
  */
 function testPruneDataSummaryAdZoneAssocOldData()
 {
     $oDate = new Date();
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('now', $oDate);
     $oDal = new OA_Maintenance_Pruning();
     $doDSAZA = OA_Dal::factoryDO('data_summary_ad_zone_assoc');
     // Test 1: table is empty : nothing to delete
     $this->assertEqual($this->_countRowsInDSAZA(), 0);
     $this->assertFalse($oDal->_pruneDataSummaryAdZoneAssocOldData());
     // generate 4 records
     $aIds = DataGenerator::generate($doDSAZA, 4);
     $this->assertEqual($this->_countRowsInDSAZA(), 4);
     // Test 2: values are current, zone_id = 1 : nothing to delete
     $this->assertFalse($oDal->_pruneDataSummaryAdZoneAssocOldData());
     $this->assertEqual($this->_countRowsInDSAZA(), 4);
     // Test 3: values are old, zone_id = 1 : should not delete anything
     foreach ($aIds as $k => $id) {
         $oDate->subtractSeconds(MAX_PREVIOUS_AD_DELIVERY_INFO_LIMIT + 100);
         $doDSAZA->data_summary_ad_zone_assoc_id = $id;
         $doDSAZA->find(true);
         $doDSAZA->created = $oDate->getDate();
         $doDSAZA->zone_id = 1;
         $doDSAZA->update();
     }
     $this->assertFalse($oDal->_pruneDataSummaryAdZoneAssocOldData());
     $this->assertEqual($this->_countRowsInDSAZA(), 4);
     // Test 4: values are old, zone_id = 0 : should delete 4 records
     foreach ($aIds as $k => $id) {
         $doDSAZA->data_summary_ad_zone_assoc_id = $id;
         $doDSAZA->find(true);
         $doDSAZA->zone_id = 0;
         $doDSAZA->update();
     }
     $this->assertTrue($oDal->_pruneDataSummaryAdZoneAssocOldData());
     $this->assertEqual($this->_countRowsInDSAZA(), 0);
 }
 /**
  * The main method of the class, that is run by the controlling
  * task runner class.
  */
 function run()
 {
     OA::debug('Running Maintenance Priority Engine: Priority Compensation', PEAR_LOG_DEBUG);
     // Record the start of this Priority Compensation run
     $oStartDate = new Date();
     // Prepare an array for the priority results
     $aPriorities = array();
     // Get the details of the last time Priority Compensation started running
     $aDates = $this->oDal->getMaintenancePriorityLastRunInfo(DAL_PRIORITY_UPDATE_PRIORITY_COMPENSATION, 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');
     }
     // Get all zone/ad information
     $aZones =& $this->_buildClasses();
     // For every zone with ads linked to it...
     if (!empty($aZones)) {
         $this->globalMessage = '';
         foreach ($aZones as $oZone) {
             // Calculate the priorities based on the required impression
             // values and the past information about previous priorities
             $aPriorities[$oZone->id] = $this->learnedPriorities($oZone);
         }
         // Store the calculated priorities
         $this->oDal->updatePriorities($aPriorities);
         // 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 Priority Compensation task', PEAR_LOG_DEBUG);
         $oEndDate = new Date();
         $this->oDal->setMaintenancePriorityLastRunInfo($oStartDate, $oEndDate, null, DAL_PRIORITY_UPDATE_PRIORITY_COMPENSATION);
     }
 }
 /**
  * A method to test the run() method.
  */
 function testRun()
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     // Register the current date/time
     $oDateNow = new Date();
     $oServiceLocator->register('now', $oDateNow);
     // Mock the DAL, and set expectations
     Mock::generate('OX_Dal_Maintenance_Statistics');
     $oDal = new MockOX_Dal_Maintenance_Statistics($this);
     $oDal->expectNever('manageCampaigns');
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     // Set the controller class
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Test
     $oManageCampaigns = new OX_Maintenance_Statistics_Task_ManageCampaigns();
     $oManageCampaigns->oController->updateIntermediate = false;
     $oManageCampaigns->run();
     $oDal->tally();
     // Register the current date/time
     $oDateNow = new Date();
     $oServiceLocator->register('now', $oDateNow);
     // Mock the DAL, and set expectations
     Mock::generate('OX_Dal_Maintenance_Statistics');
     $oDal = new MockOX_Dal_Maintenance_Statistics($this);
     $oDal->expectOnce('manageCampaigns', array($oDateNow));
     $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
     // Set the controller class
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Test
     $oManageCampaigns = new OX_Maintenance_Statistics_Task_ManageCampaigns();
     $oManageCampaigns->oController->updateIntermediate = true;
     $oManageCampaigns->run();
     $oDal->tally();
 }
 /**
  * A method to test the preloadZonesAvailableImpressionsForAgency() method.
  *
  * Requirements
  * Test 1: Test that contracts are correctly calculated based on the forecasts and allocations
  */
 function testPreloadZonesAvailableImpressionsForAgency()
 {
     // Mock the OA_Dal_Maintenance_Priority class used in the constructor method
     $oDal = new $this->mockDal($this);
     $aZonesForecasts = array(1 => 10, 2 => 20, 3 => 50);
     $oDal->setReturnReference('getZonesForecasts', $aZonesForecasts);
     $aZonesAllocations = array(1 => 10, 2 => 30, 4 => 10);
     $oDal->setReturnReference('getZonesAllocationsForEcpmRemnantByAgency', $aZonesAllocations);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Dal_Maintenance_Priority', $oDal);
     // Partially mock the OA_Maintenance_Priority_AdServer_Task_ECPMforRemnant class
     $oEcpm = new PartialMock_OA_Maintenance_Priority_AdServer_Task_ECPMforRemnant($this);
     $oEcpm->aOIDates['start'] = $oEcpm->aOIDates['end'] = new Date();
     $oEcpm->setReturnReference('_getDal', $oDal);
     $oEcpm->OA_Maintenance_Priority_AdServer_Task();
     // Test
     $aZonesExpectedContracts = array(1 => 0, 2 => 0, 3 => 50);
     $dataJustLoaded = $oEcpm->preloadZonesAvailableImpressionsForAgency(123);
     $this->assertEqual($aZonesExpectedContracts, $oEcpm->aZonesAvailableImpressions);
     $this->assertTrue($dataJustLoaded);
     $dataJustLoaded = $oEcpm->preloadZonesAvailableImpressionsForAgency(152);
     $this->assertEqual($aZonesExpectedContracts, $oEcpm->aZonesAvailableImpressions);
     $this->assertFalse($dataJustLoaded);
 }
 /**
  * A method to test the setSummaryStatisticsToday() method.
  *
  * Requirements:
  * Test 1: Test with no delivery today in the database, and ensure that
  *         zero is set for all delivery values.
  * Test 2: Test with delivery today in the database, and ensure the values
  *         are correctly stored.
  */
 function testSetSummaryStatisticsToday()
 {
     $aCampaignStats = array('advertiser_id' => 1, 'campaign_id' => 1, 'name' => 'Campaign Name', 'active' => 't', 'num_children' => 1, 'sum_requests' => 100, 'sum_views' => 99, 'sum_clicks' => 5, 'sum_conversions' => 1);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oMaxDalMaintenancePriority =& $oServiceLocator->get('OA_Dal_Maintenance_Priority');
     $oMaxDalMaintenancePriority->setReturnValueAt(0, 'getCampaignStats', null);
     $oMaxDalMaintenancePriority->setReturnValueAt(1, 'getCampaignStats', $aCampaignStats);
     $oMaxDalMaintenancePriority->expectArgumentsAt(0, 'getCampaignStats', array(1, true, '2006-11-10'));
     $oMaxDalMaintenancePriority->expectArgumentsAt(1, 'getCampaignStats', array(1, true, '2006-11-10'));
     $oMaxDalMaintenancePriority->expectCallCount('getCampaignStats', 2);
     // Test 1
     $aParams = array('campaignid' => 1);
     $oCampaign = new OX_Maintenance_Priority_Campaign($aParams);
     $this->assertNull($oCampaign->deliveredRequests);
     $this->assertNull($oCampaign->deliveredImpressions);
     $this->assertNull($oCampaign->deliveredClicks);
     $this->assertNull($oCampaign->deliveredConversions);
     $oCampaign->setSummaryStatisticsToday('2006-11-10');
     $this->assertEqual($oCampaign->deliveredRequests, 0);
     $this->assertEqual($oCampaign->deliveredImpressions, 0);
     $this->assertEqual($oCampaign->deliveredClicks, 0);
     $this->assertEqual($oCampaign->deliveredConversions, 0);
     // Test 2
     $oCampaign->setSummaryStatisticsToday('2006-11-10');
     $this->assertEqual($oCampaign->deliveredRequests, 100);
     $this->assertEqual($oCampaign->deliveredImpressions, 99);
     $this->assertEqual($oCampaign->deliveredClicks, 5);
     $this->assertEqual($oCampaign->deliveredConversions, 1);
     $oMaxDalMaintenancePriority->tally();
 }
Beispiel #21
0
 /**
  * The abstract class constructor, to be used by classes implementing
  * this class.
  */
 function OX_Maintenance_Statistics_Task()
 {
     // Set the local reference to the class which is controlling this task
     $oServiceLocator =& OA_ServiceLocator::instance();
     $this->oController =& $oServiceLocator->get('Maintenance_Statistics_Controller');
 }
 /**
  * A private method to run the "midnight" general pruning tasks.
  *
  * @access private
  */
 function _runGeneralPruning()
 {
     if (empty($GLOBALS['_MAX']['CONF']['maintenance']['pruneDataTables'])) {
         return;
     }
     // Calculate the date before which it is valid to prune data
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNowDate =& $oServiceLocator->get('now');
     if (is_null($oNowDate) || !is_a($oNowDate, 'Date')) {
         return;
     }
     $oPruneDate = new Date();
     $oPruneDate->copy($oNowDate);
     $oPruneDate->subtractSeconds(OA_MAINTENANCE_FIXED_PRUNING * SECONDS_PER_DAY);
     $oFormattedPruneDate = $this->oDbh->quote($oPruneDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     $oFormattedPruneTimestamp = $this->oDbh->quote($oPruneDate->getTime(), 'integer');
     // Prune old data from the log_maintenance_statistics table
     $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics');
     $doLog_maintenance_statistics->whereAdd("start_run < {$oFormattedPruneDate}");
     $doLog_maintenance_statistics->delete(true);
     // Prune old data from the log_maintenance_priority table
     $doLog_maintenance_priority = OA_Dal::factoryDO('log_maintenance_priority');
     $doLog_maintenance_priority->whereAdd("start_run < {$oFormattedPruneDate}");
     $doLog_maintenance_priority->delete(true);
     // Prune old data from the userlog table
     $doUserlog = OA_Dal::factoryDO('userlog');
     $doUserlog->whereAdd("timestamp < {$oFormattedPruneTimestamp}");
     $doUserlog->delete(true);
 }
 /**
  * A method to test the run() method.
  */
 function testRun()
 {
     // Reset the testing environment
     TestEnv::restoreEnv();
     $aConf =& $GLOBALS['_MAX']['CONF'];
     $oTable =& OA_DB_Table_Core::singleton();
     $oDbh =& OA_DB::singleton();
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oNow = new Date('2004-06-06 18:10:00');
     $oServiceLocator->register('now', $oNow);
     // Create and register a new OX_Maintenance_Statistics object
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Create a new OX_Maintenance_Statistics_Task_LogCompletion object
     $oLogCompletion = new OX_Maintenance_Statistics_Task_LogCompletion();
     // Set some of the object's variables, and log
     $oLogCompletion->oController->updateIntermediate = true;
     $oLogCompletion->oController->oUpdateIntermediateToDate = new Date('2004-06-06 17:59:59');
     $oLogCompletion->oController->updateFinal = false;
     $oLogCompletion->oController->oUpdateFinalToDate = null;
     $oEnd = new Date('2004-06-06 18:12:00');
     $oLogCompletion->run($oEnd);
     // Test
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['log_maintenance_statistics'], true) . "\n            WHERE\n                adserver_run_type = 0";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['start_run'], '2004-06-06 18:10:00');
     $this->assertEqual($aRow['end_run'], '2004-06-06 18:12:00');
     $this->assertEqual($aRow['duration'], 120);
     $this->assertEqual($aRow['updated_to'], '2004-06-06 17:59:59');
     // Set some of the object's variables, and log
     $oLogCompletion->oController->updateIntermediate = false;
     $oLogCompletion->oController->oUpdateIntermediateToDate = null;
     $oLogCompletion->oController->updateFinal = true;
     $oLogCompletion->oController->oUpdateFinalToDate = new Date('2004-06-06 17:59:59');
     $oEnd = new Date('2004-06-06 18:13:00');
     $oLogCompletion->run($oEnd);
     // Test
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['log_maintenance_statistics'], true) . "\n            WHERE\n                adserver_run_type = 1";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['start_run'], '2004-06-06 18:10:00');
     $this->assertEqual($aRow['end_run'], '2004-06-06 18:13:00');
     $this->assertEqual($aRow['duration'], 180);
     $this->assertEqual($aRow['updated_to'], '2004-06-06 17:59:59');
     // Set some of the object's variables, and log
     $oLogCompletion->oController->updateIntermediate = true;
     $oLogCompletion->oController->oUpdateIntermediateToDate = new Date('2004-06-06 17:59:59');
     $oLogCompletion->oController->updateFinal = true;
     $oLogCompletion->oController->oUpdateFinalToDate = new Date('2004-06-06 17:59:59');
     $oEnd = new Date('2004-06-06 18:14:00');
     $oLogCompletion->run($oEnd);
     // Test
     $query = "\n            SELECT\n                *\n            FROM\n                " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['log_maintenance_statistics'], true) . "\n            WHERE\n                adserver_run_type = 2";
     $rc = $oDbh->query($query);
     $aRow = $rc->fetchRow();
     $this->assertEqual($aRow['start_run'], '2004-06-06 18:10:00');
     $this->assertEqual($aRow['end_run'], '2004-06-06 18:14:00');
     $this->assertEqual($aRow['duration'], 240);
     $this->assertEqual($aRow['updated_to'], '2004-06-06 17:59:59');
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
 /**
  * A method to activate/deactivate campaigns, based on the date and/or the inventory
  * requirements (impressions, clicks and/or conversions). Also sends email reports
  * for any campaigns that are activated/deactivated, as well as sending email reports
  * for any campaigns that are likely to expire in the near future.
  *
  * @param Date $oDate The current date/time.
  * @return string Report on the campaigns activated/deactivated.
  */
 function manageCampaigns($oDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oEmail =& $oServiceLocator->get('OA_Email');
     if ($oEmail === false) {
         $oEmail = new OA_Email();
         $oServiceLocator->register('OA_Email', $oEmail);
     }
     $report = "\n";
     // Select all campaigns in the system, where:
     //    The campaign is ACTIVE and:
     //    - The end date stored for the campaign is not null; or
     //    - The campaign has a lifetime impression, click or conversion
     //      target set.
     //
     //    That is:
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has a valid end date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have
     //      run for a while, and if so, even campaigns with an end date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedly] halted.)
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has at leaast one lifetime target that could
     //      have been reached.
     //
     //    The campaign is INACTIVE and:
     //    - The start date stored for the campaign is not null; and
     //    - The weight is greater than zero; and
     //    - The end date stored for the campaign is either null, or is
     //      greater than "today" less one day.
     //
     //    That is:
     //    - It is possible for the inactive campaign to be automatically
     //      started, as it has a valid start date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have run
     //      for a while, and if so, even campaigns with an activation date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedy] enabled.)
     //    - The campaign is not in a permanently inactive state, as a
     //      result of the weight being less then one, which means that
     //      it cannot be activated.
     //    - The test to start the campaign is unlikely to fail on account
     //      of the end date.
     $prefix = $this->getTablePrefix();
     $oNowDate = new Date($oDate);
     $oNowDate->toUTC();
     $query = "\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate_time AS start,\n                ca.expire_time AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ((\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . " AND\n                    (\n                        ca.expire_time IS NOT NULL\n                        OR\n                        (\n                            ca.views > 0\n                            OR\n                            ca.clicks > 0\n                            OR\n                            ca.conversions > 0\n                        )\n                    )\n                ) OR (\n                    ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_AWAITING, 'integer') . " AND\n                    (\n                        ca.activate_time <= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                        AND\n                        (\n                            ca.weight > 0\n                            OR\n                            ca.priority > 0\n                        )\n                        AND\n                        (\n                            ca.expire_time >= " . $this->oDbh->quote($oNowDate->getDate(DATE_FORMAT_ISO), 'timestamp') . "\n                            OR\n                            ca.expire_time IS NULL\n                        )\n                    )\n                ))\n            ORDER BY\n                advertiser_id";
     OA::debug('- Requesting campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     while ($aCampaign = $rsResult->fetchRow()) {
         if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
             // The campaign is currently running, look at the campaign
             $disableReason = 0;
             $canExpireSoon = false;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 OA::debug('  - Selecting impressions, clicks and conversions for this running campaign ID = ' . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                 // The campaign has an impression, click and/or conversion target,
                 // so get the sum total statistics for the campaign
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 if (isset($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
                     // There were impressions, clicks and/or conversions for this
                     // campaign, so find out if campaign targets have been passed
                     if (!isset($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (!isset($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (!isset($valuesRow['conversions'])) {
                         // No conversions
                         $valuesRow['conversions'] = 0;
                     }
                     if ($aCampaign['targetimpressions'] > 0) {
                         if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
                             // The campaign has an impressions target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_IMPRESSIONS;
                         }
                     }
                     if ($aCampaign['targetclicks'] > 0) {
                         if ($aCampaign['targetclicks'] <= $valuesRow['clicks']) {
                             // The campaign has a click target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CLICKS;
                         }
                     }
                     if ($aCampaign['targetconversions'] > 0) {
                         if ($aCampaign['targetconversions'] <= $valuesRow['conversions']) {
                             // The campaign has a target limitation, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CONVERSIONS;
                         }
                     }
                     if ($disableReason) {
                         // One of the campaign targets was exceeded, so disable
                         $message = '  - Exceeded a campaign quota: Deactivating campaign ID ' . "{$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                     } else {
                         // The campaign didn't have a diable reason,
                         // it *might* possibly be diabled "soon"...
                         $canExpireSoon = true;
                     }
                 }
             }
             // Does the campaign need to be disabled due to the date?
             if (!empty($aCampaign['end'])) {
                 // The campaign has a valid end date, stored in in UTC
                 $oEndDate = new Date($aCampaign['end']);
                 $oEndDate->setTZByID('UTC');
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "  - Passed campaign end time of '" . $oEndDate->getDate() . " UTC" . "': Deactivating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                     OA::debug($message, PEAR_LOG_INFO);
                     $report .= $message . "\n";
                     $doCampaigns = OA_Dal::factoryDO('campaigns');
                     $doCampaigns->campaignid = $aCampaign['campaign_id'];
                     $doCampaigns->find();
                     $doCampaigns->fetch();
                     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                     $result = $doCampaigns->update();
                     if ($result == false) {
                         return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                     }
                     phpAds_userlogSetUser(phpAds_userMaintenance);
                     phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                 } else {
                     // The campaign wasn't disabled based on the end
                     // date, to it *might* possibly be disabled "soon"...
                     $canExpireSoon = true;
                 }
             }
             if ($disableReason) {
                 // The campaign was disabled, so send the appropriate
                 // message to the campaign's contact
                 $query = "\n                        SELECT\n                            bannerid AS advertisement_id,\n                            description AS description,\n                            alt AS alt,\n                            url AS url\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                        WHERE\n                            campaignid = {$aCampaign['campaign_id']}";
                 OA::debug("  - Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                 $rsResultAdvertisement = $this->oDbh->query($query);
                 if (PEAR::isError($rsResultAdvertisement)) {
                     return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                     $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                 }
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending campaign deactivated email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                     // Also send campaignDeliveryEmail for the campaign we just deactivated.
                     $doClients = OA_Dal::staticGetDO('clients', $aCampaign['advertiser_id']);
                     $aAdvertiser = $doClients->toArray();
                     OA::debug("  - Sending campaign delivery email ", PEAR_LOG_DEBUG);
                     $oStart = new Date($aAdvertiser['reportlastdate']);
                     $oEnd = new Date($oDate);
                     // Set end date to tomorrow so we get stats for today.
                     $oEnd->addSpan(new Date_Span('1-0-0-0'));
                     $oEmail->sendCampaignDeliveryEmail($aAdvertiser, $oStart, $oEnd, $aCampaign['campaign_id']);
                 }
             } else {
                 if ($canExpireSoon) {
                     // The campaign has NOT been deactivated - test to see if it will
                     // be deactivated "soon", and send email(s) warning of this as required
                     OA::debug("  - Sending campaign 'soon deactivated' email ", PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } elseif (!empty($aCampaign['start'])) {
             // The campaign is awaiting activation and has a valid start date, stored in UTC
             $oStartDate = new Date($aCampaign['start']);
             $oStartDate->setTZByID('UTC');
             // Find out if there are any impression, click or conversion targets for
             // the campaign (i.e. if the target values are > 0)
             $remainingImpressions = 0;
             $remainingClicks = 0;
             $remainingConversions = 0;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 OA::debug("  - The campaign ID " . $aCampaign['campaign_id'] . " has an impression, click and/or conversion target, requesting impressions so far", PEAR_LOG_DEBUG);
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 // Set the remaining impressions, clicks and conversions for the campaign
                 $remainingImpressions = $aCampaign['targetimpressions'] - $valuesRow['impressions'];
                 $remainingClicks = $aCampaign['targetclicks'] - $valuesRow['clicks'];
                 $remainingConversions = $aCampaign['targetconversions'] - $valuesRow['conversions'];
             }
             // In order for the campaign to be activated, need to test:
             // 1) That there is no impression target (<= 0), or, if there is an impression target (> 0),
             //    then there must be remaining impressions to deliver (> 0); and
             // 2) That there is no click target (<= 0), or, if there is a click target (> 0),
             //    then there must be remaining clicks to deliver (> 0); and
             // 3) That there is no conversion target (<= 0), or, if there is a conversion target (> 0),
             //    then there must be remaining conversions to deliver (> 0)
             if (($aCampaign['targetimpressions'] <= 0 || $aCampaign['targetimpressions'] > 0 && $remainingImpressions > 0) && ($aCampaign['targetclicks'] <= 0 || $aCampaign['targetclicks'] > 0 && $remainingClicks > 0) && ($aCampaign['targetconversions'] <= 0 || $aCampaign['targetconversions'] > 0 && $remainingConversions > 0)) {
                 $message = "- Passed campaign start time of '" . $oStartDate->getDate() . " UTC" . "': Activating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                 OA::debug($message, PEAR_LOG_INFO);
                 $report .= $message . "\n";
                 $doCampaigns = OA_Dal::factoryDO('campaigns');
                 $doCampaigns->campaignid = $aCampaign['campaign_id'];
                 $doCampaigns->find();
                 $doCampaigns->fetch();
                 $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
                 $result = $doCampaigns->update();
                 if ($result == false) {
                     return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 phpAds_userlogSetUser(phpAds_userMaintenance);
                 phpAds_userlogAdd(phpAds_actionActiveCampaign, $aCampaign['campaign_id']);
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     OA::debug("  - Sending activation email for campaign ID " . $aCampaign['campaign_id'], PEAR_LOG_DEBUG);
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                 }
             }
         }
     }
 }
 /**
  * A method to test the run() method.
  */
 function testRun()
 {
     // Create a reference to the OpenX configuration so that settings
     // can be changed while the tests are running
     $aConf =& $GLOBALS['_MAX']['CONF'];
     // Create the database connection and service locator objects
     $oDbh =& OA_DB::singleton();
     $oServiceLocator =& OA_ServiceLocator::instance();
     // Create the "log_maintenance_statistics" table required for the tests
     $oTables =& OA_DB_Table_Core::singleton();
     $oTables->createTable('log_maintenance_statistics');
     // Create the "controller" OX_Maintenance_Statistics class, and
     // register in the service locator
     $oMaintenanceStatistics = new OX_Maintenance_Statistics();
     $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
     // Create a partially mocked instance of the
     // OX_Maintenance_Statistics_Task_SetUpdateRequirements class
     Mock::generatePartial('OX_Maintenance_Statistics_Task_SetUpdateRequirements', 'PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements', array('_getMaintenanceStatisticsLastRunInfo', '_getEarliestLoggedDeliveryData'));
     // Prepare an array of times that the MSE should be run at, to
     // test the effects of different times and data sets
     $aMSERunTimes = array(0 => new Date('2008-08-12 13:00:01'), 1 => new Date('2008-08-12 13:30:01'), 2 => new Date('2008-08-12 14:00:01'));
     // Create an array of valid operation interval values for runnung tests
     $aOperationIntervals = array(30, 60);
     /*-------------------------------------------------------------*/
     /* NO DATA TESTS                                               */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there is no data in the database, and test that the   */
     /* result is that the MSE will not be run.                     */
     /*-------------------------------------------------------------*/
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 2);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(0, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getEarliestLoggedDeliveryData', null);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(1, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getEarliestLoggedDeliveryData', null);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
             $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
         }
     }
     /*-------------------------------------------------------------*/
     /* ONLY LOGGED DELIVERY DATA TESTS                             */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there is only delivery data in the database (i.e. no  */
     /* previous MSE run) and test that the result is that the MSE  */
     /* will be run from the appropriate date/time.                 */
     /*-------------------------------------------------------------*/
     // Set the value that will be returned for the last MSE run
     // update value, based on the earliest logged data, in terms of
     // the operation interval
     $oEarliestLoggedDataDateOI = new Date('2008-08-12 13:29:59');
     // Set the value that will be returned for the last MSE run
     // update value, based on the earliest logged data, in terms of
     // the hour
     $oEarliestLoggedDataDateHour = new Date('2008-08-12 12:59:59');
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 2);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(0, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getEarliestLoggedDeliveryData', $oEarliestLoggedDataDateOI);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(1, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getEarliestLoggedDeliveryData', $oEarliestLoggedDataDateHour);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             if ($key == 0) {
                 // There is no data logged before "now"; therefore, no udpates will be run
                 $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
             } elseif ($key == 1) {
                 // There is logged data before "now", but a complete operation interval
                 // will only have been passed at this stage IF the operation interval is
                 // 30 minutes; in that case, the MSE will update the intermedaite tables;
                 // otherwise, no updates will be run
                 if ($operationInterval == 30) {
                     $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 } else {
                     $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 }
             } elseif ($key == 2) {
                 // There is logged data before "now", and a complete operation interval
                 // will have been passed at this stage, and the update boundary is on the
                 // hour, so the MSE will update the intermedaite and final tables
                 $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertTrue($oSetUpdateRequirements->oController->updateFinal);
             }
         }
     }
     /*-------------------------------------------------------------*/
     /* REAL PAST MSE OI RUN ONLY TESTS                             */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there the MSE has run previously on the basis of the  */
     /* operation interval, but not for the hour, and test that the */
     /* result is that the MSE will be run from the appropriate     */
     /* date/time.                                                  */
     /*-------------------------------------------------------------*/
     // Set the value that will be returned for the last MSE run
     // update value, based on the the operation interval
     $oLastMSERunOI = new Date('2008-08-12 13:29:59');
     // Set the value that will be returned for the last MSE run
     // update value, based on the earliest logged data, in terms of
     // the hour
     $oEarliestLoggedDataDateHour = new Date('2008-08-12 12:59:59');
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 1);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', $oLastMSERunOI);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', null);
             $oSetUpdateRequirements->expectAt(0, '_getEarliestLoggedDeliveryData', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getEarliestLoggedDeliveryData', $oEarliestLoggedDataDateHour);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             if ($key == 0) {
                 // There is no data logged before "now"; therefore, no udpates will be run
                 $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
             } elseif ($key == 1) {
                 // There is logged data before "now", but a complete operation interval
                 // will only have been passed at this stage IF the operation interval is
                 // 30 minutes; in that case, the MSE will update the intermedaite tables;
                 // otherwise, no updates will be run
                 if ($operationInterval == 30) {
                     $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 } else {
                     $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 }
             } elseif ($key == 2) {
                 // There is logged data before "now", and a complete operation interval
                 // will have been passed at this stage, and the update boundary is on the
                 // hour, so the MSE will update the intermedaite and final tables
                 $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertTrue($oSetUpdateRequirements->oController->updateFinal);
             }
         }
     }
     /*-------------------------------------------------------------*/
     /* REAL PAST MSE RUN TESTS                                     */
     /*                                                             */
     /* Run tests where with operation intervals of 30 and 60 mins, */
     /* where there the MSE has run previously, and test that the   */
     /* result is that the MSE will be run from the appropriate     */
     /* date/time.                                                  */
     /*-------------------------------------------------------------*/
     // Set the value that will be returned for the last MSE run
     // update value, based on the the operation interval
     $oLastMSERunOI = new Date('2008-08-12 13:29:59');
     // Set the value that will be returned for the last MSE run
     // update value, based on the the hour
     $oLastMSERunHour = new Date('2008-08-12 12:59:59');
     foreach ($aMSERunTimes as $key => $oRunDate) {
         // Register the "current" date/time that the MSE is running at
         $oServiceLocator->register('now', $oRunDate);
         foreach ($aOperationIntervals as $operationInterval) {
             // Set the correct operation interval
             $aConf['maintenance']['operationInterval'] = $operationInterval;
             // Prepare the partially mocked instance of the
             // OX_Maintenance_Statistics_Task_SetUpdateRequirements class with
             // the expectations and return values required for the test run
             $oSetUpdateRequirements = new PartialOX_Maintenance_Statistics_Task_SetUpdateRequirements();
             $oSetUpdateRequirements->expectCallCount('_getMaintenanceStatisticsLastRunInfo', 2);
             $oSetUpdateRequirements->expectCallCount('_getEarliestLoggedDeliveryData', 0);
             $oSetUpdateRequirements->expectAt(0, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(0, '_getMaintenanceStatisticsLastRunInfo', $oLastMSERunOI);
             $oSetUpdateRequirements->expectAt(1, '_getMaintenanceStatisticsLastRunInfo', array(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oRunDate));
             $oSetUpdateRequirements->setReturnValueAt(1, '_getMaintenanceStatisticsLastRunInfo', $oLastMSERunHour);
             // Create the OX_Maintenance_Statistics_Task_SetUpdateRequirements
             // object and run the task
             $oSetUpdateRequirements->__construct($this);
             $oSetUpdateRequirements->run();
             // Test the results of the task run
             if ($key == 0) {
                 // There is no data logged before "now"; therefore, no udpates will be run
                 $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
             } elseif ($key == 1) {
                 // There is logged data before "now", but a complete operation interval
                 // will only have been passed at this stage IF the operation interval is
                 // 30 minutes; in that case, the MSE will update the intermedaite tables;
                 // otherwise, no updates will be run
                 if ($operationInterval == 30) {
                     $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 } else {
                     $this->assertFalse($oSetUpdateRequirements->oController->updateIntermediate);
                     $this->assertFalse($oSetUpdateRequirements->oController->updateFinal);
                 }
             } elseif ($key == 2) {
                 // There is logged data before "now", and a complete operation interval
                 // will have been passed at this stage, and the update boundary is on the
                 // hour, so the MSE will update the intermedaite and final tables
                 $this->assertTrue($oSetUpdateRequirements->oController->updateIntermediate);
                 $this->assertTrue($oSetUpdateRequirements->oController->updateFinal);
             }
         }
     }
     // Reset the testing environment
     TestEnv::restoreEnv();
 }
 /**
  * A method to test the compensatedPriorities() method.
  *
  * Requirements - NO PAST AD INFO
  * Test 1: Test with a zone of zero available impressions, and no linked ads, and
  *         ensure the returned ads array is empty, and the initial blank impression
  *         is one.
  * Test 2: Test with a zone of > zero available impressions, and no linked ads, and
  *         ensure the returned ads array is empty, and the initial blank impression
  *         is one.
  * Test 3: Test with a zone of zero available impressions, and linked ads with zero
  *         required impressions, and ensure the returned ads array has zero for all
  *         ad priorities, and the initial blank impression is one.
  * Test 4: Test with a zone of > zero available impressions, and linked ads with zero
  *         required impressions, and ensure the returned ads array has zero for all
  *         ad priorities, and the initial blank impression is one.
  * Test 5: Test with a zone of zero available impressions, and linked ads with > zero
  *         required impressions, and ensure the returned ads array has zero for all
  *         ad priorities, and the initial blank impression is one.
  * Test 6: Test with a zone of > zero available impressions, and linked ads with > zero
  *         required impressions, and ensure the returned priorities are correctly
  *         calculcated and scaled.
  *
  * Requirements - WITH PAST AD INFO
  * Test 7: Test with a zone of zero available impressions, and linked ads with zero
  *         required impressions, and ensure the returned ads array has zero for all
  *         ad priorities, and the initial blank impression is one.
  * Test 8: Test with a zone of > zero available impressions, and linked ads with zero
  *         required impressions, and ensure the returned ads array has zero for all
  *         ad priorities, and the initial blank impression is one.
  * Test 9: Test with a zone of zero available impressions, and linked ads with > zero
  *         required impressions, and ensure the returned ads array has zero for all
  *         ad priorities, and the initial blank impression is one.
  * Test 10: Test with a zone of > zero available impressions, and linked ads with > zero
  *          required impressions, but no past zone information, and ensure the returned
  *          priorities are correctly calculcated and scaled.
  * Test 11: Test with a zone of > zero available impressions, and linked ads with > zero
  *          required impressions, with past zone information, and ensure the returned
  *          priorities are correctly calculcated and scaled.
  * Test 12: Test with a factor that will be limited.
  * Test 13: Test with a factor that would be limited, but with deliveryLimitationChanged
  *          set and ensure that the priority factor is reset
  */
 function testCompensatedPriorities()
 {
     // Mock the OA_Dal_Maintenance_Priority class used in the constructor method
     $oDal = new $this->mockDal($this);
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Dal_Maintenance_Priority', $oDal);
     // Partially mock the OA_Maintenance_Priority_AdServer_Task_PriorityCompensation class
     $oPriorityCompensation = new PartialMock_OA_Maintenance_Priority_AdServer_Task_PriorityCompensation($this);
     $oPriorityCompensation->setReturnReference('_getDal', $oDal);
     $oPriorityCompensation->setReturnReference('_getOperationIntUtils', $oOperationInterval);
     $oPriorityCompensation->__construct();
     // Test 1
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 0;
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 0);
     $this->assertEqual($result['blank'], 1);
     // Test 2
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 100;
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 0);
     $this->assertEqual($result['blank'], 1);
     // Test 3
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 0;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0);
     $this->assertEqual($result['ads'][1]['required_impressions'], 0);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0);
     $this->assertEqual($result['ads'][2]['required_impressions'], 0);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0);
     $this->assertEqual($result['ads'][3]['required_impressions'], 0);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0);
     $this->assertEqual($result['ads'][9]['required_impressions'], 0);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 1);
     // Test 4
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 100;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0);
     $this->assertEqual($result['ads'][1]['required_impressions'], 0);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0);
     $this->assertEqual($result['ads'][2]['required_impressions'], 0);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0);
     $this->assertEqual($result['ads'][3]['required_impressions'], 0);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0);
     $this->assertEqual($result['ads'][9]['required_impressions'], 0);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 1);
     $this->assertEqual($result['blank'], 1);
     // Test 5
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 0;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 1);
     // Test 6
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 100;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0.1);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0.2);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0.3);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0.4);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 0);
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 200;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0.05);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0.1);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0.15);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0.2);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 0.5);
     // Test 7
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 0;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 0;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 0;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 0;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 0;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0);
     $this->assertEqual($result['ads'][1]['required_impressions'], 0);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0);
     $this->assertEqual($result['ads'][2]['required_impressions'], 0);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0);
     $this->assertEqual($result['ads'][3]['required_impressions'], 0);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0);
     $this->assertEqual($result['ads'][9]['required_impressions'], 0);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 1);
     // Test 8
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 100;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 0;
     $oAd->requestedImpressions = 0;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0);
     $this->assertEqual($result['ads'][1]['required_impressions'], 0);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0);
     $this->assertEqual($result['ads'][2]['required_impressions'], 0);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0);
     $this->assertEqual($result['ads'][3]['required_impressions'], 0);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0);
     $this->assertEqual($result['ads'][9]['required_impressions'], 0);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 0);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 1);
     // Test 9
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 0;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastActualImpressions = 0;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 1);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertNull($result['ads'][2]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 1);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertNull($result['ads'][3]['past_zone_traffic_fraction']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 1);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertNull($result['ads'][9]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 1);
     // Test 10
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 100;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0.1);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 2);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0.2);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 2);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0.3);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 2);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0.4);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 2);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertEqual($result['blank'], 0);
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 400;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0.025);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 2);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0.05);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 2);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0.075);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 2);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0.1);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 2);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertEqual($result['blank'], 0.75);
     // Test 11
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 100;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oAd->pastRequiredImpressions = 20;
     $oAd->pastRequestedImpressions = 20;
     $oAd->pastActualImpressions = 10;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oAd->pastRequiredImpressions = 30;
     $oAd->pastRequestedImpressions = 30;
     $oAd->pastActualImpressions = 15;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oAd->pastRequiredImpressions = 40;
     $oAd->pastRequestedImpressions = 40;
     $oAd->pastActualImpressions = 20;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0.1);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 2);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertEqual($result['ads'][1]['past_zone_traffic_fraction'], 0.05);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0.2);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 2);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertEqual($result['ads'][2]['past_zone_traffic_fraction'], 0.1);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0.3);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 2);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertEqual($result['ads'][3]['past_zone_traffic_fraction'], 0.15);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0.4);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 2);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertEqual($result['ads'][9]['past_zone_traffic_fraction'], 0.2);
     $this->assertEqual($result['blank'], 0);
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = 400;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = 10;
     $oAd->requestedImpressions = 10;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 2));
     $oAd->requiredImpressions = 20;
     $oAd->requestedImpressions = 20;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 3));
     $oAd->requiredImpressions = 30;
     $oAd->requestedImpressions = 30;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 9));
     $oAd->requiredImpressions = 40;
     $oAd->requestedImpressions = 40;
     $oAd->pastRequiredImpressions = 10;
     $oAd->pastRequestedImpressions = 10;
     $oAd->pastActualImpressions = 5;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 4);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 0.025);
     $this->assertEqual($result['ads'][1]['required_impressions'], 10);
     $this->assertEqual($result['ads'][1]['requested_impressions'], 10);
     $this->assertEqual($result['ads'][1]['priority_factor'], 2);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertEqual($result['ads'][2]['ad_id'], 2);
     $this->assertEqual($result['ads'][2]['zone_id'], 1);
     $this->assertEqual($result['ads'][2]['priority'], 0.05);
     $this->assertEqual($result['ads'][2]['required_impressions'], 20);
     $this->assertEqual($result['ads'][2]['requested_impressions'], 20);
     $this->assertEqual($result['ads'][2]['priority_factor'], 2);
     $this->assertFalse($result['ads'][2]['priority_factor_limited']);
     $this->assertEqual($result['ads'][3]['ad_id'], 3);
     $this->assertEqual($result['ads'][3]['zone_id'], 1);
     $this->assertEqual($result['ads'][3]['priority'], 0.075);
     $this->assertEqual($result['ads'][3]['required_impressions'], 30);
     $this->assertEqual($result['ads'][3]['requested_impressions'], 30);
     $this->assertEqual($result['ads'][3]['priority_factor'], 2);
     $this->assertFalse($result['ads'][3]['priority_factor_limited']);
     $this->assertEqual($result['ads'][9]['ad_id'], 9);
     $this->assertEqual($result['ads'][9]['zone_id'], 1);
     $this->assertEqual($result['ads'][9]['priority'], 0.1);
     $this->assertEqual($result['ads'][9]['required_impressions'], 40);
     $this->assertEqual($result['ads'][9]['requested_impressions'], 40);
     $this->assertEqual($result['ads'][9]['priority_factor'], 2);
     $this->assertFalse($result['ads'][9]['priority_factor_limited']);
     $this->assertEqual($result['blank'], 0.75);
     // Test 12
     $value = 1.2 * mt_getrandmax();
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = $value;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->requiredImpressions = $value;
     $oAd->requestedImpressions = $value;
     $oAd->pastRequiredImpressions = $value;
     $oAd->pastRequestedImpressions = $value;
     $oAd->pastActualImpressions = 1;
     $oAd->pastZoneTrafficFraction = 0;
     $oAd->pastAdZonePriorityFactor = 1;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 1);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 1);
     $this->assertEqual($result['ads'][1]['required_impressions'], $value);
     $this->assertEqual($result['ads'][1]['requested_impressions'], $value);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1 + (mt_getrandmax() - 1) / 2);
     $this->assertTrue($result['ads'][1]['priority_factor_limited']);
     $this->assertEqual($result['ads'][1]['past_zone_traffic_fraction'], 1 / $value);
     $this->assertEqual($result['blank'], 0);
     // Test 13
     $value = 1.2 * mt_getrandmax();
     $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1));
     $oZone->availableImpressions = $value;
     $oAd = new OA_Maintenance_Priority_Ad(array('ad_id' => 1));
     $oAd->deliveryLimitationChanged = true;
     $oAd->requiredImpressions = $value;
     $oAd->requestedImpressions = $value;
     $oAd->pastRequiredImpressions = $value;
     $oAd->pastRequestedImpressions = $value;
     $oAd->pastActualImpressions = 1;
     $oAd->pastZoneTrafficFraction = 0;
     $oAd->pastAdZonePriorityFactor = 1;
     $oZone->addAdvert($oAd);
     $result = $oPriorityCompensation->compensatedPriorities($oZone);
     $this->assertEqual(count($result['ads']), 1);
     $this->assertEqual($result['ads'][1]['ad_id'], 1);
     $this->assertEqual($result['ads'][1]['zone_id'], 1);
     $this->assertEqual($result['ads'][1]['priority'], 1);
     $this->assertEqual($result['ads'][1]['required_impressions'], $value);
     $this->assertEqual($result['ads'][1]['requested_impressions'], $value);
     $this->assertEqual($result['ads'][1]['priority_factor'], 1);
     $this->assertFalse($result['ads'][1]['priority_factor_limited']);
     $this->assertNull($result['ads'][1]['past_zone_traffic_fraction']);
     $this->assertEqual($result['blank'], 0);
 }
Beispiel #27
0
 /**
  * A method to activate/deactivate campaigns, based on the date and/or the inventory
  * requirements (impressions, clicks and/or conversions). Also sends email reports
  * for any campaigns that are activated/deactivated, as well as sending email reports
  * for any campaigns that are likely to expire in the near future.
  *
  * @param Date $oDate The current date/time.
  * @return string Report on the campaigns activated/deactivated.
  */
 function manageCampaigns($oDate)
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oEmail =& $oServiceLocator->get('OA_Email');
     if ($oEmail === false) {
         $oEmail = new OA_Email();
         $oServiceLocator->register('OA_Email', $oEmail);
     }
     $report = "\n";
     // Select all campaigns in the system, where:
     //    The campaign is ACTIVE and:
     //    - The end date stored for the campaign is not null; or
     //    - The campaign has a lifetime impression, click or conversion
     //      target set.
     //
     //    That is:
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has a valid end date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have
     //      run for a while, and if so, even campaigns with an end date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedly] halted.)
     //    - It is possible for the active campaign to be automatically
     //      stopped, as it has at leaast one lifetime target that could
     //      have been reached.
     //
     //    The campaign is INACTIVE and:
     //    - The start date stored for the campaign is not null; and
     //    - The weight is greater than zero; and
     //    - The end date stored for the campaign is either null, or is
     //      greater than "today" less one day.
     //
     //    That is:
     //    - It is possible for the inactive campaign to be automatically
     //      started, as it has a valid start date. (No limitations are
     //      applied to those campaigns tested, as the ME may not have run
     //      for a while, and if so, even campaigns with an activation date
     //      of many, many weeks ago should be tested to ensure they are
     //      [belatedy] enabled.)
     //    - The campaign is not in a permanently inactive state, as a
     //      result of the weight being less then one, which means that
     //      it cannot be activated.
     //    - The test to start the campaign is unlikely to fail on account
     //      of the end date. (Inactive campaigns with start dates may have
     //      passed the start date, but they may also have passed the end
     //      date - unfortunately, because the dates are not stored in UTC,
     //      it's not possible to know exactly which campaigns have passed
     //      the end date or not, until the values are converted to UTC based
     //      on the Advertiser Account timezone preference - so it's necessary
     //      to get some campaigns that might be passed the end date, and do
     //      the converstion to UTC and test to check.)
     $prefix = $this->getTablePrefix();
     $oYesterdayDate = new Date();
     $oYesterdayDate->copy($oDate);
     $oYesterdayDate->subtractSeconds(SECONDS_PER_DAY);
     $query = "\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate AS start,\n                ca.expire AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n                AND\n                (\n                    ca.expire " . OA_Dal::notEqualNoDateString() . "\n                    OR\n                    (\n                        ca.views > 0\n                        OR\n                        ca.clicks > 0\n                        OR\n                        ca.conversions > 0\n                    )\n                )\n            UNION ALL\n            SELECT\n                cl.clientid AS advertiser_id,\n                cl.account_id AS advertiser_account_id,\n                cl.agencyid AS agency_id,\n                cl.contact AS contact,\n                cl.email AS email,\n                cl.reportdeactivate AS send_activate_deactivate_email,\n                ca.campaignid AS campaign_id,\n                ca.campaignname AS campaign_name,\n                ca.views AS targetimpressions,\n                ca.clicks AS targetclicks,\n                ca.conversions AS targetconversions,\n                ca.status AS status,\n                ca.activate AS start,\n                ca.expire AS end\n            FROM\n                {$prefix}campaigns AS ca,\n                {$prefix}clients AS cl\n            WHERE\n                ca.clientid = cl.clientid\n                AND\n                ca.status != " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n                AND\n                ca.activate " . OA_Dal::notEqualNoDateString() . "\n                AND\n                (\n                    ca.weight > 0\n                    OR\n                    ca.priority > 0\n                )\n                AND\n                (\n                    ca.expire >= " . $this->oDbh->quote($oYesterdayDate->format('%Y-%m-%d'), 'timestamp') . "\n                    OR\n                    ca.expire " . OA_Dal::equalNoDateString() . "\n                )\n            ORDER BY\n                advertiser_id";
     $rsResult = $this->oDbh->query($query);
     if (PEAR::isError($rsResult)) {
         return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
     }
     OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
     while ($aCampaign = $rsResult->fetchRow()) {
         if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
             // The campaign is currently running, look at the campaign
             $disableReason = 0;
             $canExpireSoon = false;
             if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                 // The campaign has an impression, click and/or conversion target,
                 // so get the sum total statistics for the campaign
                 $query = "\n                        SELECT\n                            SUM(dia.impressions) AS impressions,\n                            SUM(dia.clicks) AS clicks,\n                            SUM(dia.conversions) AS conversions\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                        WHERE\n                            dia.ad_id = b.bannerid\n                            AND b.campaignid = {$aCampaign['campaign_id']}";
                 $rsResultInner = $this->oDbh->query($query);
                 $valuesRow = $rsResultInner->fetchRow();
                 if (!is_null($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
                     // There were impressions, clicks and/or conversions for this
                     // campaign, so find out if campaign targets have been passed
                     if (is_null($valuesRow['impressions'])) {
                         // No impressions
                         $valuesRow['impressions'] = 0;
                     }
                     if (is_null($valuesRow['clicks'])) {
                         // No clicks
                         $valuesRow['clicks'] = 0;
                     }
                     if (is_null($valuesRow['conversions'])) {
                         // No conversions
                         $valuesRow['conversions'] = 0;
                     }
                     if ($aCampaign['targetimpressions'] > 0) {
                         if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
                             // The campaign has an impressions target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_IMPRESSIONS;
                         }
                     }
                     if ($aCampaign['targetclicks'] > 0) {
                         if ($aCampaign['targetclicks'] <= $valuesRow['clicks']) {
                             // The campaign has a click target, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CLICKS;
                         }
                     }
                     if ($aCampaign['targetconversions'] > 0) {
                         if ($aCampaign['targetconversions'] <= $valuesRow['conversions']) {
                             // The campaign has a target limitation, and this has been
                             // passed, so update and disable the campaign
                             $disableReason |= OX_CAMPAIGN_DISABLED_CONVERSIONS;
                         }
                     }
                     if ($disableReason) {
                         // One of the campaign targets was exceeded, so disable
                         $message = '- Exceeded a campaign quota: Deactivating campaign ID ' . "{$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                     } else {
                         // The campaign didn't have a diable reason,
                         // it *might* possibly be diabled "soon"...
                         $canExpireSoon = true;
                     }
                 }
             }
             // Does the campaign need to be disabled due to the date?
             if ($aCampaign['end'] != OA_Dal::noDateValue()) {
                 // The campaign has a valid end date, stored in the timezone of the advertiser;
                 // create an end date in the advertiser's timezone, set the time, and then
                 // convert to UTC so that it can be compared with the MSE run time, which is
                 // in UTC
                 $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aCampaign['advertiser_account_id'], true);
                 $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']);
                 $oEndDate = new Date();
                 $oEndDate->convertTZ($oTimezone);
                 $oEndDate->setDate($aCampaign['end'] . ' 23:59:59');
                 // Campaigns end at the end of the day
                 $oEndDate->toUTC();
                 if ($oDate->after($oEndDate)) {
                     // The end date has been passed; disable the campaign
                     $disableReason |= OX_CAMPAIGN_DISABLED_DATE;
                     $message = "- Passed campaign end time of '{$aCampaign['end']} 23:59:59 {$aAdvertiserPrefs['timezone']} (" . $oEndDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEndDate->tz->getShortName() . ")': Deactivating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                     OA::debug($message, PEAR_LOG_INFO);
                     $report .= $message . "\n";
                     $doCampaigns = OA_Dal::factoryDO('campaigns');
                     $doCampaigns->campaignid = $aCampaign['campaign_id'];
                     $doCampaigns->find();
                     $doCampaigns->fetch();
                     $doCampaigns->status = OA_ENTITY_STATUS_EXPIRED;
                     $result = $doCampaigns->update();
                     if ($result == false) {
                         return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                     }
                     phpAds_userlogSetUser(phpAds_userMaintenance);
                     phpAds_userlogAdd(phpAds_actionDeactiveCampaign, $aCampaign['campaign_id']);
                 } else {
                     // The campaign wasn't disabled based on the end
                     // date, to it *might* possibly be disabled "soon"...
                     $canExpireSoon = true;
                 }
             }
             if ($disableReason) {
                 // The campaign was disabled, so send the appropriate
                 // message to the campaign's contact
                 $query = "\n                        SELECT\n                            bannerid AS advertisement_id,\n                            description AS description,\n                            alt AS alt,\n                            url AS url\n                        FROM\n                            " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                        WHERE\n                            campaignid = {$aCampaign['campaign_id']}";
                 OA::debug("- Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                 $rsResultAdvertisement = $this->oDbh->query($query);
                 if (PEAR::isError($rsResultAdvertisement)) {
                     return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                 }
                 while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                     $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                 }
                 if ($aCampaign['send_activate_deactivate_email'] == 't') {
                     $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id'], $disableReason);
                 }
             } else {
                 if ($canExpireSoon) {
                     // The campaign has NOT been deactivated - test to see if it will
                     // be deactivated "soon", and send email(s) warning of this as required
                     $oEmail->sendCampaignImpendingExpiryEmail($oDate, $aCampaign['campaign_id']);
                 }
             }
         } else {
             // The campaign is not active - does it need to be enabled,
             // based on the campaign starting date?
             if ($aCampaign['start'] != OA_Dal::noDateValue()) {
                 // The campaign has a valid start date, stored in the timezone of the advertiser;
                 // create an end date in the advertiser's timezone, set the time, and then
                 // convert to UTC so that it can be compared with the MSE run time, which is
                 // in UTC
                 $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($aCampaign['advertiser_account_id'], true);
                 $oTimezone = new Date_Timezone($aAdvertiserPrefs['timezone']);
                 $oStartDate = new Date();
                 $oStartDate->convertTZ($oTimezone);
                 $oStartDate->setDate($aCampaign['start'] . ' 00:00:00');
                 // Campaigns start at the start of the day
                 $oStartDate->toUTC();
                 if ($aCampaign['end'] != OA_Dal::noDateValue()) {
                     // The campaign has a valid end date, stored in the timezone of the advertiser;
                     // create an end date in the advertiser's timezone, set the time, and then
                     // convert to UTC so that it can be compared with the MSE run time, which is
                     // in UTC
                     $oEndDate = new Date();
                     $oEndDate->convertTZ($oTimezone);
                     $oEndDate->setDate($aCampaign['end'] . ' 23:59:59');
                     // Campaign end at the end of the day
                     $oEndDate->toUTC();
                 } else {
                     $oEndDate = null;
                 }
                 if ($oDate->after($oStartDate)) {
                     // The start date has been passed; find out if there are any impression, click
                     // or conversion targets for the campaign (i.e. if the target values are > 0)
                     $remainingImpressions = 0;
                     $remainingClicks = 0;
                     $remainingConversions = 0;
                     if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
                         // The campaign has an impression, click and/or conversion target,
                         // so get the sum total statistics for the campaign so far
                         $query = "\n                                SELECT\n                                    SUM(dia.impressions) AS impressions,\n                                    SUM(dia.clicks) AS clicks,\n                                    SUM(dia.conversions) AS conversions\n                                FROM\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n                                WHERE\n                                    dia.ad_id = b.bannerid\n                                    AND b.campaignid = {$aCampaign['campaign_id']}";
                         $rsResultInner = $this->oDbh->query($query);
                         $valuesRow = $rsResultInner->fetchRow();
                         // Set the remaining impressions, clicks and conversions for the campaign
                         $remainingImpressions = $aCampaign['targetimpressions'] - $valuesRow['impressions'];
                         $remainingClicks = $aCampaign['targetclicks'] - $valuesRow['clicks'];
                         $remainingConversions = $aCampaign['targetconversions'] - $valuesRow['conversions'];
                     }
                     // In order for the campaign to be activated, need to test:
                     // 1) That there is no impression target (<= 0), or, if there is an impression target (> 0),
                     //    then there must be remaining impressions to deliver (> 0); and
                     // 2) That there is no click target (<= 0), or, if there is a click target (> 0),
                     //    then there must be remaining clicks to deliver (> 0); and
                     // 3) That there is no conversion target (<= 0), or, if there is a conversion target (> 0),
                     //    then there must be remaining conversions to deliver (> 0); and
                     // 4) Either there is no end date, or the end date has not been passed
                     if (($aCampaign['targetimpressions'] <= 0 || $aCampaign['targetimpressions'] > 0 && $remainingImpressions > 0) && ($aCampaign['targetclicks'] <= 0 || $aCampaign['targetclicks'] > 0 && $remainingClicks > 0) && ($aCampaign['targetconversions'] <= 0 || $aCampaign['targetconversions'] > 0 && $remainingConversions > 0) && (is_null($oEndDate) || $oEndDate->format('%Y-%m-%d') != OA_Dal::noDateValue() && Date::compare($oDate, $oEndDate) < 0)) {
                         $message = "- Passed campaign start time of '{$aCampaign['start']} 00:00:00 {$aAdvertiserPrefs['timezone']} (" . $oStartDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStartDate->tz->getShortName() . ")': Activating campaign ID {$aCampaign['campaign_id']}: {$aCampaign['campaign_name']}";
                         OA::debug($message, PEAR_LOG_INFO);
                         $report .= $message . "\n";
                         $doCampaigns = OA_Dal::factoryDO('campaigns');
                         $doCampaigns->campaignid = $aCampaign['campaign_id'];
                         $doCampaigns->find();
                         $doCampaigns->fetch();
                         $doCampaigns->status = OA_ENTITY_STATUS_RUNNING;
                         $result = $doCampaigns->update();
                         if ($result == false) {
                             return MAX::raiseError($rows, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         phpAds_userlogSetUser(phpAds_userMaintenance);
                         phpAds_userlogAdd(phpAds_actionActiveCampaign, $aCampaign['campaign_id']);
                         // Get the advertisements associated with the campaign
                         $query = "\n                                SELECT\n                                    bannerid AS advertisement_id,\n                                    description AS description,\n                                    alt AS alt,\n                                    url AS url\n                                FROM\n                                    " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . "\n                                WHERE\n                                    campaignid = {$aCampaign['campaign_id']}";
                         OA::debug("- Getting the advertisements for campaign ID {$aCampaign['campaign_id']}", PEAR_LOG_DEBUG);
                         $rsResultAdvertisement = $this->oDbh->query($query);
                         if (PEAR::isError($rsResultAdvertisement)) {
                             return MAX::raiseError($rsResultAdvertisement, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
                         }
                         while ($advertisementRow = $rsResultAdvertisement->fetchRow()) {
                             $advertisements[$advertisementRow['advertisement_id']] = array($advertisementRow['description'], $advertisementRow['alt'], $advertisementRow['url']);
                         }
                         if ($aCampaign['send_activate_deactivate_email'] == 't') {
                             $oEmail->sendCampaignActivatedDeactivatedEmail($aCampaign['campaign_id']);
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * 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();
 }
Beispiel #29
0
 /**
  * A method to return a registered service.
  *
  * @static
  * @param string $serviceName The name of the service required.
  * @return mixed Either the service object requested, or false if the
  *               requested service was not registered.
  */
 function &staticGet($serviceName)
 {
     $oServiceLocator =& OA_ServiceLocator::instance();
     return $oServiceLocator->get($serviceName);
 }
 /**
  * A method to test the sending of emails from the
  * manageCampaigns() method - tests the sending of
  * the "campaign about to expire" emails.
  */
 function testManageCampaignsEmailsPlacementToExpire()
 {
     // Set the date format
     global $date_format;
     $date_format = '%Y-%m-%d';
     // Set now as 1 week before
     $oDateNow = new Date('2008-01-10');
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('now', $oDateNow);
     // Insert the required preference values for dealing with email warnings
     $warnEmailAdminPreferenceId = $this->_createPreference('warn_email_admin', OA_ACCOUNT_ADMIN);
     $warnEmailAdminPreferenceImpressionLimitId = $this->_createPreference('warn_email_admin_impression_limit', OA_ACCOUNT_ADMIN);
     $warnEmailAdminPreferenceDayLimitId = $this->_createPreference('warn_email_admin_day_limit', OA_ACCOUNT_ADMIN);
     $this->_createPreference('warn_email_manager', OA_ACCOUNT_MANAGER);
     $this->_createPreference('warn_email_manager_impression_limit', OA_ACCOUNT_MANAGER);
     $this->_createPreference('warn_email_manager_day_limit', OA_ACCOUNT_MANAGER);
     $this->_createPreference('warn_email_advertiser', OA_ACCOUNT_ADVERTISER);
     $this->_createPreference('warn_email_advertiser_impression_limit', OA_ACCOUNT_ADVERTISER);
     $this->_createPreference('warn_email_advertiser_day_limit', OA_ACCOUNT_ADVERTISER);
     // Create the required accounts & set the various ID values
     $aValues = $this->_createAccounts();
     $adminAccountId = $aValues['adminAccount'];
     $advertiserClientId = $aValues['advertiserClient'];
     // Create a currently running placement with 100 impressions
     // remaining and set to expire on 2008-01-13
     $aData = array('clientid' => $advertiserClientId, 'status' => OA_ENTITY_STATUS_RUNNING, 'views' => '100', 'expire_time' => '2008-01-13 23:59:59');
     $campaignId = $this->_insertPlacement($aData);
     // Reset now
     $oServiceLocator->remove('now');
     // Insert a banner for the placement
     $aData = array('campaignid' => $campaignId);
     $adId = $this->_insertAd($aData);
     // Create an instance of the mocked OA_Email class, and set
     // expectations on how the class' methods should be called
     // based on the above
     Mock::generate('OA_Email');
     $oEmailMock = new MockOA_Email($this);
     $oEmailMock->expectOnce('sendCampaignImpendingExpiryEmail');
     // Register the mocked OA_Email class in the service locator
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Email', $oEmailMock);
     // Run the manageCampaigns() method and ensure that the correct
     // calls to OA_Email were made
     $oDate = new Date('2008-01-11 23:00:01');
     $oFactory = new OX_Dal_Maintenance_Statistics_Factory();
     $oDalMaintenanceStatistics = $oFactory->factory();
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     $oEmailMock->tally();
     // Now set the preference that states that the admin account
     // wants to get email warnings
     $this->_insertPreference($adminAccountId, $warnEmailAdminPreferenceId, 'true');
     // Create a new instance of the mocked OA_Email class, and set
     // expectations on how the class' methods should be called
     // based on the above
     $oEmailMock = new MockOA_Email($this);
     $oEmailMock->expectOnce('sendCampaignImpendingExpiryEmail');
     // Register the mocked OA_Email class in the service locator
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Email', $oEmailMock);
     // Run the manageCampaigns() method and ensure that the correct
     // calls to OA_Email were made
     $oDate = new Date('2008-01-11 23:00:01');
     $oDalMaintenanceStatistics = $oFactory->factory();
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     $oEmailMock->tally();
     // Now set the preference that states that the admin account
     // wants to get email warnings if there are less than 50
     // impressions remaining
     $this->_insertPreference($adminAccountId, $warnEmailAdminPreferenceImpressionLimitId, '50');
     // Create a new instance of the mocked OA_Email class, and set
     // expectations on how the class' methods should be called
     // based on the above
     $oEmailMock = new MockOA_Email($this);
     $oEmailMock->expectOnce('sendCampaignImpendingExpiryEmail');
     // Register the mocked OA_Email class in the service locator
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Email', $oEmailMock);
     // Run the manageCampaigns() method and ensure that the correct
     // calls to OA_Email were made
     $oDate = new Date('2008-01-11 23:00:01');
     $oDalMaintenanceStatistics = $oFactory->factory();
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     $oEmailMock->tally();
     // Delivery 60 impressions out of the 100, so that only 40 remain
     // (i.e. less than the 50 limit set above)
     $aData = array('operation_interval_id' => 25, 'interval_start' => '2008-01-11 22:00:00', 'interval_end' => '2008-01-11 22:59:59', 'hour' => 0, 'ad_id' => $adId, 'impressions' => 60);
     $this->_insertDataIntermediateAd($aData);
     // Create a new instance of the mocked OA_Email class, and set
     // expectations on how the class' methods should be called
     // based on the above
     $oEmailMock = new MockOA_Email($this);
     $oEmailMock->expectOnce('sendCampaignImpendingExpiryEmail', array($oDate, "{$campaignId}"));
     // Register the mocked OA_Email class in the service locator
     $oServiceLocator =& OA_ServiceLocator::instance();
     $oServiceLocator->register('OA_Email', $oEmailMock);
     // Run the manageCampaigns() method and ensure that the correct
     // calls to OA_Email were made
     $oDate = new Date('2008-01-11 23:00:01');
     $oDalMaintenanceStatistics = $oFactory->factory();
     $report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
     $oEmailMock->tally();
     // Clean up
     DataGenerator::cleanUp();
 }