本文整理汇总了PHP中Date::subtractSeconds方法的典型用法代码示例。如果您正苦于以下问题:PHP Date::subtractSeconds方法的具体用法?PHP Date::subtractSeconds怎么用?PHP Date::subtractSeconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Date
的用法示例。
在下文中一共展示了Date::subtractSeconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: Date
/**
* A method to get the "now" date class, eventually subtracting
* some time
*
* @param int $subtractSeconds
* @return Date
*/
function &getDate($subtractSeconds = 0)
{
$oServiceLocator =& OA_ServiceLocator::instance();
$oNow = new Date($oServiceLocator->get('now'));
if ($subtractSeconds) {
$oNow->subtractSeconds($subtractSeconds);
}
return $oNow;
}
示例2: expandUpdate
public function expandUpdate()
{
$targetFutureCalcDate = getTargetFutureCalcDate();
if ($this->updateMode != self::UPDATE_MODE_ALL) {
return;
}
if ($this->originalRepeatUnit == $this->repeatUnit && $this->originalRepeatFrequency == $this->repeatFrequency) {
if (!is_null($this->originalEndDate)) {
$originalEndDate = $this->originalEndDate;
} else {
$originalEndDate = new Date('9999-01-01');
}
if (!is_null($this->endDate)) {
$endDate = $this->endDate;
} else {
$endDate = new Date('9999-01-01');
}
$this->updateExpandedDates($this->originalBeginDate, $originalEndDate);
if ($this->originalBeginDate->before($this->beginDate)) {
$end = new Date($this->beginDate);
$end->subtractSeconds(24 * 60 * 60);
$this->deletePlannedTransactions($this->originalBeginDate, $end, true);
} else {
if ($this->originalBeginDate->after($this->beginDate)) {
$this->expand($this->beginDate, $this->originalBeginDate);
}
}
if ($originalEndDate->before($endDate)) {
if ($endDate->before($targetFutureCalcDate)) {
$this->expand($originalEndDate, $endDate);
} else {
$this->expand($originalEndDate, $targetFutureCalcDate);
}
} else {
if ($originalEndDate->after($endDate)) {
$start = new Date($endDate);
$start->addSeconds(24 * 60 * 60);
$this->deletePlannedTransactions($start, $originalEndDate, true);
}
}
} else {
//repeat unit or frequency changed, discard all old entries and create from scratch
$this->deletePlannedTransactions(new Date('1000-01-01'), new Date('9999-12-31'), true);
$this->expand(new Date('1000-01-01'), $targetFutureCalcDate);
}
}
示例3: Date
/**
* A method to test the sending of emails from the
* manageCampaigns() method - tests the sending of
* the "campaign activated" emails.
*/
function testManageCampaignsEmailsPlacementActivated()
{
// Set now as 1 week before
$oDateNow = new Date();
$oDateNow->subtractSpan(new Date_Span('7-0-0-0'));
$oServiceLocator =& OA_ServiceLocator::instance();
$oServiceLocator->register('now', $oDateNow);
// Create the required accounts & set the various ID values
$aValues = $this->_createAccounts();
$managerAgencyId = $aValues['managerAgency'];
// Prepare a single placement that is inactive, and has an old
// activation date (so that it will need to be activated)
$aData = array('agencyid' => $managerAgencyId, 'contact' => 'Test Placement Activated Contact', 'email' => 'postmaster@placement.activated', 'reportdeactivate' => 't');
$advertiserId = $this->_insertAdvertiser($aData);
$oDate = new Date();
$oDateStart = new Date();
$oDateStart->copy($oDate);
$oDateStart->subtractSeconds(SECONDS_PER_HOUR + 1);
$aData = array('clientid' => $advertiserId, 'status' => OA_ENTITY_STATUS_AWAITING, 'activate_time' => $oDateStart->format('%Y-%m-%d 00:00:00'));
$campaignId = $this->_insertPlacement($aData);
// Reset now
$oServiceLocator->remove('now');
$aData = array('campaignid' => $campaignId);
$adId = $this->_insertAd($aData);
// Create an instance of the mocked OA_Email class, and set
// expectations on how the class' methods should be called
// based on the above
Mock::generate('OA_Email');
$oEmailMock = new MockOA_Email($this);
$oEmailMock->expectOnce('sendCampaignActivatedDeactivatedEmail', array("{$campaignId}"));
// Register the mocked OA_Email class in the service locator
$oServiceLocator =& OA_ServiceLocator::instance();
$oServiceLocator->register('OA_Email', $oEmailMock);
// Run the manageCampaigns() method and ensure that the correct
// calls to OA_Email were made
$oDate = new Date();
$oFactory = new OX_Dal_Maintenance_Statistics_Factory();
$oDalMaintenanceStatistics = $oFactory->factory();
$report = $oDalMaintenanceStatistics->manageCampaigns($oDate);
$oEmailMock->tally();
// Clean up
DataGenerator::cleanUp();
}
示例4: time
/**
* A method to test the MAX_Delivery_log_logConversion() function.
*/
function test_MAX_Delivery_log_logConversion()
{
$aConf =& $GLOBALS['_MAX']['CONF'];
$aConf['maintenance']['operationInterval'] = 60;
$GLOBALS['_MAX']['NOW'] = time();
$oNowDate = new Date($GLOBALS['_MAX']['NOW']);
$aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oNowDate);
$intervalStart = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$oConversionDate = new Date();
$oConversionDate->copy($oNowDate);
$oConversionDate->subtractSeconds(60);
$_SERVER['REMOTE_ADDR'] = '127.0.0.99';
// Test to ensure that the openXDeliveryLog plugin's data bucket
// table does not exist
$oTable = new OA_DB_Table();
$tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a');
$this->assertFalse($tableExists);
// Test calling the main logging function without any plugins installed,
// to ensure that this does not result in any kind of error
$aConversion = array('action_type' => MAX_CONNECTION_AD_CLICK, 'tracker_type' => MAX_CONNECTION_TYPE_SALE, 'status' => MAX_CONNECTION_STATUS_APPROVED, 'cid' => 2, 'zid' => 3, 'dt' => $GLOBALS['_MAX']['NOW'] - 60, 'window' => 60);
MAX_Delivery_log_logConversion(1, $aConversion);
// Install the openXDeliveryLog plugin
TestEnv::installPluginPackage('openXDeliveryLog', false);
// Test to ensure that the openXDeliveryLog plugin's data bucket
// table now does exist
$tableExists = $oTable->extistsTable($aConf['table']['prefix'] . 'data_bkt_a');
$this->assertTrue($tableExists);
// Ensure that there are is nothing logged in the data bucket table
$doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
$doData_bkt_a->find();
$rows = $doData_bkt_a->getRowCount();
$this->assertEqual($rows, 0);
// Call the conversion logging function
$aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion);
// Ensure that the data was logged correctly
$doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
$doData_bkt_a->find();
$rows = $doData_bkt_a->getRowCount();
$this->assertEqual($rows, 1);
$doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
$doData_bkt_a->server_conv_id = 1;
$doData_bkt_a->find();
$rows = $doData_bkt_a->getRowCount();
$this->assertEqual($rows, 1);
$doData_bkt_a->fetch();
$this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
$this->assertEqual($doData_bkt_a->tracker_id, 1);
$this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
$this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
$this->assertEqual($doData_bkt_a->creative_id, 2);
$this->assertEqual($doData_bkt_a->zone_id, 3);
$this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
$this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
$this->assertEqual($doData_bkt_a->window, 60);
$this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
$this->assertTrue(is_array($aConversionInfo));
$this->assertTrue(is_array($aConversionInfo['deliveryLog:oxLogConversion:logConversion']));
$this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_conv_id'], 1);
$this->assertEqual($aConversionInfo['deliveryLog:oxLogConversion:logConversion']['server_raw_ip'], 'singleDB');
$aConversion['cid'] = 5;
// Call the conversion logging function
$aConversionInfo = MAX_Delivery_log_logConversion(1, $aConversion);
// Ensure that the data was logged correctly
$doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
$doData_bkt_a->find();
$rows = $doData_bkt_a->getRowCount();
$this->assertEqual($rows, 2);
$doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
$doData_bkt_a->server_conv_id = 1;
$doData_bkt_a->find();
$rows = $doData_bkt_a->getRowCount();
$this->assertEqual($rows, 1);
$doData_bkt_a->fetch();
$this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
$this->assertEqual($doData_bkt_a->tracker_id, 1);
$this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
$this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
$this->assertEqual($doData_bkt_a->creative_id, 2);
$this->assertEqual($doData_bkt_a->zone_id, 3);
$this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
$this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
$this->assertEqual($doData_bkt_a->window, 60);
$this->assertEqual($doData_bkt_a->status, MAX_CONNECTION_STATUS_APPROVED);
$doData_bkt_a = OA_Dal::factoryDO('data_bkt_a');
$doData_bkt_a->server_conv_id = 2;
$doData_bkt_a->find();
$rows = $doData_bkt_a->getRowCount();
$this->assertEqual($rows, 1);
$doData_bkt_a->fetch();
$this->assertEqual($doData_bkt_a->server_ip, 'singleDB');
$this->assertEqual($doData_bkt_a->tracker_id, 1);
$this->assertEqual($doData_bkt_a->date_time, $oNowDate->format('%Y-%m-%d %H:%M:%S'));
$this->assertEqual($doData_bkt_a->action_date_time, $oConversionDate->format('%Y-%m-%d %H:%M:%S'));
$this->assertEqual($doData_bkt_a->creative_id, 5);
$this->assertEqual($doData_bkt_a->zone_id, 3);
$this->assertEqual($doData_bkt_a->ip_address, '127.0.0.99');
$this->assertEqual($doData_bkt_a->action, MAX_CONNECTION_AD_CLICK);
//.........这里部分代码省略.........
示例5: manageCampaigns
/**
* A method to activate/deactivate campaigns, based on the date and/or the inventory
* requirements (impressions, clicks and/or conversions). Also sends email reports
* for any campaigns that are activated/deactivated, as well as sending email reports
* for any campaigns that are likely to expire in the near future.
*
* @param Date $oDate The current date/time.
* @return string Report on the campaigns activated/deactivated.
*/
function manageCampaigns($oDate)
{
$aConf = $GLOBALS['_MAX']['CONF'];
$oServiceLocator =& OA_ServiceLocator::instance();
$oEmail =& $oServiceLocator->get('OA_Email');
if ($oEmail === false) {
$oEmail = new OA_Email();
$oServiceLocator->register('OA_Email', $oEmail);
}
$report = "\n";
// Select all campaigns in the system, where:
// The campaign is ACTIVE and:
// - The end date stored for the campaign is not null; or
// - The campaign has a lifetime impression, click or conversion
// target set.
//
// That is:
// - It is possible for the active campaign to be automatically
// stopped, as it has a valid end date. (No limitations are
// applied to those campaigns tested, as the ME may not have
// run for a while, and if so, even campaigns with an end date
// of many, many weeks ago should be tested to ensure they are
// [belatedly] halted.)
// - It is possible for the active campaign to be automatically
// stopped, as it has at leaast one lifetime target that could
// have been reached.
//
// The campaign is INACTIVE and:
// - The start date stored for the campaign is not null; and
// - The weight is greater than zero; and
// - The end date stored for the campaign is either null, or is
// greater than "today" less one day.
//
// That is:
// - It is possible for the inactive campaign to be automatically
// started, as it has a valid start date. (No limitations are
// applied to those campaigns tested, as the ME may not have run
// for a while, and if so, even campaigns with an activation date
// of many, many weeks ago should be tested to ensure they are
// [belatedy] enabled.)
// - The campaign is not in a permanently inactive state, as a
// result of the weight being less then one, which means that
// it cannot be activated.
// - The test to start the campaign is unlikely to fail on account
// of the end date. (Inactive campaigns with start dates may have
// passed the start date, but they may also have passed the end
// date - unfortunately, because the dates are not stored in UTC,
// it's not possible to know exactly which campaigns have passed
// the end date or not, until the values are converted to UTC based
// on the Advertiser Account timezone preference - so it's necessary
// to get some campaigns that might be passed the end date, and do
// the converstion to UTC and test to check.)
$prefix = $this->getTablePrefix();
$oYesterdayDate = new Date();
$oYesterdayDate->copy($oDate);
$oYesterdayDate->subtractSeconds(SECONDS_PER_DAY);
$query = "\n SELECT\n cl.clientid AS advertiser_id,\n cl.account_id AS advertiser_account_id,\n cl.agencyid AS agency_id,\n cl.contact AS contact,\n cl.email AS email,\n cl.reportdeactivate AS send_activate_deactivate_email,\n ca.campaignid AS campaign_id,\n ca.campaignname AS campaign_name,\n ca.views AS targetimpressions,\n ca.clicks AS targetclicks,\n ca.conversions AS targetconversions,\n ca.status AS status,\n ca.activate AS start,\n ca.expire AS end\n FROM\n {$prefix}campaigns AS ca,\n {$prefix}clients AS cl\n WHERE\n ca.clientid = cl.clientid\n AND\n ca.status = " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n AND\n (\n ca.expire " . OA_Dal::notEqualNoDateString() . "\n OR\n (\n ca.views > 0\n OR\n ca.clicks > 0\n OR\n ca.conversions > 0\n )\n )\n UNION ALL\n SELECT\n cl.clientid AS advertiser_id,\n cl.account_id AS advertiser_account_id,\n cl.agencyid AS agency_id,\n cl.contact AS contact,\n cl.email AS email,\n cl.reportdeactivate AS send_activate_deactivate_email,\n ca.campaignid AS campaign_id,\n ca.campaignname AS campaign_name,\n ca.views AS targetimpressions,\n ca.clicks AS targetclicks,\n ca.conversions AS targetconversions,\n ca.status AS status,\n ca.activate AS start,\n ca.expire AS end\n FROM\n {$prefix}campaigns AS ca,\n {$prefix}clients AS cl\n WHERE\n ca.clientid = cl.clientid\n AND\n ca.status != " . $this->oDbh->quote(OA_ENTITY_STATUS_RUNNING, 'integer') . "\n AND\n ca.activate " . OA_Dal::notEqualNoDateString() . "\n AND\n (\n ca.weight > 0\n OR\n ca.priority > 0\n )\n AND\n (\n ca.expire >= " . $this->oDbh->quote($oYesterdayDate->format('%Y-%m-%d'), 'timestamp') . "\n OR\n ca.expire " . OA_Dal::equalNoDateString() . "\n )\n ORDER BY\n advertiser_id";
$rsResult = $this->oDbh->query($query);
if (PEAR::isError($rsResult)) {
return MAX::raiseError($rsResult, MAX_ERROR_DBFAILURE, PEAR_ERROR_DIE);
}
OA::debug('- Found ' . $rsResult->numRows() . ' campaigns to test for activation/deactivation', PEAR_LOG_DEBUG);
while ($aCampaign = $rsResult->fetchRow()) {
if ($aCampaign['status'] == OA_ENTITY_STATUS_RUNNING) {
// The campaign is currently running, look at the campaign
$disableReason = 0;
$canExpireSoon = false;
if ($aCampaign['targetimpressions'] > 0 || $aCampaign['targetclicks'] > 0 || $aCampaign['targetconversions'] > 0) {
// The campaign has an impression, click and/or conversion target,
// so get the sum total statistics for the campaign
$query = "\n SELECT\n SUM(dia.impressions) AS impressions,\n SUM(dia.clicks) AS clicks,\n SUM(dia.conversions) AS conversions\n FROM\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['data_intermediate_ad'], true) . " AS dia,\n " . $this->oDbh->quoteIdentifier($aConf['table']['prefix'] . $aConf['table']['banners'], true) . " AS b\n WHERE\n dia.ad_id = b.bannerid\n AND b.campaignid = {$aCampaign['campaign_id']}";
$rsResultInner = $this->oDbh->query($query);
$valuesRow = $rsResultInner->fetchRow();
if (!is_null($valuesRow['impressions']) || !is_null($valuesRow['clicks']) || !is_null($valuesRow['conversions'])) {
// There were impressions, clicks and/or conversions for this
// campaign, so find out if campaign targets have been passed
if (is_null($valuesRow['impressions'])) {
// No impressions
$valuesRow['impressions'] = 0;
}
if (is_null($valuesRow['clicks'])) {
// No clicks
$valuesRow['clicks'] = 0;
}
if (is_null($valuesRow['conversions'])) {
// No conversions
$valuesRow['conversions'] = 0;
}
if ($aCampaign['targetimpressions'] > 0) {
if ($aCampaign['targetimpressions'] <= $valuesRow['impressions']) {
// The campaign has an impressions target, and this has been
//.........这里部分代码省略.........
示例6: importMatching
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;
}
示例7: array
/**
* 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;
//.........这里部分代码省略.........
示例8: getProcessLastRunInfo
/**
* A method to return data about the times that various Maintenance
* processes ran.
*
* @param string $tableName The name of the log_maintenance_* table to get data from.
* Must be a complete table name, including prefix, if
* required.
* @param array $aAdditionalFields An array of strings, representing any additional
* data fields to return, along with the default
* 'updated_to' field.
* @param string $whereClause Optional string, containing a valid SQL WHERE clause,
* if this is required to limit the results of the log data
* before ordering and returning.
* @param string $orderBy Optional string to specify the DB field used to sort the data
* into DESCENDING order, before selecting the first value. Default
* is 'start_run'.
* @param array $aAlternateInfo Optional array containing two fields, 'tableName', which
* is a string of the name of a raw table which will be searched
* for the earliest date/time, in the event that no valid
* 'updated_to' field could be found in the main table, and 'type',
* which is a string of either value 'oi' or 'hour'. The returned
* 'updated_to' value will either be the end of the operation
* interval (if 'type' is 'oi') or the end of the hour (if 'type'
* is 'hour') prior to any date/time found in the alternate raw
* table. Note that if the alternate raw table is used, then ONLY
* the 'updated_to' value is returned - any $aAdditionalFields
* values will be ignored.
* @return mixed False on error, null no no result, otherwise, an array containing the
* 'updated_to' field, which represents the time that the Maintenance
* process last completed updating data until, as well as any additional
* fields (see $aAdditionalFields parameter), unless the alternate raw table
* was used (see $alternateRawTableName parameter).
*/
function getProcessLastRunInfo($tableName, $aAdditionalFields = array(), $whereClause = null, $orderBy = 'start_run', $aAlternateInfo = array())
{
$aConf = $GLOBALS['_MAX']['CONF'];
// Test input values $aAdditionalFields and $aAlternateInfo are arrays
if (!is_array($aAdditionalFields) || !is_array($aAlternateInfo)) {
return false;
}
$query = "\n SELECT\n updated_to";
if (!empty($aAdditionalFields)) {
$query .= ', ' . implode(', ', $aAdditionalFields);
}
$tableName = $this->_getTablename($tableName);
$query .= "\n FROM\n {$tableName}";
if (!is_null($whereClause)) {
$query .= "\n {$whereClause}";
}
$query .= "\n ORDER BY {$orderBy} DESC\n LIMIT 1";
OA::debug('- Obtaining maintenance process run information from ' . $tableName, PEAR_LOG_DEBUG);
$rc = $this->oDbh->query($query);
if (PEAR::isError($rc)) {
return false;
}
$aResult = $rc->fetchRow();
if (!is_null($aResult)) {
// The process run information was found, return.
return $aResult;
}
if (!empty($aAlternateInfo['tableName']) && !empty($aAlternateInfo['type'])) {
// No result was found above, and an alternate raw table was specified,
// so search the raw table to see if a valid result can be generated
// on the basis of the earliest raw data value
$tableName = $this->_getTablename($aAlternateInfo['tableName']);
$query = "\n SELECT\n date_time AS date\n FROM\n {$tableName}\n ORDER BY date ASC\n LIMIT 1";
OA::debug('- Maintenance process run information not found - trying to get data from ' . $aAlternateInfo['tableName'], PEAR_LOG_DEBUG);
$rc = $this->oDbh->query($query);
if (PEAR::isError($rc)) {
return false;
}
if ($rc->numRows() > 0) {
// A raw data result was found - convert it to the end of the previous
// operation interval, or hour
$aResult = $rc->fetchRow();
$oDate = new Date($aResult['date']);
if ($aAlternateInfo['type'] == 'oi') {
$aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
$oResultDate = $aDates['start'];
} else {
if ($aAlternateInfo['type'] == 'hour') {
$oResultDate = new Date($oDate->format('%Y-%m-%d %H:00:00'));
}
}
$oResultDate->subtractSeconds(1);
return array('updated_to' => $oResultDate->format('%Y-%m-%d %H:%M:%S'));
}
}
// No result found, return null
return null;
}
示例9: convertStartEndDate
function convertStartEndDate(&$oStartDate, &$oEndDate, $oTimezone)
{
if (isset($oStartDate)) {
$oStartTz = new Date($oStartDate);
$oStartTz->convertTZ($oTimezone);
$oStartTz->setHour(0);
$oStartTz->setMinute(0);
$oStartTz->setSecond(0);
if ($oStartTz->after($oStartDate)) {
$oStartTz->subtractSpan(new Date_Span('1-0-0-0'));
}
} else {
$oStartTz = null;
}
if (!isset($oEndDate)) {
$oEndDate = new Date();
}
$oEndTz = new Date($oEndDate);
$oEndTz->convertTZ($oTimezone);
$oEndTz->setHour(0);
$oEndTz->setMinute(0);
$oEndTz->setSecond(0);
$oEndTz->subtractSeconds(1);
if ($oEndTz->after($oEndDate)) {
$oEndTz->subtractSpan(new Date_Span('1-0-0-0'));
}
$oStartDate = $oStartTz;
$oEndDate = $oEndTz;
}
示例10: WidgetEngine
require_once BADGER_ROOT . '/modules/account/AccountManager.class.php';
require_once BADGER_ROOT . '/modules/account/accountCommon.php';
$pageHeading = getBadgerTranslation2('forecast', 'title');
$widgets = new WidgetEngine($tpl);
$widgets->addToolTipJS();
$widgets->addCalendarJS();
$widgets->addJSValMessages();
$tpl->addJavaScript("js/prototype.js");
$tpl->addJavaScript("js/forecast.js");
$widgets->addNavigationHead();
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();
示例11: Date
/**
* A method to test the getPreviousWeekZoneForcastImpressions() method.
*
* Test 1: Test with bad input, and ensure false is returned.
* Test 2: Test with no date in the service locator, and ensure that
* false is returned.
* Test 3: Test with no data, and ensure that an array with the default
* forecast for each zone is returned.
* Test 4: Test with data, and ensure that an array with the correct
* forecasts is returned.
*/
function testGetPreviousWeekZoneForcastImpressions()
{
$aConf = $GLOBALS['_MAX']['CONF'];
$oDbh =& OA_DB::singleton();
$oDal = new OA_Dal_Maintenance_Priority();
// Test 1
$aResult = $oDal->getPreviousWeekZoneForcastImpressions('foo');
$this->assertFalse($aResult);
// Test 2
$oServiceLocator =& OA_ServiceLocator::instance();
$oServiceLocator->remove('now');
$aResult = $oDal->getPreviousWeekZoneForcastImpressions(1);
$this->assertFalse($aResult);
// Test 3
$oDate = new Date();
$oServiceLocator->register('now', $oDate);
$aResult = $oDal->getPreviousWeekZoneForcastImpressions(1);
$this->assertTrue(is_array($aResult));
$this->assertEqual(count($aResult), OX_OperationInterval::operationIntervalsPerWeek());
for ($operationIntervalID = 0; $operationIntervalID < OX_OperationInterval::operationIntervalsPerWeek(); $operationIntervalID++) {
$expected = array('zone_id' => 1, 'forecast_impressions' => $oDal->getZoneForecastDefaultZoneImpressions(), 'operation_interval_id' => $operationIntervalID);
$this->assertEqual($aResult[$operationIntervalID], $expected);
}
// Test 4
// Insert impressions for the previous operation interval
$aDates = OX_OperationInterval::convertDateToOperationIntervalStartAndEndDates($oDate);
$aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
$firstIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
$startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$doDIA = OA_Dal::factoryDO('data_intermediate_ad');
$aDIAs = DataGenerator::generate($doDIA, 4);
$doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[0]);
$startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$doDIA->date_time = $startDate;
$doDIA->interval_start = $startDate;
$doDIA->interval_end = $endDate;
$doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
$doDIA->operation_interval_id = $firstIntervalID;
$doDIA->zone_id = 1;
$doDIA->ad_id = 1;
$doDIA->impressions = 4000;
$doDIA->update();
// Insert forcast for the (N - 2) OI
// for two different ads in this OI
$aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($aDates['start']);
$secondIntervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
$startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[1]);
$doDIA->date_time = $startDate;
$doDIA->interval_start = $startDate;
$doDIA->interval_end = $endDate;
$doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
$doDIA->operation_interval_id = $secondIntervalID;
$doDIA->zone_id = 1;
$doDIA->ad_id = 1;
$doDIA->impressions = 4990;
$doDIA->update();
$doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[2]);
$doDIA->date_time = $startDate;
$doDIA->interval_start = $startDate;
$doDIA->interval_end = $endDate;
$doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
$doDIA->operation_interval_id = $secondIntervalID;
$doDIA->zone_id = 1;
$doDIA->ad_id = 2;
$doDIA->impressions = 10;
$doDIA->update();
// Insert forcast for the second previous operation interval, but
// one week ago (so it should not be in the result set)
$oNewDate = new Date();
$oNewDate->copy($aDates['start']);
$oNewDate->subtractSeconds(SECONDS_PER_WEEK);
$aDates = OX_OperationInterval::convertDateToPreviousOperationIntervalStartAndEndDates($oNewDate);
$intervalID = OX_OperationInterval::convertDateToOperationIntervalID($aDates['start']);
$startDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$endDate = $aDates['start']->format('%Y-%m-%d %H:%M:%S');
$doDIA = OA_Dal::staticGetDO('data_intermediate_ad', $aDIAs[3]);
$doDIA->date_time = $startDate;
$doDIA->interval_start = $startDate;
$doDIA->interval_end = $endDate;
$doDIA->operation_interval = $aConf['maintenance']['operationInterval'];
$doDIA->operation_interval_id = $intervalID;
$doDIA->zone_id = 1;
$doDIA->ad_id = 1;
$doDIA->impressions = 1000;
$doDIA->update();
//.........这里部分代码省略.........
开发者ID:Spark-Eleven,项目名称:revive-adserver,代码行数:101,代码来源:Priority_getPreviousWeekZoneForcastImpressions.dal.test.php
示例12: Date
function check_xp_delivered_date()
{
$mdate = new Date();
$mdate->subtractSeconds(24 * 60 * 60);
if ($this->data['xp_delivered_date'] >= $mdate->format('%Y-%m-%d') && $this->data['check_status'] != 'R' && $this->data['status'] != 'G') {
return true;
} else {
return false;
}
}
示例13: testRun
/**
* A method to test the main run() method.
*/
function testRun()
{
$aConf =& $GLOBALS['_MAX']['CONF'];
$aConf['maintenance']['operationInterval'] = 60;
$oServiceLocator =& OA_ServiceLocator::instance();
$oFactory = new OX_Dal_Maintenance_Statistics_Factory();
$oDalMaintenanceStatsticsClassName = $oFactory->deriveClassName();
// Test 1: Run, with the migration required but with no plugins installed
$oNowDate = new Date('2008-08-28 09:01:00');
$oServiceLocator->register('now', $oNowDate);
$oMaintenanceStatistics = new OX_Maintenance_Statistics();
$oMaintenanceStatistics->updateIntermediate = true;
$oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
$oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 08:59:59');
Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_1', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
$oDal = new MockOX_Dal_Maintenance_Statistics_Test_1($this);
$oDal->expectNever('summariseBucketsRaw');
$oDal->expectNever('summariseBucketsRawSupplementary');
$oDal->expectNever('summariseBucketsAggregate');
$oDal->expectNever('migrateRawRequests');
$oDal->expectNever('migrateRawImpressions');
$oDal->expectNever('migrateRawClicks');
$oDal->OX_Dal_Maintenance_Statistics();
$oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
$oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
$oSummariseIntermediate->run();
$oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
$oDal->tally();
// Create the "application_variable" table required for installing the plugin
$oTables =& OA_DB_Table_Core::singleton();
$oTables->createTable('application_variable');
// Setup the default OpenX delivery logging plugin for the next test
TestEnv::installPluginPackage('openXDeliveryLog', false);
// Test 2: Run, with plugins installed, but with the migration not required
$oNowDate = new Date('2008-08-28 09:01:00');
$oServiceLocator->register('now', $oNowDate);
$oMaintenanceStatistics = new OX_Maintenance_Statistics();
$oMaintenanceStatistics->updateIntermediate = false;
$oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_2', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
$oDal = new MockOX_Dal_Maintenance_Statistics_Test_2($this);
$oDal->expectNever('summariseBucketsRaw');
$oDal->expectNever('summariseBucketsRawSupplementary');
$oDal->expectNever('summariseBucketsAggregate');
$oDal->expectNever('migrateRawRequests');
$oDal->expectNever('migrateRawImpressions');
$oDal->expectNever('migrateRawClicks');
$oDal->OX_Dal_Maintenance_Statistics();
$oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
$oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
$oSummariseIntermediate->run();
$oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
$oDal->tally();
// Test 3: Run, with plugins installed and with the migration required for a single
// operation interval
$oNowDate = new Date('2008-08-28 09:01:00');
$oServiceLocator->register('now', $oNowDate);
$oMaintenanceStatistics = new OX_Maintenance_Statistics();
$oMaintenanceStatistics->updateIntermediate = true;
$oMaintenanceStatistics->oLastDateIntermediate = new Date('2008-08-28 07:59:59');
$oMaintenanceStatistics->oUpdateIntermediateToDate = new Date('2008-08-28 08:59:59');
$oServiceLocator->register('Maintenance_Statistics_Controller', $oMaintenanceStatistics);
Mock::generatePartial($oDalMaintenanceStatsticsClassName, 'MockOX_Dal_Maintenance_Statistics_Test_3', array('summariseBucketsRaw', 'summariseBucketsRawSupplementary', 'summariseBucketsAggregate', 'migrateRawRequests', 'migrateRawImpressions', 'migrateRawClicks'));
$oDal = new MockOX_Dal_Maintenance_Statistics_Test_3($this);
$oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversion');
$oStartDate = new Date('2008-08-28 07:59:59');
$oStartDate->addSeconds(1);
$oEndDate = new Date('2008-08-28 09:00:00');
$oEndDate->subtractSeconds(1);
$oDal->expectOnce('summariseBucketsRaw', array($aConf['table']['prefix'] . 'data_intermediate_ad_connection', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
$oComponent =& OX_Component::factory('deliveryLog', 'oxLogConversion', 'logConversionVariable');
$oStartDate = new Date('2008-08-28 07:59:59');
$oStartDate->addSeconds(1);
$oEndDate = new Date('2008-08-28 09:00:00');
$oEndDate->subtractSeconds(1);
$oDal->expectOnce('summariseBucketsRawSupplementary', array($aConf['table']['prefix'] . 'data_intermediate_ad_variable_value', $oComponent->getStatisticsMigration(), array('start' => $oStartDate, 'end' => $oEndDate)));
$aMap = array();
$oComponent =& OX_Component::factory('deliveryLog', 'oxLogClick', 'logClick');
$aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
$oComponent =& OX_Component::factory('deliveryLog', 'oxLogImpression', 'logImpression');
$aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
$oComponent =& OX_Component::factory('deliveryLog', 'oxLogRequest', 'logRequest');
$aMap[get_class($oComponent)] = $oComponent->getStatisticsMigration();
$oStartDate = new Date('2008-08-28 07:59:59');
$oStartDate->addSeconds(1);
$oEndDate = new Date('2008-08-28 09:00:00');
$oEndDate->subtractSeconds(1);
$oDal->expectOnce('summariseBucketsAggregate', array($aConf['table']['prefix'] . 'data_intermediate_ad', $aMap, array('start' => $oStartDate, 'end' => $oEndDate), array('operation_interval' => '60', 'operation_interval_id' => OX_OperationInterval::convertDateToOperationIntervalID($oStartDate), 'interval_start' => "'2008-08-28 08:00:00'", 'interval_end' => "'2008-08-28 08:59:59'", 'creative_id' => 0, 'updated' => "'2008-08-28 09:01:00'")));
$oDal->expectNever('migrateRawRequests');
$oDal->expectNever('migrateRawImpressions');
$oDal->expectNever('migrateRawClicks');
$oDal->OX_Dal_Maintenance_Statistics();
$oServiceLocator->register('OX_Dal_Maintenance_Statistics', $oDal);
$oSummariseIntermediate = new OX_Maintenance_Statistics_Task_MigrateBucketData();
$oSummariseIntermediate->run();
$oDal =& $oServiceLocator->get('OX_Dal_Maintenance_Statistics');
$oDal->tally();
//.........这里部分代码省略.........
示例14: transferFinishedTransactions
function transferFinishedTransactions($account, $plannedTransaction)
{
$now = new Date();
$date = new Date($plannedTransaction->getBeginDate());
$dayOfMonth = $date->getDay();
//While we are before now and the end date of this transaction
while (!$date->after($now) && !$date->after(is_null($tmp = $plannedTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
$account->addFinishedTransaction($plannedTransaction->getAmount(), $plannedTransaction->getTitle(), $plannedTransaction->getDescription(), new Date($date), $plannedTransaction->getTransactionPartner(), $plannedTransaction->getCategory(), $plannedTransaction->getOutsideCapital(), false, true);
//do the date calculation
switch ($plannedTransaction->getRepeatUnit()) {
case 'day':
$date->addSeconds($plannedTransaction->getRepeatFrequency() * 24 * 60 * 60);
break;
case 'week':
$date->addSeconds($plannedTransaction->getRepeatFrequency() * 7 * 24 * 60 * 60);
break;
case 'month':
//Set the month
$date = new Date(Date_Calc::endOfMonthBySpan($plannedTransaction->getRepeatFrequency(), $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
//And count back as far as the last valid day of this month
while ($date->getDay() > $dayOfMonth) {
$date->subtractSeconds(24 * 60 * 60);
}
break;
case 'year':
$newYear = $date->getYear() + $plannedTransaction->getRepeatFrequency();
if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
$date->setDay(28);
} else {
$date->setDay($dayOfMonth);
}
$date->setYear($newYear);
break;
default:
throw new BadgerException('Account', 'IllegalRepeatUnit', $plannedTransaction->getRepeatUnit());
exit;
}
}
}
示例15: expandPlannedTransactions
/**
* Expands the planned transactions.
*
* All occurences of planned transactions between now and the targetFutureCalcDate will be inserted
* in finishedTransactions. For distinction the planned transactions will have a 'p' as first character
* in their id.
*
* @throws BadgerException If an illegal repeat unit is used.
*/
public function expandPlannedTransactions()
{
$now = new Date();
$now->setHour(0);
$now->setMinute(0);
$now->setSecond(0);
foreach ($this->plannedTransactions as $currentTransaction) {
$date = new Date($currentTransaction->getBeginDate());
$dayOfMonth = $date->getDay();
//While we have not reached targetFutureCalcDate
while ($this->targetFutureCalcDate->after($date) && !$date->after(is_null($tmp = $currentTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
$inRange = true;
//Check if there is one or more valutaDate filter and apply them
foreach ($this->filter as $currentFilter) {
if ($currentFilter['key'] == 'valutaDate') {
switch ($currentFilter['op']) {
case 'eq':
if (Date::compare($date, $currentFilter['val']) != 0) {
$inRange = false;
}
break;
case 'lt':
if (Date::compare($date, $currentFilter['val']) >= 0) {
$inRange = false;
}
break;
case 'le':
if (Date::compare($date, $currentFilter['val']) > 0) {
$inRange = false;
}
break;
case 'gt':
if (Date::compare($date, $currentFilter['val']) <= 0) {
$inRange = false;
}
break;
case 'ge':
if (Date::compare($date, $currentFilter['val']) < 0) {
$inRange = false;
}
break;
case 'ne':
if (Date::compare($date, $currentFilter['val']) == 0) {
$inRange = false;
}
break;
case 'bw':
case 'ew':
case 'ct':
if (strncasecmp($date->getFormatted(), $currentFilter['val']->getFormatted(), 9999) != 0) {
$inRange = false;
}
break;
}
if (!$inRange) {
break;
}
}
}
if (!$date->before($now) && $inRange) {
$this->finishedTransactions[] = new FinishedTransaction($this->badgerDb, $this, 'p' . $currentTransaction->getId() . '_' . $date->getDate(), $currentTransaction->getTitle(), $currentTransaction->getAmount(), $currentTransaction->getDescription(), new Date($date), $currentTransaction->getTransactionPartner(), $currentTransaction->getCategory(), $currentTransaction->getOutsideCapital(), false, true, $currentTransaction, 'PlannedTransaction');
}
//do the date calculation
switch ($currentTransaction->getRepeatUnit()) {
case 'day':
$date->addSeconds($currentTransaction->getRepeatFrequency() * 24 * 60 * 60);
break;
case 'week':
$date->addSeconds($currentTransaction->getRepeatFrequency() * 7 * 24 * 60 * 60);
break;
case 'month':
//Set the month
$date = new Date(Date_Calc::endOfMonthBySpan($currentTransaction->getRepeatFrequency(), $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
//And count back as far as the last valid day of this month
while ($date->getDay() > $dayOfMonth) {
$date->subtractSeconds(24 * 60 * 60);
}
break;
case 'year':
$newYear = $date->getYear() + $currentTransaction->getRepeatFrequency();
if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
$date->setDay(28);
} else {
$date->setDay($dayOfMonth);
}
$date->setYear($newYear);
break;
default:
throw new BadgerException('Account', 'IllegalRepeatUnit', $currentTransaction->getRepeatUnit());
exit;
}
//.........这里部分代码省略.........