/** * A method that can be inherited and used by children classes to get the * required date span of a statistics page. * * @param object $oCaller The calling object. Expected to have the * the following class variables: * $oCaller->aPlugins - An array of statistics fields plugins * $oCaller->oStartDate - Will be set by method * $oCaller->spanDays - Will be set by method * $oCaller->spanWeeks - Will be set by method * $oCaller->spanMonths - Will be set by method * @param array $aParams An array of query parameters for * {@link Admin_DA::fromCache()}. */ function getSpan(&$oCaller, $aParams) { $oStartDate = new Date(date('Y-m-d')); $oStartDate->setHour(0); $oStartDate->setMinute(0); $oStartDate->setSecond(0); // Check span using all plugins foreach ($oCaller->aPlugins as $oPlugin) { $aPluginParams = call_user_func(array($oPlugin, 'getHistorySpanParams')); $aSpan = Admin_DA::fromCache('getHistorySpan', $aParams + $aPluginParams); if (!empty($aSpan['start_date'])) { $oDate = new Date($aSpan['start_date']); $oDate->setTZbyID('UTC'); if ($oDate->before($oStartDate)) { $oDate->convertTZ($oStartDate->tz); $oStartDate = new Date($oDate); } } } $oStartDate->setHour(0); $oStartDate->setMinute(0); $oStartDate->setSecond(0); $oNow = new Date(); $oSpan = new Date_Span(new Date($oStartDate), new Date($oNow->format('%Y-%m-%d'))); // Store the span data required for stats display $oCaller->oStartDate = $oStartDate; $oCaller->spanDays = (int) ceil($oSpan->toDays()); $oCaller->spanWeeks = (int) ceil($oCaller->spanDays / 7) + ($oCaller->spanDays % 7 ? 1 : 0); $oCaller->spanMonths = ($oNow->getYear() - $oStartDate->getYear()) * 12 + ($oNow->getMonth() - $oStartDate->getMonth()) + 1; // Set the caller's aDates span in the event that it's empty if (empty($oCaller->aDates)) { $oCaller->aDates['day_begin'] = $oStartDate->format('%Y-%m-%d'); $oCaller->aDates['day_end'] = $oNow->format('%Y-%m-%d'); } }
public function getExpirationDate() { $startDate = new Date(isset($this->m_data['StartDate']) ? $this->m_data['StartDate'] : 0); $timeSpan = new Date_Span(); $timeSpan->setFromDays($this->m_data['Days']); $startDate->addSpan($timeSpan); return $startDate->getDate(); }
/** * A method to store data about the times that various Maintenance * processes ran. * * @param Date $oStart The time that the script run started. * @param Date $oEnd The time that the script run ended. * @param mixed $oUpdateTo PEAR::Date representing the end of the last * operation interval ID that has been updated, * or NULL, in the case that this information * does not actually apply, and only the * start/end dates of the process run are * relevant. * @param string $tableName The name of the log_matinenance_* table to log into. * Must NOT be a complete table name, ie. no prefix. * @param boolean $setOperationInterval Should the operation intverval value be * logged, or not? * @param string $runTypeField Optional name of DB field to hold $type value. * @param integer $type Optional type of process run performed. */ function setProcessLastRunInfo($oStart, $oEnd, $oUpdateTo, $tableName, $setOperationInterval, $runTypeField = null, $type = null) { $aConf = $GLOBALS['_MAX']['CONF']; // Test input values $oStart and $oEnd are dates if (!is_a($oStart, 'Date') || !is_a($oEnd, 'Date')) { return false; } // Test $oUpdateTo is a date, or null if (!is_a($oUpdateTo, 'Date')) { if (!is_null($oUpdateTo)) { return false; } } // Test $setOperationInterval value is a boolean if (!is_bool($setOperationInterval)) { return false; } // Prepare the duraction to log from the start and end dates $oDuration = new Date_Span(); $oStartDateCopy = new Date(); $oStartDateCopy->copy($oStart); $oEndDateCopy = new Date(); $oEndDateCopy->copy($oEnd); $oDuration->setFromDateDiff($oStartDateCopy, $oEndDateCopy); // Prepare the logging query $tableName = $this->_getTablename($tableName); $query = "\n INSERT INTO\n {$tableName}\n (\n start_run,\n end_run,"; if ($setOperationInterval) { $query .= "\n operation_interval,"; } $query .= "\n duration"; if (!is_null($runTypeField) && !is_null($type)) { $query .= ",\n {$runTypeField}"; } if (!is_null($oUpdateTo)) { $query .= ",\n updated_to"; } $query .= "\n )\n VALUES\n (\n '" . $oStart->format('%Y-%m-%d %H:%M:%S') . "',\n '" . $oEnd->format('%Y-%m-%d %H:%M:%S') . "',"; if ($setOperationInterval) { $query .= "\n {$aConf['maintenance']['operationInterval']},"; } $query .= "\n " . $oDuration->toSeconds(); if (!is_null($runTypeField) && !is_null($type)) { $query .= ",\n {$type}"; } if (!is_null($oUpdateTo)) { $query .= ",\n '" . $oUpdateTo->format('%Y-%m-%d %H:%M:%S') . "'"; } $query .= "\n )"; OA::debug('- Logging maintenance process run information into ' . $tableName, PEAR_LOG_DEBUG); $rows = $this->oDbh->exec($query); if (PEAR::isError($rows)) { return false; } else { return $rows; } }
function getSpendingMoney($accountId, $startDate) { global $badgerDb; $accountManager = new AccountManager($badgerDb); $account = $accountManager->getAccountById($accountId); $account->setType('finished'); $account->setOrder(array(array('key' => 'valutaDate', 'dir' => 'asc'))); $account->setFilter(array(array('key' => 'valutaDate', 'op' => 'ge', 'val' => $startDate), array('key' => 'periodical', 'op' => 'eq', 'val' => false), array('key' => 'exceptional', 'op' => 'eq', 'val' => false))); $sum = new Amount(); $realStartDate = false; while ($currentTransaction = $account->getNextFinishedTransaction()) { if (!$realStartDate) { $realStartDate = $currentTransaction->getValutaDate(); } $sum->add($currentTransaction->getAmount()); } $span = new Date_Span($realStartDate, new Date()); $count = $span->toDays(); if ($count > 0) { $sum->div($count); } return $sum; }
/** * A private method that determines which (if any) operation intervals need the zone * impression forecast values to be updated for ALL zones. * * @access private * @return mixed One of the following three values will be returned, depending on what * ZIF values need to be updated: * - true: Update the ZIF values for all operation intervals. * - false: No ZIF values need to be updated (eg. this is the second, or greater, * time that the MPE has been run in this operation interval, so there * are no new statistics values summarised by the MSE to allow the ZIF * values to be udpated). * - array: An array with the start and end operation interval IDs of the * range to update; the first may be higher than the second, in * the event that the range spans from the end of one week into the * start of the next week. */ function _getUpdateTypeRequired() { OA::debug('- Calculating range of operation intervals which require ZIF update', PEAR_LOG_DEBUG); // Set default return value $return = false; if (is_null($this->oStatisticsUpdatedToDate)) { // The MSE has never been run; there are no stats. Update all operation intervals (with the // default zone forecast value) so that this new installation of OpenX can ran: return true OA::debug(' - No previous maintenance statisitcs run, so update all OIs required', PEAR_LOG_DEBUG); $return = true; } elseif (is_null($this->oPriorityUpdatedToDate)) { // The MPE has never updated zone forecasts before. Update all operation intervals (with the // default zone forecast value) so that this new installation of OpenX can ran: return true OA::debug(' - No previous maintenance priority run, so update all OIs required', PEAR_LOG_DEBUG); $return = true; } elseif (OX_OperationInterval::getOperationInterval() != $this->priorityOperationInterval) { // The operation interval has changed since the last run, force an update all: return true OA::debug(' - OPERATION INTERVAL LENGTH CHANGE SINCE LAST RUN', PEAR_LOG_DEBUG); OA::debug(' - Update of all OIs required', PEAR_LOG_DEBUG); $return = true; } else { // If stats was run after priority, then the maintenance stats updated to date will be equal to, // or after, the maintenance priority updated to date (as the maintenance priority updated to // date is one operation interval ahead of where statistics is) if ($this->oStatisticsUpdatedToDate->equals($this->oPriorityUpdatedToDate) || $this->oStatisticsUpdatedToDate->after($this->oPriorityUpdatedToDate)) { // If a week or more has passed since the last priority update, update all: return true $oSpan = new Date_Span(); $oUpdatedToDateCopy = new Date(); $oUpdatedToDateCopy->copy($this->oPriorityUpdatedToDate); $oDateNowCopy = new Date(); $oDateNowCopy->copy($this->oDateNow); $oSpan->setFromDateDiff($oUpdatedToDateCopy, $oDateNowCopy); if ($oSpan->day >= 7) { OA::debug(' - One week has passed since last run, so update all OIs required', PEAR_LOG_DEBUG); $return = true; } else { // Get the operation intervals for each run $statsOpIntId = OX_OperationInterval::convertDateToOperationIntervalID($this->oStatisticsUpdatedToDate); $priorityOpIntId = OX_OperationInterval::convertDateToOperationIntervalID($this->oPriorityUpdatedToDate); // Always predict one interval ahead of the statistics engine $statsOpIntId = OX_OperationInterval::nextOperationIntervalID($statsOpIntId); // As long as the operation intervals are not in the same interval, priority should be run if ($statsOpIntId != $priorityOpIntId) { OA::debug(' - Found OI range to update', PEAR_LOG_DEBUG); $return = array($priorityOpIntId, $statsOpIntId); } else { OA::debug(' - MPE has already run this operation interval, no ZIF update required', PEAR_LOG_DEBUG); $return = false; } } } } return $return; }
/** * This method check if time span for given dates is greater that daysIntervalThreshold * * @param PEAR:Date $oStartDate * @param PEAR:Date $oEndDate * @param int $daysIntervalThreshold * @return boolean true if time span in days is greater or equal to daysIntervalThreshold, else false */ function _checkDaysIntervalThreshold($oStartDate, $oEndDate, $daysIntervalThreshold = null) { if (!is_numeric($daysIntervalThreshold)) { $daysIntervalThreshold = $GLOBALS['_MAX']['CONF']['performanceStatistics']['defaultDaysIntervalThreshold']; } $span = new Date_Span(); $span->setFromDateDiff($oStartDate, $oEndDate); return $span->toDays() >= $daysIntervalThreshold; }
/** * A private method to calculate average values when an operation interval * has more than one targeting value. * * @access private * @param array $aValues The array of arrays of values to calculate the * averages from. * @param PEAR::Date $oEndDate The end date/time of the operation interval, * to be used for those values where no expiration * date is set. * @return array The array of "average" values. */ function _calculateAverages($aValues, $oEndDate) { if (empty($aValues) || !is_array($aValues)) { return array(); } reset($aValues); while (list(, $aAdValues) = each($aValues)) { if (empty($aAdValues) || !is_array($aAdValues)) { return array(); } if (count($aAdValues) != 10) { return array(); } } if (empty($oEndDate) || !is_a($oEndDate, 'Date')) { return array(); } $counter = 0; $totalSeconds = 0; $aResult = array('ad_required_impressions' => 0, 'ad_requested_impressions' => 0, 'ad_priority' => 0, 'ad_priority_factor' => 0, 'ad_priority_factor_limited' => 0, 'ad_past_zone_traffic_fraction' => 0, 'average' => true); reset($aValues); while (list(, $aAdValues) = each($aValues)) { if ($counter == 0) { $aResult['interval_start'] = $aAdValues['interval_start']; $aResult['interval_end'] = $aAdValues['interval_end']; } $oCreatedDate = new Date($aAdValues['created']); if (is_null($aAdValues['expired'])) { $oExpiredDate = new Date(); $oExpiredDate->copy($oEndDate); } else { $oExpiredDate = new Date($aAdValues['expired']); } $oSpan = new Date_Span(); $oSpan->setFromDateDiff($oCreatedDate, $oExpiredDate); $seconds = $oSpan->toSeconds(); $aResult['ad_required_impressions'] += $aAdValues['ad_required_impressions'] * $seconds; $aResult['ad_requested_impressions'] += $aAdValues['ad_requested_impressions'] * $seconds; $aResult['ad_priority'] += $aAdValues['ad_priority'] * $seconds; $aResult['ad_priority_factor'] += $aAdValues['ad_priority_factor'] * $seconds; $aResult['ad_past_zone_traffic_fraction'] += $aAdValues['ad_past_zone_traffic_fraction'] * $seconds; if ($aAdValues['ad_priority_factor_limited'] == 1) { $aResult['ad_priority_factor_limited'] = 1; } $counter++; $totalSeconds += $seconds; } $aResult['ad_required_impressions'] /= $totalSeconds; $aResult['ad_requested_impressions'] /= $totalSeconds; $aResult['ad_priority'] /= $totalSeconds; $aResult['ad_priority_factor'] /= $totalSeconds; $aResult['ad_past_zone_traffic_fraction'] /= $totalSeconds; return $aResult; }
</a> </span> </td> <td bgcolor="#dddddd" width="10%"><?php echo $row["user_username"]; ?> </td> <td align="center" width="10%"><?php echo $row["replies"]; ?> </td> <td bgcolor="#dddddd" width="150" nowrap="nowrap"> <?php if ($row["latest_reply"]) { echo $last->format("{$df} {$tf}") . '<br /><font color=#999966>('; $span = new Date_Span(); $span->setFromDateDiff($now, $last); printf("%.1f", $span->format("%d")); echo ' ' . $AppUI->_('days ago'); echo ')</font>'; } else { echo $AppUI->_("No replies"); } ?> </td> </tr> <?php //JBF } } ?>
function testGetEcpm() { $revenue = 10; $clicks = 10; $conversions = 5; // Test each type with 0 impressions. $impressions = 0; // CPM $expected = 10; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPM, $revenue, $impressions); $this->assertEqual($expected, $result); // CPC // eCPM = default click ratio * revenue * 1000 $defaultClickRatio = null; $expected = 50; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPC, $revenue, $impressions, $clicks, $conversions, null, null, $defaultClickRatio); $this->assertEqual($expected, $result); $defaultClickRatio = 0.05; $expected = 500; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPC, $revenue, $impressions, $clicks, $conversions, null, null, $defaultClickRatio); $this->assertEqual($expected, $result); // CPA // eCPM = default conversion ratio * revenue * 1000 $defaultConversionRatio = null; $expected = 1; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPA, $revenue, $impressions, $clicks, $conversions, null, null, $defaultClickRatio, $defaultConversionRatio); $this->assertEqual($expected, $result); $defaultConversionRatio = 0.01; $expected = 100; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPA, $revenue, $impressions, $clicks, $conversions, null, null, $defaultClickRatio, $defaultConversionRatio); $this->assertEqual($expected, $result); // Tenancy // eCPM = 0. $expected = 0; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_MT, $revenue, $impressions, $clicks, $conversions, '2009-01-01', '2009-01-14', $defaultClickRatio, $defaultConversionRatio); $this->assertEqual($expected, $result); // Test each type with some impressions $impressions = 100000; // CPM // eCPM = CPM $expected = 10; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPM, $revenue, $impressions); $this->assertEqual($expected, $result); // CPC // eCPM = revenue * clicks / impressions * 1000 $expected = 1; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPC, $revenue, $impressions, $clicks); $this->assertEqual($expected, $result); // CPA // eCPM = revenue * conversions / impressions * 1000 $expected = 0.5; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_CPA, $revenue, $impressions, $clicks, $conversions); $this->assertEqual($expected, $result); // Tenancy // eCPM = (revenue / totalDaysInCampaign) * daysInCampaignSoFar / impressions * 1000 $now = new Date(); $startDate = new Date($now); $endDate = new Date($now); $endDate->addSeconds(60 * 60 * 24 * 10); // 10 days in the future. $span = new Date_Span(); $span->setFromDateDiff($startDate, $endDate); $this->assertEqual(10, $span->toDays()); // Total revenue for tenancy. $revenue = 10000; $revenuePerDay = $revenue / $span->toDays(); $this->assertEqual(1000, $revenuePerDay); // Beginning of campaign (no imps served) $impressions = 0; $expected = 0; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_MT, $revenue, $impressions, $clicks, $conversions, $startDate->getDate(DATE_FORMAT_ISO), $endDate->getDate(DATE_FORMAT_ISO)); $this->assertEqual($expected, $result); // Half way through campaign (40,000 imps served) $impressions = 40000; $startDate->subtractSeconds(60 * 60 * 24 * 5); // We are 5 days into the campaign. $endDate->subtractSeconds(60 * 60 * 24 * 5); $span->setFromDateDiff($startDate, $now); $this->assertEqual(5, $span->toDays()); $span->setFromDateDiff($endDate, $now); $this->assertEqual(5, $span->toDays()); // eCPM = (revenue / totalDaysInCampaign) * daysInCampaignSoFar / impressions * 1000 $expected = 125; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_MT, $revenue, $impressions, $clicks, $conversions, $startDate->getDate(DATE_FORMAT_ISO), $endDate->getDate(DATE_FORMAT_ISO)); $this->assertEqual($expected, $result); // End of campaign (70,000 imps served) $impressions = 70000; $startDate->subtractSeconds(60 * 60 * 24 * 5); // We are 10 days into the campaign. $endDate->subtractSeconds(60 * 60 * 24 * 5); $span->setFromDateDiff($startDate, $now); $this->assertEqual(10, $span->toDays()); $expected = 142.857142857; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_MT, $revenue, $impressions, $clicks, $conversions, $startDate->getDate(DATE_FORMAT_ISO), $endDate->getDate(DATE_FORMAT_ISO)); // Is this the correct margin? $this->assertWithinMargin($expected, $result, 0.0001, "Outside of margin"); // No dates given $expected = 0; $result = OX_Util_Utils::getEcpm(MAX_FINANCE_MT, $revenue, $impressions, $clicks, $conversions, null, null); $this->assertEqual($expected, $result); }
/** * A method to return the number of days in the span, including the start and end days. * * @return integer The number of days in the span. */ function getDaysInSpan() { $oSpan = new Date_Span(); $oSpan->setFromDateDiff($this->oStartDate, $this->oEndDate); return (int) floor($oSpan->toDays()) + 1; }
/** * A method to set the cached vertsion of the template to expire after * a time span * * @param Date_Span $oSpan */ function setCacheLifetime($oSpan) { $this->cache_lifetime = $oSpan->toSeconds(); $this->caching = 2; }
?> </font> </td> <td nowrap="nowrap" align="center"><?php echo $row["forum_topics"]; ?> </td> <td nowrap="nowrap" align="center"><?php echo $row["forum_replies"]; ?> </td> <td width="225"> <?php if ($message_date !== null) { echo $message_date->format("{$df} {$tf}"); $last = new Date_Span(); $last->setFromDateDiff($now, $message_date); echo '<br /><font color=#999966>(' . $AppUI->_('Last post') . ' '; printf("%.1f", $last->format("%d")); echo ' ' . $AppUI->_('days ago') . ') </font>'; $id = $row['message_parent'] < 0 ? $row['message_id'] : $row['message_parent']; echo '<br />> <a href="?m=forums&a=viewer&forum_id=' . $row['forum_id'] . '&message_id=' . $id . '">'; echo '<font color=#777777>' . $row['message_body']; echo $row['message_length'] > $max_msg_length ? '...' : ''; echo '</font></a>'; } else { echo $AppUI->_('No posts'); } ?> </td> </tr>
function testCopy() { $time = new Date_Span(); $time->copy($this->time); $this->assertEquals(sprintf('%d:%d:%d:%d', $this->time->day, $this->time->hour, $this->time->minute, $this->time->second), sprintf('%d:%d:%d:%d', $time->day, $time->hour, $time->minute, $time->second)); }
/** * A method to send the "midnight" reports during maintenance - that * is, the delivery information report, showing what the campaign(s) * have delivered since the last time the report was sendt. * * @access private */ function _runReports() { OA::debug(' Starting to send advertiser "campaign delivery" reports.', PEAR_LOG_DEBUG); // Get all advertisers where the advertiser preference is to send reports OA::debug(' - Getting details of advertisers that require reports to be sent.', PEAR_LOG_DEBUG); $doClients = OA_Dal::factoryDO('clients'); $doClients->report = 't'; $doClients->find(); while ($doClients->fetch()) { $aAdvertiser = $doClients->toArray(); // Don't email report by default $sendReport = false; // Has the report interval date been passed? if (empty($aAdvertiser['reportlastdate'])) { $sendReport = true; $oReportLastDate = null; } else { $oNowDate = new Date(); $oReportLastDate = new Date($aAdvertiser['reportlastdate']); $oSpan = new Date_Span(); $oSpan->setFromDateDiff($oReportLastDate, $oNowDate); $daysSinceLastReport = (int) floor($oSpan->toDays()); if ($daysSinceLastReport >= $aAdvertiser['reportinterval']) { $sendReport = true; } } if ($sendReport) { // Send the advertiser's campaign delivery report $oEmail = new OA_Email(); $oEmail->sendCampaignDeliveryEmail($aAdvertiser, $oReportLastDate); } } OA::debug(' Finished sending advertiser "campaign delivery" reports.', PEAR_LOG_DEBUG); }
</a> </span> </td> <td bgcolor="#dddddd" width="10%"><?php echo $row['user_username']; ?> </td> <td align="center" width="10%"><?php echo $row['replies']; ?> </td> <td bgcolor="#dddddd" width="150" nowrap="nowrap"> <?php if ($row['latest_reply']) { echo $last->format($df . ' ' . $tf) . '<br /><font color=#999966>('; $span = new Date_Span(); $span->setFromDateDiff($now, $last); printf('%.1f', $span->format('%d')); echo ' ' . $AppUI->_('days ago') . ')</font>'; } else { echo $AppUI->_('No replies'); } ?> </td> </tr> <?php } } ?> </table>
/** * The implementation of the OA_Task::run() method that performs * the required task of logging the completion of the MSE process. * * @param PEAR::Date $oEndDate Optional date/time representing the end of the tasks. */ function run($oEndDate = null) { $oServiceLocator =& OA_ServiceLocator::instance(); $oNowDate =& $oServiceLocator->get('now'); if (is_null($oEndDate)) { $oEndDate = new Date(); } // Prepare the duraction to log from the start and end dates $oDuration = new Date_Span(); $oStartDateCopy = new Date(); $oStartDateCopy->copy($oNowDate); $oEndDateCopy = new Date(); $oEndDateCopy->copy($oEndDate); $oDuration->setFromDateDiff($oStartDateCopy, $oEndDateCopy); $message = '- Logging the completion of the maintenance statistics run'; $this->oController->report .= "{$message}.\n"; OA::debug($message, PEAR_LOG_DEBUG); // Determine the type of MSE completion logging required if ($this->oController->updateFinal && $this->oController->updateIntermediate) { // Need to log that both the intermediate and final tables were updated; // however, need to ensure that we log the correct "updated to" times $oUpdateIntermediateToDate = new Date(); $oUpdateIntermediateToDate->copy($this->oController->oUpdateIntermediateToDate); $oUpdateFinalToDate = new Date(); $oUpdateFinalToDate->copy($this->oController->oUpdateFinalToDate); if ($oUpdateIntermediateToDate->equals($oUpdateFinalToDate)) { // The dates are the same, log info with one row $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics'); $doLog_maintenance_statistics->start_run = $oNowDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->end_run = $oEndDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->duration = $oDuration->toSeconds(); $doLog_maintenance_statistics->adserver_run_type = OX_DAL_MAINTENANCE_STATISTICS_UPDATE_BOTH; $doLog_maintenance_statistics->updated_to = $this->oController->oUpdateIntermediateToDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->insert(); } else { // The dates are not the same, log info with two rows $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics'); $doLog_maintenance_statistics->start_run = $oNowDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->end_run = $oEndDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->duration = $oDuration->toSeconds(); $doLog_maintenance_statistics->adserver_run_type = OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI; $doLog_maintenance_statistics->updated_to = $this->oController->oUpdateIntermediateToDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->insert(); $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics'); $doLog_maintenance_statistics->start_run = $oNowDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->end_run = $oEndDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->duration = $oDuration->toSeconds(); $doLog_maintenance_statistics->adserver_run_type = OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR; $doLog_maintenance_statistics->updated_to = $this->oController->oUpdateFinalToDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->insert(); } } else { if ($this->oController->updateIntermediate) { $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics'); $doLog_maintenance_statistics->start_run = $oNowDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->end_run = $oEndDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->duration = $oDuration->toSeconds(); $doLog_maintenance_statistics->adserver_run_type = OX_DAL_MAINTENANCE_STATISTICS_UPDATE_OI; $doLog_maintenance_statistics->updated_to = $this->oController->oUpdateIntermediateToDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->insert(); } else { if ($this->oController->updateFinal) { $doLog_maintenance_statistics = OA_Dal::factoryDO('log_maintenance_statistics'); $doLog_maintenance_statistics->start_run = $oNowDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->end_run = $oEndDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->duration = $oDuration->toSeconds(); $doLog_maintenance_statistics->adserver_run_type = OX_DAL_MAINTENANCE_STATISTICS_UPDATE_HOUR; $doLog_maintenance_statistics->updated_to = $this->oController->oUpdateFinalToDate->format('%Y-%m-%d %H:%M:%S'); $doLog_maintenance_statistics->insert(); } else { return false; } } } // Log the report to the "user log" $this->_setMaintenanceStatisticsRunReport($this->oController->report); return true; }
$cache = new Cache_Lite(array('cacheDir' => $cacheDir, 'lifeTime' => null, 'hashedDirectoryLevel' => 2)); $httpRequest = new HTTP_Request2('http://pear.php.net/feeds/latest.rss'); $response = $httpRequest->send(); $rss = new XML_Feed_Parser($response->getBody()); $oauth = new HTTP_OAuth_Consumer($argv[1], $argv[2], $argv[3], $argv[4]); $twitter = new Services_Twitter(); $twitter->setOAuth($oauth); // Figure out the current time $tz = new Date_TimeZone(date_default_timezone_get()); $now = new Date(); $now->setTZ($tz); $all = array(); foreach ($rss as $feed) { // Is this more than an hour old? If so, skip it. $rssDate = new Date($feed->date); $span = new Date_Span($rssDate, $now); $hoursOld = (int) ceil($span->toHours()); if ($hoursOld > 1) { continue; } $all[$feed->title] = $feed->link; } // Reverse so that we tweet the oldest first $reversed = array_reverse($all, true); $exclamations = array('Cool!', 'Awesome!', 'Great Scott!', 'Sweet!', 'Holy Crap!', 'Sweet sassy molassy!', 'Huzzah!', 'Jiminey crickets!', 'Great horny toads!'); foreach ($reversed as $title => $link) { $key = md5($link); if ($cache->get($key) === false) { $exclamation = $exclamations[rand(0, count($exclamations) - 1)]; $status = "{$exclamation} {$title} was just released! {$link}"; $twitter->statuses->update($status);
?> </div> </td> <td nowrap="nowrap" align="center"><?php echo $row['forum_topics']; ?> </td> <td nowrap="nowrap" align="center"><?php echo $row['forum_replies']; ?> </td> <td width="225"> <?php if ($message_date !== null) { echo $message_date->format("{$df} {$tf}"); $last = new Date_Span(); $last->setFromDateDiff($now, $message_date); echo ' <font color=#999966>('; printf('%.1f', $last->format('%d')); echo ' ' . $AppUI->_('days ago') . ')</font>'; $id = $row['message_parent'] < 0 ? $row['message_id'] : $row['message_parent']; echo '<br /><a href="?m=forums&a=viewer&forum_id=' . $row['forum_id'] . '&message_id=' . $id . '">'; echo '<img style="padding-top: 8px" class="ico" src="images/discuss_private.gif"> '; echo '<font color=#777777>' . $row['message_body'] . ($row['message_length'] > $max_msg_length ? '...' : '') . '</font></a>'; } else { echo $AppUI->_('No posts'); } ?> </td> </tr>
/** * A method to perform basic end-to-end integration testing of the Maintenance * Priority Engine classes for the Ad Server. * * Test 0: Test that no zone forecast or priority data exists to begin with. * Test 1: Run the MPE without any stats, and without the stats engine ever * having been run before. Test that zone forecasts are updated * with the appropriate values, and that the correct priorities are * generated. * Test 2: Run the MPE without any stats, but with the stats engine having * reported that it has run. Test that zone forecasts are updated * with the appropriate values, and that the correct priorities are * generated. * Test 3: Run the MPE again, as for Test 2, but with a later date used as * for when the stats engine reported having run. */ function testAdServer() { // Test 0: Ensure correct number of links in the ad_zone_assoc table $this->assertEqual($this->_azaRows(), 7); // 4 proper associations + 3 default with zone 0 // Test 0: Ensure no links in the ad_zone_assoc table have priority > 0 $this->assertEqual($this->_azaRows(true), 0); // Test 0: Ensure no links in the data_summary_ad_zone_assoc table have priority > 0 $this->assertEqual($this->_dsazaRows(true), 0); // Test 0: Ensure no data in the log_maintenance_priority table $this->_assertLogMaintenance(); // Test 1: Set "current" date for the MPE run $oDate = new Date('2005-06-15 13:01:01'); $this->oServiceLocator->register('now', $oDate); // Test 1: Prepare the MPE object $oMaintenancePriority = new OA_Maintenance_Priority_AdServer(); // Test 1: Store the date before the MPE runs $oTest1BeforeUpdateDate = new Date(); sleep(1); // Ensure that next date is at least 1 second after above... // Test 1: Run the MPE $oMaintenancePriority->updatePriorities(); // Test 1: Store the date after the MPE runs sleep(1); // Ensure that next date is at least 1 second after above... $oTest1AfterUpdateDate = new Date(); // Test 1: Ensure correct number of links in the ad_zone_assoc table $this->assertEqual($this->_azaRows(), 7); // 4 proper associations + 3 default with zone 0 // Test 1: Ensure correct number of links in the ad_zone_assoc table with priority > 0 $this->assertEqual($this->_azaRows(true), 7); // Test 1: Ensure correct number of links in the data_summary_ad_zone_assoc table with priority > $this->assertEqual($this->_dsazaRows(true), 7); // Test 1: Ensure that the priorities in the ad_zone_assoc and data_summary_ad_zone_assoc // tables are set correctly $aTestOneZero = array(); $aTestOneZero['ad_id'] = 1; $aTestOneZero['zone_id'] = 0; $aTestOneZero['priority'] = 11 / 200; // 200 is 10 (default forecast) / 0.05 (factor) $aTestOneZero['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestOneZero['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 11, 'requested_impressions' => 11, 'priority' => $aTestOneZero['priority'], 'priority_factor' => $aTestOneZero['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestOneZero); $aTestTwoZero = array(); $aTestTwoZero['ad_id'] = 2; $aTestTwoZero['zone_id'] = 0; $aTestTwoZero['priority'] = 12 / 200; $aTestTwoZero['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestTwoZero['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 12, 'requested_impressions' => 12, 'priority' => $aTestTwoZero['priority'], 'priority_factor' => $aTestTwoZero['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestTwoZero); $aTestThreeZero = array(); $aTestThreeZero['ad_id'] = 3; $aTestThreeZero['zone_id'] = 0; $aTestThreeZero['priority'] = 6 / 200; $aTestThreeZero['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestThreeZero['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 6, 'requested_impressions' => 6, 'priority' => $aTestThreeZero['priority'], 'priority_factor' => $aTestThreeZero['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestThreeZero); $aTestOneOne = array(); $aTestOneOne['ad_id'] = 1; $aTestOneOne['zone_id'] = 1; $aTestOneOne['priority'] = 10 / 200; // Constant, only priority_factor increases $aTestOneOne['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestOneOne['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 11, 'requested_impressions' => 10, 'priority' => $aTestOneOne['priority'], 'priority_factor' => $aTestOneOne['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestOneOne); $aTestTwoThree = array(); $aTestTwoThree['ad_id'] = 2; $aTestTwoThree['zone_id'] = 3; $aTestTwoThree['priority'] = 8 / 200; // Constant, only priority_factor increases $aTestTwoThree['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestTwoThree['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 12, 'requested_impressions' => 8, 'priority' => $aTestTwoThree['priority'], 'priority_factor' => $aTestTwoThree['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestTwoThree); $aTestThreeThree = array(); $aTestThreeThree['ad_id'] = 3; $aTestThreeThree['zone_id'] = 3; $aTestThreeThree['priority'] = 2 / 200; // Constant, only priority_factor increases $aTestThreeThree['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestThreeThree['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 3, 'requested_impressions' => 2, 'priority' => $aTestThreeThree['priority'], 'priority_factor' => $aTestThreeThree['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestThreeThree); $aTestThreeFour = array(); $aTestThreeFour['ad_id'] = 3; $aTestThreeFour['zone_id'] = 4; $aTestThreeFour['priority'] = 3 / 200; // Constant, only priority_factor increases $aTestThreeFour['priority_factor'] = 1; // Initial priority run, factor starts at 1 $aTestThreeFour['history'][0] = array('operation_interval' => 60, 'operation_interval_id' => 85, 'interval_start' => '2005-06-15 13:00:00', 'interval_end' => '2005-06-15 13:59:59', 'required_impressions' => 3, 'requested_impressions' => 3, 'priority' => $aTestThreeFour['priority'], 'priority_factor' => $aTestThreeFour['priority_factor'], 'past_zone_traffic_fraction' => null); $this->_assertPriority($aTestThreeFour); // Test 1: Ensure that the values in the log_maintenance_priority table are correct $this->_assertLogMaintenance(2, $oTest1BeforeUpdateDate, $oTest1AfterUpdateDate, 60, DAL_PRIORITY_UPDATE_ECPM); // Insert data that indicates that the Maintenance Statistics Engine // has recently updated the available stats, but don't insert any // stats into the tables $this->oServiceLocator =& OA_ServiceLocator::instance(); $startDate = new Date('2005-06-15 14:00:01'); $this->oServiceLocator->register('now', $startDate); $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oMaintenanceStatistics->updateIntermediate = true; $oMaintenanceStatistics->updateFinal = true; $aOiDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($startDate); $oMaintenanceStatistics->oUpdateIntermediateToDate = $aOiDates['end']; $oMaintenanceStatistics->oUpdateFinalToDate = $aOiDates['end']; $this->oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); $oLogCompletion = new OX_Maintenance_Statistics_Task_LogCompletion(); $oLogCompletion->run(); // Test 2: Set "previous" date for the MPE run $oPreviousDate = new Date('2005-06-15 13:01:01'); $previousOperationIntervalID = $currentOperationIntervalID; // Test 2: Set "current" date for the MPE run $oDate = new Date('2005-06-15 14:01:01'); $this->oServiceLocator->register('now', $oDate); // Test 2: Prepare the MPE object $oMaintenancePriority = new OA_Maintenance_Priority_AdServer(); // Test 2: Store the date before the MPE runs $oTest2BeforeUpdateDate = new Date(); sleep(1); // Ensure that next date is at least 1 second after above... // Test 2: Run the MPE $oMaintenancePriority->updatePriorities(); // Test 2: Store the date after the MPE runs sleep(1); // Ensure that next date is at least 1 second after above... $oTest2AfterUpdateDate = new Date(); // Test 2: Ensure correct number of links in the ad_zone_assoc table $this->assertEqual($this->_azaRows(), 7); // 4 proper associations + 3 default with zone 0 // Test 2: Ensure correct number of links in the ad_zone_assoc table with priority > 0 $this->assertEqual($this->_azaRows(true), 7); // Test 2: Ensure correct number of links in the data_summary_ad_zone_assoc table with priority > 0 $this->assertEqual($this->_dsazaRows(true), 14); // Test 2: Ensure that the priorities in the ad_zone_assoc and data_summary_ad_zone_assoc // tables are set correctly $aTestOneZero['priority'] = 12 / 200; $aTestOneZero['priority_factor'] = 1; // Remains at 1, no priority compensation in Zone ID 0 $aTestOneZero['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 12, 'requested_impressions' => 12, 'priority' => $aTestOneZero['priority'], 'priority_factor' => $aTestOneZero['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestOneZero); $aTestTwoZero['priority'] = 12 / 200; $aTestTwoZero['priority_factor'] = 1; // Remains at 1, no priority compensation in Zone ID 0 $aTestTwoZero['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 12, 'requested_impressions' => 12, 'priority' => $aTestTwoZero['priority'], 'priority_factor' => $aTestTwoZero['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestTwoZero); $aTestThreeZero['priority'] = 6 / 200; $aTestThreeZero['priority_factor'] = 1; // Remains at 1, no priority compensation in Zone ID 0 $aTestThreeZero['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 6, 'requested_impressions' => 6, 'priority' => $aTestThreeZero['priority'], 'priority_factor' => $aTestThreeZero['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestThreeZero); $aTestOneOne['priority_factor'] = 1; // Remains at 1, zone was not active $aTestOneOne['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 12, 'requested_impressions' => 10, 'priority' => $aTestOneOne['priority'], 'priority_factor' => $aTestOneOne['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestOneOne); $aTestTwoThree['priority_factor'] = 1; // Remains at 1, zone was not active $aTestTwoThree['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 12, 'requested_impressions' => 8, 'priority' => $aTestTwoThree['priority'], 'priority_factor' => $aTestTwoThree['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestTwoThree); $aTestThreeThree['priority_factor'] = 1; // Remains at 1, zone was not active $aTestThreeThree['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 3, 'requested_impressions' => 2, 'priority' => $aTestThreeThree['priority'], 'priority_factor' => $aTestThreeThree['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestThreeThree); $aTestThreeFour['priority_factor'] = 1; // Remains at 1, zone was not active $aTestThreeFour['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 86, 'interval_start' => '2005-06-15 14:00:00', 'interval_end' => '2005-06-15 14:59:59', 'required_impressions' => 3, 'requested_impressions' => 3, 'priority' => $aTestThreeFour['priority'], 'priority_factor' => $aTestThreeFour['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestThreeFour); // Test 2: Ensure that the values in the log_maintenance_priority table are correct $this->_assertLogMaintenance(2, $oTest1BeforeUpdateDate, $oTest1AfterUpdateDate, 60, DAL_PRIORITY_UPDATE_ECPM); $this->_assertLogMaintenance(6, $oTest2BeforeUpdateDate, $oTest2AfterUpdateDate, 60, DAL_PRIORITY_UPDATE_ECPM); // Insert data that indicates that the Maintenance Statistics Engine // has recently updated the available stats $this->oServiceLocator =& OA_ServiceLocator::instance(); $startDate = new Date('2005-06-19 00:00:01'); $this->oServiceLocator->register('now', $startDate); $oMaintenanceStatistics = new OX_Maintenance_Statistics(); $oMaintenanceStatistics->updateIntermediate = true; $oMaintenanceStatistics->updateFinal = true; $aOiDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($startDate); $oMaintenanceStatistics->oUpdateIntermediateToDate = $aOiDates['end']; $oMaintenanceStatistics->oUpdateFinalToDate = $aOiDates['end']; $this->oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics); $oLogCompletion = new OX_Maintenance_Statistics_Task_LogCompletion(); $oLogCompletion->run(); // Insert some stats for an ad zone combination $doDIA = OA_DAL::factoryDO('data_intermediate_ad'); $doDIA->ad_id = 3; $doDIA->zone_id = 3; $doDIA->impressions = 20; $doDIA->date_time = $aOiDates['start']->getDate(); $doDIA->interval_start = $aOiDates['start']->getDate(); $doDIA->interval_end = $aOiDates['end']->getDate(); $doDIA->operation_interval = 60; $doDIA->operation_interval_id = OX_OperationInterval::convertDateToOperationIntervalID($aOiDates['start']); $doDIA->insert(); // Test 3: Set "current" date for the MPE run $oDate = new Date('2005-06-19 00:01:01'); $this->oServiceLocator->register('now', $oDate); // Test 3: Prepare the MPE object $oMaintenancePriority = new OA_Maintenance_Priority_AdServer(); // Test 3: Store the date before the MPE runs $oTest3BeforeUpdateDate = new Date(); sleep(1); // Ensure that next date is at least 1 second after above... // Test 3: Run the MPE $oMaintenancePriority->updatePriorities(); // Test 3: Store the date after the MPE runs sleep(1); // Ensure that next date is at least 1 second after above... $oTest3AfterUpdateDate = new Date(); $oLastUpdatedTo1 = new Date('2005-06-15 14:00:00'); $oNowUpdatedTo1 = new Date('2005-06-15 15:00:00'); $oSpan = new Date_Span(); $oLastUpdatedTo1Copy = new Date(); $oLastUpdatedTo1Copy->copy($oLastUpdatedTo1); $oNowUpdatedTo1Copy = new Date(); $oNowUpdatedTo1Copy->copy($oNowUpdatedTo1); $oSpan->setFromDateDiff($oLastUpdatedTo1Copy, $oNowUpdatedTo1Copy); $hours1 = $oSpan->toHours(); $oLastUpdatedTo2 = new Date('2005-06-15 15:00:00'); $oNowUpdatedTo2 = new Date('2005-06-19 01:00:00'); $oSpan = new Date_Span(); $oLastUpdatedTo2Copy = new Date(); $oLastUpdatedTo2Copy->copy($oLastUpdatedTo2); $oNowUpdatedTo2Copy = new Date(); $oNowUpdatedTo2Copy->copy($oNowUpdatedTo2); $oSpan->setFromDateDiff($oLastUpdatedTo2Copy, $oNowUpdatedTo2Copy); $hours2 = $oSpan->toHours(); // Test 3: Ensure correct number of links in the ad_zone_assoc table $this->assertEqual($this->_azaRows(), 7); // 4 proper associations + 3 default with zone 0 // Test 3: Ensure correct number of links in the ad_zone_assoc table with priority > 0 $this->assertEqual($this->_azaRows(true), 7); // Test 3: Ensure correct number of links in the data_summary_ad_zone_assoc table with priority > 0 $this->assertEqual($this->_dsazaRows(true), 21); // Test 3: Ensure that the priorities in the ad_zone_assoc and data_summary_ad_zone_assoc // tables are set correctly $aTestOneZero['priority'] = 5 / 200; $aTestOneZero['priority_factor'] = 1; // Remains at 1, no priority compensation in Zone ID 0 $aTestOneZero['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 5, 'requested_impressions' => 5, 'priority' => $aTestOneZero['priority'], 'priority_factor' => $aTestOneZero['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestOneZero); $aTestTwoZero['priority'] = 12 / 200; $aTestTwoZero['priority_factor'] = 1; // Remains at 1, no priority compensation in Zone ID 0 $aTestTwoZero['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 12, 'requested_impressions' => 12, 'priority' => $aTestTwoZero['priority'], 'priority_factor' => $aTestTwoZero['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestTwoZero); $aTestThreeZero['priority'] = 6 / 200; $aTestThreeZero['priority_factor'] = 1; // Remains at 1, no priority compensation in Zone ID 0 $aTestThreeZero['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 6, 'requested_impressions' => 6, 'priority' => $aTestThreeZero['priority'], 'priority_factor' => $aTestThreeZero['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestThreeZero); $aTestOneOne['priority'] = 5 / 200; // Changed, skipped OIs $aTestOneOne['priority_factor'] = 1; // Remains at 1, zone was not active $aTestOneOne['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 5, 'requested_impressions' => 5, 'priority' => $aTestOneOne['priority'], 'priority_factor' => $aTestOneOne['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestOneOne); $aTestTwoThree['priority'] = 12 / 20; // Zone has had some impressions, we have a forecast now $aTestTwoThree['priority_factor'] = 10; // But this ad didn't deliver. Factor increased $aTestTwoThree['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 12, 'requested_impressions' => 12, 'priority' => $aTestTwoThree['priority'], 'priority_factor' => $aTestTwoThree['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestTwoThree); $aTestThreeThree['priority'] = 4 / 20; // Ad/Zone has delivered! $aTestThreeThree['priority_factor'] = 2 / 20; // Overdelivered quite a bit! $aTestThreeThree['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 4, 'requested_impressions' => 4, 'priority' => $aTestThreeThree['priority'], 'priority_factor' => $aTestThreeThree['priority_factor'], 'past_zone_traffic_fraction' => 1); $this->_assertPriority($aTestThreeThree); $aTestThreeFour['priority'] = 2 / 200; // Ad has delivered, but not in this zone $aTestThreeFour['priority_factor'] = 1; // Remains at 1, zone was not active $aTestThreeFour['history'][1] = array('operation_interval' => 60, 'operation_interval_id' => 0, 'interval_start' => '2005-06-19 00:00:00', 'interval_end' => '2005-06-19 00:59:59', 'required_impressions' => 2, 'requested_impressions' => 2, 'priority' => $aTestThreeFour['priority'], 'priority_factor' => $aTestThreeFour['priority_factor'], 'past_zone_traffic_fraction' => 0); $this->_assertPriority($aTestThreeFour); // Test 3: Ensure that the values in the log_maintenance_priority table are correct $this->_assertLogMaintenance(2, $oTest1BeforeUpdateDate, $oTest1AfterUpdateDate, 60, DAL_PRIORITY_UPDATE_ECPM); $this->_assertLogMaintenance(6, $oTest2BeforeUpdateDate, $oTest2AfterUpdateDate, 60, DAL_PRIORITY_UPDATE_ECPM); }
/** * A method to get the hourly revenuo of a monthly tenancy campaign * * Monthly tenancy calculation sponsored by www.admost.nl * * @param array $aInfo The finance information, as returned by _saveSummaryGetAdFinanceInfo * @param Date $oStartDate * @param Date $oEndDate * @param string $table * @return double */ function getMtRevenue($aInfo, $oStartDate, $oEndDate, $table) { OA::debug(sprintf(" - Calculating MT revenue for banner [id%d] between %s and %s:", $aInfo['ad_id'], $oStartDate->format('%Y-%m-%d %H:%M:%S %Z'), $oEndDate->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG); $aConf = $GLOBALS['_MAX']['CONF']; $oMonthStart = new Date($oStartDate); // Set timezone if (!empty($aInfo['advertiser_id'])) { $doClient = OA_Dal::staticGetDO('clients', $aInfo['advertiser_id']); $aAdvertiserPrefs = OA_Preferences::loadAccountPreferences($doClient->account_id, true); if (!empty($aAdvertiserPrefs['timezone'])) { $oMonthStart->convertTZbyID($aAdvertiserPrefs['timezone']); } } // Get ad/zone combinations for the campaign if (!isset($this->aMtRevenueCache[$aInfo['campaign_id']])) { $query = "\n SELECT\n COUNT(*) as cnt\n FROM\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table'][$table], true) . " d JOIN\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " a ON (a.bannerid = d.ad_id)\n WHERE\n a.campaignid = {$aInfo['campaign_id']}\n AND d.date_time >= " . $this->oDbh->quote($oStartDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp') . "\n AND d.date_time <= " . $this->oDbh->quote($oEndDate->format('%Y-%m-%d %H:%M:%S'), 'timestamp'); $this->aMtRevenueCache[$aInfo['campaign_id']] = $this->oDbh->query($query)->fetchOne(); } $oMonthStart->setDay(1); $oMonthStart->setHour(0); $oMonthStart->setMinute(0); $oMonthStart->setSecond(0); OA::debug(sprintf(" - Month start: %s", $oMonthStart->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG); $daysInMonth = $oMonthStart->getDaysInMonth(); OA::debug(sprintf(" - Days in month: %d", $daysInMonth), PEAR_LOG_DEBUG); $oMonthEnd = new Date($oMonthStart); $oMonthEnd->setDay($daysInMonth); $oMonthEnd = $oMonthEnd->getNextDay(); $oMonthEnd->setTZ($oMonthStart->tz); OA::debug(sprintf(" - Month end: %s", $oMonthEnd->format('%Y-%m-%d %H:%M:%S %Z')), PEAR_LOG_DEBUG); $oDiff = new Date_Span(); $oDiff->setFromDateDiff($oMonthEnd, $oMonthStart); $hoursPerMonth = ceil($oDiff->toHours()); OA::debug(sprintf(" - Hours per month: %d", $hoursPerMonth), PEAR_LOG_DEBUG); $oDiff = new Date_Span(); $oDiff->setFromDateDiff($oEndDate, $oStartDate); $hoursPerInterval = ceil($oDiff->toHours()); OA::debug(sprintf(" - Hours per interval: %d", $hoursPerInterval), PEAR_LOG_DEBUG); $adZoneCombinations = $this->aMtRevenueCache[$aInfo['campaign_id']]; OA::debug(sprintf(" - Ad/zone/OI combinations for campaign [id%d]: %d", $aInfo['campaign_id'], $this->aMtRevenueCache[$aInfo['campaign_id']]), PEAR_LOG_DEBUG); $result = $aInfo['revenue'] / $hoursPerMonth * $hoursPerInterval / $adZoneCombinations; OA::debug(sprintf(" - Result: %0.4f", $result), PEAR_LOG_DEBUG); return $result; }
/** * A private method to caclucate the number of days left until a * campaign expires based on the impression, click or conversion * delivery targets & the delivery rate of the campaign to date. * * @param array $aDeliveryData An array of two items. "delivered": * the number of impressions, clicks or * conversions delivered so far; and * "day_of_first": a string in YYYY-MM-DD * format representing the day that the * first impression, click or conversion * was delivered. * @param integer $target The total number of impressions, clicks * or conversions required to be delivered * by the campaign. * @return array An array of three items. "daysLeft": the estimated * number of days remaining until the campaign ends; * "date": the estimated date of expiration; and "date_f" */ function _calculateRemainingDays($aDeliveryData, $target) { global $date_format; $oNowDate = new Date(); $aExpiration = array(); // How many days since the first impression/click/conversion? if (!empty($aDeliveryData['day_of_first'])) { $oFirstDate = new Date($aDeliveryData['day_of_first']); $oSpan = new Date_Span(); $oSpan->setFromDateDiff($oFirstDate, $oNowDate); $daysSinceFirst = ceil($oSpan->toDays()); } else { $daysSinceFirst = 1; } // Have *any* impressions/clicks/conversions been delivered? if (!empty($aDeliveryData["delivered"]) && $aDeliveryData["delivered"] > 0) { $targetRemaining = $target - $aDeliveryData["delivered"]; $deliveryRate = $aDeliveryData["delivered"] / $daysSinceFirst; $daysLeft = (int) round($targetRemaining / $deliveryRate); $oSpan = new Date_Span(); $oSpan->setFromDays($daysLeft); $oEstimatedEndDate = new Date(); $oEstimatedEndDate->addSpan($oSpan); if ($oEstimatedEndDate->before($oNowDate)) { // Ooop! Wrapped into the past - get the biggest possible date $oEstimatedEndDate = new Date('1960-01-01 00:00:00'); $oEstimatedEndDate->subtractSeconds(1); } $estimatedEndDateFormat = $oEstimatedEndDate->format($date_format); $aExpiration = array('daysLeft' => $daysLeft, 'date_f' => $estimatedEndDateFormat, 'date' => $oEstimatedEndDate); } return $aExpiration; }
/** * Calculates the effective CPM (eCPM) * * @param int $revenueType revenue type (CPM, CPA, etc) as defined in constants.php. * @param double $revenue revenue amount, eg 1.55. CPM, CPC, CPA: the rate. Tenancy: the total. * @param int $impressions the number of impressions. * @param int $clicks the number of clicks * @param int $conversions the number of conversions. * @param string $startDate start date of the campaign. Required for tenancy. * @param string $endDate end date of the campaign. Required for tenancy. * @param double defaultClickRatio click ratio to use when there are no impressions. * If null, uses the value in the config file. * @param double defaultConversionRatio conversion ratio to use when there are no impressions. * If null, uses the value in the config file. * * @return double the eCPM */ public static function getEcpm($revenueType, $revenue, $impressions = 0, $clicks = 0, $conversions = 0, $startDate = null, $endDate = null, $defaultClickRatio = null, $defaultConversionRatio = null) { $ecpm = 0.0; switch ($revenueType) { case MAX_FINANCE_CPM: // eCPM = CPM return $revenue; break; case MAX_FINANCE_CPC: if ($impressions != 0) { $ecpm = $revenue * $clicks / $impressions * 1000; } else { if (!$defaultClickRatio) { $defaultClickRatio = $GLOBALS['_MAX']['CONF']['priority']['defaultClickRatio']; } $ecpm = $defaultClickRatio * $revenue * 1000; } break; case MAX_FINANCE_CPA: if ($impressions != 0) { $ecpm = $revenue * $conversions / $impressions * 1000; } else { if (!$defaultConversionRatio) { $defaultConversionRatio = $GLOBALS['_MAX']['CONF']['priority']['defaultConversionRatio']; } $ecpm = $defaultConversionRatio * $revenue * 1000; } break; case MAX_FINANCE_MT: if ($impressions != 0) { if ($startDate && $endDate) { $oStart = new Date($startDate); $oStart->setTZbyID('UTC'); $oEnd = new Date($endDate); $oEnd->setTZbyID('UTC'); $oNow = new Date(date('Y-m-d')); $oNow->setTZbyID('UTC'); $daysInCampaign = new Date_Span(); $daysInCampaign->setFromDateDiff($oStart, $oEnd); $daysInCampaign = ceil($daysInCampaign->toDays()); $daysSoFar = new Date_Span(); $daysSoFar->setFromDateDiff($oStart, $oNow); $daysSoFar = ceil($daysSoFar->toDays()); $ecpm = $revenue / $daysInCampaign * $daysSoFar / $impressions * 1000; } else { // Not valid without start and end dates. $ecpm = 0.0; } } else { $ecpm = 0.0; } break; } return $ecpm; }
/** * A private method for calculating the required and requested impressions, * priority factor, and past zone traffic fraction for an ad/zone pair, based on * data taken from the data_summary_ad_zone_assoc table. The values may be simply * those extracted from the database table, or they may be "average" values, * based on the length of time each of a number of different rows was active for * in the delivery engine. * * @access private * * @param array $aPastPriorityResult A reference to an array of arrays indexed * by ad ID, and then zone ID, with each sub-array * returned containing the details above. * @param array $aResult An array containing the results of a database query, with * the ad_id, zone_id, required_impressions, requested_impressions, * priority_factor, past_zone_traffic_fraction, created and expired * columns from the data_summary_ad_zone_assoc table, representing * these values for a complete (single) operation interval. * May optionally contain the operation_interval, * operation_interval_id, interval_start and interval_end details. * @param Date $oDate The current Date object, taken from the OA_ServiceLocator. * @param array $aPastDeliveryResult Optional array of arrays indexed by ad ID, and then * zone ID, containing details on which ad/zone * combinations already have had their average past * priority information calculated (if any). */ function _calculateAveragePastPriorityValues(&$aPastPriorityResult, $aResult, $oDate, $aPastDeliveryResult = null) { if (is_array($aResult) && !empty($aResult)) { // Loop through the results, and ensure that an array exists for each // ad ID, zone ID pair, and also store the initial values of the data foreach ($aResult as $aRow) { if (!isset($aPastPriorityResult[$aRow['ad_id']])) { $aPastPriorityResult[$aRow['ad_id']] = array(); } if (!isset($aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']])) { $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']] = array('ad_id' => $aRow['ad_id'], 'zone_id' => $aRow['zone_id'], 'required_impressions' => $aRow['required_impressions'], 'requested_impressions' => $aRow['requested_impressions'], 'to_be_delivered' => $aRow['to_be_delivered'], 'priority_factor' => $aRow['priority_factor'], 'past_zone_traffic_fraction' => $aRow['past_zone_traffic_fraction']); if (isset($aRow['operation_interval'])) { $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['operation_interval'] = $aRow['operation_interval']; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['operation_interval_id'] = $aRow['operation_interval_id']; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['interval_start'] = $aRow['interval_start']; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['interval_end'] = $aRow['interval_end']; } } } // As more than one row of past priority information may have been found // in the data, re-loop over the array of results, to see if the values // changed during operation interval the data represents foreach ($aResult as $aRow) { // Compare set values from above, and if there is a difference, // set values to zero, and mark as requiring calculation of the // averate impressions requested and priority factor if (($aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['required_impressions'] != $aRow['required_impressions'] || $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['requested_impressions'] != $aRow['requested_impressions'] || $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['priority_factor'] != $aRow['priority_factor']) && !$aPastDeliveryResult[$aRow['ad_id']][$aRow['zone_id']]['pastPriorityFound']) { $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['required_impressions'] = 0; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['requested_impressions'] = 0; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['to_be_delivered'] = 0; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['priority_factor'] = 0; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['average'] = true; unset($aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['pastPriorityFound']); } else { $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['pastPriorityFound'] = true; } } // Loop again, summing in the impressions, priorities (scaled by the length of time // they were active for) to the values, for those ad/zone combinations that require it foreach ($aResult as $aRow) { // Does this value need to be used to calculate the average? if (!empty($aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['average']) && !$aPastDeliveryResult[$aRow['ad_id']][$aRow['zone_id']]['pastPriorityFound']) { // Add the variable values to the array, multiplied by the number of seconds the // values were active for over the "hour" (not exact, in the event that the // maintenance script is not run spot on the hour, but close enough) $oCreatedDate = new Date($aRow['created']); if (is_null($aRow['expired'])) { $oExpiredDate = new Date(); $oExpiredDate->copy($oDate); } else { $oExpiredDate = new Date($aRow['expired']); } $oSpan = new Date_Span(); $oSpan->setFromDateDiff($oCreatedDate, $oExpiredDate); $seconds = $oSpan->toSeconds(); $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['required_impressions'] += $aRow['required_impressions'] * $seconds; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['requested_impressions'] += $aRow['requested_impressions'] * $seconds; $aPastPriorityResult[$aRow['ad_id']][$aRow['zone_id']]['priority_factor'] += $aRow['priority_factor'] * $seconds; } } // Calculate the average impressions requested and priority factor used, for those // ad/zone combinations that require it if (!empty($aPastPriorityResult)) { foreach ($aPastPriorityResult as $a => $aAd) { if (is_array($aAd) && count($aAd) > 0) { foreach ($aAd as $z => $aZone) { if (!empty($aPastPriorityResult[$a][$z]['average']) && !$aPastPriorityResult[$a][$z]['pastPriorityFound']) { $aPastPriorityResult[$a][$z]['required_impressions'] /= SECONDS_PER_HOUR; $aPastPriorityResult[$a][$z]['requested_impressions'] /= SECONDS_PER_HOUR; $aPastPriorityResult[$a][$z]['priority_factor'] /= SECONDS_PER_HOUR; $aPastPriorityResult[$a][$z]['pastPriorityFound'] = true; } } } } } } }
/** * Set the time span from an array * * Any value can be a float (but it has no sense in seconds), for example: * * <code>array(23.5, 20, 0)</code> * * is interpreted as 23 hours, .5*60 + 20 = 50 minutes and 0 seconds. * * @param array $time items are counted from right to left. First * item is for seconds, second for minutes, third * for hours and fourth for days. If there are * less items than 4, zero (0) is assumed for the * absent values. * * @return bool true on success * @access public */ function setFromArray($time) { if (!is_array($time)) { return false; } $tmp1 = new Date_Span(); if (!$tmp1->setFromSeconds(@array_pop($time))) { return false; } $tmp2 = new Date_Span(); if (!$tmp2->setFromMinutes(@array_pop($time))) { return false; } $tmp1->add($tmp2); if (!$tmp2->setFromHours(@array_pop($time))) { return false; } $tmp1->add($tmp2); if (!$tmp2->setFromDays(@array_pop($time))) { return false; } $tmp1->add($tmp2); return $this->copy($tmp1); }
function getWeeks() { $span = new Date_Span(new Date($this->get('dato_start')), new Date($this->get('dato_slut'))); return round($span->toDays() / 7); }