/** * A method to test the deliveryBlocked() method. */ function testDeliveryBlocked() { OA_setTimeZoneUTC(); $aDeliveryLimitation = array('ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Hour', 'comparison' => '=~', 'data' => '1,5,7,20', 'executionorder' => 1); $oLimitationHour = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); $oDate = new Date('2006-02-07 23:15:45'); for ($i = 0; $i < 24; $i++) { $oDate->addSeconds(SECONDS_PER_HOUR); if ($i == 1 || $i == 5 || $i == 7 || $i == 20) { $this->assertFalse($oLimitationHour->deliveryBlocked($oDate)); } else { $this->assertTrue($oLimitationHour->deliveryBlocked($oDate)); } } // Test timezone $aDeliveryLimitation = array('ad_id' => 1, 'logical' => 'and', 'type' => 'deliveryLimitations:Time:Hour', 'comparison' => '=~', 'data' => '1,5,7,20@Europe/Rome', 'executionorder' => 1); $oLimitationHour = OA_Maintenance_Priority_DeliveryLimitation_Factory::factory($aDeliveryLimitation); $oDate = new Date('2006-02-07 23:15:45'); for ($i = 0; $i < 24; $i++) { $oDate->addSeconds(SECONDS_PER_HOUR); if ($i == 0 || $i == 4 || $i == 6 || $i == 19) { $this->assertFalse($oLimitationHour->deliveryBlocked($oDate)); } else { $this->assertTrue($oLimitationHour->deliveryBlocked($oDate)); } } OA_setTimeZoneLocal(); }
function get_init_time($name) { global $log; $date = new Date(); $log->log("name = $name") ; if ($name == 'end'){ $add_hour = 1; $date->addSeconds(3600); } if ($date->getMinute() ==0 ) { $init_time = $date->getHour() . ":00"; } elseif($date->getMinute() <= 15) { $init_time = $date->getHour() . ":00"; } elseif ($date->getMinute() <= 30) { $init_time = $date->getHour() . ":15"; } elseif ($date->getMinute() <= 45) { $init_time = $date->getHour() . ":30"; } else { $init_time = $date->getHour() . ":45"; } $log->log("init_time $init_time mins:" . $date->getMinute()) ; return $init_time ; }
/** * A method to test the run() method. */ function testRun() { $oServiceLocator =& OA_ServiceLocator::instance(); $aConf =& $GLOBALS['_MAX']['CONF']; $className = 'OX_Dal_Maintenance_Statistics_' . ucfirst(strtolower($aConf['database']['type'])); $mockClassName = 'MockOX_Dal_Maintenance_Statistics_' . ucfirst(strtolower($aConf['database']['type'])); $aConf['maintenance']['operationInterval'] = 60; // Test 1: Test with the bucket data not having been migrated, // and ensure that the DAL calls to de-duplicate and // reject conversions are not made // Set the controller class $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); // Mock the MSE DAL used to de-duplicate conversions, // and set the expectations of the calls to the DAL Mock::generate($className); $oDal = new $mockClassName($this); $oDal->expectNever('deduplicateConversions'); $oDal->expectNever('rejectEmptyVarConversions'); $oDal->OX_Dal_Maintenance_Statistics(); $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal); // Set the controlling class' status and test $oDeDuplicateConversions = new OX_Maintenance_Statistics_Task_DeDuplicateConversions(); $oDeDuplicateConversions->oController->updateIntermediate = false; $oDeDuplicateConversions->run(); $oDal->tally(); // Test 2: Test with the bucket data having been migrated, and // ensure that the DALL calls to de-duplicate and reject // conversions are made correctly // Set the controller class $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); // Mock the MSE DAL used to de-duplicate conversions, // and set the expectations of the calls to the DAL Mock::generate($className); $oDal = new $mockClassName($this); $oDate = new Date('2008-09-08 16:59:59'); $oDate->addSeconds(1); $oDal->expectOnce('deduplicateConversions', array($oDate, new Date('2008-09-08 17:59:59'))); $oDal->expectOnce('rejectEmptyVarConversions', array($oDate, new Date('2008-09-08 17:59:59'))); $oDal->OX_Dal_Maintenance_Statistics(); $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal); // Set the controlling class' status and test $oDeDuplicateConversions = new OX_Maintenance_Statistics_Task_DeDuplicateConversions(); $oDeDuplicateConversions->oController->updateIntermediate = true; $oDeDuplicateConversions->oController->oLastDateIntermediate = new Date('2008-09-08 16:59:59'); $oDeDuplicateConversions->oController->oUpdateIntermediateToDate = new Date('2008-09-08 17:59:59'); $oDeDuplicateConversions->run(); $oDal->tally(); TestEnv::restoreConfig(); }
/** * The implementation of the OA_Task::run() method that performs * the required task of managing conversions. */ function run() { if ($this->oController->updateIntermediate) { // Preapre the start date for the management of conversions $oStartDate = new Date(); $oStartDate->copy($this->oController->oLastDateIntermediate); $oStartDate->addSeconds(1); // Get the MSE DAL to perform the conversion management $oServiceLocator =& OA_ServiceLocator::instance(); $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics'); // Manage conversions $oDal->manageConversions($oStartDate, $this->oController->oUpdateIntermediateToDate); } }
/** * The implementation of the OA_Task::run() method that performs * the required task of migrating data_intermediate_% table data * into the data_summary_% tables. */ function run() { if ($this->oController->updateIntermediate || $this->oController->updateFinal) { $message = '- Saving request, impression, click and conversion data into the final tables.'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); } if ($this->oController->updateFinal) { // Update the hourly summary table $oStartDate = new Date(); $oStartDate->copy($this->oController->oLastDateFinal); $oStartDate->addSeconds(1); $this->_saveSummary($oStartDate, $this->oController->oUpdateFinalToDate); } }
/** * The implementation of the OA_Task::run() method that performs * the required task of de-duplicating and rejecting conversions. */ function run() { if ($this->oController->updateIntermediate) { // Preapre the start date for the de-duplication/rejection $oStartDate = new Date(); $oStartDate->copy($this->oController->oLastDateIntermediate); $oStartDate->addSeconds(1); // Get the MSE DAL to perform the de-duplication $oServiceLocator =& OA_ServiceLocator::instance(); $oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics'); // De-duplicate conversions $oDal->deduplicateConversions($oStartDate, $this->oController->oUpdateIntermediateToDate); // Reject empty variable conversions $oDal->rejectEmptyVarConversions($oStartDate, $this->oController->oUpdateIntermediateToDate); } }
/** * A method to modify an array of history data so that it can be displayed in a format * compatible with the weekly breakdown template. * * @param array $aData A reference to an array of arrays, containing the rows of data. * @param object $oCaller The calling object. Expected to have the the class variable * "statsBreakdown" set. */ function prepareWeekBreakdown(&$aData, $oCaller) { // Only prepare the weekly breakdown if the statsBreakdown // in the caller is set to "week" if ($oCaller->statsBreakdown != 'week') { return; } $beginOfWeek = OA_Admin_DaySpan::getBeginOfWeek(); $aWeekData = array(); ksort($aData); foreach ($aData as $key => $aRowData) { // Get the date for this row's data $oDate = new Date($key); if ($beginOfWeek != 0) { // Need to change the date used for the data so // that the day appears in the correct week $daysToGoback = (int) (SECONDS_PER_DAY * $beginOfWeek); $oDate->subtractSeconds($daysToGoback); } // Get the week this date is in, in YYYY-MM format $week = sprintf('%04d-%02d', $oDate->getYear(), $oDate->getWeekOfYear()); // Prepare the data array for this week, if not set, where // the week is in the "week" index, there is a "data" index // for all the rows that make up the week, and the array // has all the columns of an empty data row if (!isset($aWeekData[$week])) { $aWeekData[$week] = $oCaller->aEmptyRow; $aWeekData[$week]['week'] = $week; $aWeekData[$week]['data'] = array(); } // Add the data from the row to the totals of the week foreach (array_keys($oCaller->aColumns) as $colKey) { $aWeekData[$week][$colKey] += $aRowData[$colKey]; } // Store the row in the week $aWeekData[$week]['data'][$key] = $aRowData; } foreach (array_keys($aWeekData) as $week) { // Now that the totals are complete, fill any // remaining days in the week with empty data $days = count($aWeekData[$week]['data']); if ($days < 7) { // Locate the first day of the week in the days that make // up the week so far ksort($aWeekData[$week]['data']); $key = key($aWeekData[$week]['data']); $oDate = new Date($key); $firstDataDayOfWeek = $oDate->getDayOfWeek(); // Is this after the start of the week? if ($firstDataDayOfWeek > $beginOfWeek) { // Change the date to be the first day of this week $daysToGoback = (int) (SECONDS_PER_DAY * ($firstDataDayOfWeek - $beginOfWeek)); $oDate->subtractSeconds($daysToGoback); } // Check each day in the week for ($counter = 0; $counter < 7; $counter++) { if (is_null($aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')])) { // Set the day's data to the empty row, plus the "day" heading for the day $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')] = $oCaller->aEmptyRow; $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')]['day'] = $oDate->format($GLOBALS['date_format']); } elseif (!is_null($aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')]) && !array_key_exists('day', $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')])) { $aWeekData[$week]['data'][$oDate->format('%Y-%m-%d')]['day'] = $oDate->format($GLOBALS['date_format']); } $oDate->addSeconds(SECONDS_PER_DAY); } } // Ensure the day data is sorted correctly ksort($aWeekData[$week]['data']); // Format all day rows foreach (array_keys($aWeekData[$week]['data']) as $key) { $oCaller->_formatStatsRowRecursive($aWeekData[$week]['data'][$key]); } // Calculate CTR and other columns, making sure that the method is available if (is_callable(array($oCaller, '_summarizeStats'))) { $oCaller->_summarizeStats($aWeekData[$week]); } } // Set the new weekly-formatted data as the new data array to use $aData = $aWeekData; }
function getNextPaymentData($mode = '') { $mode = $mode ? $mode : 'plan'; $balance = $this->data['balance_kp'] + $this->data['balance_kaf'] + $this->data['balance_kat']; $date = new Date($this->data['r_from_date']); $data['pmt_date'] = $mode == 'plan' ? $this->data['xp_pmt_date'] : $this->data['cn_date']; $n = 0; while ($date->format('%Y-%m-%d') != $data['pmt_date']) { $date->addSeconds(24 * 60 * 60); $n++; } $data['xp_pmt_date'] = $this->next_payment_date(); $data['r_from_date'] = $date->format('%Y-%m-%d'); $data['interest'] = round($balance * (0.01 * $this->data['rates_r'] / $this->data['calendar_type']) * $n, 2); $data['fees'] = round($this->data['P_KAT'] * ($this->data['pmt'] - $data['interest']), 2); $data['insurances'] = round($this->data['P_KAF'] * ($this->data['pmt'] - $data['interest']), 2); $data['principal'] = $this->data['pmt'] - $data['interest'] - $data['fees'] - $data['insurances']; $data['balance_kp'] = $this->data['balance_kp'] - $data['principal']; $data['balance_kaf'] = $this->data['balance_kaf'] - $data['insurances']; $data['balance_kat'] = $this->data['balance_kat'] - $data['fees']; $this->load_penalties(); $data['delay'] = $this->data['delay']; $data['penalties'] = $this->data['penalties']; $data['pmt'] = $this->data['pmt'] + $this->data['penalties']; $data['xp_pmt'] = $this->data['pmt']; // <-- esto hay que revisarlo if ($data['balance_kp'] < 0 || $data['balance_kaf'] < 0 || $data['balance_kat'] < 0) { $data['fees'] = $this->data['balance_kat']; $data['insurances'] = $this->data['balance_kaf']; $data['principal'] = $this->data['balance_kp']; $data['balance_kp'] = 0; $data['balance_kaf'] = 0; $data['balance_kat'] = 0; $data['pmt'] = $data['interest'] + $data['fees'] + $data['insurances'] + $data['principal'] + $data['penalties']; $data['xp_pmt'] = 0; } return $data; }
$aRunDates = array(); while ($oOIEnd->before($oEndDate) || $oOIEnd->equals($oEndDate)) { echo "Adding " . $oOIStart->format('%Y-%m-%d %H:%M:%S') . "' -> '" . $oOIEnd->format('%Y-%m-%d %H:%M:%S') . " to the list of run dates<br />\n"; // Store the dates $oStoreStartDate = new Date(); $oStoreStartDate->copy($oOIStart); $oStoreEndDate = new Date(); $oStoreEndDate->copy($oOIEnd); $aRunDates[] = array('start' => $oStoreStartDate, 'end' => $oStoreEndDate); $oOIEnd = OX_OperationInterval::addOperationIntervalTimeSpan($oOIEnd); $oOIStart = OX_OperationInterval::addOperationIntervalTimeSpan($oOIStart); } // The summariseFinal process requires complete hours (not OI's), so record these too $oOIStart = new Date(INTERVAL_START); $oOIEnd = new Date(INTERVAL_START); $oOIEnd->addSeconds(60 * 60 - 1); $aRunHours = array(); while ($oOIEnd->before($oEndDate) || $oOIEnd->equals($oEndDate)) { echo "Adding " . $oOIStart->format('%Y-%m-%d %H:%M:%S') . "' -> '" . $oOIEnd->format('%Y-%m-%d %H:%M:%S') . " to the list of run dates<br />\n"; // Store the dates $oStoreStartDate = new Date(); $oStoreStartDate->copy($oOIStart); $oStoreEndDate = new Date(); $oStoreEndDate->copy($oOIEnd); $aRunHours[] = array('start' => $oStoreStartDate, 'end' => $oStoreEndDate); $oOIEnd->addSeconds(60 * 60); $oOIStart->addSeconds(60 * 60); } // Create and register an instance of the OA_Dal_Maintenance_Statistics DAL class for the following tasks to use $oServiceLocator =& OA_ServiceLocator::instance(); if (!$oServiceLocator->get('OX_Dal_Maintenance_Statistics')) {
echo $tpl->getHeader($pageHeading); echo $widgets->addToolTipLayer(); //Settings formular //help funktions for automatical calculation of pocket money from the finished transactions $standardStartDate = new Date(); $standardStartDate->subtractSeconds(60 * 60 * 24 * 180); $calculatePocketMoneyStartDateField = $widgets->addDateField("startDate", $standardStartDate->getFormatted()); $writeCalcuatedPocketMoneyButton = $widgets->createButton("writePocketMoney", getBadgerTranslation2("forecast", "calculatedPocketMoneyButton"), 'calcPocketMoney2();', "Widgets/accept.gif"); $calculatedPocketMoneyLabel = getBadgerTranslation2("forecast", "calculatedPocketMoneyLabel") . ":"; $writeCalculatedToolTip = $widgets->addToolTip(getBadgerTranslation2("forecast", "calculatedPocketMoneyToolTip")); //field for selecting end date of forecasting $legendSetting = getBadgerTranslation2("forecast", "legendSetting"); $legendGraphs = getBadgerTranslation2("forecast", "legendGraphs"); $endDateLabel = getBadgerTranslation2("forecast", "endDateField") . ":"; $standardEndDate = new Date(); $standardEndDate->addSeconds(60 * 60 * 24 * 180); $endDateField = $widgets->addDateField("endDate", $standardEndDate->getFormatted()); $endDateToolTip = $widgets->addToolTip(getBadgerTranslation2("forecast", "endDateToolTip")); //get accounts from db & field to select the account for forecsatung $am = new AccountManager($badgerDb); $account = array(); while ($currentAccount = $am->getNextAccount()) { $account[$currentAccount->getId()] = $currentAccount->getTitle(); } //Drop down to select account $accountLabel = $widgets->createLabel("selectedAccount", getBadgerTranslation2("forecast", "accountField") . ":", true); $accountField = $widgets->createSelectField("selectedAccount", $account, $us->getProperty('forecastStandardAccount'), getBadgerTranslation2("forecast", "accountToolTip"), true, 'style="width: 10em;"'); //field to select saving target, default is 0 $savingTargetLabel = $widgets->createLabel("savingTarget", getBadgerTranslation2("forecast", "savingTargetField") . ":", true); $savingTargetField = $widgets->createField("savingTarget", 5, 0, getBadgerTranslation2("forecast", "savingTargetToolTip"), true, "text", 'style="width: 10em;"'); //field to insert pocketmoney1
/** * A private method to convert the ZIF update type from _getUpdateTypeRequired() into * a range of operation intervals where all zones require their ZIF values to be updated. * * @access private * @param mixed $type The update type required. Possible values are the same as * those returned from the * {@link OA_Maintenance_Priority_AdServer_Task_ForecastZoneImpressions::getUpdateTypeRequired()} * method. * @return array An array of hashes where keys are operation interval IDs, and * values are PEAR Dates. One element in the array indicates a * contiguous range, two elements indicate a non-contiguous range. */ function _getOperationIntervalRanges($type) { // Initialise result array $aResult = array(); switch (true) { case is_bool($type) && $type === false: // Update none, return an empty array return $aResult; case is_bool($type) && $type === true: // Update all - need one week's worth of operation intervals up until the end // of the operation interval *after* the one that statistics have been updated // to, as we need to predict one interval ahead of now $oStatsDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($this->oDateNow); $oStartDate = new Date(); $oStartDate->copy($oStatsDates['start']); $oStartDate->subtractSeconds(SECONDS_PER_WEEK); $startId = OX_OperationInterval::convertDateToOperationIntervalID($oStartDate); $totalIntervals = OX_OperationInterval::operationIntervalsPerWeek(); break; case is_array($type) && $type[0] < $type[1]: // A contiguous (ie. inter-week) range, where the first operation interval // ID is the lower bound, and the second operation interval ID is the upper // The start operation interval ID is the operation interval ID right after // the operation interval ID that priority was updated to (ie. $type[0]) $aDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($this->oPriorityUpdatedToDate); $oStartDate = $aDates['start']; $startId = OX_OperationInterval::nextOperationIntervalID($type[0], 1); $totalIntervals = $type[1] - $type[0]; break; case is_array($type) && $type[0] > $type[1]: // A non-contiguous range, so calculate as above, but use the first operation // interval ID as the upper bound, and the second operation interval ID as the // lower bound in the proceeding week // The start operation interval ID is the operation interval ID right after // the operation interval ID that priority was updated to (ie. $type[0]) $aDates = OX_OperationInterval::convertDateToNextOperationIntervalStartAndEndDates($this->oPriorityUpdatedToDate); $oStartDate = $aDates['start']; $startId = OX_OperationInterval::nextOperationIntervalID($type[0], 1); $totalIntervals = OX_OperationInterval::operationIntervalsPerWeek() - $type[0] + $type[1]; break; default: OA::debug('OA_Maintenance_Priority_AdServer_Task_ForecastZoneImpressions::getOperationIntRangeByType() called with unexpected type, exiting', PEAR_LOG_CRIT); exit; } // Build the update range array $aRange = array(); $totalIntervalPerWeek = OX_OperationInterval::operationIntervalsPerWeek(); for ($x = $startId, $y = 0; $y < $totalIntervals; $x++, $y++) { if ($x == $totalIntervalPerWeek) { $x = 0; } $aDates = array(); $aDates['start'] = new Date($oStartDate); //->format('%Y-%m-%d %H:%M:%S'); $oEndDate = new Date(); $oEndDate->copy($oStartDate); $oEndDate->addSeconds(OX_OperationInterval::secondsPerOperationInterval() - 1); $aDates['end'] = $oEndDate; //->format('%Y-%m-%d %H:%M:%S'); unset($oEndDate); $aRange[$x] = $aDates; $oStartDate->addSeconds(OX_OperationInterval::secondsPerOperationInterval()); } // Is the update range array a contiguous (inter-weeek) range? if (array_key_exists($totalIntervalPerWeek - 1, $aRange) && array_key_exists(0, $aRange)) { // The range contains the first and the last operation interval IDs, is the // last date before the first date? $oFirstIntervalStartDate = new Date($aRange[0]['start']); $oLastIntervalStartDate = new Date($aRange[$totalIntervalPerWeek - 1]['start']); if ($oLastIntervalStartDate->before($oFirstIntervalStartDate)) { // It's a non-contiguous range, so split into two ranges $aRange1 = array(); $aRange2 = array(); for ($x = $startId; $x < $totalIntervalPerWeek; $x++) { $aRange1[$x] = $aRange[$x]; } for ($x = 0; $x < $startId; $x++) { if (isset($aRange[$x])) { $aRange2[$x] = $aRange[$x]; } } $aResult[] = $aRange1; $aResult[] = $aRange2; return $aResult; } } $aResult[] = $aRange; return $aResult; }
/** * @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; }
/** * 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 obtain the sum of the zone forecast impression value, for all the zones * an advertisement is linked to, cloned out over the advertisement's entire remaining * lifetime in the campaign, with any blocked operation intervals removed. * * Requires that the getActiveAdOperationIntervals() method have previously been * called to function correctly. * * @param PEAR::Date $oNowDate The current date. * @param PEAR::Date $oEndDate The end date of the campaign. Note that if the end * date supplied is not at the end of a day, it will be * converted to be treated as such. * @param array $aCumulativeZoneForecast The cumulative forecast impressions, indexed * by operation interval ID, of all the zones the * advertisement is linked to. * array( * [operation_interval_id] => forecast_impressions, * [operation_interval_id] => forecast_impressions * . * . * . * ) * @return integer The ad's total remaining zone impression forecast for all zone for * the remaining life of the ad. */ function getAdLifetimeZoneImpressionsRemaining($oNowDate, $oEndDate, $aCumulativeZoneForecast) { $totalAdLifetimeZoneImpressionsRemaining = 0; // Test the parameters, if invalid, return zero if (!is_a($oNowDate, 'date') || !is_a($oEndDate, 'date') || !is_array($aCumulativeZoneForecast) || count($aCumulativeZoneForecast) != OX_OperationInterval::operationIntervalsPerWeek()) { OA::debug(' - Invalid parameters to getAdLifetimeZoneImpressionsRemaining, returning 0', PEAR_LOG_ERR); return $totalAdLifetimeZoneImpressionsRemaining; } // Ensure that the end of campaign date is at the end of the day $oEndDateCopy = new Date($oEndDate); $oEndDateCopy->setHour(23); $oEndDateCopy->setMinute(59); $oEndDateCopy->setSecond(59); // Ensure that the $aCumulativeZoneForecast array is sorted by key, so that it can // be accessed by array_slice, regardless of the order that the forecast data was added // to the array ksort($aCumulativeZoneForecast); // Step 1: Calculate the sum of the forecast values from "now" until the end of "today" $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate); $oEndOfToday = new Date($aDates['start']); $oEndOfToday->setTZ($oEndDate->tz); $oEndOfToday->setHour(23); $oEndOfToday->setMinute(59); $oEndOfToday->setSecond(59); $oStart = $aDates['start']; while ($oStart->before($oEndOfToday)) { // Find the Operation Interval ID for this Operation Interval $operationIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($oStart); // As iteration over every OI is required anyway, test to see if // the ad is blocked in this OI; if not, add the forecast values to the // running total if (empty($this->aBlockedOperationIntervalDates[$oStart->format('%Y-%m-%d %H:%M:%S')])) { $totalAdLifetimeZoneImpressionsRemaining += $aCumulativeZoneForecast[$operationIntervalID]; } // Go to the next operation interval in "today" $oStart = OX_OperationInterval::addOperationIntervalTimeSpan($oStart); } // Step 2: Calculate how many times each day of the week occurs between the end of // "today" (i.e. starting "tomorrow morning") and the last day the ad can run $aDays = array(); $oStartOfTomorrow = new Date($oEndOfToday); $oStartOfTomorrow->addSeconds(1); $oTempDate = new Date(); $oTempDate->copy($oStartOfTomorrow); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate); while ($aDates['start']->before($oEndDateCopy)) { // Increase the count for this day of the week $aDays[$aDates['start']->getDayOfWeek()]++; // Go to the next day $oTempDate->addSeconds(SECONDS_PER_DAY); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate); } // Step 3: For every possible day of the week (assuming that day of the week is in the // ad's remaining lifetime), calculate the sum of the forecast values for every // operation interval in that day if (!empty($aDays)) { $operationIntervalsPerDay = OX_OperationInterval::operationIntervalsPerDay(); $oTempDate = new Date($oStartOfTomorrow); $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate); for ($counter = 0; $counter < 7; $counter++) { // Are there any instances of this day in the campaign? if ($aDays[$oTempDate->getDayOfWeek()] > 0) { // Calculate the sum of the zone forecasts for this day of week $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oTempDate); $dayStartOperationIntervalId = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']); $aDayCumulativeZoneForecast = array_slice($aCumulativeZoneForecast, $dayStartOperationIntervalId, $operationIntervalsPerDay); $forecastSum = array_sum($aDayCumulativeZoneForecast); // Multiply this day's forecast sum value by the number of times this // day of week appears in the remainder of the campaign and add the // value to the running total $totalAdLifetimeZoneImpressionsRemaining += $forecastSum * $aDays[$oTempDate->getDayOfWeek()]; } // Go to the next day $oTempDate->addSeconds(SECONDS_PER_DAY); } } // Step 4: Subtract any blocked interval values if ($this->blockedOperationIntervalCount > 0) { OA::debug(" - Subtracting {$this->blockedOperationIntervalCount} blocked intervals", PEAR_LOG_DEBUG); foreach ($this->aBlockedOperationIntervalDates as $aDates) { if ($aDates['start']->after($oEndOfToday)) { $blockedOperationInvervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']); $totalAdLifetimeZoneImpressionsRemaining -= $aCumulativeZoneForecast[$blockedOperationInvervalID]; } } } // Return the calculated value return $totalAdLifetimeZoneImpressionsRemaining; }
/** * A method to test the run() method. */ function testRun() { $oServiceLocator =& OA_ServiceLocator::instance(); $aTypes = array('types' => array(0 => 'request', 1 => 'impression', 2 => 'click'), 'connections' => array(1 => MAX_CONNECTION_AD_IMPRESSION, 2 => MAX_CONNECTION_AD_CLICK)); // Mock the DAL, and set expectations Mock::generate('OX_Dal_Maintenance_Statistics'); $oDal = new MockOX_Dal_Maintenance_Statistics($this); $oDal->expectNever('saveSummary'); $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal); // Set the controller class $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); // Test $oSummariseFinal = new OX_Maintenance_Statistics_Task_SummariseFinal(); $oSummariseFinal->oController->updateIntermediate = false; $oSummariseFinal->oController->updateFinal = false; $oSummariseFinal->run(); $oDal->tally(); // Prepare the dates $olastDateIntermediate = new Date('2006-03-09 10:59:59'); $oStartDate = new Date(); $oStartDate->copy($olastDateIntermediate); $oStartDate->addSeconds(1); $oUpdateIntermediateToDate = new Date('2006-03-09 11:59:59'); // Mock the DAL, and set expectations Mock::generate('OX_Dal_Maintenance_Statistics'); $oDal = new MockOX_Dal_Maintenance_Statistics($this); $oDal->expectNever('saveSummary'); $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal); // Set the controller class $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); // Test $oSummariseFinal = new OX_Maintenance_Statistics_Task_SummariseFinal(); $oSummariseFinal->oController->updateIntermediate = true; $oSummariseFinal->oController->oLastDateIntermediate = $olastDateIntermediate; $oSummariseFinal->oController->oUpdateIntermediateToDate = $oUpdateIntermediateToDate; $oSummariseFinal->oController->updateFinal = false; $oSummariseFinal->run(); $oDal->tally(); // Prepare the dates $olastDateFinal = new Date('2006-03-09 10:59:59'); $oStartDate = new Date(); $oStartDate->copy($olastDateFinal); $oStartDate->addSeconds(1); $oUpdateFinalToDate = new Date('2006-03-09 11:59:59'); // Mock the DAL, and set expectations Mock::generate('OX_Dal_Maintenance_Statistics'); $oDal = new MockOX_Dal_Maintenance_Statistics($this); $oDal->expectOnce('saveSummary', array($oStartDate, $oUpdateFinalToDate, $aTypes, 'data_intermediate_ad', 'data_summary_ad_hourly')); $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal); // Set the controller class $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); // Test $oSummariseFinal = new OX_Maintenance_Statistics_Task_SummariseFinal(); $oSummariseFinal->oController->updateIntermediate = false; $oSummariseFinal->oController->updateFinal = true; $oSummariseFinal->oController->oLastDateFinal = $olastDateFinal; $oSummariseFinal->oController->oUpdateFinalToDate = $oUpdateFinalToDate; $oSummariseFinal->run(); $oDal->tally(); // Prepare the dates $olastDateIntermediate = new Date('2006-03-09 10:59:59'); $oStartDate = new Date(); $oStartDate->copy($olastDateIntermediate); $oStartDate->addSeconds(1); $oUpdateIntermediateToDate = new Date('2006-03-09 11:59:59'); $olastDateFinal = new Date('2006-03-09 10:59:59'); $oStartDate = new Date(); $oStartDate->copy($olastDateFinal); $oStartDate->addSeconds(1); $oUpdateFinalToDate = new Date('2006-03-09 11:59:59'); // Mock the DAL, and set expectations Mock::generate('OX_Dal_Maintenance_Statistics'); $oDal = new MockOX_Dal_Maintenance_Statistics($this); $oDal->expectOnce('saveSummary', array($oStartDate, $oUpdateFinalToDate, $aTypes, 'data_intermediate_ad', 'data_summary_ad_hourly')); $oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal); // Set the controller class $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); // Test $oSummariseFinal = new OX_Maintenance_Statistics_Task_SummariseFinal(); $oSummariseFinal->oController->updateIntermediate = true; $oSummariseFinal->oController->oLastDateIntermediate = $olastDateIntermediate; $oSummariseFinal->oController->oUpdateIntermediateToDate = $oUpdateIntermediateToDate; $oSummariseFinal->oController->updateFinal = true; $oSummariseFinal->oController->oLastDateFinal = $olastDateFinal; $oSummariseFinal->oController->oUpdateFinalToDate = $oUpdateFinalToDate; $oSummariseFinal->run(); $oDal->tally(); }
/** * Returns the Pear Date containing the date/time of beginning * of tomorrow. * * @return PEAR_Date Date of tomorrow at 00:00:00 */ public function getBeginningOfTomorrow() { $tomorrow = new Date(); $tomorrow->copy($this->getDateNow()); $tomorrow->addSeconds(24 * 3600); $tomorrow->setHour('00'); $tomorrow->setMinute('00'); $tomorrow->setSecond('00'); return $tomorrow; }
function importMatching($importedTransaction, $accountId) { global $us; global $badgerDb; static $dateDelta = null; static $amountDelta = null; static $textSimilarity = null; static $categories = null; if (is_null($dateDelta)) { try { $dateDelta = $us->getProperty('matchingDateDelta'); } catch (BadgerException $ex) { $dateDelta = 5; } try { $amountDelta = $us->getProperty('matchingAmountDelta'); } catch (BadgerException $ex) { $amountDelta = 0.1; } try { $textSimilarity = $us->getProperty('matchingTextSimilarity'); } catch (BadgerException $ex) { $textSimilarity = 0.25; } $categoryManager = new CategoryManager($badgerDb); while ($currentCategory = $categoryManager->getNextCategory()) { $categories[$currentCategory->getId()] = preg_split('/[\\n]+/', $currentCategory->getKeywords(), -1, PREG_SPLIT_NO_EMPTY); } } if (!$importedTransaction['valutaDate']) { return $importedTransaction; } $minDate = new Date($importedTransaction['valutaDate']); $minDate->subtractSeconds($dateDelta * 24 * 60 * 60); $maxDate = new Date($importedTransaction['valutaDate']); $maxDate->addSeconds($dateDelta * 24 * 60 * 60); if (!$importedTransaction['amount']) { return $importedTransaction; } $minAmount = new Amount($importedTransaction['amount']); $minAmount->mul(1 - $amountDelta); $maxAmount = new Amount($importedTransaction['amount']); $maxAmount->mul(1 + $amountDelta); $accountManager = new AccountManager($badgerDb); $account = $accountManager->getAccountById($accountId); $account->setFilter(array(array('key' => 'valutaDate', 'op' => 'ge', 'val' => $minDate), array('key' => 'valutaDate', 'op' => 'le', 'val' => $maxDate), array('key' => 'amount', 'op' => 'ge', 'val' => $minAmount), array('key' => 'amount', 'op' => 'le', 'val' => $maxAmount))); $similarTransactions = array(); while ($currentTransaction = $account->getNextTransaction()) { $titleSimilarity = getSimilarity($importedTransaction['title'], $currentTransaction->getTitle(), $textSimilarity); $descriptionSimilarity = getSimilarity($importedTransaction['description'], $currentTransaction->getDescription(), $textSimilarity); $transactionPartnerSimilarity = getSimilarity($importedTransaction['transactionPartner'], $currentTransaction->getTransactionPartner(), $textSimilarity); $currDate = $currentTransaction->getValutaDate(); $impDate = $importedTransaction['valutaDate']; $dateSimilarity = 1 - abs(Date_Calc::dateDiff($currDate->getDay(), $currDate->getMonth(), $currDate->getYear(), $impDate->getDay(), $impDate->getMonth(), $impDate->getYear())) / $dateDelta; $cmpAmount = new Amount($currentTransaction->getAmount()); $impAmount = new Amount($importedTransaction['amount']); $cmpAmount->sub($impAmount); $cmpAmount->abs(); $impAmount->mul($amountDelta); $impAmount->abs(); $amountSimilarity = 1 - $cmpAmount->div($impAmount)->get(); $currentTextSimilarity = ($titleSimilarity + $descriptionSimilarity + $transactionPartnerSimilarity) / 3; // if ($currentTextSimilarity >= $textSimilarity) { $overallSimilarity = ($titleSimilarity + $descriptionSimilarity + $transactionPartnerSimilarity + $dateSimilarity + $amountSimilarity) / 5; //$similarTransactions["$overallSimilarity t:$titleSimilarity d:$descriptionSimilarity tp:$transactionPartnerSimilarity vd:$dateSimilarity a:$amountSimilarity"] = $currentTransaction; $similarTransactions[$overallSimilarity] = $currentTransaction; // } } krsort($similarTransactions); if (count($similarTransactions)) { $importedTransaction['similarTransactions'] = $similarTransactions; return $importedTransaction; } if ($importedTransaction['categoryId']) { return $importedTransaction; } $transactionStrings = array($importedTransaction['title'], $importedTransaction['description'], $importedTransaction['transactionPartner']); foreach ($transactionStrings as $currentTransactionString) { foreach ($categories as $currentCategoryId => $keywords) { foreach ($keywords as $keyword) { if (stripos($currentTransactionString, trim($keyword)) !== false) { $importedTransaction['categoryId'] = $currentCategoryId; break 3; } //if keyword found } //foreach keywords } //foreach categories } //foreach transactionStrings return $importedTransaction; }
public function _commonTest($oMaxDalMaintenance, $priority) { $oNow = new Date(); $doClients = OA_Dal::factoryDO('clients'); $idClient = DataGenerator::generateOne($doClients, true); $agencyId1 = DataGenerator::getReferenceId('agency'); // Test 1 $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId1); $this->assertTrue(is_array($result)); $this->assertEqual(count($result), 0); $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->status = OA_ENTITY_STATUS_RUNNING; $doCampaigns->clientid = $idClient; $oYesterday = new Date(); $oYesterday->subtractSeconds(86400); $oTomorrow = new Date(); $oTomorrow->addSeconds(86400); $doCampaigns->activate_time = $oYesterday->format('%Y-%m-%d %H:%M:%S'); $doCampaigns->expire_time = $oTomorrow->format('%Y-%m-%d %H:%M:%S'); $doCampaigns->priority = '1'; $doCampaigns->active = 1; $doCampaigns->views = 100; $doCampaigns->clicks = 200; $doCampaigns->conversions = 300; $doCampaigns->updated = $oNow->format('%Y-%m-%d %H:%M:%S'); $idCampaign = DataGenerator::generateOne($doCampaigns); $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $idCampaign; $doBanners->active = 1; $doBanners->status = OA_ENTITY_STATUS_RUNNING; $doBanners->acls_updated = $oNow->format('%Y-%m-%d %H:%M:%S'); $doBanners->updated = $oNow->format('%Y-%m-%d %H:%M:%S'); $idBanner = DataGenerator::generateOne($doBanners); $doInterAd = OA_Dal::factoryDO('data_intermediate_ad'); $doInterAd->operation_interval = 60; $doInterAd->operation_interval_id = 0; $doInterAd->ad_id = $idBanner; $doInterAd->day = '2005-06-24'; $doInterAd->creative_id = 0; $doInterAd->zone_id = 1; $doInterAd->requests = 500; $doInterAd->impressions = 475; $doInterAd->clicks = 25; $doInterAd->conversions = 5; $doInterAd->updated = $oNow->format('%Y-%m-%d %H:%M:%S'); $doInterAd->interval_start = '2005-06-24 10:00:00'; $doInterAd->date_time = '2005-06-24 10:00:00'; $doInterAd->interval_end = '2005-06-24 10:59:59'; $doInterAd->hour = 10; $idInterAd = DataGenerator::generateOne($doInterAd); $doInterAd->interval_start = '2005-06-24 11:00:00'; $doInterAd->date_time = '2005-06-24 11:00:00'; $doInterAd->interval_end = '2005-06-24 11:59:59'; $doInterAd->hour = 11; $idInterAd = DataGenerator::generateOne($doInterAd); $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId1); $this->assertTrue(is_array($result)); $this->assertEqual(count($result), 1); foreach ($result as $id => $data) { $this->assertEqual($idCampaign, $id); } $this->assertEqual($result[$idCampaign]['sum_impressions'], 950); $this->assertEqual($result[$idCampaign]['sum_clicks'], 50); $this->assertEqual($result[$idCampaign]['sum_conversions'], 10); // Test 3 $doClients = OA_Dal::factoryDO('clients'); $idClient2 = DataGenerator::generateOne($doClients, true); $agencyId2 = DataGenerator::getReferenceId('agency'); $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->clientid = $idClient2; $doCampaigns->priority = $priority; $doCampaigns->ecpm_enabled = 1; $doCampaigns->status = OA_ENTITY_STATUS_RUNNING; $doCampaigns->revenue_type = MAX_FINANCE_CPC; $this->idCampaign2 = DataGenerator::generateOne($doCampaigns); $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $this->idCampaign2; $doBanners->status = OA_ENTITY_STATUS_RUNNING; $idBanner2 = DataGenerator::generateOne($doBanners); $doInterAd->ad_id = $idBanner2; $idInterAd = DataGenerator::generateOne($doInterAd); // Check that results for agency 1 are still the same $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId1); $this->assertTrue(is_array($result)); $this->assertEqual(count($result), 1); foreach ($result as $id => $data) { $this->assertEqual($idCampaign, $id); } $this->assertEqual($result[$idCampaign]['sum_impressions'], 950); $this->assertEqual($result[$idCampaign]['sum_clicks'], 50); $this->assertEqual($result[$idCampaign]['sum_conversions'], 10); // Check results for agency 2 $result = $oMaxDalMaintenance->getAgencyCampaignsDeliveriesToDate($agencyId2); $this->assertTrue(is_array($result)); $this->assertEqual(count($result), 1); foreach ($result as $id => $data) { $this->assertEqual($this->idCampaign2, $id); } $this->assertEqual($result[$this->idCampaign2]['sum_impressions'], 475); $this->assertEqual($result[$this->idCampaign2]['sum_clicks'], 25); $this->assertEqual($result[$this->idCampaign2]['sum_conversions'], 5); return array($agencyId1, $agencyId2); }
/** * A method to convert a Date into an array containing the start * and end Dates of the operation interval after the operation * interval that the date is in. * * @static * @param Date $oDate The date to convert. * @param integer $operationInterval Optional length of the operation interval * in minutes. If not given, will use the * currently defined operation interval. * @return array An array of the start and end Dates of the operation interval. */ function convertDateToNextOperationIntervalStartAndEndDates($oDate, $operationInterval = 0) { // Get the start and end Dates of the operation interval that // contains the current date $aResult = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate, $operationInterval); // Subtract one second from the start Date $oNewDate = new Date(); $oNewDate->copy($aResult['end']); $oNewDate->addSeconds(1); // Return the result from the new date return OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNewDate, $operationInterval); }
/** * The implementation of the OA_Task::run() method that performs * the required task of determining what operation intervals * and/or hours, if any, need to be updated during the MSE run. */ function run() { $aConf = $GLOBALS['_MAX']['CONF']; $oServiceLocator =& OA_ServiceLocator::instance(); $oNowDate =& $oServiceLocator->get('now'); if (!$oNowDate) { $oNowDate = new Date(); } $this->oController->report = "Maintenance Statistics Report\n"; $this->oController->report .= "=====================================\n\n"; $message = '- Maintenance start run time is ' . $oNowDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oNowDate->tz->getShortName(); $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); // Don't update unless the time is right! $this->oController->updateIntermediate = false; $this->oController->updateFinal = false; // Test to see if a date for when the statistics were last updated // has been set in the service locator (for re-generation of stats) $oLastUpdatedDate =& $oServiceLocator->get('lastUpdatedDate'); // Determine when the last intermediate table update happened if (is_a($oLastUpdatedDate, 'Date')) { $this->oController->oLastDateIntermediate = $oLastUpdatedDate; } else { $this->oController->oLastDateIntermediate = $this->_getMaintenanceStatisticsLastRunInfo(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI, $oNowDate); if (is_null($this->oController->oLastDateIntermediate)) { // The MSE has never run, look to see if delivery data exists $this->oController->oLastDateIntermediate = $this->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI); } } if (is_null($this->oController->oLastDateIntermediate)) { // Could not find a last update date, so don't run MSE $message = '- Maintenance statistics has never been run before, and no logged delivery data was located in '; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); $message = ' the database, so maintenance statistics will not be run for the intermediate tables'; $this->oController->report .= $message . "\n\n"; OA::debug($message, PEAR_LOG_DEBUG); } else { // Found a last update date $message = '- Maintenance statistics last updated intermediate table statistics to ' . $this->oController->oLastDateIntermediate->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateIntermediate->tz->getShortName(); $this->oController->report .= $message . ".\n"; OA::debug($message, PEAR_LOG_DEBUG); // Does the last update date found occur on the end of an operation interval? $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($this->oController->oLastDateIntermediate); if (Date::compare($this->oController->oLastDateIntermediate, $aDates['end']) != 0) { $message = '- Last intermediate table updated to date of ' . $this->oController->oLastDateIntermediate->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateIntermediate->tz->getShortName() . ' is not on the current operation interval boundary'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); $message = '- OPERATION INTERVAL LENGTH CHANGE SINCE LAST RUN'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); $message = '- Extending the time until next update'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); $this->oController->sameOI = false; } // Calculate the date after which the next operation interval-based update can happen $oRequiredDate = new Date(); if ($this->oController->sameOI) { $oRequiredDate->copy($this->oController->oLastDateIntermediate); $oRequiredDate->addSeconds($aConf['maintenance']['operationInterval'] * 60); } else { $oRequiredDate->copy($aDates['end']); } $message = '- Current time must be after ' . $oRequiredDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oRequiredDate->tz->getShortName() . ' for the next intermediate table update to happen'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); if (Date::compare($oNowDate, $oRequiredDate) > 0) { $this->oController->updateIntermediate = true; // Update intermediate tables to the end of the previous (not current) operation interval $aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate); $this->oController->oUpdateIntermediateToDate = new Date(); $this->oController->oUpdateIntermediateToDate->copy($aDates['start']); $this->oController->oUpdateIntermediateToDate->subtractSeconds(1); } else { // An operation interval hasn't passed, so don't update $message = "- At least {$aConf['maintenance']['operationInterval']} minutes have " . 'not passed since the last operation interval update'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); } } // Determine when the last final table update happened if ($oLastUpdatedDate !== false) { $this->oController->oLastDateFinal = $oLastUpdatedDate; } else { $this->oController->oLastDateFinal = $this->_getMaintenanceStatisticsLastRunInfo(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR, $oNowDate); if (is_null($this->oController->oLastDateFinal)) { // The MSE has never run, look to see if delivery data exists $this->oController->oLastDateFinal = $this->_getEarliestLoggedDeliveryData(OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR); } } if (is_null($this->oController->oLastDateFinal)) { // Could not find a last update date, so don't run MSE $message = '- Maintenance statistics has never been run before, and no logged delivery data was located in '; $this->oController->report .= $message . "\n" . OA::debug($message, PEAR_LOG_DEBUG); $message = ' the database, so maintenance statistics will not be run for the final tables'; $this->oController->report .= $message . "\n\n"; OA::debug($message, PEAR_LOG_DEBUG); } else { // Found a last update date $message = '- Maintenance statistics last updated final table statistics to ' . $this->oController->oLastDateFinal->format('%Y-%m-%d %H:%M:%S') . ' ' . $this->oController->oLastDateFinal->tz->getShortName(); $this->oController->report .= $message . ".\n"; OA::debug($message, PEAR_LOG_DEBUG); // Calculate the date after which the next hour-based update can happen $oRequiredDate = new Date(); $oRequiredDate->copy($this->oController->oLastDateFinal); $oRequiredDate->addSeconds(60 * 60); $message = '- Current time must be after ' . $oRequiredDate->format('%Y-%m-%d %H:%M:%S') . ' ' . $oRequiredDate->tz->getShortName() . ' for the next intermediate table update to happen'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); if (Date::compare($oNowDate, $oRequiredDate) > 0) { $this->oController->updateFinal = true; // Update final tables to the end of the previous (not current) hour $this->oController->oUpdateFinalToDate = new Date($oNowDate->format('%Y-%m-%d %H:00:00')); $this->oController->oUpdateFinalToDate->subtractSeconds(1); } else { // An hour hasn't passed, so don't update $message = '- At least 60 minutes have NOT passed since the last final table update'; $this->oController->report .= $message . "\n"; OA::debug($message, PEAR_LOG_DEBUG); } } // Is an update of any type going to happen? if ($this->oController->updateIntermediate || $this->oController->updateFinal) { $message = "- Maintenance statistics will be run"; $this->oController->report .= $message . ".\n"; OA::debug($message, PEAR_LOG_INFO); if ($this->oController->updateIntermediate) { $message = '- The intermediate table statistics will be updated'; $this->oController->report .= $message . ".\n"; OA::debug($message, PEAR_LOG_INFO); } if ($this->oController->updateFinal) { $message = '- The final table statistics will be updated'; $this->oController->report .= $message . ".\n"; OA::debug($message, PEAR_LOG_INFO); } $this->oController->report .= "\n"; } else { $message = "- Maintenance statistics will NOT be run"; $this->oController->report .= $message . ".\n"; OA::debug($message, PEAR_LOG_INFO); $this->oController->report .= "\n"; } }
} else { $aDates = array(); $oDayDate = new Date(); $oDayDate->setDate($day, DATE_FORMAT_TIMESTAMP); if (!empty($hour)) { // If hour is set build day date including hour $aDates['day_hour'] = $oDayDate->format('%Y-%m-%d') . ' ' . $hour; } else { // Build month, day, day_begin and day_end dependends on $howLong switch ($howLong) { case 'm': $aDates['month'] = $oDayDate->format('%Y-%m'); break; case 'w': $aDates['day_begin'] = $oDayDate->format('%Y-%m-%d'); $oDayDate->addSeconds(60 * 60 * 24 * 7); // Add 7 days $aDates['day_end'] = $oDayDate->format('%Y-%m-%d'); break; case 'd': default: $aDates['day'] = $oDayDate->format('%Y-%m-%d'); break; } } } // Restrict to the current manager ID $aParams['agency_id'] = OA_Permission::getAgencyId(); /*-------------------------------------------------------*/ /* Main code */ /*-------------------------------------------------------*/
function _add24Hours($base_date) { $modified_date = new Date($base_date); $modified_date->addSeconds(60 * 60 * 24); return $modified_date; }
/** * A method to update the summary table from the intermediate tables. * * @param PEAR::Date $oStartDate The start date/time to update from. * @param PEAR::Date $oEndDate The end date/time to update to. * @param array $aActions An array of data types to summarise. Contains * two array, the first containing the data types, * and the second containing the connection type * values associated with those data types, if * appropriate. For example: * array( * 'types' => array( * 0 => 'request', * 1 => 'impression', * 2 => 'click' * ), * 'connections' => array( * 1 => MAX_CONNECTION_AD_IMPRESSION, * 2 => MAX_CONNECTION_AD_CLICK * ) * ) * Note that the order of the items must match * the order of the items in the database tables * (e.g. in data_intermediate_ad and * data_summary_ad_hourly for the above example). * @param string $fromTable The name of the intermediate table to summarise * from (e.g. 'data_intermediate_ad'). * @param string $toTable The name of the summary table to summarise to * (e.g. 'data_summary_ad_hourly'). */ function saveSummary($oStartDate, $oEndDate, $aActions, $fromTable, $toTable) { $aConf = $GLOBALS['_MAX']['CONF']; // Check that there are types to summarise if (empty($aActions['types']) || empty($aActions['connections'])) { return; } // How many days does the start/end period span? $days = Date_Calc::dateDiff($oStartDate->getDay(), $oStartDate->getMonth(), $oStartDate->getYear(), $oEndDate->getDay(), $oEndDate->getMonth(), $oEndDate->getYear()); if ($days == 0) { // Save the data $this->_saveSummary($oStartDate, $oEndDate, $aActions, $fromTable, $toTable); } else { // Save each day's data separately for ($counter = 0; $counter <= $days; $counter++) { if ($counter == 0) { // This is the first day $oInternalStartDate = new Date(); $oInternalStartDate->copy($oStartDate); $oInternalEndDate = new Date($oStartDate->format('%Y-%m-%d') . ' 23:59:59'); } elseif ($counter == $days) { // This is the last day $oInternalStartDate = new Date($oEndDate->format('%Y-%m-%d') . ' 00:00:00'); $oInternalEndDate = new Date(); $oInternalEndDate->copy($oEndDate); } else { // This is a day in the middle $oDayDate = new Date(); $oDayDate->copy($oStartDate); $oDayDate->addSeconds(SECONDS_PER_DAY * $counter); $oInternalStartDate = new Date($oDayDate->format('%Y-%m-%d') . ' 00:00:00'); $oInternalEndDate = new Date($oDayDate->format('%Y-%m-%d') . ' 23:59:59'); } $this->_saveSummary($oInternalStartDate, $oInternalEndDate, $aActions, $fromTable, $toTable); } } }
/** * A method to test the getDaysLeftString() method. */ function testGetDaysLeftString() { /* Possible cases for testing: Case 1 -> Campaign without expiration date and without a estimated expiration date yet Case 2 -> Campaign without expiration date and with a estimated expiration date Case 3 -> Campaign with expiration date and without a estimated expiration date Case 4 -> Campaign with expiration date reached Case 5 -> Campaign with expiration date and with estimated expiration date minor than the expiration date Case 6 -> Campaign with expiration date and with estimated expiration date equals to the expiration date Case 7 -> Campaign with expiration date and with estimated expiration date higher than the expiration date */ $GLOBALS['strExpirationDate'] = "Expiration date"; $GLOBALS['strNoExpiration'] = "No expiration date set"; $GLOBALS['strEstimated'] = "Estimated expiration date"; $GLOBALS['strNoExpirationEstimation'] = "No expiration estimated yet"; $GLOBALS['strCampaignStop'] = "Campaign stop"; $GLOBALS['strDaysAgo'] = "days ago"; $GLOBALS['strDaysLeft'] = "Days left"; $GLOBALS['date_format'] = '%d.%m.%Y'; // Case 1 // Test an unlimited campaign without expiration date and without a // estimated expiration date yet $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = 0; $doCampaigns->clicks = 0; $doCampaigns->conversions = 0; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strNoExpiration']); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 2.1 // Test a campaign (an impression limited campaign) without // expiration date and with a estimated expiration date $totalImpressions = 1000; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = $totalImpressions; $doCampaigns->clicks = 0; $doCampaigns->conversions = 0; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert impression delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Delivered 50 impressions in 1 day. So, expect to take 19 days // to deliver remaining 950 $daysLeft = 19; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 2.2 // Test a campaign (click limited campaign) without // expiration date and with a estimated expiration date $totalClicks = 500; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = 0; $doCampaigns->clicks = $totalClicks; $doCampaigns->conversions = 0; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert click delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver // remaining 495 $daysLeft = 99; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 2.3 // Test a campaign (conversion limited campaign) // without expiration date and with a estimated expiration date $totalConversions = 10; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = 0; $doCampaigns->clicks = 0; $doCampaigns->conversions = $totalConversions; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert conversion delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver remaining 9 $daysLeft = 9; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 2.4 // Test a triple limited campaign without expiration date // and with a estimated expiration date $totalImpressions = 1000; $totalClicks = 500; $totalConversions = 10; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = $totalImpressions; $doCampaigns->clicks = $totalClicks; $doCampaigns->conversions = $totalConversions; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert conversion delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Delivered 50 impressions in 1 day. So, expect to take 19 days to // deliver remaining 950 // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver // remaining 495 // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver // remaining 9 // The estimated expiration will be calucalated based on impression targets // or based on click targets or based on conversion targets (following this order). $daysLeft = 19; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $GLOBALS['strNoExpiration']); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 3 // Test a campaign with expiration date and without a estimated expiration date // Prepare a date 10 days in the future $daysLeft = 10; $oDate = new Date(); $oDate->setHour(23); $oDate->setMinute(59); $oDate->setSecond(59); $oDate->addSeconds($daysLeft * SECONDS_PER_DAY); $oDate->toUTC(); // Test an unlimited campaign which expires 10 days in the future $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = 0; $doCampaigns->clicks = 0; $doCampaigns->conversions = 0; $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO); $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $GLOBALS['strNoExpirationEstimation'], 'campaignExpiration' => $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")"); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 4 // Campaign with expiration date reached // Prepare a campaign with expiration date reached $daysExpired = 5; $oDate = new Date(); $oDate->setHour(23); $oDate->setMinute(59); $oDate->setSecond(59); $oDate->subtractSeconds($daysExpired * SECONDS_PER_DAY); $oDate->toUTC(); // Test an unlimited campaign which expired 5 days ago $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = 0; $doCampaigns->clicks = 0; $doCampaigns->conversions = 0; $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO); $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $GLOBALS['strCampaignStop'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $daysExpired . " " . $GLOBALS['strDaysAgo'] . ")"); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 5 // Campaign with expiration date and with estimated // expiration date minor than the expiration date // Prepare a date 25 days in the future $daysLeft = 25; $oDate = new Date(); $oDate->setHour(23); $oDate->setMinute(59); $oDate->setSecond(59); $oDate->addSeconds($daysLeft * SECONDS_PER_DAY); $oDate->toUTC(); $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")"; $totalImpressions = 1000; $totalClicks = 500; $totalConversions = 10; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO); $doCampaigns->views = $totalImpressions; $doCampaigns->clicks = $totalClicks; $doCampaigns->conversions = $totalConversions; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert conversion delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Delivered 50 impressions in 1 day. So, expect to take 19 days to // deliver remaining 950 // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver // remaining 495 // Delivered 1 conversion in 1 day. So, expect to take 9 days to deliver // remaining 9 // The estimated expiration will be calucalated based onimpression targets // or based on click targets or based on conversion targets (following this order). $daysLeft = 19; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 6 // Campaign with expiration date and with estimated // expiration date equals to the expiration date // Prepare a date 19 days in the future $daysLeft = 19; $oDate = new Date(); $oDate->setHour(23); $oDate->setMinute(59); $oDate->setSecond(59); $oDate->addSeconds($daysLeft * SECONDS_PER_DAY); $oDate->toUTC(); $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")"; $totalImpressions = 1000; $totalClicks = 500; $totalConversions = 10; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO); $doCampaigns->views = $totalImpressions; $doCampaigns->clicks = $totalClicks; $doCampaigns->conversions = $totalConversions; $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert conversion delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Delivered 50 impressions in 1 day. So, expect to take 19 days to // deliver remaining 950 // Delivered 5 clicks in 1 day. So, expect to take 99 days to deliver // remaining 495 // Delivered 1 conversion in 1 day. So, expect to take 9 days to // deliver remaining 9 // The estimated expiration will be calucalated based on impression targets // or based on click targets or based on conversion targets (following this order). $daysLeft = 19; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($daysLeft * SECONDS_PER_DAY); $expected = array('estimatedExpiration' => $GLOBALS['strEstimated'] . ": " . $oExpirationDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")", 'campaignExpiration' => $campaignExpiration); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); // Case 7 // Campaign with expiration date and with estimated // expiration date higher than the expiration date // Prepare a date 10 days in the future $daysLeft = 10; $oDate = new Date(); $oDate->setHour(23); $oDate->setMinute(59); $oDate->setSecond(59); $oDate->addSeconds($daysLeft * SECONDS_PER_DAY); $oDate->toUTC(); // Test a triple limited campaign with an expiration date 10 days // in the future $totalImpressions = 1000; $totalClicks = 500; $totalConversions = 10; $doCampaigns = OA_Dal::factoryDO('campaigns'); $doCampaigns->views = $totalImpressions; $doCampaigns->clicks = $totalClicks; $doCampaigns->conversions = $totalConversions; $doCampaigns->expire_time = $oDate->getDate(DATE_FORMAT_ISO); $aData = array('reportlastdate' => array('2007-04-03 18:39:45')); $dg = new DataGenerator(); $dg->setData('clients', $aData); $aCampaignIds = $dg->generate($doCampaigns, 1, true); $campaignId = $aCampaignIds[0]; $campaignExpiration = $GLOBALS['strExpirationDate'] . ": " . $oDate->format('%d.%m.%Y') . " (" . $GLOBALS['strDaysLeft'] . ": " . $daysLeft . ")"; // Link a banner to this campaign $doBanners = OA_Dal::factoryDO('banners'); $doBanners->campaignid = $campaignId; $doBanners->acls_updated = '2007-04-03 18:39:45'; $bannerId = DataGenerator::generateOne($doBanners); // Insert conversion delivery data occurring today $oDate = new Date(); $impressions = 50; $clicks = 5; $conversions = 1; $doDSAH = OA_Dal::factoryDO('data_intermediate_ad'); $doDSAH->day = $oDate->format('%Y-%m-%d'); $doDSAH->hour = 10; $doDSAH->ad_id = $bannerId; $doDSAH->impressions = $impressions; $doDSAH->clicks = $clicks; $doDSAH->conversions = $conversions; $dsahId = DataGenerator::generateOne($doDSAH); // Expiration date is in 10 days // Delivered 50 impressions in 1 day. So, expect to take 19 days to // deliver remaining 950 // Delivered 5 clicks in 1 day. So, expect to take 99 days to // deliver remaining 495 // Delivered 1 conversion in 1 day. So, expect to take 9 days to // deliver remaining 9 // The estimated expiration will be calucalated based on impression targets // or based on click targets or based on conversion targets (following this order) $estimatedDaysLeft = 19; $oExpirationDate = new Date(); $oExpirationDate->copy($oDate); $oExpirationDate->addSeconds($estimatedDaysLeft * SECONDS_PER_DAY); // The extimated expiration is higher than the expiration set by the user // so the value of the extimated expiration will be null because is not a // relevant estimation because the campaign will expire before this estimation. $expected = array('estimatedExpiration' => '', 'campaignExpiration' => $campaignExpiration); $actual = $this->oDalCampaigns->getDaysLeftString($campaignId); $this->assertEqual($actual, $expected); }
/** * 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); } } }
/** * A private method to check if the returned stats may be inaccurate * becuase of an upgrade from a non TZ-enabled version * */ function _checkStatsAccuracy() { $utcUpdate = OA_Dal_ApplicationVariables::get('utc_update'); if (!empty($utcUpdate)) { $oUpdate = new Date($utcUpdate); $oUpdate->setTZbyID('UTC'); // Add 12 hours $oUpdate->addSeconds(3600 * 12); if (!empty($this->aDates['day_begin']) && !empty($this->aDates['day_end'])) { $startDate = new Date($this->aDates['day_begin']); $endDate = new Date($this->aDates['day_end']); if ($oUpdate->after($endDate) || $oUpdate->after($startDate)) { $this->displayInaccurateStatsWarning = true; } } else { // All statistics $this->displayInaccurateStatsWarning = true; } } }
/** * A private method to prepare the report range information from an * OA_Admin_DaySpan object. * * @access private * @param OA_Admin_DaySpan $oDaySpan The OA_Admin_DaySpan object to set * the report range information from. */ function _prepareReportRange($oDaySpan) { global $date_format; if (!empty($oDaySpan)) { $this->_oDaySpan = $oDaySpan; $this->_startDateString = $oDaySpan->getStartDateString($date_format); $this->_endDateString = $oDaySpan->getEndDateString($date_format); } else { $oDaySpan = new OA_Admin_DaySpan(); // take as the start date the date when adds were serverd $aConf = $GLOBALS['_MAX']['CONF']; $oDbh = OA_DB::singleton(); $query = "SELECT MIN(date_time) as min_datetime FROM " . $oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_summary_ad_hourly'], true) . " WHERE 1=1"; $startDate = $oDbh->queryRow($query); $startDate = $startDate['min_datetime']; $oStartDate = new Date($startDate); $oEndDate = new Date(); $oDaySpan->setSpanDays($oStartDate, $oEndDate); $this->_oDaySpan =& $oDaySpan; $this->_startDateString = MAX_Plugin_Translation::translate('Beginning', $this->module, $this->package); $this->_endDateString = $oDaySpan->getEndDateString($date_format); } $utcUpdate = OA_Dal_ApplicationVariables::get('utc_update'); if (!empty($utcUpdate)) { $oUpdate = new Date($utcUpdate); $oUpdate->setTZbyID('UTC'); // Add 12 hours $oUpdate->addSeconds(3600 * 12); $startDate = new Date($oDaySpan->oStartDate); $endDate = new Date($oDaySpan->oEndDate); if ($oUpdate->after($endDate) || $oUpdate->after($startDate)) { $this->_displayInaccurateStatsWarning = true; } } }
/** * A method to return an array containing the days in the span, including the start * and end days, where each day in the array is formatted as a string. * * @param string $format An optional PEAR::Date compatible format string. * @return array An array of the days in the span. */ function getDayArray($format = '%Y-%m-%d') { $aDays = array(); $oDate = new Date(); $oDate->copy($this->oStartDate); while (!$oDate->after($this->oEndDate)) { $aDays[] = $oDate->format($format); $oDate->addSeconds(SECONDS_PER_DAY); } return $aDays; }
$datetest = new Date($date); $datetest->addSeconds(-885427200, true); compare("11/12/1977 01.00.22.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-885427200"); $datetest = new Date($date); $datetest->addSeconds(-917049600, true); compare("10/12/1976 01.00.23.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-917049600"); $datetest = new Date($date); $datetest->addSeconds(-948672000, true); compare("10/12/1975 01.00.24.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-948672000"); $datetest = new Date($date); $datetest->addSeconds(-980294400, true); compare("09/12/1974 01.00.25.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-980294400"); $datetest = new Date($date); $datetest->addSeconds(-1011916800, true); compare("08/12/1973 01.00.26.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-1011916800"); $datetest = new Date($date); $datetest->addSeconds(-1043539200, true); compare("07/12/1972 01.00.27.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-1043539200"); $datetest = new Date($date); $datetest->addSeconds(-1075161600, true); compare("07/12/1971 01.00.28.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-1075161600"); // 23 leap seconds $datetest = new Date($date); $datetest->addSeconds(-1106784000, true); compare("06/12/1970 01.00.28.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-1106784000"); $datetest = new Date($date); $datetest->addSeconds(-1138406400, true); compare("05/12/1969 01.00.28.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-1138406400"); $datetest = new Date($date); $datetest->addSeconds(-1170028800, true); compare("04/12/1968 01.00.28.98765", $datetest->formatLikeSQL("DD/MM/YYYY HH.MI.SS.FFFFF"), "-1170028800");
/** * 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(); }