/** * A mathod to quickly check the data in the database for the date * range given, to ensure that the range being tested & corrected * seems reasonable. * * @param Date $oStartDate The start date/time of the range to test & correct. * @param Date $oEndDate The end date/time of the range to test & correct. * @return boolean True if the date range seems okay, false otherwise. */ function checkRangeData($oStartDate, $oEndDate) { // Test that there are no rows in the data_intermediate_ad table where the // operation interval value does not match that in the configuration file $doData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $doData_intermediate_ad->whereAdd('date_time >= ' . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp')); $doData_intermediate_ad->whereAdd('date_time <= ' . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp')); $doData_intermediate_ad->whereAdd('operation_interval != ' . $this->oDbh->quote(OX_OperationInterval::getOperationInterval(), 'integer')); $doData_intermediate_ad->find(); $rows = $doData_intermediate_ad->getRowCount(); if ($rows > 0) { $message = "\n Detected at least one row in the data_intermediate_ad table with operation interval != " . OX_OperationInterval::getOperationInterval() . ".\n"; echo $message; return false; } // Test that all of the date/time values in the data_summary_ad_hourly // table align with the start of operation intervals $doData_summary_ad_hourly = OA_Dal::factoryDO('data_summary_ad_hourly'); $doData_summary_ad_hourly->selectAdd(); $doData_summary_ad_hourly->selectAdd('DISTINCT date_time'); $doData_summary_ad_hourly->whereAdd('date_time >= ' . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp')); $doData_summary_ad_hourly->whereAdd('date_time <= ' . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp')); $doData_summary_ad_hourly->find(); while ($doData_summary_ad_hourly->fetch()) { $oDate = new Date($doData_summary_ad_hourly->date_time); $result = OX_OperationInterval::checkDateIsStartDate($oDate); if (!$result) { $message = "\n Detected at least one row in the data_summary_ad_hourly table with date_time value not on the hour start interval.\n"; echo $message; return false; } } return true; }
/** * A method to run maintenance. */ function run() { // Print a blank line in the debug log file when maintenance starts OA::debug(); // Do not run if distributed stats are enabled if (!empty($this->aConf['lb']['enabled'])) { OA::debug('Distributed stats enabled, not running maintenance tasks', PEAR_LOG_INFO); return; } // Acquire the maintenance lock $oLock =& OA_DB_AdvisoryLock::factory(); if ($oLock->get(OA_DB_ADVISORYLOCK_MAINTENANCE)) { OA::switchLogIdent('maintenance'); OA::debug(); OA::debug('Running Maintenance Engine', PEAR_LOG_INFO); // Attempt to increase PHP memory OX_increaseMemoryLimit(OX_getMinimumRequiredMemory('maintenance')); // Set UTC timezone OA_setTimeZoneUTC(); // Get last run $oLastRun = $this->getLastRun(); // Update the timestamp for old maintenance code and auto-maintenance $this->updateLastRun(); // Record the current time, and register with the OA_ServiceLocator $oDate = new Date(); $oServiceLocator =& OA_ServiceLocator::instance(); $oServiceLocator->register('now', $oDate); // Check the operation interval is valid $result = OX_OperationInterval::checkOperationIntervalValue($this->aConf['maintenance']['operationInterval']); if (PEAR::isError($result)) { // Unable to continue! $oLock->release(); OA::debug('Aborting maintenance: Invalid Operation Interval length', PEAR_LOG_CRIT); exit; } // Run the Maintenance Statistics Engine (MSE) process $this->_runMSE(); // Run the "midnight" tasks, if required if ($this->isMidnightMaintenance($oLastRun)) { $this->_runMidnightTasks(); } // Release lock before starting MPE $oLock->release(); // Run the Maintenance Priority Engine (MPE) process, ensuring that the // process always runs, even if instant update of priorities is disabled $this->_runMPE(); // Log the completion of the entire ME process OA::switchLogIdent('maintenance'); $oEndDate = new Date(); $oDateSpan = new Date_Span(); $oDateSpan->setFromDateDiff($oDate, $oEndDate); OA::debug('Maintenance Engine Completed (Started at ' . $oDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oDate->tz->getShortName() . ', taking ' . $oDateSpan->format('%H:%M:%S') . ')', PEAR_LOG_INFO); OA::switchLogIdent(); } else { OA::switchLogIdent('maintenance'); OA::debug('Maintenance Engine not run: could not acquire lock', PEAR_LOG_INFO); OA::switchLogIdent(); } }
/** * Check start/end dates - note that check is the reverse of normal check: * if the operation interval is <= 60, must be start/end of an hour, to * make sure we update all the operation intervals in the hour, and if * the operation interval > 60, must be the start/end of an operation * interval, to make sure we update all the hours in the operation interval. * * @static * @param Date $oStartDate * @param Date $oEndDate * @return boolean */ function checkDates($oStartDate, $oEndDate) { $aConf = $GLOBALS['_MAX']['CONF']; $operationInterval = $aConf['maintenance']['operation_interval']; if ($operationInterval <= 60) { // Must ensure that only one hour is being summarised if (!OX_OperationInterval::checkDatesInSameHour($oStartDate, $oEndDate)) { return false; } // Now check that the start and end dates are match the start and // end of the hour $oHourStart = new Date(); $oHourStart->setYear($oStartDate->getYear()); $oHourStart->setMonth($oStartDate->getMonth()); $oHourStart->setDay($oStartDate->getDay()); $oHourStart->setHour($oStartDate->getHour()); $oHourStart->setMinute('00'); $oHourStart->setSecond('00'); $oHourEnd = new Date(); $oHourEnd->setYear($oEndDate->getYear()); $oHourEnd->setMonth($oEndDate->getMonth()); $oHourEnd->setDay($oEndDate->getDay()); $oHourEnd->setHour($oEndDate->getHour()); $oHourEnd->setMinute('59'); $oHourEnd->setSecond('59'); if (!$oStartDate->equals($oHourStart)) { return false; } if (!$oEndDate->equals($oHourEnd)) { return false; } } else { // Must ensure that only one operation interval is being summarised $operationIntervalID = OX_OperationInterval::convertDaySpanToOperationIntervalID($oStartDate, $oEndDate, $operationInterval); if (is_bool($operationIntervalID) && !$operationIntervalID) { return false; } // Now check that the start and end dates match the start and end // of the operation interval list($oOperationIntervalStart, $oOperationIntervalEnd) = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate, $operationInterval); if (!$oStartDate->equals($oOperationIntervalStart)) { return false; } if (!$oEndDate->equals($oOperationIntervalEnd)) { return false; } } return true; }
/** * 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); }
/** * A private method to return the current cumulative zone forecast data for all zones * associated with a given advertisement. The returned array is keyed by operation interval * ID (i.e. from 0 [zero] to the maximum operation interval ID value, depending on the current * configuration value for the operation interval length). The zone forecast values used * in calculating the cumulative forecast are taken from the end of the current operation * interval to one week prior (i.e. the most recent week's worth of forecasts). * * @access private * @param integer $adId The advertisement ID. * @param array $aAdZones An array of arrays, no particular index in the outer array, in the * inner arrays, each as an index "zone_id" containing one zone ID that * the ad is linked to. * @return mixed Array on success, false on failure. If an array, it is of the format: * array( * [operation_interval_id] => forecast_impressions, * [operation_interval_id] => forecast_impressions * . * . * . * ) */ function _getCumulativeZoneForecast($adId, $aAdZones) { $aConf = $GLOBALS['_MAX']['CONF']; if (empty($adId) || !is_numeric($adId)) { OA::debug('- Invalid advertisement ID argument', PEAR_LOG_ERR); return false; } if (!is_array($aAdZones)) { OA::debug('- Invalid zone array argument', PEAR_LOG_ERR); return false; } // Initialise the results array with the number operation intervals in a week $aResults = array_fill(0, OX_OperationInterval::operationIntervalsPerWeek(), 0); // Get the forcast impressions for the previous week if (!empty($aAdZones)) { foreach ($aAdZones as $aZone) { if (!is_array($this->aZoneForecasts[$aZone['zone_id']])) { $this->aZoneForecasts[$aZone['zone_id']] = $this->oDal->getPreviousWeekZoneForcastImpressions($aZone['zone_id']); } if (is_array($this->aZoneForecasts[$aZone['zone_id']]) && !empty($this->aZoneForecasts[$aZone['zone_id']])) { foreach ($this->aZoneForecasts[$aZone['zone_id']] as $aValues) { $aResults[$aValues['operation_interval_id']] += (int) $aValues['forecast_impressions']; } } } } return $aResults; }
/** * Method to test the updatePriorities method. * * Test 1: Test with no Date registered in the service locator, ensure false returned. * Test 2: Test with no data in the database, ensure data is correctly stored. * Test 3: Test with previous test data in the database, ensure data is correctly stored. * Test 4: Test with an obscene number of items, and ensure that the packet size is * not exceeded (no asserts, test suite will simply fail if unable to work). */ function testUpdatePriorities() { /** * @TODO Locate where clean up doesn't happen before this test, and fix! */ TestEnv::restoreEnv(); $conf = $GLOBALS['_MAX']['CONF']; $oDbh =& OA_DB::singleton(); $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority(); // Insert the data into the ad_zone_assoc table, as an ad is linked to a zone $this->_generateTestData(); // Test 1 $oServiceLocator =& OA_ServiceLocator::instance(); $oServiceLocator->remove('now'); $aData = array(array('ads' => array(array('ad_id' => $this->aIds['ad'], 'zone_id' => $this->aIds['zone'], 'required_impressions' => '1000', 'requested_impressions' => '1000', 'priority' => '0.45', 'priority_factor' => null, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => null)))); $result = $oMaxDalMaintenance->updatePriorities($aData); $this->assertFalse($result); // Test 2 $oDate = new Date(); $oServiceLocator->register('now', $oDate); $result = $oMaxDalMaintenance->updatePriorities($aData); $this->assertTrue($result); $query = "\n SELECT\n ad_id,\n zone_id,\n priority\n FROM\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['ad_zone_assoc'], true) . "\n WHERE\n ad_id = {$this->aIds['ad']} AND zone_id = {$this->aIds['zone']}"; $rc = $oDbh->query($query); $aRow = $rc->fetchRow(); $this->assertEqual($aRow['ad_id'], $this->aIds['ad']); $this->assertEqual($aRow['zone_id'], $this->aIds['zone']); $this->assertEqual($aRow['priority'], 0.45); $query = "\n SELECT\n operation_interval,\n operation_interval_id,\n interval_start,\n interval_end,\n ad_id,\n zone_id,\n required_impressions,\n requested_impressions,\n priority,\n priority_factor,\n priority_factor_limited,\n past_zone_traffic_fraction,\n created,\n created_by,\n expired,\n expired_by\n FROM\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n WHERE\n ad_id = {$this->aIds['ad']}"; $rc = $oDbh->query($query); $aRow = $rc->fetchRow(); $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']); $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID); $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['ad_id'], $this->aIds['ad']); $this->assertEqual($aRow['zone_id'], $this->aIds['zone']); $this->assertEqual($aRow['required_impressions'], 1000); $this->assertEqual($aRow['requested_impressions'], 1000); $this->assertEqual($aRow['priority'], 0.45); $this->assertNull($aRow['priority_factor']); $this->assertFalse($aRow['priority_factor_limited']); $this->assertNull($aRow['past_zone_traffic_fraction']); $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['created_by'], 0); $this->assertNull($aRow['expired']); $this->assertNull($aRow['expired_by']); // Test 3 $aData = array(array('ads' => array(array('ad_id' => $this->aIds['ad'], 'zone_id' => $this->aIds['zone'], 'required_impressions' => 2000, 'requested_impressions' => 2000, 'priority' => 0.9, 'priority_factor' => 0.1, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => 0.99), array('ad_id' => $this->aIds['ad'] + 1, 'zone_id' => $this->aIds['ad'] + 1, 'required_impressions' => 500, 'requested_impressions' => 500, 'priority' => 0.1, 'priority_factor' => 0.2, 'priority_factor_limited' => true, 'past_zone_traffic_fraction' => 0.45)))); $oOldDate = new Date(); $oOldDate->copy($oDate); $oDate = new Date(); $oServiceLocator->register('now', $oDate); $result = $oMaxDalMaintenance->updatePriorities($aData); $this->assertTrue($result); $query = "\n SELECT\n ad_id,\n zone_id,\n priority\n FROM\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['ad_zone_assoc'], true) . "\n WHERE\n ad_id = {$this->aIds['ad']} AND zone_id = {$this->aIds['zone']}"; $rc = $oDbh->query($query); $aRow = $rc->fetchRow(); $this->assertEqual($aRow['ad_id'], $this->aIds['ad']); $this->assertEqual($aRow['zone_id'], $this->aIds['zone']); $this->assertEqual($aRow['priority'], 0.9); $query = "\n SELECT\n operation_interval,\n operation_interval_id,\n interval_start,\n interval_end,\n ad_id,\n zone_id,\n required_impressions,\n requested_impressions,\n priority,\n priority_factor,\n priority_factor_limited,\n past_zone_traffic_fraction,\n created,\n created_by,\n expired,\n expired_by\n FROM\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n WHERE\n ad_id = {$this->aIds['ad']}\n AND expired IS NOT NULL"; $rc = $oDbh->query($query); $aRow = $rc->fetchRow(); $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oOldDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oOldDate); $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']); $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID); $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['ad_id'], $this->aIds['ad']); $this->assertEqual($aRow['zone_id'], $this->aIds['ad']); $this->assertEqual($aRow['required_impressions'], 1000); $this->assertEqual($aRow['requested_impressions'], 1000); $this->assertEqual($aRow['priority'], 0.45); $this->assertNull($aRow['priority_factor']); $this->assertFalse($aRow['priority_factor_limited']); $this->assertNull($aRow['past_zone_traffic_fraction']); $this->assertEqual($aRow['created'], $oOldDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['created_by'], 0); $this->assertEqual($aRow['expired'], $oDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['expired_by'], 0); $query = "\n SELECT\n operation_interval,\n operation_interval_id,\n interval_start,\n interval_end,\n ad_id,\n zone_id,\n required_impressions,\n requested_impressions,\n priority,\n priority_factor,\n priority_factor_limited,\n past_zone_traffic_fraction,\n created,\n created_by,\n expired,\n expired_by\n FROM\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n WHERE\n ad_id = {$this->aIds['ad']}\n AND expired IS NULL"; $rc = $oDbh->query($query); $aRow = $rc->fetchRow(); $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']); $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID); $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['ad_id'], $this->aIds['ad']); $this->assertEqual($aRow['zone_id'], $this->aIds['ad']); $this->assertEqual($aRow['required_impressions'], 2000); $this->assertEqual($aRow['requested_impressions'], 2000); $this->assertEqual($aRow['priority'], 0.9); $this->assertEqual($aRow['priority_factor'], 0.1); $this->assertFalse($aRow['priority_factor_limited']); $this->assertEqual($aRow['past_zone_traffic_fraction'], 0.99); $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['created_by'], 0); $this->assertNull($aRow['expired']); $this->assertNull($aRow['expired_by']); $query = "\n SELECT\n operation_interval,\n operation_interval_id,\n interval_start,\n interval_end,\n ad_id,\n zone_id,\n required_impressions,\n requested_impressions,\n priority,\n priority_factor,\n priority_factor_limited,\n past_zone_traffic_fraction,\n created,\n created_by,\n expired,\n expired_by\n FROM\n " . $oDbh->quoteIdentifier($conf['table']['prefix'] . $conf['table']['data_summary_ad_zone_assoc'], true) . "\n WHERE\n ad_id = " . ($this->aIds['ad'] + 1); $rc = $oDbh->query($query); $aRow = $rc->fetchRow(); $currentOperationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $this->assertEqual($aRow['operation_interval'], $conf['maintenance']['operationInterval']); $this->assertEqual($aRow['operation_interval_id'], $currentOperationIntervalID); $this->assertEqual($aRow['interval_start'], $aDates['start']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['interval_end'], $aDates['end']->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['ad_id'], $this->aIds['ad'] + 1); $this->assertEqual($aRow['zone_id'], $this->aIds['ad'] + 1); $this->assertEqual($aRow['required_impressions'], 500); $this->assertEqual($aRow['requested_impressions'], 500); $this->assertEqual($aRow['priority'], 0.1); $this->assertEqual($aRow['priority_factor'], 0.2); $this->assertTrue($aRow['priority_factor_limited']); $this->assertEqual($aRow['past_zone_traffic_fraction'], 0.45); $this->assertEqual($aRow['created'], $oDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($aRow['created_by'], 0); $this->assertNull($aRow['expired']); $this->assertNull($aRow['expired_by']); // Test 4 $aData = array(); for ($i = 1; $i < 5000; $i++) { $aData[$i] = array('ads' => array(array('ad_id' => $i, 'zone_id' => $i, 'required_impressions' => 2000, 'requested_impressions' => 2000, 'priority' => 0.9, 'priority_factor' => 0.1, 'priority_factor_limited' => false, 'past_zone_traffic_fraction' => 0.99))); } $oOldDate = new Date(); $oOldDate->copy($oDate); $oDate = new Date(); $oServiceLocator->register('now', $oDate); $result = $oMaxDalMaintenance->updatePriorities($aData); TestEnv::restoreEnv('dropTmpTables'); }
/** * A private method to test the parameters of the getAdTargetingStatistics() * and getZoneTargetingStatistics methods. * * @access private * @param integer $id The ad or zone ID. * @param PEAR::Date $oStartDate The start date of the operation interval. * @param PEAR::Date $oEndDate The end date of the operation interval. * @return boolean True if the parameters are okay, false otherwise. */ function _testParameters($id, $oStartDate, $oEndDate) { // Ensure the parameters are valid if (empty($id) || !is_int($id)) { return false; } if (empty($oStartDate) || !is_a($oStartDate, 'Date')) { return false; } if (empty($oEndDate) || !is_a($oEndDate, 'Date')) { return false; } // Ensure that the date range specified is indeed an operation interval if (!OX_OperationInterval::checkIntervalDates($oStartDate, $oEndDate)) { return false; } return true; }
/** * A method to manage the migration of conversions from the final conversion * tables to the old-style intermediate table. * * @TODO Deprecate, when conversion data is no longer required in the * old format intermediate and summary tables. * * @param PEAR::Date $oStart The start date/time to migrate from. * @param PEAR::Date $oEnd The end date/time to migrate to. */ function manageConversions($oStart, $oEnd) { $aConf = $GLOBALS['_MAX']['CONF']; // The custom IF function in PgSQL is not suitable for this query, we need explicit use of CASE if ($this->oDbh->dbsyntax == 'pgsql') { $sqlBasketValue = "CASE WHEN v.purpose = 'basket_value' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " THEN diavv.value::numeric ELSE 0 END"; $sqlNumItems = "CASE WHEN v.purpose = 'num_items' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . " THEN diavv.value::integer ELSE 0 END"; } else { $sqlBasketValue = "IF(v.purpose = 'basket_value' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . ", diavv.value, 0)"; $sqlNumItems = "IF(v.purpose = 'num_items' AND diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . ", diavv.value, 0)"; } // Prepare the query to obtain all of the conversions, and their associated total number // of items and total basket values (where they exist), ready for update/insertion into // the data_intermediate_ad table $query = "\n SELECT\n DATE_FORMAT(diac.tracker_date_time, '%Y-%m-%d %H:00:00'){$this->timestampCastString} AS date_f,\n diac.ad_id AS ad_id,\n diac.zone_id AS zone_id,\n COUNT(DISTINCT(diac.data_intermediate_ad_connection_id)) AS conversions,\n SUM({$sqlBasketValue}) AS total_basket_value,\n SUM({$sqlNumItems}) AS total_num_items\n FROM\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad_connection', true) . " AS diac\n LEFT JOIN\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', true) . " AS diavv\n USING\n (\n data_intermediate_ad_connection_id\n )\n LEFT JOIN\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'variables', true) . " AS v\n ON\n (\n diavv.tracker_variable_id = v.variableid\n AND v.purpose IN ('basket_value', 'num_items')\n )\n WHERE\n diac.connection_status = " . MAX_CONNECTION_STATUS_APPROVED . "\n AND diac.inside_window = 1\n AND diac.tracker_date_time >= " . $this->oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND diac.tracker_date_time <= " . $this->oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n GROUP BY\n diac.data_intermediate_ad_connection_id,\n date_f,\n diac.ad_id,\n diac.zone_id"; OA::debug('- Selecting conversion data for migration to the "old style" intermediate table for ', PEAR_LOG_DEBUG); OA::debug(' conversion in the range ' . $oStart->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStart->tz->getShortName() . ' to ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG); $rsResult = $this->oDbh->query($query); if (PEAR::isError($rsResult)) { return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE); } while ($aRow = $rsResult->fetchRow()) { // Prepare the update query $query = "\n UPDATE\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad', true) . "\n SET\n conversions = conversions + " . $this->oDbh->quote($aRow['conversions'], 'integer') . ",\n total_basket_value = total_basket_value + " . $this->oDbh->quote($aRow['total_basket_value'], 'float') . ",\n total_num_items = total_num_items + " . $this->oDbh->quote($aRow['total_num_items'], 'integer') . "\n WHERE\n date_time = " . $this->oDbh->quote($aRow['date_f'], 'timestamp') . "\n AND ad_id = " . $this->oDbh->quote($aRow['ad_id'], 'integer') . "\n AND zone_id = " . $this->oDbh->quote($aRow['zone_id'], 'integer'); $rsUpdateResult = $this->oDbh->exec($query); if (PEAR::isError($rsUpdateResult)) { return MAX::raiseError($rsUpdateResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE); } if ($rsUpdateResult == 0) { // Could not perform the update - try an insert instead $oDate = new Date($aRow['date_f']); $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $query = "\n INSERT INTO\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . 'data_intermediate_ad', true) . "\n (\n date_time,\n operation_interval,\n operation_interval_id,\n interval_start,\n interval_end,\n ad_id,\n creative_id,\n zone_id,\n conversions,\n total_basket_value,\n total_num_items\n )\n VALUES\n (\n " . $this->oDbh->quote($aRow['date_f'], 'timestamp') . ",\n " . $this->oDbh->quote($aConf['maintenance']['operationInterval'], 'integer') . ",\n " . $this->oDbh->quote($operationIntervalId, 'integer') . ",\n " . $this->oDbh->quote($aDates['start']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . ",\n " . $this->oDbh->quote($aDates['end']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . ",\n " . $this->oDbh->quote($aRow['ad_id'], 'integer') . ",\n 0,\n " . $this->oDbh->quote($aRow['zone_id'], 'integer') . ",\n " . $this->oDbh->quote($aRow['conversions'], 'integer') . ",\n " . $this->oDbh->quote($aRow['total_basket_value'], 'float') . ",\n " . $this->oDbh->quote($aRow['total_num_items'], 'integer') . "\n )"; $rsInsertResult = $this->oDbh->exec($query); } } }
if (PEAR::isError($result)) { $message = "\nThe operation interval in your OpenX configuration file is not valid. Please see the OpenX\ndocumentation for more details on valid operation interval values.\n"; echo $message; echo $haltMessage; exit; } $oStartDate = new Date(INTERVAL_START); $result = OX_OperationInterval::checkDateIsStartDate($oStartDate); if (!$result) { $message = "\nThe start date defined in the {$scriptName} script is not a valid operation interval start date.\nPlease edit the statisticsTestAndCorrect.php script before running.\n"; echo $message; echo $haltMessage; exit; } $oEndDate = new Date(INTERVAL_END); $result = OX_OperationInterval::checkDateIsEndDate($oEndDate); if (!$result) { $message = "\nThe end date defined in the {$scriptName} script is not a valid operation interval start date.\nPlease edit the statisticsTestAndCorrect.php script before running.\n"; echo $message; echo $haltMessage; exit; } $oMigrateBucketData = new OX_Maintenance_Statistics_MigrateBucketData(); if (PEAR::isError($oMigrateBucketData->oDbh)) { $message = "\nUnable to connect to the OpenX database.\n"; echo $message; echo $haltMessage; exit; } // Check date range? // Advise the user of the operations that will be performed, and ask for
/** * The main method of the class, that is run by the controlling * task runner class. */ function run() { OA::debug('Running Maintenance Priority Engine: ' . $this->taskName, PEAR_LOG_DEBUG); // Record the start of this ECPM run $oStartDate = new Date(); // Get the details of the last time Priority Compensation started running $aDates = $this->oDal->getMaintenancePriorityLastRunInfo(DAL_PRIORITY_UPDATE_ECPM, array('start_run', 'end_run')); if (!is_null($aDates)) { // Set the details of the last time Priority Compensation started running $this->aLastRun['start_run'] = new Date($aDates['start_run']); // Set the details of the current date/time $oServiceLocator =& OA_ServiceLocator::instance(); $this->aLastRun['now'] =& $oServiceLocator->get('now'); } $this->oDateNow = $this->getDateNow(); $this->aOIDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->oDateNow); $this->runAlgorithm(); // Record the completion of the task in the database // Note that the $oUpdateTo parameter is "null", as this value is not // appropriate when recording Priority Compensation task runs - all that // matters is the start/end dates. OA::debug('- Recording completion of the ' . $this->taskName, PEAR_LOG_DEBUG); $oEndDate = new Date(); $this->oDal->setMaintenancePriorityLastRunInfo($oStartDate, $oEndDate, null, DAL_PRIORITY_UPDATE_ECPM); }
/** * The method to test the getZonesForecasts() method. */ function testgetZonesForecasts() { $this->_createTestData(); $operationInterval = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval']; $oDal = new OA_Dal_Maintenance_Priority(); $oLowerDate = new Date('2007-09-16 12:00:00'); $oUpperDate = new Date('2007-09-16 17:00:00'); $lowerDateStr = $oLowerDate->format(self::DATE_TIME_FORMAT); $upperDateStr = $oUpperDate->format(self::DATE_TIME_FORMAT); $weeks = 2; // Test with bad input $badAgencyId = -1; $result = $oDal->getZonesForecasts($lowerDateStr, $upperDateStr); $expected = array(); $this->assertEqual($result, $expected); // Test with data outside the range $oDate = new Date('2007-09-16 11:00:00'); $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $previousOIDate = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $startDateStr = $aDates['start']->format(self::DATE_TIME_FORMAT); $endDateStr = $aDates['end']->format(self::DATE_TIME_FORMAT); $doDIA = OA_Dal::factoryDO('data_intermediate_ad'); $aDIAs = DataGenerator::generate($doDIA, 1); $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]); $doDIA->date_time = $startDateStr; $doDIA->operation_interval = $operationInterval; $doDIA->zone_id = $this->zoneId1; $doDIA->ad_id = 1; $doDIA->impressions = 1000; $doDIA->update(); $result = $oDal->getZonesForecasts($startDateStr, $endDateStr); $expected = array(); $this->assertEqual($result, $expected); // Test with data inside the range $oDate = new Date('2007-09-16 13:00:00'); $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $previousOIDate = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $startDateStr = $aDates['start']->format(self::DATE_TIME_FORMAT); $endDateStr = $aDates['end']->format(self::DATE_TIME_FORMAT); $aDIAs = DataGenerator::generate($doDIA, 1); $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]); $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT); $doDIA->operation_interval = $operationInterval; $doDIA->zone_id = $this->zoneId1; $doDIA->ad_id = 1; $doDIA->impressions = 70; $doDIA->update(); $result = $oDal->getZonesForecasts($startDateStr, $endDateStr); $expected = array($this->zoneId1 => 70); $this->assertEqual($result, $expected); // Test with more data from the same zone $oDate = new Date('2007-09-16 14:00:00'); $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $previousOIDate = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $startDateStr = $aDates['start']->format(self::DATE_TIME_FORMAT); $endDateStr = $aDates['end']->format(self::DATE_TIME_FORMAT); $aDIAs = DataGenerator::generate($doDIA, 3); $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]); $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT); $doDIA->operation_interval = $operationInterval; $doDIA->zone_id = $this->zoneId1; $doDIA->ad_id = 2; $doDIA->impressions = 90; $doDIA->update(); $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[1]); $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT); $doDIA->operation_interval = $operationInterval; $doDIA->zone_id = $this->zoneId1; $doDIA->ad_id = 4; $doDIA->impressions = 110; $doDIA->update(); $doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[2]); $doDIA->date_time = $previousOIDate['start']->format(self::DATE_TIME_FORMAT); $doDIA->operation_interval = $operationInterval; $doDIA->zone_id = $this->zoneId2; $doDIA->ad_id = 4; $doDIA->impressions = 15000; $doDIA->update(); $result = $oDal->getZonesForecasts($startDateStr, $endDateStr); $expected = array($this->zoneId1 => 200, $this->zoneId2 => 15000); $this->assertEqual($result, $expected); DataGenerator::cleanUp(); }
/** * The implementation of the OA_Task::run() method that performs * the required task of migrating bucket-based logged data to the * statistics table(s) specified by the appropriate plugin * components. */ function run() { $aConf = $GLOBALS['_MAX']['CONF']; if ($this->oController->updateIntermediate) { // Locate all plugin components which may require bucket data to be // migrated from bucket tables to statistics tables $aSummariseComponents = $this->_locateComponents(); // Are there any components that require data to be migrated? if (empty($aSummariseComponents)) { OA::debug('There are no installed plugins that require data migration', PEAR_LOG_DEBUG); return; } $message = '- Migrating bucket-based logged data to the statistics tables.'; $this->oController->report .= $message . "\n"; // Get the MSE DAL to perform the data migration $oServiceLocator =& OA_ServiceLocator::instance(); $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics'); // Prepare the "now" date $oNowDate =& $oServiceLocator->get('now'); if (!$oNowDate) { $oNowDate = new Date(); } // Prepare an array of possible start and end dates for the migration, unless they have been set already if (empty($this->aRunDates)) { $this->aRunDates = array(); $oStartDate = new Date(); $oStartDate->copy($this->oController->oLastDateIntermediate); $oStartDate->addSeconds(1); while (Date::compare($oStartDate, $this->oController->oUpdateIntermediateToDate) < 0) { // Calcuate the end of the operation interval $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStartDate); $oEndDate = new Date(); $oEndDate->copy($aDates['end']); // Store the dates $oStoreStartDate = new Date(); $oStoreStartDate->copy($oStartDate); $oStoreEndDate = new Date(); $oStoreEndDate->copy($oEndDate); $this->aRunDates[] = array('start' => $oStoreStartDate, 'end' => $oStoreEndDate); // Go to the next operation interval $oStartDate->copy($oEndDate); $oStartDate->addSeconds(1); } } // Check to see if any historical raw data needs to be migrated, // post-upgrade, and if so, migrate the data; requires that the // default openXDeliveryLog plugin is installed, so the migration // will not be called if it is not if (key_exists('openXDeliveryLog', $this->aPackages)) { $this->_postUpgrade(); } // Prepare arrays of all of the migration maps of raw migrations $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'raw'); // Run each migration map separately, even if it's for the same table foreach ($aRunComponents as $statisticsTable => $aMaps) { foreach ($aMaps as $componentClassName => $aMigrationDetails) { foreach ($this->aRunDates as $aDates) { $message = "- Migrating raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table"; OA::debug($message, PEAR_LOG_DEBUG); $message = " to the '{$statisticsTable}' table, for operation interval range"; OA::debug($message, PEAR_LOG_DEBUG); $message = ' ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName(); OA::debug($message, PEAR_LOG_DEBUG); $result = $oDal->summariseBucketsRaw($statisticsTable, $aMigrationDetails, $aDates); if (PEAR::isError($result)) { // Oh noz! The bucket data could not be migrated // Tell the user all about it, but then just keep on truckin'... $message = " ERROR: Could not migrate raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table"; OA::debug($message, PEAR_LOG_ERR); $message = " Error message was: {$result->message}"; OA::debug($message, PEAR_LOG_ERR); } else { $message = " - Migrated {$result} row(s)"; OA::debug($message, PEAR_LOG_DEBUG); $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']); if (PEAR::isError($pruneResult)) { // Oh noz! The bucket data could not be pruned, and this is // critical - if we can't prune the data, we'll end up double // counting, so exit with a critical error... $message = " ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table"; OA::debug($message, PEAR_LOG_CRIT); $message = " Error message was: {$pruneResult->message}"; OA::debug($message, PEAR_LOG_CRIT); $message = " Aborting maintenance execution"; OA::debug($message, PEAR_LOG_CRIT); exit; } else { $message = " - Pruned {$pruneResult} row(s)"; OA::debug($message, PEAR_LOG_DEBUG); } } } } } // Prepare arrays of all of the migration maps of supplementary raw migrations $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'rawSupplementary'); // Run each migration map separately, even if it's for the same table foreach ($aRunComponents as $statisticsTable => $aMaps) { foreach ($aMaps as $componentClassName => $aMigrationDetails) { foreach ($this->aRunDates as $aDates) { $message = "- Migrating supplementary raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table"; OA::debug($message, PEAR_LOG_DEBUG); $message = " to the '{$statisticsTable}' table, for operation interval range"; OA::debug($message, PEAR_LOG_DEBUG); $message = ' ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName(); OA::debug($message, PEAR_LOG_DEBUG); $result = $oDal->summariseBucketsRawSupplementary($statisticsTable, $aMigrationDetails, $aDates); if (PEAR::isError($result)) { // Oh noz! The bucket data could not be migrated // Tell the user all about it, but then just keep on truckin'... $message = " ERROR: Could not migrate supplementary raw bucket data from the '{$aMigrationDetails['bucketTable']}' bucket table"; OA::debug($message, PEAR_LOG_ERR); $message = " Error message was: {$result->message}"; OA::debug($message, PEAR_LOG_ERR); } else { $message = " - Migrated {$result} row(s)"; OA::debug($message, PEAR_LOG_DEBUG); $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']); if (PEAR::isError($pruneResult)) { // Oh noz! The bucket data could not be pruned, and this is // critical - if we can't prune the data, we'll end up double // counting, so exit with a critical error... $message = " ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table"; OA::debug($message, PEAR_LOG_CRIT); $message = " Error message was: {$pruneResult->message}"; OA::debug($message, PEAR_LOG_CRIT); $message = " Aborting maintenance execution"; OA::debug($message, PEAR_LOG_CRIT); exit; } else { $message = " - Pruned {$pruneResult} row(s)"; OA::debug($message, PEAR_LOG_DEBUG); } } } } } // Prepare arrays of all of the migration maps of aggregate migrations $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'aggregate'); // Run each migration map by statistics table foreach ($aRunComponents as $statisticsTable => $aMaps) { $aBucketTables = array(); foreach ($aMaps as $aMap) { $aBucketTables[] = $aMap['bucketTable']; } foreach ($this->aRunDates as $aDates) { $aExtras = array(); // Is this the data_intermeidate_ad statistics table? It's special! if ($statisticsTable == $aConf['table']['prefix'] . 'data_intermediate_ad') { $aExtras = array('operation_interval' => $aConf['maintenance']['operationInterval'], 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']), 'interval_start' => $oDal->oDbh->quote($aDates['start']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString, 'interval_end' => $oDal->oDbh->quote($aDates['end']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString, 'creative_id' => 0, 'updated' => $oDal->oDbh->quote($oNowDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDal->timestampCastString); } $message = "- Migrating aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)"; OA::debug($message, PEAR_LOG_DEBUG); $message = " to the '{$statisticsTable}' table, for operation interval range"; OA::debug($message, PEAR_LOG_DEBUG); $message = ' ' . $aDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName(); OA::debug($message, PEAR_LOG_DEBUG); $result = $oDal->summariseBucketsAggregate($statisticsTable, $aMaps, $aDates, $aExtras); if (PEAR::isError($result)) { // Oh noz! The bucket data could not be migrated // Tell the user all about it, but then just keep on truckin'... $message = " ERROR: Could not migrate aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)"; OA::debug($message, PEAR_LOG_ERR); $message = " Error message was: {$result->message}"; OA::debug($message, PEAR_LOG_ERR); } else { $message = " - Migrated {$result} row(s)"; OA::debug($message, PEAR_LOG_DEBUG); foreach ($aMaps as $componentClassName => $aMap) { $pruneResult = $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']); if (PEAR::isError($pruneResult)) { // Oh noz! The bucket data could not be pruned, and this is // critical - if we can't prune the data, we'll end up double // counting, so exit with a critical error... $message = " ERROR: Could not prune aggregate bucket data from the '" . $aSummariseComponents[$statisticsTable][$componentClassName]->getBucketName() . "' bucket table"; OA::debug($message, PEAR_LOG_CRIT); $message = " Error message was: {$pruneResult->message}"; OA::debug($message, PEAR_LOG_CRIT); $message = " Aborting maintenance execution"; OA::debug($message, PEAR_LOG_CRIT); exit; } else { $message = " - Pruned {$pruneResult} row(s)"; OA::debug($message, PEAR_LOG_DEBUG); } } } } } // Prepare arrays of all of the migration maps of custom migrations // (If we refactor stats this will be the one and only method.) $aRunComponents = $this->_prepareMaps($aSummariseComponents, 'custom'); // Run each migration map by statistics table foreach ($aRunComponents as $statisticsTable => $aMaps) { $aBucketTables = array(); foreach ($aMaps as $aMap) { $aBucketTables[] = $aMap['bucketTable']; } foreach ($this->aRunDates as $aDates) { $aExtras = array(); $message = "- Migrating aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)"; OA::debug($message, PEAR_LOG_DEBUG); $message = " to the '{$statisticsTable}' table, for operation interval range"; OA::debug($message, PEAR_LOG_DEBUG); $message = ' ' . $aDates['start']->format('%Y-%m%d %H:%M:%S') . ' ' . $aDates['start']->tz->getShortName() . ' to ' . $aDates['end']->format('%Y-%m%d %H:%M:%S') . ' ' . $aDates['end']->tz->getShortName(); OA::debug($message, PEAR_LOG_DEBUG); // Call the components migrateStats method. foreach ($aMaps as $componentClassName => $aMap) { $result = $aSummariseComponents[$statisticsTable][$componentClassName]->migrateStatistics($aDates['end']); if (PEAR::isError($result)) { // Oh noz! The bucket data could not be migrated // Tell the user all about it, but then just keep on truckin'... $message = " ERROR: Could not migrate aggregate bucket data from the '" . implode("', '", $aBucketTables) . "' bucket table(s)"; OA::debug($message, PEAR_LOG_ERR); $message = " Error message was: {$result->message}."; OA::debug($message, PEAR_LOG_ERR); } else { // Only prune the bucket if we migrated the stats successfully. $aSummariseComponents[$statisticsTable][$componentClassName]->pruneBucket($aDates['end'], $aDates['start']); } } } } } $this->aRunDates = array(); }
/** * A private method to calculate the operation interval start date at the * upper bound of a range of operation intervals that require a ZIF update, * where the upper bound has been set back by the required number of * operation intervals so that current trends in differences between * forecast and actual delivery can be calculated. * * @access private * @param PEAR::Date $oDate The start date of the operation interval at the * upper bound of the operation interval range * requiring a ZIF update. * @return PEAR::Date The new upper bound date. */ function _getTrendUpperDate($oDate) { $seconds = ZONE_FORECAST_TREND_OFFSET * OX_OperationInterval::secondsPerOperationInterval(); $oDate->subtractSeconds($seconds); return $oDate; }
/** * A method to determine the lifetime ad conversions left before expiration. * * @param integer $campaignId The campaign ID. * @param PEAR::Date $oDate An optional date. If present, sets an upper * date boundary of the end of the operation * interval the date is in to limit the delivery * statistics used in determining how many * conversions have delivered. Can be used to * determine the the lifetime ad conversions left * before expiration at a previous time. * @return mixed The number of ad conversions remaining, or the * string "unlimited". */ function getAdConversionsLeft($campaignId, $oDate = null) { global $strUnlimited; $prefix = $this->getTablePrefix(); // Get the campaign info $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->get($campaignId); $aData = $doCampaigns->toArray(); if ($aData['clicks'] > 0) { // Get the campaign delivery info if (!is_null($oDate)) { // Get the end of operation interval the date represents $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $oDate = $aDates['end']; } $dalDataIntermediateAd = OA_Dal::factoryDAL('data_intermediate_ad'); $record = $dalDataIntermediateAd->getDeliveredByCampaign($campaignId, $oDate); $aDeliveryData = $record->toArray(); return $aData['conversions'] - $aDeliveryData['conversions_delivered']; } else { return $strUnlimited; } }
/** * A method to return the forcast impressions for a zone, indexed by operation interval, * from the current operation interval through the past week. If no forecast stored in * the database, uses the defualt value from the configuration file. * * @param integer $zoneId The Zone ID. * @return mixed An array on success, false on failure. The array is of the format: * array( * [operation_interval_id] => array( * ['zone_id'] => zone_id, * ['forecast_impressions'] => forecast_impressions, * ['operation_interval_id'] => operation_interval_id * ) * [operation_interval_id] => array( * ['zone_id'] => zone_id, * ['forecast_impressions'] => forecast_impressions, * ['operation_interval_id'] => operation_interval_id * ) * . * . * . * ) */ function getPreviousWeekZoneForcastImpressions($zoneId) { if (empty($zoneId) || !is_numeric($zoneId)) { OA::debug('Invalid zone ID argument', PEAR_LOG_ERR); return false; } $aConf = $GLOBALS['_MAX']['CONF']; $oServiceLocator =& OA_ServiceLocator::instance(); $oDate =& $oServiceLocator->get('now'); if (!$oDate) { return false; } // Get the start and end ranges of the current week $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $oDateWeekStart = new Date(); $oDateWeekStart->copy($aDates['end']); $oDateWeekStart->subtractSeconds(SECONDS_PER_WEEK - 1); $oDateWeekEnd = new Date(); $oDateWeekEnd->copy($aDates['end']); // Select the zone forecasts from the database $tableName = $this->_getTablename('data_summary_zone_impression_history'); $query = "\n SELECT\n zone_id AS zone_id,\n forecast_impressions AS forecast_impressions,\n operation_interval_id AS operation_interval_id,\n interval_start AS interval_start,\n interval_end AS interval_end\n FROM\n {$tableName}\n WHERE\n zone_id = {$zoneId}\n AND operation_interval = {$aConf['maintenance']['operationInterval']}\n AND interval_start >= '" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "'\n AND interval_end <= '" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "'\n AND zone_id != 0\n ORDER BY\n interval_start"; $rc = $this->oDbh->query($query); if (!PEAR::isError($rc)) { // Sort the results into an array indexed by the operation interval ID $aFinalResult = array(); while ($aRow = $rc->fetchRow()) { $aFinalResult[$aRow['operation_interval_id']] = array('zone_id' => $aRow['zone_id'], 'forecast_impressions' => $aRow['forecast_impressions'], 'operation_interval_id' => $aRow['operation_interval_id']); } } // Check each operation interval ID has a forecast impression value, // and if not, set to the system default. for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) { if (!isset($aFinalResult[$operationIntervalID])) { $aFinalResult[$operationIntervalID] = array('zone_id' => $zoneId, 'forecast_impressions' => ZONE_FORECAST_DEFAULT_ZONE_IMPRESSIONS, 'operation_interval_id' => $operationIntervalID); } } return $aFinalResult; }
/** * @param $oDate * @param $campaignId * @return int Number of emails sent */ function sendCampaignImpendingExpiryEmail($oDate, $campaignId) { $aConf = $GLOBALS['_MAX']['CONF']; global $date_format; $oPreference = new OA_Preferences(); if (!isset($this->aAdminCache)) { // Get admin account ID $adminAccountId = OA_Dal_ApplicationVariables::get('admin_account_id'); // Get admin prefs $adminPrefsNames = $this->_createPrefsListPerAccount(OA_ACCOUNT_ADMIN); $aAdminPrefs = $oPreference->loadAccountPreferences($adminAccountId, $adminPrefsNames, OA_ACCOUNT_ADMIN); // Get admin users $aAdminUsers = $this->getAdminUsersLinkedToAccount(); // Store admin cache $this->aAdminCache = array($aAdminPrefs, $aAdminUsers); } else { // Retrieve admin cache list($aAdminPrefs, $aAdminUsers) = $this->aAdminCache; } $aPreviousOIDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aPreviousOIDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aPreviousOIDates['start']); $doCampaigns = OA_Dal::staticGetDO('campaigns', $campaignId); if (!$doCampaigns) { return 0; } $aCampaign = $doCampaigns->toArray(); if (!isset($this->aClientCache[$aCampaign['clientid']])) { $doClients = OA_Dal::staticGetDO('clients', $aCampaign['clientid']); // Add advertiser linked users $aLinkedUsers['advertiser'] = $this->getUsersLinkedToAccount('clients', $aCampaign['clientid']); // Add advertiser prefs $advertiserPrefsNames = $this->_createPrefsListPerAccount(OA_ACCOUNT_ADVERTISER); $aPrefs['advertiser'] = $oPreference->loadAccountPreferences($doClients->account_id, $advertiserPrefsNames, OA_ACCOUNT_ADVERTISER); if (!isset($aAgencyCache[$doClients->agencyid])) { // Add manager linked users $doAgency = OA_Dal::staticGetDO('agency', $doClients->agencyid); $aLinkedUsers['manager'] = $this->getUsersLinkedToAccount('agency', $doClients->agencyid); // Add manager preferences $managerPrefsNames = $this->_createPrefsListPerAccount(OA_ACCOUNT_MANAGER); $aPrefs['manager'] = $oPreference->loadAccountPreferences($doAgency->account_id, $managerPrefsNames, OA_ACCOUNT_MANAGER); // Get agency "From" details $aAgencyFromDetails = $this->_getAgencyFromDetails($doAgency->agencyid); // Store in the agency cache $this->aAgencyCache = array($doClients->agencyid => array($aLinkedUsers['manager'], $aPrefs['manager'], $aAgencyFromDetails)); } else { // Retrieve agency cache list($aLinkedUsers['manager'], $aPrefs['manager'], $aAgencyFromDetails) = $this->aAgencyCache[$doClients->agencyid]; } // Add admin linked users and preferences $aLinkedUsers['admin'] = $aAdminUsers; $aPrefs['admin'] = $aAdminPrefs; // Create a linked user 'special' for the advertiser that will take the admin preferences for advertiser $aLinkedUsers['special']['advertiser'] = $doClients->toArray(); $aLinkedUsers['special']['advertiser']['contact_name'] = $aLinkedUsers['special']['advertiser']['contact']; $aLinkedUsers['special']['advertiser']['email_address'] = $aLinkedUsers['special']['advertiser']['email']; $aLinkedUsers['special']['advertiser']['language'] = ''; $aLinkedUsers['special']['advertiser']['user_id'] = 0; // Check that every user is not going to receive more than one email if they // are linked to more than one account $aLinkedUsers = $this->_deleteDuplicatedUser($aLinkedUsers); // Create the linked special user preferences from the admin preferences // the special user is the client that doesn't have preferences in the database $aPrefs['special'] = $aPrefs['admin']; $aPrefs['special']['warn_email_special'] = $aPrefs['special']['warn_email_advertiser']; $aPrefs['special']['warn_email_special_day_limit'] = $aPrefs['special']['warn_email_advertiser_day_limit']; $aPrefs['special']['warn_email_special_impression_limit'] = $aPrefs['special']['warn_email_advertiser_impression_limit']; // Store in the client cache $this->aClientCache = array($aCampaign['clientid'] => array($aLinkedUsers, $aPrefs, $aAgencyFromDetails)); } else { // Retrieve client cache list($aLinkedUsers, $aPrefs, $aAgencyFromDetails) = $this->aClientCache[$aCampaign['clientid']]; } $copiesSent = 0; foreach ($aLinkedUsers as $accountType => $aUsers) { if ($accountType == 'special' || $accountType == 'advertiser') { // Get the agency details and use them for emailing advertisers $aFromDetails = $aAgencyFromDetails; } else { // Use the Admin details $aFromDetails = ''; } if ($aPrefs[$accountType]['warn_email_' . $accountType]) { // Does the account type want warnings when the impressions are low? if ($aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit'] > 0 && $aCampaign['views'] > 0) { // Test to see if the placements impressions remaining are less than the limit $dalCampaigns = OA_Dal::factoryDAL('campaigns'); $remainingImpressions = $dalCampaigns->getAdImpressionsLeft($aCampaign['campaignid']); if ($remainingImpressions < $aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit']) { // Yes, the placement will expire soon! But did the placement just reach // the point where it is about to expire, or did it happen a while ago? $previousRemainingImpressions = $dalCampaigns->getAdImpressionsLeft($aCampaign['campaignid'], $aPreviousOIDates['end']); if ($previousRemainingImpressions >= $aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit']) { // Yes! This is the operation interval that the boundary // was crossed to the point where it's about to expire, // so send that email, baby! foreach ($aUsers as $aUser) { $aEmail = $this->prepareCampaignImpendingExpiryEmail($aUser, $aCampaign['clientid'], $aCampaign['campaignid'], 'impressions', $aPrefs[$accountType]['warn_email_' . $accountType . '_impression_limit'], $accountType); if ($aEmail !== false) { if ($this->sendMail($aEmail['subject'], $aEmail['contents'], $aUser['email_address'], $aUser['contact_name'], $aFromDetails)) { $copiesSent++; if ($aConf['email']['logOutgoing']) { phpAds_userlogSetUser(phpAds_userMaintenance); phpAds_userlogAdd(phpAds_actionWarningMailed, $aPlacement['campaignid'], "{$aEmail['subject']}\n\n\n {$aUser['contact_name']}({$aUser['email_address']})\n\n\n {$aEmail['contents']}"); } } } } } } } // Does the account type want warnings when the days are low? if ($aPrefs[$accountType]['warn_email_' . $accountType . '_day_limit'] > 0 && !empty($aCampaign['expire_time'])) { // Calculate the date that should be used to see if the warning needs to be sent $warnSeconds = (int) ($aPrefs[$accountType]['warn_email_' . $accountType . '_day_limit'] + 1) * SECONDS_PER_DAY; $oEndDate = new Date($aCampaign['expire_time']); $oEndDate->setTZbyID('UTC'); $oTestDate = new Date(); $oTestDate->copy($oDate); $oTestDate->addSeconds($warnSeconds); // Test to see if the test date is after the placement's expiration date if ($oTestDate->after($oEndDate)) { // Yes, the placement will expire soon! But did the placement just reach // the point where it is about to expire, or did it happen a while ago? $oiSeconds = (int) $aConf['maintenance']['operationInterval'] * 60; $oTestDate->subtractSeconds($oiSeconds); if (!$oTestDate->after($oEndDate)) { // Yes! This is the operation interval that the boundary // was crossed to the point where it's about to expire, // so send those emails, baby! foreach ($aUsers as $aUser) { $aEmail = $this->prepareCampaignImpendingExpiryEmail($aUser, $aCampaign['clientid'], $aCampaign['campaignid'], 'date', $oEndDate->format($date_format), $accountType); if ($aEmail !== false) { if ($this->sendMail($aEmail['subject'], $aEmail['contents'], $aUser['email_address'], $aUser['contact_name'], $aFromDetails)) { $copiesSent++; if ($aConf['email']['logOutgoing']) { phpAds_userlogSetUser(phpAds_userMaintenance); phpAds_userlogAdd(phpAds_actionWarningMailed, $aPlacement['campaignid'], "{$aEmail['subject']}\n\n\n {$aUser['contact_name']}({$aUser['email_address']})\n\n\n {$aEmail['contents']}"); } } } } } } } } } // Restore the default language strings Language_Loader::load('default'); return $copiesSent; }
/** * A method to return data about the times that various Maintenance * processes ran. * * @param string $tableName The name of the log_maintenance_* table to get data from. * Must be a complete table name, including prefix, if * required. * @param array $aAdditionalFields An array of strings, representing any additional * data fields to return, along with the default * 'updated_to' field. * @param string $whereClause Optional string, containing a valid SQL WHERE clause, * if this is required to limit the results of the log data * before ordering and returning. * @param string $orderBy Optional string to specify the DB field used to sort the data * into DESCENDING order, before selecting the first value. Default * is 'start_run'. * @param array $aAlternateInfo Optional array containing two fields, 'tableName', which * is a string of the name of a raw table which will be searched * for the earliest date/time, in the event that no valid * 'updated_to' field could be found in the main table, and 'type', * which is a string of either value 'oi' or 'hour'. The returned * 'updated_to' value will either be the end of the operation * interval (if 'type' is 'oi') or the end of the hour (if 'type' * is 'hour') prior to any date/time found in the alternate raw * table. Note that if the alternate raw table is used, then ONLY * the 'updated_to' value is returned - any $aAdditionalFields * values will be ignored. * @return mixed False on error, null no no result, otherwise, an array containing the * 'updated_to' field, which represents the time that the Maintenance * process last completed updating data until, as well as any additional * fields (see $aAdditionalFields parameter), unless the alternate raw table * was used (see $alternateRawTableName parameter). */ function getProcessLastRunInfo($tableName, $aAdditionalFields = array(), $whereClause = null, $orderBy = 'start_run', $aAlternateInfo = array()) { $aConf = $GLOBALS['_MAX']['CONF']; // Test input values $aAdditionalFields and $aAlternateInfo are arrays if (!is_array($aAdditionalFields) || !is_array($aAlternateInfo)) { return false; } $query = "\n SELECT\n updated_to"; if (!empty($aAdditionalFields)) { $query .= ', ' . implode(', ', $aAdditionalFields); } $tableName = $this->_getTablename($tableName); $query .= "\n FROM\n {$tableName}"; if (!is_null($whereClause)) { $query .= "\n {$whereClause}"; } $query .= "\n ORDER BY {$orderBy} DESC\n LIMIT 1"; OA::debug('- Obtaining maintenance process run information from ' . $tableName, PEAR_LOG_DEBUG); $rc = $this->oDbh->query($query); if (PEAR::isError($rc)) { return false; } $aResult = $rc->fetchRow(); if (!is_null($aResult)) { // The process run information was found, return. return $aResult; } if (!empty($aAlternateInfo['tableName']) && !empty($aAlternateInfo['type'])) { // No result was found above, and an alternate raw table was specified, // so search the raw table to see if a valid result can be generated // on the basis of the earliest raw data value $tableName = $this->_getTablename($aAlternateInfo['tableName']); $query = "\n SELECT\n date_time AS date\n FROM\n {$tableName}\n ORDER BY date ASC\n LIMIT 1"; OA::debug('- Maintenance process run information not found - trying to get data from ' . $aAlternateInfo['tableName'], PEAR_LOG_DEBUG); $rc = $this->oDbh->query($query); if (PEAR::isError($rc)) { return false; } if ($rc->numRows() > 0) { // A raw data result was found - convert it to the end of the previous // operation interval, or hour $aResult = $rc->fetchRow(); $oDate = new Date($aResult['date']); if ($aAlternateInfo['type'] == 'oi') { $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $oResultDate = $aDates['start']; } else { if ($aAlternateInfo['type'] == 'hour') { $oResultDate = new Date($oDate->format('%Y-%m-%d %H:00:00')); } } $oResultDate->subtractSeconds(1); return array('updated_to' => $oResultDate->format('%Y-%m-%d %H:%M:%S')); } } // No result found, return null return null; }
/** * Method to test the getPreviousAdDeliveryInfo method. * * Requirements: * Test 1: Test with no Date registered in the service locator, ensure false returned. * Test 2: Test with a Date registered in the service locator, no data in the database, * and ensure no data is returned. * * Test 3: Test with ONLY impression data, but NOT in the previous OI, and ensure no * data is returned. * Test 4: Test with ONLY impression data, in the previous OI, and ensure that ONLY * data relating to the impressions is returned. * Test 5: Test with ONLY impression data, in the 2nd previous OI, and ensure that * no data is returned. * Test 5a: Re-test with ONLY impression data, in the 2nd previous OI, but pass in the * ad/zone pair, and ensure that no data is returned. * * Test 6: Test with ONLY prioritisation data, but NOT in the previous OI, and * ensure no data is returned. * Test 7: Test with ONLY prioritisation data, in the previous OI, and ensure that * ONLY data relating to the prioritisation is returned. * Test 8: Test with ONLY prioritisation data, in the 2nd previous OI, and ensure no * data is returned. * Test 8a: Re-test with ONLY prioritisation data, in the 2nd previous OI, but pass in * the ad/zone pair, and ensure that ONLY data relating to the prioritisation * is returned. * * Test 9: Test with BOTH impressions data NOT in the previous OI, and prioritisation * data NOT in the previous OI, and ensure no data is returned. * Test 10: Test with BOTH impressions data NOT in the previous OI, and prioritisation * data in the previous OI, and ensure ONLY data relating to the prioritisation * is returned. * Test 11: Test with BOTH impressions data NOT in the previous OI, and prioritisation * data in the 2nd previous OI, and ensure no data is returned. * Test 11a: Re-test with BOTH impressions data NOT in the previous OI, and prioritisation * data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that * ONLY data relating to the prioritisation is returned. * * Test 12: Test with BOTH impressions data in the 2nd previous OI, and prioritisation * data NOT in the previous OI, and ensure no data is returned. * Test 13: Test with BOTH impressions data in the 2nd previous OI, and prioritisation * data in the previous OI, and ensure ONLY data relating to the prioritisation * is returned. * Test 14: Test with BOTH impressions data in the 2nd previous OI, and prioritisation * data in the 2nd previous OI, and ensure no data is returned. * Test 14a: Re-test with BOTH impressions data in the 2nd previous OI, and prioritisation * data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that * all data is returned. * * Test 15: Test with BOTH impressions data in the previous OI, and prioritisation * data NOT in the previous OI, and ensure that ONLY data relating to the * impressions is returned. * Test 16: Test with BOTH impressions data in the previous OI, and prioritisation * data in the previous OI, and ensure that all data is returned. * Test 17: Test with BOTH impressions data in the previous OI, and prioritisation * data in the 2nd previous OI, and ensure that all data is returned. * Test 17a: Re-test with BOTH impressions data in the previous OI, and prioritisation * data in the 2nd previous OI, but pass in the ad/zone pair, and ensure that * all data is returned. * * Test 18: Perform a more realistic test, with data for the ads/zones in various * past OIs, and including some ads with multiple prioritisation data * per OI, as well as ads with no prioritisation data in some OIs, and * ensure that the correct values are returned for each one. Test that: * - Only ad/zones that delivered in the previous operation interval, * or were requested to deliver in the previous operation interval, * but didn't (i.e. not in other intervals) are returned in the * results. * - That prioritisation information where just ONE set of data exists * is returned correctly. * - That prioritisation information where multiple sets of INDENTICAL * data exists is returned correctly. * - That prioritisation information where multiple sets of DIFFERENT * data exists is returned correctly. * - That prioritisation information from older sets of data is * returned correctly. * Test 18a: Re-test, but also include ad/zone pairs that are in/not in the above * set of data, and ensure that these ad/zone pairs are also included * in the results. */ function testGetPreviousAdDeliveryInfo() { $conf = $GLOBALS['_MAX']['CONF']; $oDbh =& OA_DB::singleton(); $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority(); $aEmptyZoneAdArray = array(); $aAdParams = array('ad_id' => 1, 'active' => 't', 'type' => 'sql', 'weight' => 1); $oAd = new OA_Maintenance_Priority_Ad($aAdParams); $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 1)); $oZone->addAdvert($oAd); $aZoneAdArray = array($oZone->id => $oZone); // Test 1 $oServiceLocator =& OA_ServiceLocator::instance(); $oServiceLocator->remove('now'); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertFalse($result); // Test 2 $oDate = new Date(); $oServiceLocator->register('now', $oDate); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); // Test 3 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $oNow = new Date(); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 4 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertNull($result[1][1]['required_impressions']); $this->assertNull($result[1][1]['requested_impressions']); $this->assertNull($result[1][1]['priority_factor']); $this->assertNull($result[1][1]['past_zone_traffic_fraction']); $this->assertEqual($result[1][1]['impressions'], 1); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 5, 5a $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray); $this->assertEqual(count($result), 0); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 6 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0.1, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 7 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertNull($result[1][1]['impressions']); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 8, 8a $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertNull($result[1][1]['impressions']); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 9 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 10 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertNull($result[1][1]['impressions']); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 11, 11a $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertNull($result[1][1]['impressions']); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 12 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 13 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertNull($result[1][1]['impressions']); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 14, 14a $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 0); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertEqual($result[1][1]['impressions'], 1); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 15 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $aData = array($conf['maintenance']['operationInterval'], $operationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertNull($result[1][1]['required_impressions']); $this->assertNull($result[1][1]['requested_impressions']); $this->assertNull($result[1][1]['priority_factor']); $this->assertNull($result[1][1]['past_zone_traffic_fraction']); $this->assertEqual($result[1][1]['impressions'], 1); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 16 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertEqual($result[1][1]['impressions'], 1); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 17, 17a $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 1, 1, 1, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertEqual($result[1][1]['impressions'], 1); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray); $this->assertEqual(count($result), 1); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertEqual($result[1][1]['required_impressions'], 1); $this->assertEqual($result[1][1]['requested_impressions'], 1); $this->assertEqual($result[1][1]['priority_factor'], 0.5); $this->assertEqual($result[1][1]['past_zone_traffic_fraction'], 0.99); $this->assertEqual($result[1][1]['impressions'], 1); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 18 $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $bannerId2 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 2, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 2, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $bannerId3 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 5, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 100, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 100, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 200, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 200, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 4, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $oSpecialDate = new Date($aDates['end']); $oSpecialDate->addSeconds(1); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 2, 10, 10, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 9, 9, 59, 59, 0, 95, 0.995, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $aDates['end']->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 10, 10, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 20, 20, 0, 0.8, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $oSpecialDate = new Date($aDates['end']); $oSpecialDate->addSeconds(1); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 200, 200, 0, 0.2, 0.95, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 100, 100, 0, 0.4, 0.95, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aEmptyZoneAdArray); $this->assertEqual(count($result), 4); $this->assertEqual(count($result[1]), 2); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertNull($result[1][1]['required_impressions']); $this->assertNull($result[1][1]['requested_impressions']); $this->assertNull($result[1][1]['priority_factor']); $this->assertNull($result[1][1]['past_zone_traffic_fraction']); $this->assertEqual($result[1][1]['impressions'], 1); $this->assertEqual($result[1][2]['ad_id'], $bannerId1); $this->assertEqual($result[1][2]['zone_id'], 2); $this->assertEqual($result[1][2]['required_impressions'], 10); $this->assertEqual($result[1][2]['requested_impressions'], 10); $this->assertEqual($result[1][2]['priority_factor'], 0.5); $this->assertEqual($result[1][2]['past_zone_traffic_fraction'], 0.99); $this->assertEqual($result[1][2]['impressions'], 1); $this->assertEqual(count($result[2]), 2); $this->assertEqual($result[2][3]['ad_id'], $bannerId2); $this->assertEqual($result[2][3]['zone_id'], 3); $this->assertEqual($result[2][3]['required_impressions'], 30); $this->assertEqual($result[2][3]['requested_impressions'], 30); $this->assertEqual($result[2][3]['priority_factor'], 0.4); $this->assertEqual($result[2][3]['past_zone_traffic_fraction'], 0.5); $this->assertEqual($result[2][3]['impressions'], 2); $this->assertEqual($result[2][4]['ad_id'], $bannerId2); $this->assertEqual($result[2][4]['zone_id'], 4); $this->assertEqual($result[2][4]['required_impressions'], 15); $this->assertEqual($result[2][4]['requested_impressions'], 15); $this->assertEqual($result[2][4]['priority_factor'], 0.6); $this->assertEqual($result[2][4]['past_zone_traffic_fraction'], 0.5); $this->assertEqual($result[2][4]['impressions'], 2); $this->assertEqual(count($result[3]), 1); $this->assertEqual($result[3][5]['ad_id'], $bannerId3); $this->assertEqual($result[3][5]['zone_id'], 5); $this->assertEqual($result[3][5]['required_impressions'], 150); $this->assertEqual($result[3][5]['requested_impressions'], 150); $this->assertEqual($result[3][5]['priority_factor'], 0.3); $this->assertEqual($result[3][5]['past_zone_traffic_fraction'], 0.95); $this->assertEqual($result[3][5]['impressions'], 5); $this->assertEqual(count($result[9]), 1); $this->assertEqual($result[9][9]['ad_id'], 9); $this->assertEqual($result[9][9]['zone_id'], 9); $this->assertEqual($result[9][9]['required_impressions'], 59); $this->assertEqual($result[9][9]['requested_impressions'], 59); $this->assertEqual($result[9][9]['priority_factor'], 95); $this->assertEqual($result[9][9]['past_zone_traffic_fraction'], 0.995); $this->assertNull($result[9][9]['impressions']); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 18a $oZone = new OX_Maintenance_Priority_Zone(array('zoneid' => 4)); $aAdParams = array('ad_id' => 10, 'active' => 't', 'type' => 'sql', 'weight' => 1); $oAd = new OA_Maintenance_Priority_Ad($aAdParams); $oZone->addAdvert($oAd); $aAdParams = array('ad_id' => 11, 'active' => 't', 'type' => 'sql', 'weight' => 1); $oAd = new OA_Maintenance_Priority_Ad($aAdParams); $oZone->addAdvert($oAd); $aZoneAdArray = array($oZone->id => $oZone); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $bannerId1 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 1, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $bannerId2 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 2, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 2, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $bannerId3 = $this->_insertCampaignBanner(); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 5, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 1, 100, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId1, 0, 2, 100, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 3, 200, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId2, 0, 4, 200, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), $bannerId3, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 4, 0, 5, 500, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 10, 0, 4, 1000, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) { $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); } $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) { $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); } $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $aDates['start']->format('%Y-%m-%d'), $aDates['start']->format('%H'), 11, 0, 4, 2000, $oNow->format('%Y-%m-%d %H:%M:%S')); $idDia = $this->_insertDataIntermediateAd($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $oSpecialDate = new Date($aDates['end']); $oSpecialDate->addSeconds(1); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId1, 2, 10, 10, 0, 0.5, 0.99, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 9, 9, 59, 59, 0, 95, 0.995, $oNow->format('%Y-%m-%d %H:%M:%S'), 0); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 3, 30, 30, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $aDates['end']->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 10, 10, 0, 0.4, 0.5, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId2, 4, 20, 20, 0, 0.8, 0.5, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); $oSpecialDate = new Date($aDates['end']); $oSpecialDate->addSeconds(1); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 200, 200, 0, 0.2, 0.95, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), 0, $aDates['end']->format('%Y-%m-%d %H:30:00')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), $bannerId3, 5, 100, 100, 0, 0.4, 0.95, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 10, 4, 1000, 1000, 0, 1, 0.9, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($operationIntervalID); for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) { $previousOperationIntervalID = OX_OperationInterval::previousOperationIntervalID($previousOperationIntervalID); } $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); for ($i = 0; $i <= MINUTES_PER_WEEK / $conf['maintenance']['operationInterval']; $i++) { $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']); } $oSpecialDate = new Date($aDates['end']); $oSpecialDate->addSeconds(1); $aData = array($conf['maintenance']['operationInterval'], $previousOperationIntervalID, $aDates['start']->format('%Y-%m-%d %H:%M:%S'), $aDates['end']->format('%Y-%m-%d %H:%M:%S'), 11, 4, 2000, 2000, 0, 1, 0.9, $aDates['start']->format('%Y-%m-%d %H:30:00'), 0, $oSpecialDate->format('%Y-%m-%d %H:%M:%S')); $this->_insertDataSummaryAdZoneAssoc($aData); $result =& $oMaxDalMaintenance->getPreviousAdDeliveryInfo($aZoneAdArray); $this->assertEqual(count($result), 5); $this->assertEqual(count($result[1]), 2); $this->assertEqual($result[1][1]['ad_id'], $bannerId1); $this->assertEqual($result[1][1]['zone_id'], 1); $this->assertNull($result[1][1]['required_impressions']); $this->assertNull($result[1][1]['requested_impressions']); $this->assertNull($result[1][1]['priority_factor']); $this->assertNull($result[1][1]['past_zone_traffic_fraction']); $this->assertEqual($result[1][1]['impressions'], 1); $this->assertEqual($result[1][2]['ad_id'], $bannerId1); $this->assertEqual($result[1][2]['zone_id'], 2); $this->assertEqual($result[1][2]['required_impressions'], 10); $this->assertEqual($result[1][2]['requested_impressions'], 10); $this->assertEqual($result[1][2]['priority_factor'], 0.5); $this->assertEqual($result[1][2]['past_zone_traffic_fraction'], 0.99); $this->assertEqual($result[1][2]['impressions'], 1); $this->assertEqual(count($result[2]), 2); $this->assertEqual($result[2][3]['ad_id'], $bannerId2); $this->assertEqual($result[2][3]['zone_id'], 3); $this->assertEqual($result[2][3]['required_impressions'], 30); $this->assertEqual($result[2][3]['requested_impressions'], 30); $this->assertEqual($result[2][3]['priority_factor'], 0.4); $this->assertEqual($result[2][3]['past_zone_traffic_fraction'], 0.5); $this->assertEqual($result[2][3]['impressions'], 2); $this->assertEqual($result[2][4]['ad_id'], $bannerId2); $this->assertEqual($result[2][4]['zone_id'], 4); $this->assertEqual($result[2][4]['required_impressions'], 15); $this->assertEqual($result[2][4]['requested_impressions'], 15); $this->assertEqual($result[2][4]['priority_factor'], 0.6); $this->assertEqual($result[2][4]['past_zone_traffic_fraction'], 0.5); $this->assertEqual($result[2][4]['impressions'], 2); $this->assertEqual(count($result[3]), 1); $this->assertEqual($result[3][5]['ad_id'], $bannerId3); $this->assertEqual($result[3][5]['zone_id'], 5); $this->assertEqual($result[3][5]['required_impressions'], 150); $this->assertEqual($result[3][5]['requested_impressions'], 150); $this->assertEqual($result[3][5]['priority_factor'], 0.3); $this->assertEqual($result[3][5]['past_zone_traffic_fraction'], 0.95); $this->assertEqual($result[3][5]['impressions'], 5); $this->assertEqual(count($result[9]), 1); $this->assertEqual($result[9][9]['ad_id'], 9); $this->assertEqual($result[9][9]['zone_id'], 9); $this->assertEqual($result[9][9]['required_impressions'], 59); $this->assertEqual($result[9][9]['requested_impressions'], 59); $this->assertEqual($result[9][9]['priority_factor'], 95); $this->assertEqual($result[9][9]['past_zone_traffic_fraction'], 0.995); $this->assertNull($result[9][9]['impressions']); $this->assertEqual(count($result[10]), 1); $this->assertEqual($result[10][4]['ad_id'], 10); $this->assertEqual($result[10][4]['zone_id'], 4); $this->assertEqual($result[10][4]['required_impressions'], 1000); $this->assertEqual($result[10][4]['requested_impressions'], 1000); $this->assertEqual($result[10][4]['priority_factor'], 1); $this->assertEqual($result[10][4]['past_zone_traffic_fraction'], 0.9); $this->assertEqual($result[10][4]['impressions'], 1000); TestEnv::restoreEnv(); }
/** * A method to get the number of operation intervals in a given * start & end date range must be valid OI start & end date range * * @static * @param object $oStartDate PEAR::Date object * @param object $oEndDate PEAR::Date object * @return integer number of operation intervals remaining */ function getIntervalsRemaining($oStartDate, $oEndDate) { $operationIntervalSeconds = OX_OperationInterval::getOperationInterval() * 60; // Convert to UTC $oStartCopy = new Date($oStartDate); $oStartCopy->toUTC(); $oEndCopy = new Date($oEndDate); $oEndCopy->toUTC(); // Get timestamp of start date/time - in seconds $startDateSeconds = mktime($oStartCopy->getHour(), $oStartCopy->getMinute(), $oStartCopy->getSecond(), $oStartCopy->getMonth(), $oStartCopy->getDay(), $oStartCopy->getYear()); // Get timestamp of end date/time - in seconds $endDateSeconds = mktime($oEndCopy->getHour(), $oEndCopy->getMinute(), $oEndCopy->getSecond(), $oEndCopy->getMonth(), $oEndCopy->getDay(), $oEndCopy->getYear()); // calculate interval length in seconds $interval = $endDateSeconds - $startDateSeconds; // find number of operation intervals during interval return $interval <= 0 ? 0 : round($interval / $operationIntervalSeconds); }
/** * A method to test the summariseBucketsAggregate() method. */ function testSummariseBucketsAggregate() { $aConf =& $GLOBALS['_MAX']['CONF']; $aConf['maintenance']['operationInterval'] = 60; // Prepare standard test parameters $statisticsTableName = $aConf['table']['prefix'] . 'data_intermediate_ad'; $aMigrationMaps = array(0 => array('method' => 'aggregate', 'bucketTable' => $aConf['table']['prefix'] . 'data_bkt_r', 'dateTimeColumn' => 'interval_start', 'groupSource' => array(0 => 'interval_start', 1 => 'creative_id', 2 => 'zone_id'), 'groupDestination' => array(0 => 'date_time', 1 => 'ad_id', 2 => 'zone_id'), 'sumSource' => array(0 => 'count'), 'sumDestination' => array(0 => 'requests'), 'sumDefault' => array(0 => 0)), 1 => array('method' => 'aggregate', 'bucketTable' => $aConf['table']['prefix'] . 'data_bkt_m', 'dateTimeColumn' => 'interval_start', 'groupSource' => array(0 => 'interval_start', 1 => 'creative_id', 2 => 'zone_id'), 'groupDestination' => array(0 => 'date_time', 1 => 'ad_id', 2 => 'zone_id'), 'sumSource' => array(0 => 'count'), 'sumDestination' => array(0 => 'impressions'), 'sumDefault' => array(0 => 0)), 2 => array('method' => 'aggregate', 'bucketTable' => $aConf['table']['prefix'] . 'data_bkt_c', 'dateTimeColumn' => 'interval_start', 'groupSource' => array(0 => 'interval_start', 1 => 'creative_id', 2 => 'zone_id'), 'groupDestination' => array(0 => 'date_time', 1 => 'ad_id', 2 => 'zone_id'), 'sumSource' => array(0 => 'count'), 'sumDestination' => array(0 => 'clicks'), 'sumDefault' => array(0 => 0))); $aDates = array('start' => new Date('2008-08-21 09:00:00'), 'end' => new Date('2008-08-21 09:59:59')); // Prepare the DAL object $oFactory = new OX_Dal_Maintenance_Statistics_Factory(); $oDalMaintenanceStatistics = $oFactory->factory(); $oNowDate = new Date(); $aExtras = array('operation_interval' => $aConf['maintenance']['operationInterval'], 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']), 'interval_start' => $oDalMaintenanceStatistics->oDbh->quote($aDates['start']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDalMaintenanceStatistics->timestampCastString, 'interval_end' => $oDalMaintenanceStatistics->oDbh->quote($aDates['end']->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDalMaintenanceStatistics->timestampCastString, 'creative_id' => 0, 'updated' => $oDalMaintenanceStatistics->oDbh->quote($oNowDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . $oDalMaintenanceStatistics->timestampCastString); // Test 1: Test with an incorrect method name in the mapping array $savedValue = $aMigrationMaps[0]['method']; $aMigrationMaps[0]['method'] = 'foo'; $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with migration map index '0' having method 'foo' != 'aggregate'."); $aMigrationMaps[0]['method'] = $savedValue; // Test 2: Test with a different number of groupSource and groupDestination columns $savedValue = $aMigrationMaps[0]['groupSource'][1]; unset($aMigrationMaps[0]['groupSource'][1]); $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with migration map index '0' having different number of 'groupSource' and 'groupDestination' columns."); $aMigrationMaps[0]['groupSource'][1] = $savedValue; // Test 3: Test with a different number of sumSource and sumDestination columns $savedValue = $aMigrationMaps[1]['sumSource'][0]; unset($aMigrationMaps[1]['sumSource'][0]); $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with migration map index '1' having different number of 'sumSource' and 'sumDestination' columns."); $aMigrationMaps[1]['sumSource'][0] = $savedValue; // Test 4: Test with a different number of sumSource and sumDefault columns $savedValue = $aMigrationMaps[2]['sumDefault'][0]; unset($aMigrationMaps[2]['sumDefault'][0]); $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with migration map index '2' having different number of 'sumSource' and 'sumDefault' columns."); $aMigrationMaps[2]['sumDefault'][0] = $savedValue; // Test 5: Test with a different groupDestination sets $savedValue = $aMigrationMaps[2]['groupDestination'][0]; $aMigrationMaps[2]['groupDestination'][0] = 'foo'; $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with migration map indexes '0' and '2' having different 'groupDestination' arrays."); $aMigrationMaps[2]['groupDestination'][0] = $savedValue; // Test 6: Test with date parameters that are not really dates $savedValue = $aDates['start']; $aDates['start'] = 'foo'; $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with invalid start/end date parameters -- not Date objects."); $aDates['start'] = $savedValue; $savedValue = $aDates['end']; $aDates['end'] = 'foo'; $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with invalid start/end date parameters -- not Date objects."); $aDates['end'] = $savedValue; // Test 7: Test with invalid start/end dates $savedValue = $aDates['start']; $aDates['start'] = new Date('2008-08-21 08:00:00'); $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with invalid start/end date parameters -- not operation interval bounds."); $aDates['start'] = $savedValue; $savedValue = $aDates['end']; $aDates['end'] = new Date('2008-08-22 09:59:59'); $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDARGS); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with invalid start/end date parameters -- not operation interval bounds."); $aDates['end'] = $savedValue; // Test 8: Test with an invalid statistics table name $savedValue = $statisticsTableName; $statisticsTableName = 'foo'; $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDREQUEST); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with invalid statistics table 'foo'."); $statisticsTableName = $savedValue; // Test 9: Test with no data_bkt_r table in the database $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertTrue(is_a($result, 'PEAR_Error')); $this->assertEqual($result->code, MAX_ERROR_INVALIDREQUEST); $this->assertEqual($result->message, "OX_Dal_Maintenance_Statistics::summariseBucketsAggregate() called with migration map index '0' having invalid bucket table '{$aConf['table']['prefix']}data_bkt_r'."); // Install the openXDeliveryLog plugin, which will create the // data_bkt_r, data_bkt_m and data_bkt_c tables required for testing TestEnv::installPluginPackage('openXDeliveryLog', false); // Test 10: Test with all tables present, but no data $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertEqual($result, 0); // Insert some data into the data_bkt_r, data_bkt_m and // data_bkt_c tables in the incorrect operation interval $oData_bkt_r = OA_Dal::factoryDO('data_bkt_r'); $oData_bkt_r->interval_start = '2008-08-21 08:00:00'; $oData_bkt_r->creative_id = 1; $oData_bkt_r->zone_id = 2; $oData_bkt_r->count = 10; DataGenerator::generateOne($oData_bkt_r); $oData_bkt_m = OA_Dal::factoryDO('data_bkt_m'); $oData_bkt_m->interval_start = '2008-08-21 08:00:00'; $oData_bkt_m->creative_id = 1; $oData_bkt_m->zone_id = 2; $oData_bkt_m->count = 9; DataGenerator::generateOne($oData_bkt_m); $oData_bkt_c = OA_Dal::factoryDO('data_bkt_c'); $oData_bkt_c->interval_start = '2008-08-21 08:00:00'; $oData_bkt_c->creative_id = 1; $oData_bkt_c->zone_id = 2; $oData_bkt_c->count = 1; DataGenerator::generateOne($oData_bkt_c); // Test 11: Test with data in the incorrect operation interval $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertEqual($result, 0); // Insert some data into the data_bkt_r, data_bkt_m and // data_bkt_c tables in the incorrect operation interval $oData_bkt_r = OA_Dal::factoryDO('data_bkt_r'); $oData_bkt_r->interval_start = '2008-08-21 09:00:00'; $oData_bkt_r->creative_id = 1; $oData_bkt_r->zone_id = 2; $oData_bkt_r->count = 10; DataGenerator::generateOne($oData_bkt_r); $oData_bkt_m = OA_Dal::factoryDO('data_bkt_m'); $oData_bkt_m->interval_start = '2008-08-21 09:00:00'; $oData_bkt_m->creative_id = 1; $oData_bkt_m->zone_id = 2; $oData_bkt_m->count = 9; DataGenerator::generateOne($oData_bkt_m); $oData_bkt_c = OA_Dal::factoryDO('data_bkt_c'); $oData_bkt_c->interval_start = '2008-08-21 09:00:00'; $oData_bkt_c->creative_id = 1; $oData_bkt_c->zone_id = 2; $oData_bkt_c->count = 1; DataGenerator::generateOne($oData_bkt_c); // Test 12: Test with data in the correct operation interval $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertEqual($result, 1); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->find(); $rows = $oData_intermediate_ad->getRowCount(); $this->assertEqual($rows, 1); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->ad_id = 1; $oData_intermediate_ad->find(); $rows = $oData_intermediate_ad->getRowCount(); $this->assertEqual($rows, 1); $oData_intermediate_ad->fetch(); $this->assertEqual($oData_intermediate_ad->date_time, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->operation_interval, $aConf['maintenance']['operationInterval']); $this->assertEqual($oData_intermediate_ad->operation_interval_id, OX_OperationInterval::convertDateToOperationIntervalID($aDates['start'])); $this->assertEqual($oData_intermediate_ad->interval_start, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->interval_end, '2008-08-21 09:59:59'); $this->assertEqual($oData_intermediate_ad->ad_id, 1); $this->assertEqual($oData_intermediate_ad->creative_id, 0); $this->assertEqual($oData_intermediate_ad->zone_id, 2); $this->assertEqual($oData_intermediate_ad->requests, 10); $this->assertEqual($oData_intermediate_ad->impressions, 9); $this->assertEqual($oData_intermediate_ad->clicks, 1); // Clean up generated data DataGenerator::cleanUp(); // Insert some new data into the data_bkt_r, data_bkt_m and // data_bkt_c tables in the incorrect operation interval $oData_bkt_r = OA_Dal::factoryDO('data_bkt_r'); $oData_bkt_r->interval_start = '2008-08-21 09:00:00'; $oData_bkt_r->creative_id = 2; $oData_bkt_r->zone_id = 2; $oData_bkt_r->count = 10; DataGenerator::generateOne($oData_bkt_r); $oData_bkt_m = OA_Dal::factoryDO('data_bkt_m'); $oData_bkt_m->interval_start = '2008-08-21 09:00:00'; $oData_bkt_m->creative_id = 2; $oData_bkt_m->zone_id = 2; $oData_bkt_m->count = 9; DataGenerator::generateOne($oData_bkt_m); $oData_bkt_c = OA_Dal::factoryDO('data_bkt_c'); $oData_bkt_c->interval_start = '2008-08-21 09:00:00'; $oData_bkt_c->creative_id = 2; $oData_bkt_c->zone_id = 2; $oData_bkt_c->count = 1; DataGenerator::generateOne($oData_bkt_c); $oData_bkt_r = OA_Dal::factoryDO('data_bkt_r'); $oData_bkt_r->interval_start = '2008-08-21 09:00:00'; $oData_bkt_r->creative_id = 11; $oData_bkt_r->zone_id = 12; $oData_bkt_r->count = 10000; DataGenerator::generateOne($oData_bkt_r); $oData_bkt_m = OA_Dal::factoryDO('data_bkt_m'); $oData_bkt_m->interval_start = '2008-08-21 09:00:00'; $oData_bkt_m->creative_id = 11; $oData_bkt_m->zone_id = 12; $oData_bkt_m->count = 9960; DataGenerator::generateOne($oData_bkt_m); $oData_bkt_c = OA_Dal::factoryDO('data_bkt_c'); $oData_bkt_c->interval_start = '2008-08-21 09:00:00'; $oData_bkt_c->creative_id = 11; $oData_bkt_c->zone_id = 12; $oData_bkt_c->count = 500; DataGenerator::generateOne($oData_bkt_c); // Test 13: Test with new data in the correct operation interval $result = $oDalMaintenanceStatistics->summariseBucketsAggregate($statisticsTableName, $aMigrationMaps, $aDates, $aExtras); $this->assertEqual($result, 2); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->find(); $rows = $oData_intermediate_ad->getRowCount(); $this->assertEqual($rows, 3); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->ad_id = 1; $oData_intermediate_ad->find(); $rows = $oData_intermediate_ad->getRowCount(); $this->assertEqual($rows, 1); $oData_intermediate_ad->fetch(); $this->assertEqual($oData_intermediate_ad->date_time, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->operation_interval, $aConf['maintenance']['operationInterval']); $this->assertEqual($oData_intermediate_ad->operation_interval_id, OX_OperationInterval::convertDateToOperationIntervalID($aDates['start'])); $this->assertEqual($oData_intermediate_ad->interval_start, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->interval_end, '2008-08-21 09:59:59'); $this->assertEqual($oData_intermediate_ad->ad_id, 1); $this->assertEqual($oData_intermediate_ad->creative_id, 0); $this->assertEqual($oData_intermediate_ad->zone_id, 2); $this->assertEqual($oData_intermediate_ad->requests, 10); $this->assertEqual($oData_intermediate_ad->impressions, 9); $this->assertEqual($oData_intermediate_ad->clicks, 1); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->ad_id = 2; $oData_intermediate_ad->find(); $rows = $oData_intermediate_ad->getRowCount(); $this->assertEqual($rows, 1); $oData_intermediate_ad->fetch(); $this->assertEqual($oData_intermediate_ad->date_time, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->operation_interval, $aConf['maintenance']['operationInterval']); $this->assertEqual($oData_intermediate_ad->operation_interval_id, OX_OperationInterval::convertDateToOperationIntervalID($aDates['start'])); $this->assertEqual($oData_intermediate_ad->interval_start, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->interval_end, '2008-08-21 09:59:59'); $this->assertEqual($oData_intermediate_ad->ad_id, 2); $this->assertEqual($oData_intermediate_ad->creative_id, 0); $this->assertEqual($oData_intermediate_ad->zone_id, 2); $this->assertEqual($oData_intermediate_ad->requests, 10); $this->assertEqual($oData_intermediate_ad->impressions, 9); $this->assertEqual($oData_intermediate_ad->clicks, 1); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->ad_id = 11; $oData_intermediate_ad->find(); $rows = $oData_intermediate_ad->getRowCount(); $this->assertEqual($rows, 1); $oData_intermediate_ad->fetch(); $this->assertEqual($oData_intermediate_ad->date_time, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->operation_interval, $aConf['maintenance']['operationInterval']); $this->assertEqual($oData_intermediate_ad->operation_interval_id, OX_OperationInterval::convertDateToOperationIntervalID($aDates['start'])); $this->assertEqual($oData_intermediate_ad->interval_start, '2008-08-21 09:00:00'); $this->assertEqual($oData_intermediate_ad->interval_end, '2008-08-21 09:59:59'); $this->assertEqual($oData_intermediate_ad->ad_id, 11); $this->assertEqual($oData_intermediate_ad->creative_id, 0); $this->assertEqual($oData_intermediate_ad->zone_id, 12); $this->assertEqual($oData_intermediate_ad->requests, 10000); $this->assertEqual($oData_intermediate_ad->impressions, 9960); $this->assertEqual($oData_intermediate_ad->clicks, 500); // Clean up generated data DataGenerator::cleanUp(); // Also clean up the data migrated into the statistics table $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->data_intermediate_ad_id = 1; $oData_intermediate_ad->find(); $oData_intermediate_ad->delete(); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->data_intermediate_ad_id = 2; $oData_intermediate_ad->find(); $oData_intermediate_ad->delete(); $oData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $oData_intermediate_ad->data_intermediate_ad_id = 3; $oData_intermediate_ad->find(); $oData_intermediate_ad->delete(); // Uninstall the installed plugin TestEnv::uninstallPluginPackage('openXDeliveryLog', false); // Restore the test environment configuration TestEnv::restoreConfig(); }
$aConVariables = Admin_DA::fromCache('getConnectionVariables', $conversionId); // Sum up basket values $basketValue = 0; $numItems = 0; foreach ($aConVariables as $conVariable) { if ($conVariable['purpose'] == 'basket_value') { $basketValue += $conVariable['value']; } elseif ($conVariable['purpose'] == 'num_items') { $numItems += $conVariable['value']; } } // Get day, $hour and operation interval $dateTime = $aConversions[$conversionId]['date_time']; $oConnectionDate = new Date($dateTime); $oConnectionDate->toUTC(); $optIntID = OX_OperationInterval::convertDateToOperationIntervalID($oConnectionDate); $opDay = $oConnectionDate->format('%Y-%m-%d'); $opHour = $oConnectionDate->format('%H'); // Get ad_id, creative_id and zone_id $ad_id = $aConversions[$conversionId]['ad_id']; $creative_id = $aConversions[$conversionId]['creative_id']; $zone_id = $aConversions[$conversionId]['zone_id']; $operation = null; // If conversion was changed to connection if ($aConversions[$conversionId]['connection_status'] == MAX_CONNECTION_STATUS_APPROVED) { // Substract conversion from "data_intermediate_ad" and from "data_summary_ad_hourly" // and remove $connectionBasketValue from total_basket_value $operation = '-'; } // If connection was changed to conversion if ($statusId == MAX_CONNECTION_STATUS_APPROVED) {
/** * A private method to calculate an equivalent "last time that maintenance * statistics was run" value from logged delivery data, if possible. * * Enables the MSE process to be kick-started for new installations, where * the MSE has not been run before; but without causing the MSE to run * until the installation is actually logging data. * * @access private * @param integer $type The update type that "occurred" - that is, * OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI if the required * calculated "update date" needs to be in terms of the * operation interval; or * OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR if the * required calculated "update date" needs to be in terms * of the hour. * @return Date A Date representing the end of the operation interval * which is before the date found of the earliest known * logged delivery data record. Returns null if no logged * delivery data can be located. */ function _getEarliestLoggedDeliveryData($type) { // Obtain all components from the deliveryLog plugin group $aDeliveryLogComponents = OX_Component::getComponents('deliveryLog'); // Are there any components? if (empty($aDeliveryLogComponents)) { return null; } // Call the "getEarliestLoggedDataDate()" method on each // component, to find out what is the date of the earliest // logged data that the component knows about $aResult = OX_Component::callOnComponents($aDeliveryLogComponents, 'getEarliestLoggedDataDate'); if ($aResults === false) { return null; } // Iterate over the results from above, and see if any of // the components returned valid dates, and if so, which // of the results is the earliest $oDate = null; foreach ($aResult as $oComponentDate) { if (is_a($oComponentDate, 'Date')) { // Logged data was located! Is this date earlier than // any previous "earliest" logged delivery data? if (is_null($oDate)) { $oDate = new Date(); $oDate->copy($oComponentDate); } else { if ($oComponentDate->before($oDate)) { $oDate->copy($oComponentDate); } } } } // Was a date found? if (is_null($oDate) || !is_a($oDate, 'Date')) { return null; } // Convert the located earliest logged data date into either the // end of the previous operation interval, or the end of the previous // hour, depending on the required type if ($type == OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI) { $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); } else { $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate, 60); } // Return the date return $aDates['end']; }
/** * A method to prune a bucket of all records up to and * including the time given. * * @param Date $oEnd Prune until this interval_start (inclusive). * @param Date $oStart Only prune before this interval_start date (inclusive) * as well. Optional. * @return mixed Either the number of rows pruned, or an MDB2_Error objet. */ public function pruneBucket($oBucket, $oEnd, $oStart = null) { $sTableName = $oBucket->getBucketTableName(); if (!is_null($oStart)) { OA::debug(' - Pruning the ' . $sTableName . ' table for data with operation interval start between ' . $oStart->format('%Y-%m-%d %H:%M:%S') . ' ' . $oStart->tz->getShortName() . ' and ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG); } else { OA::debug(' - Pruning the ' . $sTableName . ' table for all data with operation interval start equal to or before ' . $oEnd->format('%Y-%m-%d %H:%M:%S') . ' ' . $oEnd->tz->getShortName(), PEAR_LOG_DEBUG); } // As this is raw data being processed, data will not be logged based on the operation interval, // but based on the time the raw data was collected. Adjust the $oEnd value accordingly... if (!is_null($oStart)) { $aStartDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oStart); } $aEndDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oEnd); OA::debug(' - The ' . $sTableName . ' table is a raw data table. Data logged in real-time, not operation intervals.', PEAR_LOG_INFO); if (!is_null($oStart)) { OA::debug(' - Accordingly, pruning of the ' . $sTableName . ' table will be performed based on data that has a logged date between ', PEAR_LOG_INFO); OA::debug(' ' . $aStartDates['start']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aStartDates['start']->tz->getShortName() . ' and ' . $aEndDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aEndDates['end']->tz->getShortName(), PEAR_LOG_INFO); } else { OA::debug(' - Accordingly, pruning of the ' . $sTableName . ' table will be performed based on data that has a logged date equal to', PEAR_LOG_INFO); OA::debug(' or before ' . $aEndDates['end']->format('%Y-%m-%d %H:%M:%S') . ' ' . $aEndDates['end']->tz->getShortName(), PEAR_LOG_INFO); } $query = "\n DELETE FROM\n {$sTableName}\n WHERE\n date_time <= " . DBC::makeLiteral($aEndDates['end']->format('%Y-%m-%d %H:%M:%S')); if (!is_null($oStart)) { $query .= "\n AND\n date_time >= " . DBC::makeLiteral($aStartDates['start']->format('%Y-%m-%d %H:%M:%S')); } $oDbh = OA_DB::singleton(); return $oDbh->exec($query); }
/** * A method to test the MAX_Delivery_log_logAdRequest(), * MAX_Delivery_log_logAdImpression() and MAX_Delivery_log_logAdClick() * functions. */ function testRequestImpressionClickFunction() { $aConf =& $GLOBALS['_MAX']['CONF']; $aConf['maintenance']['operationInterval'] = 60; $GLOBALS['_MAX']['NOW'] = time(); $oNowDate = new Date($GLOBALS['_MAX']['NOW']); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate); $intervalStart = $aDates['start']->format('%Y-%m-%d %H:%M:%S'); $aTables = array('MAX_Delivery_log_logAdRequest' => 'data_bkt_r', 'MAX_Delivery_log_logAdImpression' => 'data_bkt_m', 'MAX_Delivery_log_logAdClick' => 'data_bkt_c'); foreach ($aTables as $function => $table) { // Test to ensure that the openXDeliveryLog plugin's data bucket // table does not exist $oTable = new OA_DB_Table(); $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . $table); $this->assertFalse($tableExists); // Test calling the main logging function without any plugins installed, // to ensure that this does not result in any kind of error unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']); call_user_func_array($function, array(1, 1)); } // Install the openXDeliveryLog plugin TestEnv::installPluginPackage('openXDeliveryLog', false); foreach ($aTables as $function => $table) { // Test to ensure that the openXDeliveryLog plugin's data bucket // table now does exist $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . $table); $this->assertTrue($tableExists); // Ensure that there are is nothing logged in the data bucket table $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 0); // Call the main logging function unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']); call_user_func_array($function, array(1, 1)); // Ensure that the data was logged correctly $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); if ($table == 'data_bkt_r') { // Request logging is disabled by default. Nothing should have been logged by now $this->assertEqual($rows, 0); // Enable it $GLOBALS['_MAX']['CONF']['logging']['adRequests'] = true; unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']); call_user_func_array($function, array(1, 1)); // Now ensure that the data was logged correctly $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); } $this->assertEqual($rows, 1); $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->creative_id = 1; $doData_bkt->zone_id = 1; $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt->fetch(); $this->assertEqual($doData_bkt->count, 1); $this->assertEqual($doData_bkt->interval_start, $intervalStart); // Call the main logging function again unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']); call_user_func_array($function, array(1, 1)); // Ensure that the data was logged correctly $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->creative_id = 1; $doData_bkt->zone_id = 1; $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt->fetch(); $this->assertEqual($doData_bkt->count, 2); $this->assertEqual($doData_bkt->interval_start, $intervalStart); // Call the main logging function again, but with a differen // creative/zone pair unset($GLOBALS['_MAX']['deliveryData']['Plugin_deliveryDataPrepare_oxDeliveryDataPrepare_dataCommon']); call_user_func_array($function, array(2, 1)); // Ensure that the data was logged correctly $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 2); $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->creative_id = 1; $doData_bkt->zone_id = 1; $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt->fetch(); $this->assertEqual($doData_bkt->count, 2); $this->assertEqual($doData_bkt->interval_start, $intervalStart); $doData_bkt = OA_Dal::factoryDO($table); $doData_bkt->creative_id = 2; $doData_bkt->zone_id = 1; $doData_bkt->find(); $rows = $doData_bkt->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt->fetch(); $this->assertEqual($doData_bkt->count, 1); $this->assertEqual($doData_bkt->interval_start, $intervalStart); } // Uninstall the openXDeliveryLog plugin TestEnv::uninstallPluginPackage('openXDeliveryLog', false); // Restore the test configuration file TestEnv::restoreConfig(); }
/** * A method to test the MAX_Delivery_log_logConversion() function. */ function test_MAX_Delivery_log_logConversion() { $aConf =& $GLOBALS['_MAX']['CONF']; $aConf['maintenance']['operationInterval'] = 60; $GLOBALS['_MAX']['NOW'] = time(); $oNowDate = new Date($GLOBALS['_MAX']['NOW']); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate); $intervalStart = $aDates['start']->format('%Y-%m-%d %H:%M:%S'); $oConversionDate = new Date(); $oConversionDate->copy($oNowDate); $oConversionDate->subtractSeconds(60); $_SERVER['REMOTE_ADDR'] = '127.0.0.99'; // Test to ensure that the openXDeliveryLog plugin's data bucket // table does not exist $oTable = new OA_DB_Table(); $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a'); $this->assertFalse($tableExists); // Test calling the main logging function without any plugins installed, // to ensure that this does not result in any kind of error $aConversion = array('action_type' => MAX_CONNECTION_AD_CLICK, 'tracker_type' => MAX_CONNECTION_TYPE_SALE, 'status' => MAX_CONNECTION_STATUS_APPROVED, 'cid' => 2, 'zid' => 3, 'dt' => $GLOBALS['_MAX']['NOW'] - 60, 'window' => 60); MAX_Delivery_log_logConversion(1, $aConversion); // Install the openXDeliveryLog plugin TestEnv::installPluginPackage('openXDeliveryLog', false); // Test to ensure that the openXDeliveryLog plugin's data bucket // table now does exist $tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a'); $this->assertTrue($tableExists); // Ensure that there are is nothing logged in the data bucket table $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a'); $doData_bkt_a->find(); $rows = $doData_bkt_a->getRowCount(); $this->assertEqual($rows, 0); // Call the conversion logging function $aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion); // Ensure that the data was logged correctly $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a'); $doData_bkt_a->find(); $rows = $doData_bkt_a->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a'); $doData_bkt_a->server_conv_id = 1; $doData_bkt_a->find(); $rows = $doData_bkt_a->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt_a->fetch(); $this->assertEqual($doData_bkt_a->server_ip, 'singleDB'); $this->assertEqual($doData_bkt_a->tracker_id, 1); $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($doData_bkt_a->creative_id, 2); $this->assertEqual($doData_bkt_a->zone_id, 3); $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99'); $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK); $this->assertEqual($doData_bkt_a->window, 60); $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED); $this->assertTrue(is_array($aConversionInfo)); $this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion'])); $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 1); $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB'); $aConversion['cid'] = 5; // Call the conversion logging function $aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion); // Ensure that the data was logged correctly $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a'); $doData_bkt_a->find(); $rows = $doData_bkt_a->getRowCount(); $this->assertEqual($rows, 2); $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a'); $doData_bkt_a->server_conv_id = 1; $doData_bkt_a->find(); $rows = $doData_bkt_a->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt_a->fetch(); $this->assertEqual($doData_bkt_a->server_ip, 'singleDB'); $this->assertEqual($doData_bkt_a->tracker_id, 1); $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($doData_bkt_a->creative_id, 2); $this->assertEqual($doData_bkt_a->zone_id, 3); $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99'); $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK); $this->assertEqual($doData_bkt_a->window, 60); $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED); $doData_bkt_a = OA_Dal::factoryDO('data_bkt_a'); $doData_bkt_a->server_conv_id = 2; $doData_bkt_a->find(); $rows = $doData_bkt_a->getRowCount(); $this->assertEqual($rows, 1); $doData_bkt_a->fetch(); $this->assertEqual($doData_bkt_a->server_ip, 'singleDB'); $this->assertEqual($doData_bkt_a->tracker_id, 1); $this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S')); $this->assertEqual($doData_bkt_a->creative_id, 5); $this->assertEqual($doData_bkt_a->zone_id, 3); $this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99'); $this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK); $this->assertEqual($doData_bkt_a->window, 60); $this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED); $this->assertTrue(is_array($aConversionInfo)); $this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion'])); $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 2); $this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB'); // Uninstall the openXDeliveryLog plugin TestEnv::uninstallPluginPackage('openXDeliveryLog', false); // Restore the test configuration file TestEnv::restoreConfig(); }
/** * The test to ensure that a campaign with banners that have time-based * delivery limitations are correctly prioritised by the MPE. * * Test Basis: * * - One campaign, running from 2008-02-26 to 2008-02-27 (2 days). * - Booked impressions of 48,000 impressions (i.e. 1,000 per hour * required on average). * - Two banners in the zone, both with weight one. * - Banner ID 1 has a Time:Date delivery limitation, to only allow * the banner to deliver on 2008-02-26. * - Banner ID 2 has a Time:Date delivery limitation, to only allow * the banner to deliver on 2008-02-27. * - The campaign is linked to one constantly delivering zone (at * 1,000 impressions per hour). * * - Run the MPE with an OI of 60 minutes for the two days of the * campaign lifetime, and assume that all required impressions * allocated to the banner(s) are delivered. * * The expected result of this is that the MPE should allocate 1,000 * impressions per hour for Banner ID 1 all day on 2008-02-26, and * 1,000 impressions per hour for Banner ID 2 all day on 2008-02-37. */ function testCampaign() { $aConf =& $GLOBALS['_MAX']['CONF']; $aConf['maintenance']['operationInteval'] = 60; $aConf['priority']['useZonePatterning'] = false; OA_setTimeZone('GMT'); $oServiceLocator =& OA_ServiceLocator::instance(); $oServiceLocator->register('now', new Date('2008-02-27')); // Prepare the test campaign $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = 48000; $doCampaigns->clicks = -1; $doCampaigns->conversions = -1; $doCampaigns->activate_time = '2008-02-26 00:00:00'; $doCampaigns->expire_time = '2008-02-27 23:59:59'; $doCampaigns->priority = 10; $doCampaigns->target_impression = 0; $doCampaigns->target_click = 0; $doCampaigns->target_conversion = 0; $campaignId = DataGenerator::generateOne($doCampaigns); // Prepare the first banner $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->active = 't'; $doBanners->weight = 1; $bannerId1 = DataGenerator::generateOne($doBanners); $doAcls = OA_Dal::factoryDO('acls'); $doAcls->bannerid = $bannerId1; $doAcls->logical = 'and'; $doAcls->type = 'deliveryLimitations:Time:Date'; $doAcls->comparison = '=='; $doAcls->data = '20080226'; $doAcls->executionorder = 0; DataGenerator::generateOne($doAcls); // Prepare the second banner $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->active = 't'; $doBanners->weight = 1; $bannerId2 = DataGenerator::generateOne($doBanners); $doAcls = OA_Dal::factoryDO('acls'); $doAcls->bannerid = $bannerId2; $doAcls->logical = 'and'; $doAcls->type = 'deliveryLimitations:Time:Date'; $doAcls->comparison = '=='; $doAcls->data = '20080227'; $doAcls->executionorder = 0; DataGenerator::generateOne($doAcls); // Prepare the zone $doZones = OA_Dal::factoryDO('zones'); $zoneId = DataGenerator::generateOne($doZones); // Link the banners to the zone $doAd_zone_assoc = OA_Dal::factoryDO('ad_zone_assoc'); $doAd_zone_assoc->zone_id = $zoneId; $doAd_zone_assoc->ad_id = $bannerId1; DataGenerator::generateOne($doAd_zone_assoc); $doAd_zone_assoc = OA_Dal::factoryDO('ad_zone_assoc'); $doAd_zone_assoc->zone_id = $zoneId; $doAd_zone_assoc->ad_id = $bannerId2; DataGenerator::generateOne($doAd_zone_assoc); // Run the code to get the required ad impressions over // the 48 hour period of the test for ($counter = 1; $counter <= 48; $counter++) { // Set the "current" date/time that the MPE would be // running at for the appropriate hour of the test $oNowDate = new Date('2008-02-26 00:00:01'); $oNowDate->addSeconds(($counter - 1) * SECONDS_PER_HOUR); $oServiceLocator->register('now', $oNowDate); // Run the code to get the required ad impressions $oGetRequiredAdImpressionsLifetime = new OA_Maintenance_Priority_AdServer_Task_GetRequiredAdImpressionsLifetime(); $oGetRequiredAdImpressionsLifetime->run(); // Test that 1,000 impressions have been "required" for // the appropriate banner $query = "SELECT * FROM tmp_ad_required_impression"; $rsRequiredImpression = DBC::NewRecordSet($query); $rsRequiredImpression->find(); $aRequiredImpressions = $rsRequiredImpression->getAll(); $this->assertTrue(is_array($aRequiredImpressions), "No array for required impressions SQL result in test hour {$counter}"); $this->assertEqual(count($aRequiredImpressions), 1, "More than one row found for required impressions SQL result in test hour {$counter}"); $this->assertTrue(is_array($aRequiredImpressions[0]), "Badly formatted result row for required impressions SQL result in test hour {$counter}"); $this->assertEqual(count($aRequiredImpressions[0]), 2, "Badly formatted result row for required impressions SQL result in test hour {$counter}"); $bannerId = $aRequiredImpressions[0]['ad_id']; if ($counter <= 24) { $this->assertEqual($bannerId, $bannerId1, "Expected required impressions for banner ID {$bannerId1} in test hour {$counter}"); } else { $this->assertEqual($bannerId, $bannerId2, "Expected required impressions for banner ID {$bannerId2} in test hour {$counter}"); } $impressions = $aRequiredImpressions[0]['required_impressions']; $this->assertEqual($impressions, 1000, "Incorrectly requested {$impressions} impressions instead of 1000 in test hour {$counter}"); // Insert the required impressions for the banner into the // data_intermediate_ad table, as if the delivery has occurred, // so that the next hour's test is based on delivery having happened $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate); $operationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($oNowDate); $doData_intermediate_ad = OA_Dal::factoryDO('data_intermediate_ad'); $doData_intermediate_ad->day = $aDates['start']->format('%Y-%m-%d'); $doData_intermediate_ad->hour = $aDates['start']->format('%H'); $doData_intermediate_ad->operation_interval = $aConf['maintenance']['operationInteval']; $doData_intermediate_ad->operation_interval_id = $operationIntervalId; $doData_intermediate_ad->interval_start = $aDates['start']->format('%Y-%m-%d %H:%M:%S'); $doData_intermediate_ad->interval_end = $aDates['end']->format('%Y-%m-%d %H:%M:%S'); $doData_intermediate_ad->ad_id = $bannerId; $doData_intermediate_ad->zone_id = $zoneId; $doData_intermediate_ad->requests = $impressions; $doData_intermediate_ad->impressions = $impressions; $doData_intermediate_ad->clicks = 0; $doData_intermediate_ad->conversions = 0; DataGenerator::generateOne($doData_intermediate_ad); // Drop the temporary table that is used to store the // required impressions, so that it does not interfer // with the next test run in the loop unset($GLOBALS['_OA']['DB_TABLES']['tmp_ad_required_impression']); $oTable =& OA_DB_Table_Priority::singleton(); foreach ($oTable->aDefinition['tables'] as $tableName => $aTable) { $oTable->truncateTable($tableName); $oTable->dropTable($tableName); } } }
/** * Method to test the getZonesForecastsForAllZones method. * * Requirements: * Test 1: Test with no Date registered in the service locator, ensure false returned. * Test 2: Test with a Date registered in the service locator, no data in the database, * and ensure no data is returned. * Test 3: Test with forecast data but no actual impressions * Test 3.5: Test with actual data but no forecast impressions * Test 4: Test with data both in, and not in, the current OI, and ensure the correct * data is returned. * Test 5: Repeat Test 4, but with additional zones (that don't have data) in the zones * table. */ function testGetAllZonesImpInv() { $conf = $GLOBALS['_MAX']['CONF']; $oDbh =& OA_DB::singleton(); $oMaxDalMaintenance = new OA_Dal_Maintenance_Priority(); $zoneForecastDefaultZoneImpressions = 0; // $oMaxDalMaintenance->getZoneForecastDefaultZoneImpressions(); // Test 1 $oServiceLocator =& OA_ServiceLocator::instance(); $oServiceLocator->remove('now'); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $this->assertFalse($result); // Test 2 $oDate = new Date(); $oServiceLocator->register('now', $oDate); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $this->assertEqual($result, array(0 => $zoneForecastDefaultZoneImpressions)); // Zone 0 // Test 3 // generate the first zone $aZones = $this->_generateTestZones(1); // only generate previous OI delivered impressions, should return zone 0 only $oDate =& $oServiceLocator->get('now'); $oNewDate = new Date(); $oNewDate->copy($oDate); $oNewDate->subtractSeconds($conf['maintenance']['operationInterval'] * 60 + 1); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate); $this->_generateTestHistory(1, $aDates, 42, 0); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => $zoneForecastDefaultZoneImpressions); $this->assertEqual($result, $expected); // Test 3.5 // generate the second zone $aZones = $this->_generateTestZones(1); // only generate previous OI forecasted impressions, should return zone 0 only $oNewDate = new Date(); $oNewDate->copy($aDates['start']); $oNewDate->subtractSeconds(1); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate); $this->_generateTestHistory(2, $aDates, 0, 37); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => $zoneForecastDefaultZoneImpressions, 2 => $zoneForecastDefaultZoneImpressions); $this->assertEqual($result, $expected); $oDate =& $oServiceLocator->get('now'); DataGenerator::cleanUp(); $oServiceLocator->register('now', $oDate); // Test 4 $oDate =& $oServiceLocator->get('now'); // generate three zone $this->_generateTestZones(3); // set forecast and impressions for OI - 1 $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate); $this->_generateTestHistory(1, $aDates, 42, 100); $this->_generateTestHistory(2, $aDates, 5, 2); $this->_generateTestHistory(3, $aDates, 9999, 9999); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => 42, 2 => 5, 3 => 9999); $this->assertEqual($result, $expected); // Test 5 // New zone must appear in the array with default forecast $aZones = $this->_generateTestZones(1); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $expected = array(0 => $zoneForecastDefaultZoneImpressions, 1 => 42, 2 => 5, 3 => 9999, 4 => $zoneForecastDefaultZoneImpressions); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $this->assertEqual($result, $expected); // register forecast for the OI before, this should not affect current OI forecast $oDate =& $oServiceLocator->get('now'); $aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oDate); $currentOpIntID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']); $this->_generateTestHistory(1, $aDates, 3700, 0); $this->_generateTestHistory(2, $aDates, 300, 0); $this->_generateTestHistory(3, $aDates, 500, 0); $result =& $oMaxDalMaintenance->getZonesForecastsForAllZones(); $this->assertEqual($result, $expected); DataGenerator::cleanUp(); }
/** * A method to return the forecast impressions for a zone, indexed by operation interval, * from the current operation interval through the past week. If no forecast stored in * the database for a given OI, uses average of forecasts found. * * @param integer $zoneId The Zone ID. * @return mixed An array on success, false on failure. The array is of the format: * array( * [operation_interval_id] => array( * ['zone_id'] => zone_id, * ['_impressions'] => forecast_impressions, * ['operation_interval_id'] => operation_interval_id * ) * [operation_interval_id] => array( * ['zone_id'] => zone_id, * ['forecast_impressions'] => forecast_impressions, * ['operation_interval_id'] => operation_interval_id * ) * . * . * . * ) */ function getPreviousWeekZoneForcastImpressions($zoneId) { if (empty($zoneId) || !is_numeric($zoneId)) { OA::debug('Invalid zone ID argument', PEAR_LOG_ERR); return false; } $aConf = $GLOBALS['_MAX']['CONF']; $oServiceLocator =& OA_ServiceLocator::instance(); $oDate =& $oServiceLocator->get('now'); if (!$oDate) { return false; } // Get previous OI $oPreviousOI = new Date($oDate); $oPreviousOI->subtractSeconds(OX_OperationInterval::getOperationInterval() * 60); // Get the start and end ranges of the current week, up to the previous OI $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oPreviousOI); $oDateWeekStart = new Date(); $oDateWeekStart->copy($aDates['end']); $oDateWeekStart->subtractSeconds(SECONDS_PER_WEEK - 1); $oDateWeekEnd = new Date(); $oDateWeekEnd->copy($aDates['end']); // Select the zone forecasts from the database $tableName = $this->_getTablename('data_intermediate_ad'); $oneHourInterval = OA_Dal::quoteInterval(1, 'hour'); $query = "\n SELECT\n SUM(impressions) AS forecast_impressions,\n operation_interval_id AS operation_interval_id,\n interval_start AS interval_start,\n interval_end AS interval_end\n FROM\n {$tableName}\n WHERE\n zone_id = {$zoneId}\n AND operation_interval = {$aConf['maintenance']['operationInterval']}\n AND interval_start >= '" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "'\n AND interval_end <= '" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "'\n AND date_time > DATE_SUB('" . $oDateWeekStart->format('%Y-%m-%d %H:%M:%S') . "', {$oneHourInterval})\n AND date_time < DATE_ADD('" . $oDateWeekEnd->format('%Y-%m-%d %H:%M:%S') . "', {$oneHourInterval})\n AND zone_id != 0\n GROUP BY\n \tinterval_start,\n \tinterval_end,\n \toperation_interval_id\n ORDER BY\n interval_start"; $rc = $this->oDbh->query($query); $totalForecastImpressions = 0; $count = 0; if (!PEAR::isError($rc)) { // Sort the results into an array indexed by the operation interval ID $aFinalResult = array(); while ($aRow = $rc->fetchRow()) { $aFinalResult[$aRow['operation_interval_id']] = array('zone_id' => $zoneId, 'forecast_impressions' => $aRow['forecast_impressions'], 'operation_interval_id' => $aRow['operation_interval_id']); $count++; $totalForecastImpressions += $aRow['forecast_impressions']; } } $averageForecastImpressions = 0; if ($count > 0) { $averageForecastImpressions = floor($totalForecastImpressions / $count); } if ($averageForecastImpressions == 0) { $averageForecastImpressions = $this->getZoneForecastDefaultZoneImpressions(); } // Check each operation interval ID has a forecast impression value, // and if not, set to the system default. for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) { if (!isset($aFinalResult[$operationIntervalID])) { $aFinalResult[$operationIntervalID] = array('zone_id' => $zoneId, 'forecast_impressions' => $averageForecastImpressions, 'operation_interval_id' => $operationIntervalID); } } // Overwrite current OI with previous OI to match the zone forecasting algorithm $currOI = OX_OperationInterval::convertDateToOperationIntervalID($oDate); $prevOI = OX_OperationInterval::previousOperationIntervalID($currOI); $aFinalResult[$currOI]['forecast_impressions'] = $aFinalResult[$prevOI]['forecast_impressions']; // Return data return $aFinalResult; }
/** * A method to test the getOperationInterval() method. */ function testGetOperationInterval() { $this->assertEqual(OX_OperationInterval::getOperationInterval(), $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval']); }
function _getOperationIntervalInfo(&$operationIntervalId, &$operationInterval, &$dateStart, &$dateEnd) { $date = new Date(); $operationInterval = new OX_OperationInterval(); $operationIntervalId = $operationInterval->convertDateToOperationIntervalID($date); $operationInterval = OX_OperationInterval::getOperationInterval(); $aOperationIntervalDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($date); $dateStart = DBC::makeLiteral($aOperationIntervalDates['start']->format(TIMESTAMP_FORMAT)); $dateEnd = DBC::makeLiteral($aOperationIntervalDates['end']->format(TIMESTAMP_FORMAT)); }